Search in sources :

Example 26 with Instant

use of java.time.Instant in project spring-framework by spring-projects.

the class ResponseEntityResultHandlerTests method handleReturnValueLastModified.

@Test
public void handleReturnValueLastModified() throws Exception {
    Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
    Instant oneMinAgo = currentTime.minusSeconds(60);
    MockServerWebExchange exchange = get("/path").ifModifiedSince(currentTime.toEpochMilli()).toExchange();
    ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body");
    MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
    HandlerResult result = handlerResult(entity, returnType);
    this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
    assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
}
Also used : Instant(java.time.Instant) MockServerWebExchange(org.springframework.mock.http.server.reactive.test.MockServerWebExchange) HandlerResult(org.springframework.web.reactive.HandlerResult) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.Test)

Example 27 with Instant

use of java.time.Instant in project keywhiz by square.

the class ExpirationExtractor method expirationFromOpenPGP.

@Nullable
public static Instant expirationFromOpenPGP(byte[] content) {
    JcaPGPPublicKeyRingCollection collection;
    try {
        collection = new JcaPGPPublicKeyRingCollection(new ByteArrayInputStream(content));
    } catch (IOException | PGPException e) {
        // Unable to parse
        logger.info("Failed to parse OpenPGP keyring", e);
        return null;
    }
    Instant earliest = null;
    // Iterate over all key rings in file
    Iterator rings = collection.getKeyRings();
    while (rings.hasNext()) {
        Object ringItem = rings.next();
        if (ringItem instanceof PGPPublicKeyRing) {
            PGPPublicKeyRing ring = (PGPPublicKeyRing) ringItem;
            // Iterate over all keys in ring
            Iterator keys = ring.getPublicKeys();
            while (keys.hasNext()) {
                Object keyItem = keys.next();
                if (keyItem instanceof PGPPublicKey) {
                    PGPPublicKey key = (PGPPublicKey) keyItem;
                    // Get validity for key (zero means no expiry)
                    long validSeconds = key.getValidSeconds();
                    if (validSeconds > 0) {
                        Instant expiry = key.getCreationTime().toInstant().plusSeconds(validSeconds);
                        if (earliest == null || expiry.isBefore(earliest)) {
                            earliest = expiry;
                        }
                    }
                }
            }
        }
    }
    return earliest;
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) ByteArrayInputStream(java.io.ByteArrayInputStream) Instant(java.time.Instant) Iterator(java.util.Iterator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) PemObject(org.bouncycastle.util.io.pem.PemObject) IOException(java.io.IOException) JcaPGPPublicKeyRingCollection(org.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection) Nullable(javax.annotation.Nullable)

Example 28 with Instant

use of java.time.Instant in project keywhiz by square.

the class ExpirationExtractor method expirationFromEncodedCertificateChain.

@Nullable
public static Instant expirationFromEncodedCertificateChain(byte[] content) {
    PemReader reader = new PemReader(new InputStreamReader(new ByteArrayInputStream(content), UTF_8));
    PemObject object;
    try {
        object = reader.readPemObject();
    } catch (IOException e) {
        // Should never occur (reading form byte array)
        throw Throwables.propagate(e);
    }
    Instant earliest = null;
    while (object != null) {
        if (object.getType().equals("CERTIFICATE")) {
            Instant expiry = expirationFromRawCertificate(object.getContent());
            if (earliest == null || expiry.isBefore(earliest)) {
                earliest = expiry;
            }
        }
        try {
            object = reader.readPemObject();
        } catch (IOException e) {
            // Should never occur (reading form byte array)
            throw Throwables.propagate(e);
        }
    }
    return earliest;
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) Instant(java.time.Instant) IOException(java.io.IOException) Nullable(javax.annotation.Nullable)

Example 29 with Instant

use of java.time.Instant in project keywhiz by square.

the class ExpirationExtractor method expirationFromKeystore.

@Nullable
public static Instant expirationFromKeystore(String type, String password, byte[] content) {
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(type);
    } catch (KeyStoreException e) {
        // Should never occur (assuming JCE is installed)
        throw Throwables.propagate(e);
    }
    try {
        ks.load(new ByteArrayInputStream(content), password.toCharArray());
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        // Failed to parse
        logger.info("Failed to parse keystore", e);
        return null;
    }
    Instant earliest = null;
    try {
        for (String alias : list(ks.aliases())) {
            Certificate[] chain = ks.getCertificateChain(alias);
            if (chain == null) {
                Certificate certificate = ks.getCertificate(alias);
                if (certificate == null) {
                    // No certs in this entry
                    continue;
                }
                chain = new Certificate[] { certificate };
            }
            for (Certificate cert : chain) {
                if (cert instanceof X509Certificate) {
                    X509Certificate c = (X509Certificate) cert;
                    if (earliest == null || c.getNotAfter().toInstant().isBefore(earliest)) {
                        earliest = c.getNotAfter().toInstant();
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        // Should never occur (ks was initialized)
        throw Throwables.propagate(e);
    }
    return earliest;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Instant(java.time.Instant) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Nullable(javax.annotation.Nullable)

Example 30 with Instant

use of java.time.Instant in project keywhiz by square.

the class ClientDAO method sawClient.

public void sawClient(Client client) {
    Instant now = Instant.now();
    Instant lastSeen = Optional.ofNullable(client.getLastSeen()).map(ls -> Instant.ofEpochSecond(ls.toEpochSecond())).orElse(null);
    // this way we can have less granularity on lastSeen and save db writes
    if (lastSeen == null || now.isAfter(lastSeen.plus(lastSeenThreshold, SECONDS))) {
        dslContext.transaction(configuration -> {
            Param<Long> val = DSL.val(now.getEpochSecond(), CLIENTS.LASTSEEN);
            DSL.using(configuration).update(CLIENTS).set(CLIENTS.LASTSEEN, DSL.when(CLIENTS.LASTSEEN.isNull(), val).otherwise(DSL.greatest(CLIENTS.LASTSEEN, val))).where(CLIENTS.ID.eq(client.getId())).execute();
        });
    }
}
Also used : SECONDS(java.time.temporal.ChronoUnit.SECONDS) MEMBERSHIPS(keywhiz.jooq.tables.Memberships.MEMBERSHIPS) ImmutableSet(com.google.common.collect.ImmutableSet) DSL(org.jooq.impl.DSL) ClientsRecord(keywhiz.jooq.tables.records.ClientsRecord) ApiDate(keywhiz.api.ApiDate) Readonly(keywhiz.service.config.Readonly) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Instant(java.time.Instant) Inject(javax.inject.Inject) Param(org.jooq.Param) Configuration(org.jooq.Configuration) List(java.util.List) CLIENTS(keywhiz.jooq.tables.Clients.CLIENTS) OffsetDateTime(java.time.OffsetDateTime) ChronoUnit(java.time.temporal.ChronoUnit) Optional(java.util.Optional) DSLContext(org.jooq.DSLContext) Client(keywhiz.api.model.Client) Instant(java.time.Instant)

Aggregations

Instant (java.time.Instant)321 Test (org.testng.annotations.Test)136 Test (org.junit.Test)65 ZonedDateTime (java.time.ZonedDateTime)36 Clock (java.time.Clock)26 OffsetDateTime (java.time.OffsetDateTime)23 LocalDateTime (java.time.LocalDateTime)18 Duration (java.time.Duration)17 LocalDate (java.time.LocalDate)15 IOException (java.io.IOException)11 LocalTime (java.time.LocalTime)11 DateTimeFormatter (java.time.format.DateTimeFormatter)11 Date (java.util.Date)11 Timestamp (java.sql.Timestamp)10 DateTimeFormatterBuilder (java.time.format.DateTimeFormatterBuilder)8 ZoneRules (java.time.zone.ZoneRules)8 MockServerWebExchange (org.springframework.mock.http.server.reactive.test.MockServerWebExchange)8 JsonArray (io.vertx.core.json.JsonArray)7 JsonObject (io.vertx.core.json.JsonObject)7 OffsetTime (java.time.OffsetTime)7