Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

In this page you can find the example usage for java.time LocalDateTime now.

Prototype

public static LocalDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java

protected ServiceLevelAgreementGroup createOneHourAgoFeedProcessingDeadlineSla(String feedName, String feedId) {
    LOG.info("Creating 'one hour ago' feed processing deadline SLA for feed " + feedName);
    return createFeedProcessingDeadlineSla(feedName, feedId, LocalDateTime.now().minusHours(1), "0");
}

From source file:ch.algotrader.simulation.SimulationExecutorImpl.java

private void reportStatisticsToFile(SimulationResultVO resultVO) {

    if (!this.commonConfig.isDisableReports()) {

        try {/*from ww  w  .ja v a2s .co m*/

            File reportLocation = this.commonConfig.getReportLocation();
            File reportFile = new File(reportLocation != null ? reportLocation : new File("."),
                    "BackTestReport.csv");
            BackTestReport backTestReport = new BackTestReport(reportFile);

            backTestReport.write("dateTime", DateTimePatterns.LOCAL_DATE_TIME.format(LocalDateTime.now()));
            backTestReport.write("executionTime", resultVO.getMins());
            backTestReport.write("dataSet", this.commonConfig.getDataSet());

            if (resultVO.getAllTrades().getCount() == 0) {
                backTestReport.write("allTradesCount", 0);
                backTestReport.close();
                return;
            }

            double netLiqValue = resultVO.getNetLiqValue();
            backTestReport.write("netLiqValue", twoDigitFormat.format(netLiqValue));

            // monthlyPerformances
            Collection<PeriodPerformanceVO> monthlyPerformances = resultVO.getMonthlyPerformances();
            double maxDrawDownM = 0d;
            double bestMonthlyPerformance = Double.NEGATIVE_INFINITY;
            int positiveMonths = 0;
            int negativeMonths = 0;
            if ((monthlyPerformances != null)) {
                for (PeriodPerformanceVO monthlyPerformance : monthlyPerformances) {
                    maxDrawDownM = Math.min(maxDrawDownM, monthlyPerformance.getValue());
                    bestMonthlyPerformance = Math.max(bestMonthlyPerformance, monthlyPerformance.getValue());
                    if (monthlyPerformance.getValue() > 0) {
                        positiveMonths++;
                    } else {
                        negativeMonths++;
                    }
                }
            }

            // yearlyPerformances
            int positiveYears = 0;
            int negativeYears = 0;
            Collection<PeriodPerformanceVO> yearlyPerformances = resultVO.getYearlyPerformances();
            if ((yearlyPerformances != null)) {
                for (PeriodPerformanceVO yearlyPerformance : yearlyPerformances) {
                    if (yearlyPerformance.getValue() > 0) {
                        positiveYears++;
                    } else {
                        negativeYears++;
                    }
                }
            }

            if ((monthlyPerformances != null)) {
                backTestReport.write("posMonths", positiveMonths);
                backTestReport.write("negMonths", negativeMonths);
                if ((yearlyPerformances != null)) {
                    backTestReport.write("posYears", positiveYears);
                    backTestReport.write("negYears", negativeYears);
                }
            }

            PerformanceKeysVO performanceKeys = resultVO.getPerformanceKeys();
            MaxDrawDownVO maxDrawDownVO = resultVO.getMaxDrawDown();
            if (performanceKeys != null && maxDrawDownVO != null) {
                backTestReport.write("avgM", performanceKeys.getAvgM());
                backTestReport.write("stdM", performanceKeys.getStdM());
                backTestReport.write("avgY", performanceKeys.getAvgY());
                backTestReport.write("stdY", performanceKeys.getStdY());
                backTestReport.write("sharpeRatio", performanceKeys.getSharpeRatio());

                backTestReport.write("maxMonthlyDrawDown", -maxDrawDownM);
                backTestReport.write("bestMonthlyPerformance", bestMonthlyPerformance);
                backTestReport.write("maxDrawDown", maxDrawDownVO.getAmount());
                backTestReport.write("maxDrawDownPeriod", maxDrawDownVO.getPeriod() / 86400000);
                backTestReport.write("colmarRatio", performanceKeys.getAvgY() / maxDrawDownVO.getAmount());
            }

            reportTrades(backTestReport, "winningTrades", resultVO.getWinningTrades(),
                    resultVO.getAllTrades().getCount());
            reportTrades(backTestReport, "losingTrades", resultVO.getLoosingTrades(),
                    resultVO.getAllTrades().getCount());
            reportTrades(backTestReport, "allTrades", resultVO.getAllTrades(),
                    resultVO.getAllTrades().getCount());

            backTestReport.write("returns");
            if ((monthlyPerformances != null)) {
                for (PeriodPerformanceVO monthlyPerformance : monthlyPerformances) {
                    backTestReport.write(
                            DateTimePatterns.LOCAL_DATE
                                    .format(DateTimeLegacy.toLocalDate(monthlyPerformance.getDate())),
                            monthlyPerformance.getValue());
                }
            }

            backTestReport.close();

            // make sure BackTestReport.xlsx exists
            File excelReportFile = new File(reportLocation != null ? reportLocation : new File("."),
                    "BackTestReport.xlsm");
            if (!excelReportFile.exists()) {
                InputStream is = getClass().getResourceAsStream("/BackTestReport.xlsm");
                FileUtils.copyInputStreamToFile(is, excelReportFile);
            }

            if (this.commonConfig.isOpenBackTestReport()) {
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().open(excelReportFile);
                    } catch (IOException e) {
                        // no application registered to .xlsm files
                        RESULT_LOGGER.info("BackTestReport available at: " + excelReportFile);
                    }
                } else {
                    RESULT_LOGGER.info("BackTestReport available at: " + excelReportFile);
                }
            }

        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}

From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java

protected ServiceLevelAgreementGroup createOneHourAheadFeedProcessingDeadlineSla(String feedName,
        String feedId) {/*from  w  w  w. j  a v a  2s  .co  m*/
    LOG.info("Creating 'one hour ahead' feed processing deadline SLA for feed " + feedName);
    return createFeedProcessingDeadlineSla(feedName, feedId, LocalDateTime.now().plusHours(1), "24");
}

From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java

/**
 * Method for adding Composite API related information
 *
 * @param connection DB Connection//www  .  ja  v a 2  s  . co m
 * @param statement  PreparedStatement
 * @param api        Composite API object
 * @throws SQLException if error occurs while accessing data layer
 */
private void addCompositeAPIRelatedInformation(Connection connection, PreparedStatement statement,
        final CompositeAPI api) throws SQLException {
    String apiPrimaryKey = api.getId();
    statement.setString(1, api.getProvider());
    statement.setString(2, api.getName());
    statement.setString(3, api.getContext());
    statement.setString(4, api.getVersion());
    statement.setString(5, api.getDescription());
    statement.setString(6, apiPrimaryKey);

    statement.setInt(7, getApiTypeId(connection, ApiType.COMPOSITE));
    statement.setString(8, api.getCreatedBy());
    statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
    statement.setTimestamp(10, Timestamp.valueOf(LocalDateTime.now()));
    statement.setString(11, api.getCopiedFromApiId());
    statement.setString(12, api.getUpdatedBy());
    statement.setString(13, APILCWorkflowStatus.APPROVED.toString());
    statement.execute();

    addLabelMapping(connection, apiPrimaryKey, api.getLabels());
    addGatewayConfig(connection, apiPrimaryKey, api.getGatewayConfig(), api.getCreatedBy());
    addTransports(connection, apiPrimaryKey, api.getTransport());
    addUrlMappings(connection, api.getUriTemplates().values(), apiPrimaryKey);
    addAPIDefinition(connection, apiPrimaryKey, api.getApiDefinition(), api.getCreatedBy());
    addAPIPermission(connection, api.getPermissionMap(), apiPrimaryKey);
}

From source file:com.ccserver.digital.service.LOSService.java

private EmployeeInfoType getEmploymentInfo(CreditCardApplicationDTO dto) {
    EmployeeInfoType employeeInfoType = new EmployeeInfoType();
    employeeInfoType.setEmploymentType(dto.getTypeOfEmployement().toString());
    // los: occupation, ccapp: industry
    employeeInfoType.setOccupation(dto.getIndustry() != null ? dto.getIndustry().getCode() : "OCP8");
    // los: position,ccapp: occupation
    SelectionListDTO occupation = dto.getOccupation();
    if (occupation != null) {
        employeeInfoType.setPosition(occupation.getCode());
        employeeInfoType.setJobTitle(occupation.getCode());
    }/*from ww w.ja  v  a  2 s.c o m*/

    ContractInfoType contractInfoType = new ContractInfoType();
    contractInfoType.setContractType(getConfiguration("LOS_CONTRACT_TYPE", "CON14"));
    employeeInfoType.setContractInfo(contractInfoType);

    if (dto.getTypeOfEmployement().equals(TypeOfEmployment.Business)) {
        employeeInfoType.setStartDate(dateToXMLGregorianCalendar(dto.getBusinessStartDate()));
        employeeInfoType.setDuration(getDurationFormat(dto.getBusinessStartDate()));
        employeeInfoType.setPosition(getConfiguration("LOS_POSITION_BO_DEFAULT", "POSH36"));
    } else {
        int year = dto.getYearsOfWorking() != null ? dto.getYearsOfWorking() : 0;
        int month = dto.getMonthsOfWorking() != null ? dto.getMonthsOfWorking() : 0;

        int totalMonth = year * 12 + month;
        employeeInfoType.setDuration(String.valueOf(totalMonth));

        employeeInfoType.setStartDate(dateToXMLGregorianCalendar(LocalDateTime.now().minusMonths(totalMonth)));
    }

    employeeInfoType.setOrganizationInfo(getOrganizationInfoType(dto));
    return employeeInfoType;
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * PAAA services//from   w w w  .j  a  v a2s . co  m
 */
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, String patronid, String token, String service) throws IOException {

    String baseurl = httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort();
    this.logger.info("[" + config.getProperty("service.name") + "] " + "baseurl = " + baseurl);

    ObjectMapper mapper = new ObjectMapper();

    if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {

        try {
            IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class);
            // init ILS
            integratedLibrarySystem.init(this.config);

            switch (service) {

            case "signup": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                if (patron2create.getAccount() == null || patron2create.getAccount().equals("")) {
                    if (!patronid.equals("")) {
                        patron2create.setAccount(patronid);
                    } else {
                        patron2create.setAccount(UUID.randomUUID().toString());
                    }
                }

                patron = integratedLibrarySystem.signup(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    Block block = new Block();
                    LocalDateTime timePoint = LocalDateTime.now();
                    block.setDate(timePoint.getYear() + "-"
                            + (timePoint.getMonthValue() < 10 ? "0" + timePoint.getMonthValue()
                                    : timePoint.getMonthValue())
                            + "-" + (timePoint.getDayOfMonth() < 10 ? "0" + timePoint.getDayOfMonth()
                                    : timePoint.getDayOfMonth()));
                    block.setKey("93");
                    integratedLibrarySystem.blockpatron(patron, block);

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                patron2create.setAccount(patronid);

                patron = integratedLibrarySystem.newpatron(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "updatepatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2update = mapper.readValue(jb.toString(), Patron.class);
                patron2update.setAccount(patronid);

                // TODO Was tun bei nderung des 'status'?

                patron = integratedLibrarySystem.updatepatron(patron2update);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "blockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2block = new Patron();
                patron2block.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.blockpatron(patron2block, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "unblockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2unblock = new Patron();
                patron2unblock.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.unblockpatron(patron2unblock, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "deletepatron": {

                Patron patron = null;

                Patron patron2delete = new Patron();
                patron2delete.setAccount(patronid);

                patron = integratedLibrarySystem.deletepatron(patron2delete);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newfee": {

                Patron patron = null;
                Fee resultFee = null;

                patron = new Patron();
                patron.setAccount(patronid);

                // read Fee
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Fee = " + jb);

                Fee fee = mapper.readValue(jb.toString(), Fee.class);

                resultFee = integratedLibrarySystem.newfee(patron, fee);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");
                StringWriter stringWriter = new StringWriter();
                mapper.writeValue(stringWriter, resultFee);
                this.logger.debug(
                        "[" + config.getProperty("service.name") + "] " + "Fee: " + stringWriter.toString());

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, resultFee);
                    this.logger.debug(json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            default: {
                // TODO: keine gltige Funktion
            }
            }
        } catch (ILSException e) {

            this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service
                    + "' event for patron '" + patronid + "' >>> failed!");
            this.logger.error("[" + config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": ILS Error! " + e.getMessage());

            // TODO e.getMessage = 403
            if (e.getMessage().equals("403")) {

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(
                        this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN)));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            } else {

                // Mail to Bib-IT wg. Socket-Error
                try {

                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);

                    Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));
                    mailer.postMail(
                            "[" + this.config.getProperty("service.name") + "] ILS Error! " + e.getMessage(),
                            sw.toString());

                } catch (MessagingException | IOException e1) {

                    this.logger.error(e1.getMessage(), e1.getCause());
                }

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            }
        }
    } else {

        this.logger.error("[" + config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

        httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
        httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
        requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        requestError.setDescription(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
        requestError.setErrorUri(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

        StringWriter json = new StringWriter();
        mapper.writeValue(json, requestError);
        this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

        // send response
        httpServletResponse.getWriter().println(json);
    }

}

From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java

/**
 * Update an existing API//ww w  .j  a va  2  s  . c o m
 *
 * @param apiID         The {@link String} of the API that needs to be updated
 * @param substituteAPI Substitute {@link API} object that will replace the existing API
 * @throws APIMgtDAOException if error occurs while accessing data layer
 */
@Override
public void updateAPI(String apiID, API substituteAPI) throws APIMgtDAOException {
    final String query = "UPDATE AM_API SET CONTEXT = ?, IS_DEFAULT_VERSION = ?, DESCRIPTION = ?, VISIBILITY = ?, "
            + "IS_RESPONSE_CACHED = ?, CACHE_TIMEOUT = ?, TECHNICAL_OWNER = ?, TECHNICAL_EMAIL = ?, "
            + "BUSINESS_OWNER = ?, BUSINESS_EMAIL = ?, CORS_ENABLED = ?, CORS_ALLOW_ORIGINS = ?, "
            + "CORS_ALLOW_CREDENTIALS = ?, CORS_ALLOW_HEADERS = ?, CORS_ALLOW_METHODS = ?, LAST_UPDATED_TIME = ?,"
            + "UPDATED_BY = ?, LC_WORKFLOW_STATUS=? WHERE UUID = ?";

    try (Connection connection = DAOUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement(query)) {
        try {
            connection.setAutoCommit(false);
            statement.setString(1, substituteAPI.getContext());
            statement.setBoolean(2, substituteAPI.isDefaultVersion());
            statement.setString(3, substituteAPI.getDescription());
            statement.setString(4, substituteAPI.getVisibility().toString());
            statement.setBoolean(5, substituteAPI.isResponseCachingEnabled());
            statement.setInt(6, substituteAPI.getCacheTimeout());

            BusinessInformation businessInformation = substituteAPI.getBusinessInformation();
            statement.setString(7, businessInformation.getTechnicalOwner());
            statement.setString(8, businessInformation.getTechnicalOwnerEmail());
            statement.setString(9, businessInformation.getBusinessOwner());
            statement.setString(10, businessInformation.getBusinessOwnerEmail());

            CorsConfiguration corsConfiguration = substituteAPI.getCorsConfiguration();
            statement.setBoolean(11, corsConfiguration.isEnabled());
            statement.setString(12, String.join(",", corsConfiguration.getAllowOrigins()));
            statement.setBoolean(13, corsConfiguration.isAllowCredentials());
            statement.setString(14, String.join(",", corsConfiguration.getAllowHeaders()));
            statement.setString(15, String.join(",", corsConfiguration.getAllowMethods()));

            statement.setTimestamp(16, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(17, substituteAPI.getUpdatedBy());
            statement.setString(18, substituteAPI.getWorkflowStatus());
            statement.setString(19, apiID);

            statement.execute();

            deleteVisibleRoles(connection, apiID); // Delete current visible roles if they exist

            if (API.Visibility.RESTRICTED == substituteAPI.getVisibility()) {
                addVisibleRole(connection, apiID, substituteAPI.getVisibleRoles());
            }

            deleteAPIPermission(connection, apiID);
            updateApiPermission(connection, substituteAPI.getPermissionMap(), apiID);

            deleteTransports(connection, apiID);
            addTransports(connection, apiID, substituteAPI.getTransport());

            deleteTagsMapping(connection, apiID); // Delete current tag mappings if they exist
            addTagsMapping(connection, apiID, substituteAPI.getTags());
            deleteLabelsMapping(connection, apiID);
            addLabelMapping(connection, apiID, substituteAPI.getLabels());
            deleteSubscriptionPolicies(connection, apiID);
            addSubscriptionPolicies(connection, substituteAPI.getPolicies(), apiID);
            deleteEndPointsForApi(connection, apiID);
            addEndPointsForApi(connection, apiID, substituteAPI.getEndpoint());
            deleteEndPointsForOperation(connection, apiID);
            deleteUrlMappings(connection, apiID);
            addUrlMappings(connection, substituteAPI.getUriTemplates().values(), apiID);
            deleteApiPolicy(connection, apiID);
            if (substituteAPI.getApiPolicy() != null) {
                addApiPolicy(connection, substituteAPI.getApiPolicy().getUuid(), apiID);
            }
            connection.commit();
        } catch (SQLException | IOException e) {
            String msg = "Couldn't update api : " + substituteAPI.getName();
            connection.rollback();
            log.error(msg, e);
            throw new APIMgtDAOException(e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        throw new APIMgtDAOException(e);
    }
}

From source file:org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler.java

private void updateStatusIfChanged(ThingStatus status, ThingStatusDetail statusDetail,
        @Nullable String description) {
    ThingStatusInfo newStatusInfo = new ThingStatusInfo(status, statusDetail, description);
    Duration durationSinceLastUpdate = Duration.between(lastStatusInfoUpdate, LocalDateTime.now());
    boolean intervalElapsed = MIN_STATUS_INFO_UPDATE_INTERVAL.minus(durationSinceLastUpdate).isNegative();
    if (statusInfo.getStatus() == ThingStatus.UNKNOWN || !statusInfo.equals(newStatusInfo) || intervalElapsed) {
        statusInfo = newStatusInfo;/*from  ww w  .j a  va2 s .  c om*/
        lastStatusInfoUpdate = LocalDateTime.now();
        updateStatus(newStatusInfo);
    }
}

From source file:ffx.potential.ForceFieldEnergy.java

/**
 * <p>// w ww.  j a va2 s  .com
 * energy</p>
 *
 * @param gradient a boolean.
 * @param print a boolean.
 * @return a double.
 */
public double energy(boolean gradient, boolean print) {
    try {
        bondTime = 0;
        angleTime = 0;
        stretchBendTime = 0;
        ureyBradleyTime = 0;
        outOfPlaneBendTime = 0;
        torsionTime = 0;
        piOrbitalTorsionTime = 0;
        torsionTorsionTime = 0;
        improperTorsionTime = 0;
        vanDerWaalsTime = 0;
        electrostaticTime = 0;
        restraintBondTime = 0;
        ncsTime = 0;
        coordRestraintTime = 0;
        totalTime = System.nanoTime();

        // Zero out the potential energy of each bonded term.
        bondEnergy = 0.0;
        angleEnergy = 0.0;
        stretchBendEnergy = 0.0;
        ureyBradleyEnergy = 0.0;
        outOfPlaneBendEnergy = 0.0;
        torsionEnergy = 0.0;
        piOrbitalTorsionEnergy = 0.0;
        torsionTorsionEnergy = 0.0;
        improperTorsionEnergy = 0.0;
        totalBondedEnergy = 0.0;

        // Zero out potential energy of restraint terms
        restraintBondEnergy = 0.0;
        ncsEnergy = 0.0;
        restrainEnergy = 0.0;

        // Zero out bond and angle RMSDs.
        bondRMSD = 0.0;
        angleRMSD = 0.0;

        // Zero out the potential energy of each non-bonded term.
        vanDerWaalsEnergy = 0.0;
        permanentMultipoleEnergy = 0.0;
        polarizationEnergy = 0.0;
        totalElectrostaticEnergy = 0.0;
        totalNonBondedEnergy = 0.0;

        // Zero out the solvation energy.
        solvationEnergy = 0.0;

        // Zero out the relative solvation energy (sequence optimization)
        relativeSolvationEnergy = 0.0;
        nRelativeSolvations = 0;

        esvBias = 0.0;

        // Zero out the total potential energy.
        totalEnergy = 0.0;

        // Zero out the Cartesian coordinate gradient for each atom.
        if (gradient) {
            for (int i = 0; i < nAtoms; i++) {
                atoms[i].setXYZGradient(0.0, 0.0, 0.0);
                atoms[i].setLambdaXYZGradient(0.0, 0.0, 0.0);
            }
        }

        /**
         * Computed the bonded energy terms in parallel.
         */
        try {
            bondedRegion.setGradient(gradient);
            parallelTeam.execute(bondedRegion);
        } catch (Exception e) {
            e.printStackTrace();
            logger.severe(e.toString());
        }

        if (!lambdaBondedTerms) {
            /**
             * Compute restraint terms.
             */
            if (ncsTerm) {
                ncsTime = -System.nanoTime();
                ncsEnergy = ncsRestraint.residual(gradient, print);
                ncsTime += System.nanoTime();
            }
            if (restrainTerm && !coordRestraints.isEmpty()) {
                coordRestraintTime = -System.nanoTime();
                for (CoordRestraint restraint : coordRestraints) {
                    restrainEnergy += restraint.residual(gradient, print);
                }
                coordRestraintTime += System.nanoTime();
            }
            if (comTerm) {
                comRestraintTime = -System.nanoTime();
                comRestraintEnergy = comRestraint.residual(gradient, print);
                comRestraintTime += System.nanoTime();
            }
            /**
             * Compute non-bonded terms.
             */
            if (vanderWaalsTerm) {
                vanDerWaalsTime = -System.nanoTime();
                vanDerWaalsEnergy = vanderWaals.energy(gradient, print);
                nVanDerWaalInteractions = this.vanderWaals.getInteractions();
                vanDerWaalsTime += System.nanoTime();
            }
            if (multipoleTerm) {
                electrostaticTime = -System.nanoTime();
                totalElectrostaticEnergy = particleMeshEwald.energy(gradient, print);
                permanentMultipoleEnergy = particleMeshEwald.getPermanentEnergy();
                polarizationEnergy = particleMeshEwald.getPolarizationEnergy();
                nPermanentInteractions = particleMeshEwald.getInteractions();
                solvationEnergy = particleMeshEwald.getGKEnergy();
                nGKInteractions = particleMeshEwald.getGKInteractions();
                electrostaticTime += System.nanoTime();
            }
        }

        if (relativeSolvationTerm) {
            List<Residue> residuesList = molecularAssembly.getResidueList();
            for (Residue residue : residuesList) {
                if (residue instanceof MultiResidue) {
                    Atom refAtom = residue.getSideChainAtoms().get(0);
                    if (refAtom != null && refAtom.getUse()) {
                        /**
                         * Reasonably confident that it should be -=, as we
                         * are trying to penalize residues with strong
                         * solvation energy.
                         */
                        double thisSolvation = relativeSolvation.getSolvationEnergy(residue, false);
                        relativeSolvationEnergy -= thisSolvation;
                        if (thisSolvation != 0) {
                            nRelativeSolvations++;
                        }
                    }
                }
            }
        }

        totalTime = System.nanoTime() - totalTime;

        totalBondedEnergy = bondEnergy + restraintBondEnergy + angleEnergy + stretchBendEnergy
                + ureyBradleyEnergy + outOfPlaneBendEnergy + torsionEnergy + piOrbitalTorsionEnergy
                + improperTorsionEnergy + torsionTorsionEnergy + ncsEnergy + restrainEnergy;
        totalNonBondedEnergy = vanDerWaalsEnergy + totalElectrostaticEnergy + relativeSolvationEnergy;
        totalEnergy = totalBondedEnergy + totalNonBondedEnergy + solvationEnergy;
        if (esvTerm) {
            esvBias = esvSystem.getBiasEnergy(null);
            totalEnergy += esvBias;
        }
    } catch (EnergyException ex) {
        if (printOnFailure) {
            String timeString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd-HH_mm_ss"));

            String filename = String.format("%s-ERROR-%s.pdb",
                    FilenameUtils.removeExtension(molecularAssembly.getFile().getName()), timeString);

            PotentialsFunctions ef = new PotentialsUtils();
            filename = ef.versionFile(filename);
            logger.info(String.format(" Writing on-error snapshot to file %s", filename));
            ef.saveAsPDB(molecularAssembly, new File(filename));
        }
        if (ex.doCauseSevere()) {
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
            return 0.0;
        } else {
            throw ex; // Rethrow exception
        }
    }

    if (print || printOverride) {
        if (printCompact) {
            logger.info(this.toString());
        } else {
            StringBuilder sb = new StringBuilder();
            if (gradient) {
                sb.append("\n Computed Potential Energy and Atomic Coordinate Gradients\n");
            } else {
                sb.append("\n Computed Potential Energy\n");
            }
            sb.append(this);
            logger.info(sb.toString());
        }
    }
    return totalEnergy;
}

From source file:io.hops.hopsworks.common.project.ProjectController.java

public String[] forceCleanup(String projectName, String userEmail, String sessionId) {
    CleanupLogger cleanupLogger = new CleanupLogger(projectName);
    DistributedFileSystemOps dfso = null;
    YarnClientWrapper yarnClientWrapper = null;
    try {//from   w  ww. ja  v  a2s .  c om
        dfso = dfs.getDfsOps();
        yarnClientWrapper = ycs.getYarnClientSuper(settings.getConfiguration());
        Project project = projectFacade.findByName(projectName);
        if (project != null) {
            cleanupLogger.logSuccess("Project not found in the database");

            // Run custom handler for project deletion
            for (ProjectHandler projectHandler : projectHandlers) {
                try {
                    projectHandler.preDelete(project);
                    cleanupLogger.logSuccess("Handler " + projectHandler.getClassName() + " successfully run");
                } catch (Exception e) {
                    cleanupLogger.logError("Error running handler: " + projectHandler.getClassName()
                            + " during project cleanup");
                    cleanupLogger.logError(e.getMessage());
                }
            }

            // Remove from Project team
            try {
                updateProjectTeamRole(project, ProjectRoleTypes.UNDER_REMOVAL);
                cleanupLogger.logSuccess("Updated team role");
            } catch (Exception ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Get Yarn applications
            List<ApplicationReport> projectApps = null;
            try {
                Collection<ProjectTeam> team = project.getProjectTeamCollection();
                Set<String> hdfsUsers = new HashSet<>();
                for (ProjectTeam pt : team) {
                    String hdfsUsername = hdfsUsersController.getHdfsUserName(project, pt.getUser());
                    hdfsUsers.add(hdfsUsername);
                }
                hdfsUsers.add(project.getProjectGenericUser());

                projectApps = getYarnApplications(hdfsUsers, yarnClientWrapper.getYarnClient());
                cleanupLogger.logSuccess("Gotten Yarn applications");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when reading YARN apps during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Kill Zeppelin jobs
            try {
                killZeppelin(project.getId(), sessionId);
                cleanupLogger.logSuccess("Killed Zeppelin");
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "Error when killing Zeppelin during project cleanup", ex);
                cleanupLogger.logError(ex.getMessage());
            }

            // Stop Jupyter
            try {
                jupyterProcessFacade.stopProject(project);
                cleanupLogger.logSuccess("Stopped Jupyter");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when killing Jupyter during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Kill Yarn Jobs
            try {
                killYarnJobs(project);
                cleanupLogger.logSuccess("Killed Yarn jobs");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when killing YARN jobs during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Wait for Yarn logs
            try {
                waitForJobLogs(projectApps, yarnClientWrapper.getYarnClient());
                cleanupLogger.logSuccess("Gotten logs for jobs");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when getting Yarn logs during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Log removal
            try {
                logProject(project, OperationType.Delete);
                cleanupLogger.logSuccess("Logged project removal");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when logging project removal during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Change ownership of root dir
            try {
                Path path = new Path(File.separator + Settings.DIR_ROOT + File.separator + project.getName());
                changeOwnershipToSuperuser(path, dfso);
                cleanupLogger.logSuccess("Changed ownership of root Project dir");
            } catch (Exception ex) {
                cleanupLogger
                        .logError("Error when changing ownership of root Project dir during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Change ownership of tmp file
            Path dummy = new Path("/tmp/" + project.getName());
            try {
                changeOwnershipToSuperuser(dummy, dfso);
                cleanupLogger.logSuccess("Changed ownership of dummy inode");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when changing ownership of dummy inode during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove Kafka
            try {
                removeKafkaTopics(project);
                cleanupLogger.logSuccess("Removed Kafka topics");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing kafka topics during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove certificates
            try {
                certificatesController.deleteProjectCertificates(project);
                cleanupLogger.logSuccess("Removed certificates");
            } catch (CAException ex) {
                if (ex.getErrorCode() != RESTCodes.CAErrorCode.CERTNOTFOUND) {
                    cleanupLogger.logError("Error when removing certificates during project cleanup");
                }
            } catch (IOException ex) {
                cleanupLogger.logError("Error when removing certificates during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            List<HdfsUsers> usersToClean = getUsersToClean(project);
            List<HdfsGroups> groupsToClean = getGroupsToClean(project);

            // Remove project related files
            try {
                removeProjectRelatedFiles(usersToClean, dfso);
                cleanupLogger.logSuccess("Removed project related files");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing project-related files during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove quotas
            try {
                removeQuotas(project);
                cleanupLogger.logSuccess("Removed quotas");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing quota during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Change owner for files in shared datasets
            try {
                fixSharedDatasets(project, dfso);
                cleanupLogger.logSuccess("Fixed shared datasets");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when changing ownership during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // 16) Delete Hive database - will automatically cleanup all the Hive's metadata
            try {
                hiveController.dropDatabase(project, dfso, true);
                cleanupLogger.logSuccess("Removed Hive db");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing hive db during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Delete elasticsearch template for this project
            try {
                removeElasticsearch(project);
                cleanupLogger.logSuccess("Removed ElasticSearch");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing elastic during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // delete project group and users
            try {
                removeGroupAndUsers(groupsToClean, usersToClean);
                cleanupLogger.logSuccess("Removed HDFS Groups and Users");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing HDFS groups/users during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // remove anaconda repos
            try {
                removeJupyter(project);
                cleanupLogger.logSuccess("Removed Jupyter");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing Anaconda during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // remove running tensorboards repos
            try {
                removeTensorBoard(project);
                cleanupLogger.logSuccess("Removed local TensorBoards");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing running TensorBoards during project cleanup");
            }

            try {
                tfServingController.deleteTfServings(project);
                cleanupLogger.logSuccess("Removed Tf Servings");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing Tf Serving instances");
                cleanupLogger.logError(ex.getMessage());
            }

            // remove dumy Inode
            try {
                dfso.rm(dummy, true);
                cleanupLogger.logSuccess("Removed dummy Inode");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing dummy Inode during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // remove folder
            try {
                removeProjectFolder(project.getName(), dfso);
                cleanupLogger.logSuccess("Removed root Project folder");
            } catch (Exception ex) {
                cleanupLogger.logError("Error when removing root Project dir during project cleanup");
                cleanupLogger.logError(ex.getMessage());
            }

            // Run custom handler for project deletion
            for (ProjectHandler projectHandler : projectHandlers) {
                try {
                    projectHandler.postDelete(project);
                    cleanupLogger.logSuccess("Handler " + projectHandler.getClassName() + " successfully run");
                } catch (Exception e) {
                    cleanupLogger.logError("Error running handler: " + projectHandler.getClassName()
                            + " during project cleanup");
                    cleanupLogger.logError(e.getMessage());
                }
            }
        } else {
            // Create /tmp/Project and add to database so we lock in case someone tries to create a Project
            // with the same name at the same time
            cleanupLogger.logSuccess("Project is *NOT* in the database, going to remove as much as possible");
            Date now = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
            Users user = userFacade.findByEmail(userEmail);
            Project toDeleteProject = new Project(projectName, user, now, PaymentType.PREPAID);
            toDeleteProject.setKafkaMaxNumTopics(settings.getKafkaMaxNumTopics());
            Path tmpInodePath = new Path(File.separator + "tmp" + File.separator + projectName);
            try {
                if (!dfso.exists(tmpInodePath.toString())) {
                    dfso.touchz(tmpInodePath);
                }
                Inode tmpInode = inodes.getInodeAtPath(tmpInodePath.toString());
                if (tmpInode != null) {
                    toDeleteProject.setInode(tmpInode);
                    projectFacade.persistProject(toDeleteProject);
                    projectFacade.flushEm();
                    cleanupLogger.logSuccess("Created dummy Inode");
                }
            } catch (IOException ex) {
                cleanupLogger.logError("Could not create dummy Inode, moving on unsafe");
            }

            // Kill jobs
            List<HdfsUsers> projectHdfsUsers = hdfsUsersController.getAllProjectHdfsUsers(projectName);
            try {
                Set<String> hdfsUsersStr = new HashSet<>();
                for (HdfsUsers hdfsUser : projectHdfsUsers) {
                    hdfsUsersStr.add(hdfsUser.getName());
                }
                hdfsUsersStr.add(projectName + "__" + Settings.PROJECT_GENERIC_USER_SUFFIX);

                List<ApplicationReport> projectApps = getYarnApplications(hdfsUsersStr,
                        yarnClientWrapper.getYarnClient());
                waitForJobLogs(projectApps, yarnClientWrapper.getYarnClient());
                cleanupLogger.logSuccess("Killed all Yarn Applications");
            } catch (Exception ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Cleanup Jupyter project
            try {
                jupyterProcessFacade.stopProject(toDeleteProject);
                cleanupLogger.logSuccess("Cleaned Jupyter environment");
            } catch (Exception ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove project related files
            try {
                removeProjectRelatedFiles(projectHdfsUsers, dfso);
                cleanupLogger.logSuccess("Removed project related files from HDFS");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove Hive database
            try {
                hiveController.dropDatabase(toDeleteProject, dfso, true);
                cleanupLogger.logSuccess("Dropped Hive database");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove ElasticSearch index
            try {
                removeElasticsearch(project);
                cleanupLogger.logSuccess("Removed ElasticSearch");
            } catch (Exception ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove HDFS Groups and Users
            try {
                List<HdfsGroups> projectHdfsGroups = hdfsUsersController.getAllProjectHdfsGroups(projectName);
                removeGroupAndUsers(projectHdfsGroups, projectHdfsUsers);
                cleanupLogger.logSuccess("Removed HDFS Groups and Users");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove Yarn project quota
            try {
                removeQuotas(toDeleteProject);
                cleanupLogger.logSuccess("Removed project quota");
            } catch (Exception ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove Certificates
            try {
                opensslOperations.deleteProjectCertificate(projectName);
                userCertsFacade.removeAllCertsOfAProject(projectName);
                cleanupLogger.logSuccess("Deleted certificates");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove root project directory
            try {
                removeProjectFolder(projectName, dfso);
                cleanupLogger.logSuccess("Removed root project directory");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }

            // Remove /tmp/project
            try {
                dfso.rm(new Path(File.separator + "tmp" + File.separator + projectName), true);
                cleanupLogger.logSuccess("Removed /tmp");
            } catch (IOException ex) {
                cleanupLogger.logError(ex.getMessage());
            }
        }
    } finally {
        dfs.closeDfsClient(dfso);
        ycs.closeYarnClient(yarnClientWrapper);
        LOGGER.log(Level.INFO, cleanupLogger.getSuccessLog().toString());
        LOGGER.log(Level.SEVERE, cleanupLogger.getErrorLog().toString());
        sendInbox(cleanupLogger.getSuccessLog().append("\n").append(cleanupLogger.getErrorLog()).append("\n")
                .toString(), userEmail);
    }
    String[] logs = new String[2];
    logs[0] = cleanupLogger.getSuccessLog().toString();
    logs[1] = cleanupLogger.getErrorLog().toString();
    return logs;
}