Java Code Examples for java.time.Instant#plusSeconds()

The following examples show how to use java.time.Instant#plusSeconds() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   File: SecurityTokenTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testLifetimeNoCreated() throws Exception {
    String key = "key";
    Element tokenElement = DOMUtils.createDocument().createElement("token");

    // Create Lifetime
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    Instant created = Instant.now().truncatedTo(ChronoUnit.MILLIS);
    Instant expires = created.plusSeconds(20L);

    writer.writeStartElement("wst", "Lifetime", WST_NS_05_12);

    writer.writeStartElement("wsu", "Expires", WSU_NS);
    writer.writeCharacters(expires.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();
    writer.writeEndElement();

    SecurityToken token = new SecurityToken(key, tokenElement, writer.getDocument().getDocumentElement());
    assertEquals(key, token.getId());
    // It should default to the current time
    assertNotNull(token.getCreated());
    assertEquals(expires, token.getExpires());
}
 
Example 2
Source Project: cxf   File: JwtUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void validateJwtExpiry(JwtClaims claims, int clockOffset, boolean claimRequired) {
    Long expiryTime = claims.getExpiryTime();
    if (expiryTime == null) {
        if (claimRequired) {
            throw new JwtException("The token has expired");
        }
        return;
    }
    Instant now = Instant.now();
    Instant expires = Instant.ofEpochMilli(expiryTime * 1000L);
    if (clockOffset != 0) {
        expires = expires.plusSeconds(clockOffset);
    }
    if (expires.isBefore(now)) {
        throw new JwtException("The token has expired");
    }
}
 
Example 3
Source Project: cxf   File: SecurityTokenTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testParseLifetimeElement() throws Exception {
    String key = "key";
    Element tokenElement = DOMUtils.createDocument().createElement("token");

    // Create Lifetime
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    Instant created = Instant.now().truncatedTo(ChronoUnit.MILLIS);
    Instant expires = created.plusSeconds(20L);

    writer.writeStartElement("wst", "Lifetime", WST_NS_05_12);
    writer.writeStartElement("wsu", "Created", WSU_NS);
    writer.writeCharacters(created.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();

    writer.writeStartElement("wsu", "Expires", WSU_NS);
    writer.writeCharacters(expires.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();
    writer.writeEndElement();

    SecurityToken token = new SecurityToken(key, tokenElement, writer.getDocument().getDocumentElement());
    assertEquals(key, token.getId());
    assertEquals(created, token.getCreated());
    assertEquals(expires, token.getExpires());
}
 
Example 4
Source Project: trellis   File: GetHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testLimitMementoHeaders() {
    final Instant time1 = now();
    final Instant time2 = time1.plusSeconds(10L);
    final Instant time3 = time1.plusSeconds(20L);
    final Instant time4 = time1.plusSeconds(30L);
    final Instant time5 = time1.plusSeconds(40L);
    final SortedSet<Instant> mementos = new TreeSet<>();
    mementos.add(time1);
    mementos.add(time2);
    mementos.add(time3);
    mementos.add(time4);
    mementos.add(time5);
    final GetConfiguration config = new GetConfiguration(false, true, false, null, baseUrl);
    final GetHandler handler = new GetHandler(mockTrellisRequest, mockBundler, extensions, config);
    try (final Response res = handler.addMementoHeaders(handler.standardHeaders(handler.initialize(mockResource)),
            mementos).build()) {
        assertAll("Check MementoHeaders",
                checkMementoLinks(res.getStringHeaders().get(LINK).stream().map(Link::valueOf).collect(toList())));
    }
}
 
Example 5
Source Project: staffjoy   File: ServiceHelperTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testIsAlmostSameInstant() {
    Instant now = Instant.now();
    Instant twoSecondsLater = now.plusSeconds(2);
    assertThat(serviceHelper.isAlmostSameInstant(now, twoSecondsLater)).isFalse();

    Instant oneSecondLater = now.plusSeconds(1);
    assertThat(serviceHelper.isAlmostSameInstant(now, oneSecondLater)).isFalse();

    Instant haveSecondLater = now.plus(500000, ChronoUnit.MICROS);
    assertThat(serviceHelper.isAlmostSameInstant(now, haveSecondLater)).isTrue();
}
 
Example 6
Source Project: cxf   File: SecurityTokenTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateSecurityToken() throws Exception {
    String key = "key";
    Instant created = Instant.now().truncatedTo(ChronoUnit.MILLIS);
    Instant expires = created.plusSeconds(20L);

    SecurityToken token = new SecurityToken(key, created, expires);
    assertEquals(key, token.getId());
    assertEquals(created, token.getCreated());
    assertEquals(expires, token.getExpires());
}
 
Example 7
public static Instant messageQueryDateStringToInstant(String date, Instant referenceInstant) {
    Instant refDate;
    try {
        refDate = Instant.parse(date);
    } catch (DateTimeException dtex) {
        refDate = referenceInstant.plusSeconds(Long.parseLong(date));
    }

    return refDate;
}
 
Example 8
Source Project: cxf   File: JWTProviderLifetimeTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with a with a lifetime
 * which exceeds configured maximum lifetime
 * Lifetime reduced to maximum lifetime
 */
@org.junit.Test
public void testJWTExceededConfiguredMaxLifetimeButUpdated() throws Exception {

    long maxLifetime = 30 * 60L;  // 30 minutes
    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setMaxLifetime(maxLifetime);
    claimsProvider.setFailLifetimeExceedance(false);
    claimsProvider.setAcceptClientLifetime(true);
    tokenProvider.setJwtClaimsProvider(claimsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE);

    // Set expected lifetime to 35 minutes
    Instant creationTime = Instant.now();
    long requestedLifetime = 35 * 60L;
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(maxLifetime, duration);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT), providerResponse.getCreated().getEpochSecond());
}
 
Example 9
@Test(dataProvider="PlusSeconds")
public void plusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.ofEpochSecond(seconds, nanos);
    t = t.plusSeconds(amount);
    assertEquals(t.getEpochSecond(), expectedSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 10
Source Project: jdk8u60   File: TCKInstant.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="PlusSeconds")
public void plusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.ofEpochSecond(seconds, nanos);
    t = t.plusSeconds(amount);
    assertEquals(t.getEpochSecond(), expectedSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 11
Source Project: cxf   File: SimpleBatchSTSClient.java    License: Apache License 2.0 5 votes vote down vote up
protected void addLifetime(XMLStreamWriter writer) throws XMLStreamException {
    Instant creationTime = Instant.now();
    Instant expirationTime = creationTime.plusSeconds(ttl);

    writer.writeStartElement("wst", "Lifetime", namespace);
    writer.writeNamespace("wsu", WSS4JConstants.WSU_NS);
    writer.writeStartElement("wsu", "Created", WSS4JConstants.WSU_NS);
    writer.writeCharacters(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();

    writer.writeStartElement("wsu", "Expires", WSS4JConstants.WSU_NS);
    writer.writeCharacters(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();
    writer.writeEndElement();
}
 
Example 12
Source Project: cxf   File: JwtUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void validateJwtIssuedAt(JwtClaims claims, int timeToLive, int clockOffset, boolean claimRequired) {
    Long issuedAtInSecs = claims.getIssuedAt();
    if (issuedAtInSecs == null) {
        if (claimRequired) {
            throw new JwtException("Invalid issuedAt");
        }
        return;
    }

    Instant createdDate = Instant.ofEpochMilli(issuedAtInSecs * 1000L);

    Instant validCreation = Instant.now();
    if (clockOffset != 0) {
        validCreation = validCreation.plusSeconds(clockOffset);
    }

    // Check to see if the IssuedAt time is in the future
    if (createdDate.isAfter(validCreation)) {
        throw new JwtException("Invalid issuedAt");
    }

    if (timeToLive > 0) {
        // Calculate the time that is allowed for the message to travel
        validCreation = validCreation.minusSeconds(timeToLive);

        // Validate the time it took the message to travel
        if (createdDate.isBefore(validCreation)) {
            throw new JwtException("Invalid issuedAt");
        }
    }
}
 
Example 13
Source Project: cxf   File: JWTProviderLifetimeTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with a valid requested lifetime
 */
@org.junit.Test
public void testJWTValidLifetime() throws Exception {

    int requestedLifetime = 60;
    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setAcceptClientLifetime(true);
    tokenProvider.setJwtClaimsProvider(claimsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE);

    // Set expected lifetime to 1 minute
    Instant creationTime = Instant.now();
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(requestedLifetime, duration);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT), providerResponse.getCreated().getEpochSecond());
}
 
Example 14
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooBig() {
    Instant t = Instant.ofEpochSecond(1, 0);
    t.plusSeconds(Long.MAX_VALUE);
}
 
Example 15
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooSmall() {
    Instant t = Instant.ofEpochSecond(-1, 0);
    t.plusSeconds(Long.MIN_VALUE);
}
 
Example 16
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooSmall() {
    Instant t = Instant.ofEpochSecond(-1, 0);
    t.plusSeconds(Long.MIN_VALUE);
}
 
Example 17
Source Project: jdk8u60   File: TCKInstant.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooBig() {
    Instant t = Instant.ofEpochSecond(1, 0);
    t.plusSeconds(Long.MAX_VALUE);
}
 
Example 18
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooBig() {
    Instant t = Instant.ofEpochSecond(1, 0);
    t.plusSeconds(Long.MAX_VALUE);
}
 
Example 19
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooBig() {
    Instant t = Instant.ofEpochSecond(1, 0);
    t.plusSeconds(Long.MAX_VALUE);
}
 
Example 20
@Test(expectedExceptions=ArithmeticException.class)
public void plusSeconds_long_overflowTooBig() {
    Instant t = Instant.ofEpochSecond(1, 0);
    t.plusSeconds(Long.MAX_VALUE);
}