Example usage for java.time ZonedDateTime isBefore

List of usage examples for java.time ZonedDateTime isBefore

Introduction

In this page you can find the example usage for java.time ZonedDateTime isBefore.

Prototype

default boolean isBefore(ChronoZonedDateTime<?> other) 

Source Link

Document

Checks if the instant of this date-time is before that of the specified date-time.

Usage

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Intialize the database based on the passed in configuration object.
 * @param config//ww w .  j  a v  a2s.  c om
 */
public void initialize(DbConfig config) {
    try {
        dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass())
                .newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource
    // exceptions will make the driver hang while retrying, and will also bury the underlying cause

    try {
        Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance();
        Properties props = new Properties();
        props.setProperty("user", config.getUsername());
        props.setProperty("password", config.getPassword());
        try (Connection conn = driver.connect(config.getUrl(), props)) {
            Statement st = conn.createStatement();
            ResultSet results = st.executeQuery("SELECT 1 AS oneCol");
            results.next();
            Long i = results.getLong("oneCol");
            assert i == 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    /*
    try {
    try (Connection conn = cpds.getConnection()) {
        Statement st = conn.createStatement();
        ResultSet results = st.executeQuery("SELECT 1");
        Long i = results.getLong(0);
        assert i == 1L;
    }
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
            
    */
    try {
        cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }

    String url = config.getUrl();
    if (!url.contains("?")) {
        url += "?";
    }
    // Assume the database server is in UTC
    if (!url.contains("&useLegacyDatetimeCode=")) {
        url += "&useLegacyDatetimeCode=false";
    }
    if (!url.contains("&serverTimezone=")) {
        url += "&serverTimezone=UTC";
    }
    //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

    cpds.setJdbcUrl(url);
    cpds.setUser(config.getUsername());
    cpds.setPassword(config.getPassword());

    if (url.contains("utf8mb4_unicode_ci")) {
        cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer");
    }

    cpds.setAcquireRetryAttempts(10);
    cpds.setAcquireRetryDelay(200);
    //cpds.setCheckoutTimeout(1);
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    cpds.setIdleConnectionTestPeriod(5000);
    cpds.setTestConnectionOnCheckin(true);

    this.dataSource = cpds;

    // Make sure the database server time is UTC and in sync with the local server time
    // or else stop execution to prevent nasty and insiduious errors.
    //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    ZonedDateTime now = utcNow();
    ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC"));

    //LocalDateTime now = utcNow().toLocalDateTime();
    ZonedDateTime max = now.plusMinutes(2);
    ZonedDateTime min = now.minusMinutes(2);

    //LocalDateTime dbTime = date.toLocalDateTime();
    if (dbTime.isAfter(max) || dbTime.isBefore(min)) {
        throw new ConfigException(
                "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime
                        + ". Server time is " + now
                        + ". Make sure the database server is in UTC and that all your servers clocks are matched. ");
    }

    // Todo: why not lazy load converters???
    registerConverter(new JsonMapConverter());
    registerConverter(new JsonSetConverter());
    registerConverter(new JsonObjectConverter());
    registerConverter(new JsonListConverter());

    this.tickets = dbImplementation.initTicketsService(this);

}

From source file:no.digipost.api.useragreements.client.filters.response.ResponseDateInterceptor.java

private void sjekkAtDatoHeaderIkkeErForGammel(final String headerDate, final ZonedDateTime parsedDate,
        HttpResponse response) {/*w  w w  . j av  a2s . c o  m*/
    if (parsedDate.isBefore(now(clock).minusMinutes(AKSEPTABEL_TIDSDIFFERANSE_MINUTTER))) {
        throw new ServerSignatureException(response.getStatusLine(),
                "Date-header fra server er for gammel: " + headerDate);
    }
}

From source file:org.commonjava.indy.subsys.prefetch.PrefetchRepoComparator.java

@Override
public int compare(RemoteRepository r1, RemoteRepository r2) {
    if (r1 == null) {
        return 1;
    }//from w  w w  .j  a  v  a  2  s  . co  m
    if (r2 == null) {
        return -1;
    }

    final int priorityCompareResult = r2.getPrefetchPriority() - r1.getPrefetchPriority();
    if (StringUtils.isBlank(r1.getPrefetchRescanTimestamp())
            && StringUtils.isBlank(r2.getPrefetchRescanTimestamp())) {
        return priorityCompareResult;
    }

    if (StringUtils.isBlank(r1.getPrefetchRescanTimestamp())
            && StringUtils.isNotBlank(r2.getPrefetchRescanTimestamp())) {
        return -1;
    } else if (StringUtils.isBlank(r2.getPrefetchRescanTimestamp())
            && StringUtils.isNotBlank(r1.getPrefetchRescanTimestamp())) {
        return 1;
    }

    final ZonedDateTime rescanTime1 = ZonedDateTime.parse(r1.getPrefetchRescanTimestamp(),
            RescanTimeUtils.UTC_TIME_FORMATTER);
    final ZonedDateTime rescanTime2 = ZonedDateTime.parse(r2.getPrefetchRescanTimestamp(),
            RescanTimeUtils.UTC_TIME_FORMATTER);

    if (rescanTime1.isBefore(rescanTime2)) {
        return -1;
    } else if (rescanTime1.isAfter(rescanTime2)) {
        return 1;
    } else {
        return priorityCompareResult;
    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.handler.EchoHandler.java

public void updateNotifications(ZonedDateTime currentTime, ZonedDateTime now,
        @Nullable JsonCommandPayloadPushNotificationChange pushPayload,
        JsonNotificationResponse[] notifications) {
    Device device = this.device;
    if (device == null) {
        return;/*from  ww  w.j  av  a  2 s .  co m*/
    }

    ZonedDateTime nextReminder = null;
    ZonedDateTime nextAlarm = null;
    ZonedDateTime nextMusicAlarm = null;
    ZonedDateTime nextTimer = null;
    for (JsonNotificationResponse notification : notifications) {
        if (StringUtils.equals(notification.deviceSerialNumber, device.serialNumber)) {
            // notification for this device
            if (StringUtils.equals(notification.status, "ON")) {
                if ("Reminder".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextReminder == null || alarmTime.isBefore(nextReminder)) {
                        nextReminder = alarmTime;
                    }
                } else if ("Timer".equals(notification.type)) {
                    // use remaining time
                    ZonedDateTime alarmTime = currentTime.plus(notification.remainingTime, ChronoUnit.MILLIS);
                    if (nextTimer == null || alarmTime.isBefore(nextTimer)) {
                        nextTimer = alarmTime;
                    }
                } else if ("Alarm".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextAlarm == null || alarmTime.isBefore(nextAlarm)) {
                        nextAlarm = alarmTime;
                    }
                } else if ("MusicAlarm".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextMusicAlarm == null || alarmTime.isBefore(nextMusicAlarm)) {
                        nextMusicAlarm = alarmTime;
                    }
                }
            }
        }
    }

    updateState(CHANNEL_NEXT_REMINDER, nextReminder == null ? UnDefType.UNDEF : new DateTimeType(nextReminder));
    updateState(CHANNEL_NEXT_ALARM, nextAlarm == null ? UnDefType.UNDEF : new DateTimeType(nextAlarm));
    updateState(CHANNEL_NEXT_MUSIC_ALARM,
            nextMusicAlarm == null ? UnDefType.UNDEF : new DateTimeType(nextMusicAlarm));
    updateState(CHANNEL_NEXT_TIMER, nextTimer == null ? UnDefType.UNDEF : new DateTimeType(nextTimer));
}

From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Applies the given configuration to the given timestamp.
 *
 * @param dateTime timestamp represented as {@link ZonedDateTime}
 * @param config {@link DarkSkyChannelConfiguration} instance
 * @return the modified timestamp//from w ww  . j ava2  s. c o m
 */
private ZonedDateTime applyChannelConfig(ZonedDateTime dateTime, @Nullable DarkSkyChannelConfiguration config) {
    ZonedDateTime modifiedDateTime = dateTime;
    if (config != null) {
        if (config.getOffset() != 0) {
            if (logger.isTraceEnabled()) {
                logger.trace("Apply offset of {} min to timestamp '{}'.", config.getOffset(),
                        modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            modifiedDateTime = modifiedDateTime.plusMinutes(config.getOffset());
        }
        long earliestInMinutes = config.getEarliestInMinutes();
        if (earliestInMinutes > 0) {
            ZonedDateTime earliestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(earliestInMinutes);
            if (modifiedDateTime.isBefore(earliestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use earliest timestamp '{}' instead of '{}'.",
                            earliestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return earliestDateTime;
            }
        }
        long latestInMinutes = config.getLatestInMinutes();
        if (latestInMinutes > 0) {
            ZonedDateTime latestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(latestInMinutes);
            if (modifiedDateTime.isAfter(latestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use latest timestamp '{}' instead of '{}'.",
                            latestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return latestDateTime;
            }
        }
    }
    return modifiedDateTime;
}

From source file:sg.ncl.MainController.java

private List<String> getDates(String start, String end, DateTimeFormatter formatter) {
    List<String> dates = new ArrayList<>();
    ZonedDateTime currentZonedDateTime = convertToZonedDateTime(start);
    ZonedDateTime endZoneDateTime = convertToZonedDateTime(end);
    while (currentZonedDateTime.isBefore(endZoneDateTime)) {
        String date = currentZonedDateTime.format(formatter);
        dates.add(date);//from   w  ww.j  a  v a  2 s.c  om
        currentZonedDateTime = currentZonedDateTime.plusDays(1);
    }
    dates.add(currentZonedDateTime.format(formatter));
    return dates;
}