Example usage for java.time ZonedDateTime isAfter

List of usage examples for java.time ZonedDateTime isAfter

Introduction

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

Prototype

default boolean isAfter(ChronoZonedDateTime<?> other) 

Source Link

Document

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

Usage

From source file:com.match_tracker.twitter.TwitterSearch.java

protected ZonedDateTime calculatePostedTimeEnd(ZonedDateTime endTime) {
    ZonedDateTime postedTimeEnd = ZonedDateTime.now(ZoneOffset.UTC).minusSeconds(SEARCH_END_DELAY_SECONDS);
    if (postedTimeEnd.isAfter(endTime)) {
        postedTimeEnd = endTime;/*from   ww  w  .  jav  a 2 s.  c om*/
    }

    return postedTimeEnd;
}

From source file:nu.yona.server.analysis.service.AnalysisEngineService.java

private void assertValidTimes(UserAnonymizedDto userAnonymized, String application,
        ZonedDateTime correctedStartTime, ZonedDateTime correctedEndTime) {
    if (correctedEndTime.isBefore(correctedStartTime)) {
        throw AnalysisException.appActivityStartAfterEnd(userAnonymized.getId(), application,
                correctedStartTime, correctedEndTime);
    }/*from   w w  w .j av a 2  s  .  c o  m*/
    if (correctedStartTime.isAfter(ZonedDateTime.now().plus(DEVICE_TIME_INACCURACY_MARGIN))) {
        throw AnalysisException.appActivityStartsInFuture(userAnonymized.getId(), application,
                correctedStartTime);
    }
    if (correctedEndTime.isAfter(ZonedDateTime.now().plus(DEVICE_TIME_INACCURACY_MARGIN))) {
        throw AnalysisException.appActivityEndsInFuture(userAnonymized.getId(), application, correctedEndTime);
    }
}

From source file:io.werval.modules.jose.JwtPluginTest.java

@Test
public void http() throws InterruptedException {
    String tokenHeaderName = WERVAL.application().config().string(JWT.HTTP_HEADER_CONFIG_KEY);
    JWT jwt = WERVAL.application().plugin(JWT.class);

    // Unauthorized access to authenticated resource
    when().get("/authenticated").then().statusCode(UNAUTHORIZED_CODE);

    // Login//from www . jav a 2s. c  o  m
    String token = given().body("{\"email\":\"admin@example.com\",\"password\":\"admin-password\"}")
            .contentType(APPLICATION_JSON).when().post("/login").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Authenticated access
    given().header(tokenHeaderName, token).when().get("/authenticated").then().statusCode(OK_CODE);

    // Authorized access
    given().header(tokenHeaderName, token).when().get("/authorized").then().statusCode(OK_CODE);

    // Gather time related claims from token
    ZoneId utc = ZoneId.of("UTC");
    Map<String, Object> claims = jwt.claimsOfToken(token);
    ZonedDateTime iat = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)),
            utc);
    ZonedDateTime nbf = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)),
            utc);
    ZonedDateTime exp = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)),
            utc);

    // Wait at least one second before renewal so new dates will be different
    Thread.sleep(1200);

    // Renew token
    String renewed = given().header(tokenHeaderName, token).when().post("/renew").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Gather time related claims from renewed token
    claims = jwt.claimsOfToken(renewed);
    ZonedDateTime renewedIat = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)), utc);
    ZonedDateTime renewedNbf = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)), utc);
    ZonedDateTime renewedExp = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)), utc);

    // Assert renewed token time related claims are greater than the ones in the original token
    assertTrue(renewedIat.isAfter(iat));
    assertTrue(renewedNbf.isAfter(nbf));
    assertTrue(renewedExp.isAfter(exp));
}

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

/**
 * Intialize the database based on the passed in configuration object.
 * @param config//from  ww  w.  j  a  v  a2s. co  m
 */
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 sjekkAtDatoHeaderIkkeErForNy(final String headerDate, final ZonedDateTime parsedDate,
        HttpResponse response) {/*  w ww . j ava  2 s . co m*/
    if (parsedDate.isAfter(now(clock).plusMinutes(AKSEPTABEL_TIDSDIFFERANSE_MINUTTER))) {
        throw new ServerSignatureException(response.getStatusLine(),
                "Date-header fra server er for ny: " + headerDate);
    }
}

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

@Override
public int compare(RemoteRepository r1, RemoteRepository r2) {
    if (r1 == null) {
        return 1;
    }// w  w w .j a  va2 s. c o  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.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  w  w  .  j a va2 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:sorcer.file.ScratchDirManager.java

private boolean isCutoffTime(Path path, long cutOffTime) throws IOException {
    ZonedDateTime now = ZonedDateTime.now();
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    ZonedDateTime created = ZonedDateTime.ofInstant(attrs.creationTime().toInstant(), now.getZone());

    created = created.withYear(now.getYear()).withMonth(now.getMonthValue());

    ZonedDateTime cutoff = created.plus(cutOffTime, MILLIS);

    log.info("Created {}", created);
    log.info("now     {}", now);
    log.info("cutoff  {}", cutoff);

    return now.isAfter(cutoff);
}