Example usage for java.time Instant now

List of usage examples for java.time Instant now

Introduction

In this page you can find the example usage for java.time Instant now.

Prototype

public static Instant now() 

Source Link

Document

Obtains the current instant from the system clock.

Usage

From source file:com.amazonaws.sample.entitlement.authorization.CognitoIdentityAuthorizationHandler.java

/**
 * @param authorization//from w w  w.j a  va  2s  .  co m
 *     An authorization string. The first part of the string must match one of the keys in AUTHORIZATION_TYPES
 *     The remainder of the string must be an OAuth2 or OpenId access token.
 * @return an Identity containing the IdentityID from Amazon Cognito, and email, and name from the third-party
 * @throws AuthorizationException
 */
@Override
public Identity processAuthorization(String authorization) throws AuthorizationException {
    String authorizationType;
    Identity thirdPartyIdentity;
    String trimmedAuthorization = authorization.trim();
    try {
        String[] splitString = trimmedAuthorization.split("\\s");
        authorizationType = splitString[0];
    } catch (Exception e) {
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    if (!AUTHORIZATION_TYPES.containsKey(authorizationType)) {
        throw new AuthorizationException("Don't know how to handle authorization type: " + authorizationType);
    }
    Util.checkAuthorizationString(authorizationType, authorization);
    // Verify that the access token is valid and belongs to us.
    // If the access token can be verified and also profile information can be retrieved with one call to the oauth2
    // provider then return an Identity object here, otherwise return null and a separate call will be made
    // in getIdentity to retrieve the profile information and create an Identity object.
    switch (authorizationType) {
    case "FacebookOAuth2":
        thirdPartyIdentity = facebookAuthorizationHandler.processAuthorization(authorization);
        log.info("Email from Facebook: " + thirdPartyIdentity.getEmail());
        break;
    case "GoogleOAuth2":
        thirdPartyIdentity = googleAuthorizationHandler.processAuthorization(authorization);
        break;
    case "AmazonOAuth2":
        thirdPartyIdentity = loginWithAmazonAuthorizationHandler.processAuthorization(authorization);
        log.info("Email from Amazon: " + thirdPartyIdentity.getEmail());
        break;
    default:
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    try {
        Instant fifteenMinutesFromNow = Instant.now().plus(15, ChronoUnit.MINUTES);
        String base64EncEmail = Base64.getEncoder().withoutPadding()
                .encodeToString(thirdPartyIdentity.getEmail().getBytes("utf-8"));
        GetOpenIdTokenForDeveloperIdentityRequest req = new GetOpenIdTokenForDeveloperIdentityRequest();
        req.setIdentityPoolId(awsCognitoIdentityPool);
        req.addLoginsEntry(awsCognitoDeveloperProviderName, base64EncEmail);
        GetOpenIdTokenForDeveloperIdentityResult res = cognitoIdentityClient
                .getOpenIdTokenForDeveloperIdentity(req);
        thirdPartyIdentity.setId(res.getIdentityId());
        thirdPartyIdentity.setToken(res.getToken());
        thirdPartyIdentity.setExpires(fifteenMinutesFromNow.toEpochMilli());
    } catch (UnsupportedEncodingException e) {
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    return thirdPartyIdentity;
}

From source file:com.arrow.acs.client.api.ApiAbstract.java

private HttpRequestBase sign(HttpRequestBase request) {
    String method = "sign";
    Instant timestamp = Instant.now();
    String signature = getSigner(request, timestamp).signV1();
    logDebug(method, SIGNATURE_MSG, signature);
    addHeaders(request, timestamp, signature);
    return request;
}

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Run the reader. Reader implements runnable, so that we can
 * do this in its own thread.// w  ww.  java2 s.c o m
 */
@Override
public void run() {
    LOG.info("Spinning up reader!");
    ReaderConfig.Type type = Config.getCurrentConfig().getReader(options.getId()).getType();
    if (type == ReaderConfig.Type.LLRP) {
        initSpeedway();
        if (!speedwayInitialized) {
            shutdownHook();
            return;
        }
    } else if (type == ReaderConfig.Type.SIMULATOR) {
        initSimulator();
    }
    Thread commandThread = new Thread(commandProcessor);
    commandThread.start();
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTED_UP,
            String.format("Started up reader %s!", options.getId())));
    try {
        while (!Thread.currentThread().isInterrupted()) {
            Duration maxUpdateInterval = Duration.ofMillis(Config.getCurrentConfig().getMaxUpdateInterval());
            if (maxUpdateInterval.minus(Duration.between(lastUpdate, Instant.now())).isNegative()) {
                lastUpdate = Instant.now();
                LOG.warn("No update received in {} seconds!", maxUpdateInterval.getSeconds());
                statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NO_UPDATES,
                        String.format("No update received in %s seconds!", maxUpdateInterval.getSeconds())));
            }
            Thread.sleep(1000L);
        }
    } catch (InterruptedException e) {
        // We don't care about this exception
    }
    commandProcessor.stop();
    commandThread.interrupt();
    try {
        commandThread.join();
    } catch (InterruptedException ignored) {
    }
    shutdownHook();
}

From source file:dk.nversion.jwt.JWTTest.java

/**
 * Test of JWT construction and validation speed
 *///from  w ww .j a va2s.  co  m
@Test
public void testJWTDecodePublicKeySpeed() {
    try {
        int i;
        System.out.println("decode speed");

        // Load private key
        String privatekeyfile = getClass().getClassLoader().getResource("example.org.pem").getFile();
        PrivateKey privkey = loadPrivateKey(privatekeyfile);
        JWT token = new JWT(Algorithm.RS256, privkey);

        long unixtime = Instant.now().getEpochSecond();

        token.setId("1"); // TODO generate random number
        token.setIssuer("http://localhost/oauth/");
        token.setAudience("http://localhost/service");
        token.setIssuedAt(unixtime);
        token.setNotBefore(unixtime - 5 * 60); // 5 minutes before issued at
        token.setExpires(unixtime + 10 * 60); // 10 minutes after issued at            
        token.setSubject("tlb@nversion.dk");

        String result = token.encode();

        String certificatefile = getClass().getClassLoader().getResource("example.org.crt").getFile();
        PublicKey pubkey = loadCertificate(certificatefile);

        // Warmup
        for (i = 0; i < 1000; i++) {
            JWT token2 = new JWT(result, pubkey, "http://localhost/service");
        }

        long startTime = System.currentTimeMillis();
        for (i = 0; i < 10000; i++) {
            JWT token2 = new JWT(result, pubkey, "http://localhost/service");
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out
                .println("time taken for pubkey: " + totalTime + " ms, " + (i / (totalTime / 1000.0)) + " i/s");

    } catch (JWTException | IOException | InvalidKeyException | NoSuchAlgorithmException ex) {
        fail("Failed with exception");
    } catch (SignatureException | InvalidKeySpecException | CertificateException ex) {
        Logger.getLogger(JWTTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.gameontext.map.auth.PlayerClient.java

/**
 * Obtain a JWT for the player id that can be used to invoke player REST services.
 *
 * We can create this, because we have access to the private certificate
 * required to sign such a JWT.// w ww .  j  av a  2 s. c om
 *
 * @param playerId The id to build the JWT for
 * @return The JWT as a string.
 * @throws IOException
 */
private String buildClientJwtForId(String playerId) throws IOException {
    // grab the key if needed
    if (signingKey == null)
        getKeyStoreInfo();

    Claims onwardsClaims = Jwts.claims();

    // Set the subject using the "id" field from our claims map.
    onwardsClaims.setSubject(playerId);

    // We'll use this claim to know this is a user token
    onwardsClaims.setAudience("client");

    // we set creation time to 24hrs ago, to avoid timezone issues
    // client JWT has 24 hrs validity from now.
    Instant timePoint = Instant.now();
    onwardsClaims.setIssuedAt(Date.from(timePoint.minus(hours24)));
    onwardsClaims.setExpiration(Date.from(timePoint.plus(hours24)));

    // finally build the new jwt, using the claims we just built, signing it
    // with our signing key, and adding a key hint as kid to the encryption
    // header, which is optional, but can be used by the receivers of the
    // jwt to know which key they should verifiy it with.
    String newJwt = Jwts.builder().setHeaderParam("kid", "playerssl").setClaims(onwardsClaims)
            .signWith(SignatureAlgorithm.RS256, signingKey).compact();

    return newJwt;
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

private Instant buildReachableFutureDate() {
    return Instant.now().plusSeconds(REACHABLE_FUTURE_SECONDS);
}

From source file:tech.beshu.ror.utils.containers.ESWithReadonlyRestContainer.java

private WaitStrategy waitStrategy(Optional<ESWithReadonlyRestContainer.ESInitalizer> initalizer) {
    final ObjectMapper mapper = new ObjectMapper();
    return new GenericContainer.AbstractWaitStrategy() {
        @Override/*from  w  w  w. j a v  a2 s  .  c o m*/
        protected void waitUntilReady() {
            logger.info("Waiting for ES container ...");
            final RestClient client = getAdminClient();
            final Instant startTime = Instant.now();
            while (!isReady(client) && !checkTimeout(startTime, startupTimeout)) {
                try {
                    Thread.sleep(WAIT_BETWEEN_RETRIES.toMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            initalizer.ifPresent(i -> i.initialize(client));
            logger.info("ES container stated");
        }

        private boolean isReady(RestClient client) {
            try {
                HttpResponse result = client.execute(new HttpGet(client.from("_cluster/health")));
                if (result.getStatusLine().getStatusCode() != 200)
                    return false;
                Map<String, String> healthJson = mapper.readValue(result.getEntity().getContent(),
                        new TypeReference<Map<String, String>>() {
                        });
                return "green".equals(healthJson.get("status"));
            } catch (IOException | URISyntaxException e) {
                return false;
            }
        }
    };
}

From source file:org.noorganization.instalist.server.api.ListResourceTest.java

@Test
public void testGetLists() throws Exception {
    String url = "/groups/%d/lists";

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request().get();
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").get();
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(401, wrongGroupResponse.getStatus());

    Response okResponse1 = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse1.getStatus());
    ListInfo[] allListInfo = okResponse1.readEntity(ListInfo[].class);
    assertEquals(3, allListInfo.length);
    for (ListInfo current : allListInfo) {
        if (mListWC.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals("list1", current.getName());
            assertEquals(mCat.getUUID(), UUID.fromString(current.getCategoryUUID()));
            assertNotNull(current.getLastChanged());
            assertFalse(current.getDeleted());
        } else if (mListWOC.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals("list2", current.getName());
            assertNull(current.getCategoryUUID());
            assertNotNull(current.getLastChanged());
            assertFalse(current.getDeleted());
        } else if (mDeletedList.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertNull(current.getName());
            assertNull(current.getCategoryUUID());
            assertNotNull(current.getLastChanged());
            assertTrue(current.getDeleted());
        } else/*from  w  w w  .ja  v  a2  s . c  om*/
            fail("Unexpected list.");
    }

    Thread.sleep(1000);
    mManager.getTransaction().begin();
    Instant current = Instant.now();
    System.err.println("Current: " + current);
    mListWC.setUpdated(current);
    mManager.getTransaction().commit();
    Response okResponse2 = target(String.format(url, mGroup.getId()))
            .queryParam("changedsince", ISO8601Utils.format(new Date(current.toEpochMilli() - 500), true))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse2.getStatus());
    ListInfo[] oneListInfo = okResponse2.readEntity(ListInfo[].class);
    assertEquals(1, oneListInfo.length);
    assertEquals(mListWC.getUUID(), UUID.fromString(oneListInfo[0].getUUID()));
    assertEquals("list1", oneListInfo[0].getName());
    assertEquals(mCat.getUUID(), UUID.fromString(oneListInfo[0].getCategoryUUID()));
    assertFalse(oneListInfo[0].getDeleted());
}

From source file:eu.hansolo.tilesfx.tools.Location.java

public void set(final double LATITUDE, final double LONGITUDE) {
    latitude = LATITUDE;//from w  ww .ja  va 2s .com
    longitude = LONGITUDE;
    timestamp = Instant.now();
    fireLocationEvent(new LocationEvent(Location.this));
}

From source file:com.orange.cepheus.broker.LocalRegistrations.java

/**
 * Removed expired registrations every min
 *///  w  ww.  j  a  v  a2s . c  o  m
@Scheduled(fixedDelay = 60000)
public void purgeExpiredContextRegistrations() {
    final Instant now = Instant.now();
    registrations.forEach((registrationId, registration) -> {
        if (registration.getExpirationDate().isBefore(now)) {
            registrations.remove(registrationId);
            remoteRegistrations.removeRegistration(registrationId);
            try {
                registrationsRepository.removeRegistration(registrationId);
            } catch (RegistrationPersistenceException e) {
                logger.error("Failed to remove registration from database", e);
            }
        }
    });
}