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:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java

@Override
public void addComment(Comment comment, String apiId) throws APIMgtDAOException {
    final String addCommentQuery = "INSERT INTO AM_API_COMMENTS (UUID, COMMENT_TEXT, USER_IDENTIFIER, API_ID, "
            + "CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME" + ") VALUES (?,?,?,?,?,?,?,?)";
    try (Connection connection = DAOUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement(addCommentQuery)) {
        try {/*from   w  w w  .j ava  2s.  c om*/
            connection.setAutoCommit(false);
            statement.setString(1, comment.getUuid());
            statement.setString(2, comment.getCommentText());
            statement.setString(3, comment.getCommentedUser());
            statement.setString(4, apiId);
            statement.setString(5, comment.getCreatedUser());
            statement.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(7, comment.getUpdatedUser());
            statement.setTimestamp(8, Timestamp.valueOf(LocalDateTime.now()));
            statement.execute();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "Error while adding comment for api id: " + apiId;
            log.error(errorMessage, e);
            throw new APIMgtDAOException(e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        log.error("Error while creating database connection/prepared-statement", e);
        throw new APIMgtDAOException(e);
    }
}

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

@Override
public void updateComment(Comment comment, String commentId, String apiId) throws APIMgtDAOException {
    final String updateCommentQuery = "UPDATE AM_API_COMMENTS SET COMMENT_TEXT = ? "
            + ", UPDATED_BY = ? , LAST_UPDATED_TIME = ?" + " WHERE UUID = ? AND API_ID = ?";
    try (Connection connection = DAOUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement(updateCommentQuery)) {
        try {// w w  w . j  a  v a2  s .  c om
            connection.setAutoCommit(false);
            statement.setString(1, comment.getCommentText());
            statement.setString(2, comment.getUpdatedUser());
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, commentId);
            statement.setString(5, apiId);
            statement.execute();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "Error while updating comment for api id: " + apiId + " and comment id: "
                    + commentId;
            log.error(errorMessage, e);
            throw new APIMgtDAOException(e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        log.error("Error while creating database connection/prepared-statement", e);
        throw new APIMgtDAOException(e);
    }

}

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

@Override
public void addRating(String apiId, Rating rating) throws APIMgtDAOException {
    final String addRatingQuery = "INSERT INTO AM_API_RATINGS (UUID, API_ID, RATING, USER_IDENTIFIER, "
            + "CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME" + ") VALUES (?,?,?,?,?,?,?,?)";
    try (Connection connection = DAOUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement(addRatingQuery)) {
        try {/*from ww w .  j a v  a2 s.com*/
            connection.setAutoCommit(false);
            statement.setString(1, rating.getUuid());
            statement.setString(2, apiId);
            statement.setInt(3, rating.getRating());
            statement.setString(4, rating.getUsername());
            statement.setString(5, rating.getCreatedUser());
            statement.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(7, rating.getLastUpdatedUser());
            statement.setTimestamp(8, Timestamp.valueOf(LocalDateTime.now()));
            statement.execute();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "Error while adding rating for api id: " + apiId;
            log.error(errorMessage, e);
            throw new APIMgtDAOException(e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        log.error("Error while creating database connection/prepared-statement", e);
        throw new APIMgtDAOException(e);
    }
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl.java

private void unloadNamespacesFromOverLoadedBrokers(Map<ResourceUnit, String> namespaceBundlesToUnload) {
    for (Map.Entry<ResourceUnit, String> bundle : namespaceBundlesToUnload.entrySet()) {
        String brokerName = bundle.getKey().getResourceId();
        String bundleName = bundle.getValue();
        try {/*w w  w .  j  a  v  a 2 s . co  m*/
            if (unloadedHotNamespaceCache.getIfPresent(bundleName) == null) {
                if (!isUnloadDisabledInLoadShedding()) {
                    log.info("Unloading namespace {} from overloaded broker {}", bundleName, brokerName);
                    adminCache.get(brokerName).namespaces().unloadNamespaceBundle(
                            getNamespaceNameFromBundleName(bundleName),
                            getBundleRangeFromBundleName(bundleName));
                    log.info("Successfully unloaded namespace {} from broker {}", bundleName, brokerName);
                } else {
                    log.info("DRY RUN: Unload in Load Shedding is disabled. Namespace {} would have been "
                            + "unloaded from overloaded broker {} otherwise.", bundleName, brokerName);
                }
                unloadedHotNamespaceCache.put(bundleName, System.currentTimeMillis());
            } else {
                // we can't unload this namespace so move to next one
                log.info("Can't unload Namespace {} because it was unloaded last at {} and unload interval has "
                        + "not exceeded.", bundleName, LocalDateTime.now());
            }
        } catch (Exception e) {
            log.warn("ERROR failed to unload the bundle {} from overloaded broker {}", bundleName, brokerName,
                    e);
        }
    }
}

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

@Override
public void updateRating(String apiId, String ratingId, Rating rating) throws APIMgtDAOException {
    final String updateRatingQuery = "UPDATE AM_API_RATINGS SET RATING = ? , UPDATED_BY = ? , LAST_UPDATED_TIME = ?"
            + " WHERE API_ID = ? AND UUID = ?";
    try (Connection connection = DAOUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement(updateRatingQuery)) {
        try {/*from www  .  j  a va 2  s.  c om*/
            connection.setAutoCommit(false);
            statement.setInt(1, rating.getRating());
            statement.setString(2, rating.getUsername());
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, apiId);
            statement.setString(5, ratingId);
            statement.execute();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "Error while updating comment for api id: " + apiId + " and comment id: "
                    + rating.getUuid();
            log.error(errorMessage, e);
            throw new APIMgtDAOException(e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        log.error("Error while creating database connection/prepared-statement", e);
        throw new APIMgtDAOException(e);
    }

}

From source file:org.apache.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl.java

private void unloadNamespacesFromOverLoadedBrokers(Map<ResourceUnit, String> namespaceBundlesToUnload) {
    for (Map.Entry<ResourceUnit, String> bundle : namespaceBundlesToUnload.entrySet()) {
        String brokerName = bundle.getKey().getResourceId();
        String bundleName = bundle.getValue();
        try {//  w  w  w  .j a  v a2  s.  c o m
            if (unloadedHotNamespaceCache.getIfPresent(bundleName) == null) {
                if (!LoadManagerShared.isUnloadDisabledInLoadShedding(pulsar)) {
                    log.info("Unloading namespace {} from overloaded broker {}", bundleName, brokerName);
                    pulsar.getAdminClient().namespaces().unloadNamespaceBundle(
                            LoadManagerShared.getNamespaceNameFromBundleName(bundleName),
                            LoadManagerShared.getBundleRangeFromBundleName(bundleName));
                    log.info("Successfully unloaded namespace {} from broker {}", bundleName, brokerName);
                } else {
                    log.info("DRY RUN: Unload in Load Shedding is disabled. Namespace {} would have been "
                            + "unloaded from overloaded broker {} otherwise.", bundleName, brokerName);
                }
                unloadedHotNamespaceCache.put(bundleName, System.currentTimeMillis());
            } else {
                // we can't unload this namespace so move to next one
                log.info("Can't unload Namespace {} because it was unloaded last at {} and unload interval has "
                        + "not exceeded.", bundleName, LocalDateTime.now());
            }
        } catch (Exception e) {
            log.warn("ERROR failed to unload the bundle {} from overloaded broker {}", bundleName, brokerName,
                    e);
        }
    }
}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void changePassword() {

    Task<Void> task = new Task<Void>() {

        @Override//from   w  w w.jav  a 2  s  .co  m
        protected Void call() throws Exception {

            NewPasswordController npc = newPasswordControllerProvider.get();

            Platform.runLater(() -> {
                try {
                    npc.showAndWait();
                } catch (Exception exc) {
                    logger.error("error showing change password form", exc);
                }
            });

            synchronized (npc) {
                try {
                    npc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                } catch (InterruptedException exc) {
                    logger.error("change password operation interrupted", exc);
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("[CHANGE PASSWORD] npc={}", npc.getHashedPassword());
            }

            if (StringUtils.isNotEmpty(npc.getHashedPassword())) {

                activeConfiguration.setHashedPassword(npc.getHashedPassword());
                activeConfiguration.setUnhashedPassword(npc.getUnhashedPassword());
                activeConfiguration.setLastUpdatedDateTime(LocalDateTime.now());

                configurationDS.saveConfiguration();

                configurationDS.loadConfiguration();

            } else {

                Platform.runLater(() -> {
                    Alert noPassword = new Alert(Alert.AlertType.INFORMATION, "Password change cancelled.");
                    noPassword.showAndWait();
                });

            }

            return null;
        }
    };
    new Thread(task).start();
}

From source file:ffx.potential.ForceFieldEnergy.java

/**
 * {@inheritDoc}//from  w ww . j a va2s. c  om
 */
@Override
public double energyAndGradient(double x[], double g[], boolean verbose) {
    /**
     * Un-scale the coordinates.
     */
    if (optimizationScaling != null) {
        int len = x.length;
        for (int i = 0; i < len; i++) {
            x[i] /= optimizationScaling[i];
        }
    }
    setCoordinates(x);
    double e = energy(true, verbose);

    // Try block already exists inside energy(boolean, boolean), so only
    // need to try-catch getGradients.
    try {
        getGradients(g);
        /**
         * Scale the coordinates and gradients.
         */
        if (optimizationScaling != null) {
            int len = x.length;
            for (int i = 0; i < len; i++) {
                x[i] *= optimizationScaling[i];
                g[i] /= optimizationScaling[i];
            }
        }
        return e;
    } catch (EnergyException ex) {
        ex.printStackTrace();
        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()) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
        } else {
            ex.printStackTrace();
            throw ex; // Rethrow exception
        }

        return 0; // Should ordinarily be unreachable.
    }
}

From source file:org.kitodo.production.services.data.ProcessService.java

/**
 * Calculate and return duration/age of given process as a String.
 *
 * @param process ProcessDTO object for which duration/age is calculated
 * @return process age of given process/*  ww  w .  j  a  v a 2s.c o  m*/
 */
public static String getProcessDuration(ProcessDTO process) {
    String creationDateTimeString = process.getCreationDate();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime createLocalDate = LocalDateTime.parse(creationDateTimeString, formatter);
    Duration duration = Duration.between(createLocalDate, LocalDateTime.now());
    return String.format("%sd; %sh", duration.toDays(),
            duration.toHours() - TimeUnit.DAYS.toHours(duration.toDays()));
}

From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java

@Override
public void processComponentIntegration(String componentId, String integrationConfigId) {
    ComponentIntegration integrationExample = new ComponentIntegration();
    integrationExample.setActiveStatus(ComponentIntegration.ACTIVE_STATUS);
    integrationExample.setComponentId(componentId);
    ComponentIntegration integration = persistenceService.queryOneByExample(ComponentIntegration.class,
            integrationExample);//from www.ja v a2s.c  o  m
    if (integration != null) {

        boolean run = true;
        if (RunStatus.WORKING.equals(integration.getStatus())) {
            //check for override
            String overrideTime = PropertiesManager.getValue(PropertiesManager.KEY_JOB_WORKING_STATE_OVERRIDE,
                    "30");
            if (integration.getLastStartTime() != null) {
                LocalDateTime maxLocalDateTime = LocalDateTime
                        .ofInstant(integration.getLastStartTime().toInstant(), ZoneId.systemDefault());
                maxLocalDateTime.plusMinutes(Convert.toLong(overrideTime));
                if (maxLocalDateTime.compareTo(LocalDateTime.now()) <= 0) {
                    log.log(Level.FINE, "Overriding the working state...assume it was stuck.");
                    run = true;
                } else {
                    run = false;
                }
            } else {
                throw new OpenStorefrontRuntimeException("Missing Last Start time.  Data is corrupt.",
                        "Delete the job (Integration) and recreate it.", ErrorTypeCode.INTEGRATION);
            }
        }

        if (run) {
            Component component = persistenceService.findById(Component.class, integration.getComponentId());
            ComponentIntegration liveIntegration = persistenceService.findById(ComponentIntegration.class,
                    integration.getComponentId());

            log.log(Level.FINE, MessageFormat.format("Processing Integration for: {0}", component.getName()));

            liveIntegration.setStatus(RunStatus.WORKING);
            liveIntegration.setLastStartTime(TimeUtil.currentDate());
            liveIntegration.setUpdateDts(TimeUtil.currentDate());
            liveIntegration.setUpdateUser(OpenStorefrontConstant.SYSTEM_USER);
            persistenceService.persist(liveIntegration);

            ComponentIntegrationConfig integrationConfigExample = new ComponentIntegrationConfig();
            integrationConfigExample.setActiveStatus(ComponentIntegrationConfig.ACTIVE_STATUS);
            integrationConfigExample.setComponentId(componentId);
            integrationConfigExample.setIntegrationConfigId(integrationConfigId);

            List<ComponentIntegrationConfig> integrationConfigs = persistenceService
                    .queryByExample(ComponentIntegrationConfig.class, integrationConfigExample);
            boolean errorConfig = false;
            if (integrationConfigs.isEmpty() == false) {
                for (ComponentIntegrationConfig integrationConfig : integrationConfigs) {
                    ComponentIntegrationConfig liveConfig = persistenceService.findById(
                            ComponentIntegrationConfig.class, integrationConfig.getIntegrationConfigId());
                    try {
                        log.log(Level.FINE,
                                MessageFormat.format("Working on {1} Configuration for Integration for: {0}",
                                        component.getName(), integrationConfig.getIntegrationType()));

                        liveConfig.setStatus(RunStatus.WORKING);
                        liveConfig.setLastStartTime(TimeUtil.currentDate());
                        liveConfig.setUpdateDts(TimeUtil.currentDate());
                        liveConfig.setUpdateUser(OpenStorefrontConstant.SYSTEM_USER);
                        persistenceService.persist(liveConfig);

                        BaseIntegrationHandler baseIntegrationHandler = BaseIntegrationHandler
                                .getIntegrationHandler(integrationConfig);
                        if (baseIntegrationHandler != null) {
                            baseIntegrationHandler.processConfig();
                        } else {
                            throw new OpenStorefrontRuntimeException(
                                    "Intergration handler not supported for "
                                            + integrationConfig.getIntegrationType(),
                                    "Add handler", ErrorTypeCode.INTEGRATION);
                        }

                        liveConfig.setStatus(RunStatus.COMPLETE);
                        liveConfig.setLastEndTime(TimeUtil.currentDate());
                        liveConfig.setUpdateDts(TimeUtil.currentDate());
                        liveConfig.setUpdateUser(OpenStorefrontConstant.SYSTEM_USER);
                        persistenceService.persist(liveConfig);

                        log.log(Level.FINE,
                                MessageFormat.format("Completed {1} Configuration for Integration for: {0}",
                                        component.getName(), integrationConfig.getIntegrationType()));
                    } catch (Exception e) {
                        errorConfig = true;
                        //This is a critical loop
                        ErrorInfo errorInfo = new ErrorInfo(e, null);
                        SystemErrorModel errorModel = getSystemService().generateErrorTicket(errorInfo);

                        //put in fail state
                        liveConfig.setStatus(RunStatus.ERROR);
                        liveConfig.setErrorMessage(errorModel.getMessage());
                        liveConfig.setErrorTicketNumber(errorModel.getErrorTicketNumber());
                        liveConfig.setLastEndTime(TimeUtil.currentDate());
                        liveConfig.setUpdateDts(TimeUtil.currentDate());
                        liveConfig.setUpdateUser(OpenStorefrontConstant.SYSTEM_USER);
                        persistenceService.persist(liveConfig);

                        log.log(Level.FINE,
                                MessageFormat.format("Failed on {1} Configuration for Integration for: {0}",
                                        component.getName(), integrationConfig.getIntegrationType()),
                                e);
                    }
                }
            } else {
                log.log(Level.WARNING,
                        MessageFormat.format(
                                "No Active Integration configs for: {0} (Integration is doing nothing)",
                                component.getName()));
            }

            if (errorConfig) {
                liveIntegration.setStatus(RunStatus.ERROR);
            } else {
                liveIntegration.setStatus(RunStatus.COMPLETE);
            }
            liveIntegration.setLastEndTime(TimeUtil.currentDate());
            liveIntegration.setUpdateDts(TimeUtil.currentDate());
            liveIntegration.setUpdateUser(OpenStorefrontConstant.SYSTEM_USER);
            persistenceService.persist(liveIntegration);

            log.log(Level.FINE, MessageFormat.format("Completed Integration for: {0}", component.getName()));
        } else {
            log.log(Level.FINE, MessageFormat.format(
                    "Not time to run integration or the system is currently working on the integration. Component Id: {0}",
                    componentId));
        }
    } else {
        log.log(Level.WARNING, MessageFormat
                .format("There is no active integration for this component. Id: {0}", componentId));
    }
}