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:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

void handleEchoRequest(final Message<String> request) {
    log.info("*** RECIEVED MESSAGE : " + request.body());
    MessageHeader.getReplyToAddress(request).ifPresent(replyTo -> {
        vertx.eventBus().send(replyTo,/*from  w  w  w. j a v a2  s . com*/
                String.format("%s: RECEIVED MESSAGE: %s", Instant.now(), request.body()));
    });
}

From source file:cloudfoundry.norouter.f5.Agent.java

private void updatePoolModifiedTimestamp(String poolName) {
    final Pool pool = client.getPool(poolName);
    final PoolDescription description = PoolDescription.fromJsonish(pool.getDescription())
            .orElse(new PoolDescription());
    description.setModified(Instant.now());
    client.updatePoolDescription(poolName, description.toJsonish());
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedURIWithEncodedCharacters() throws IOException {
    final String path = testPathPrefix + " quack ";

    mantaClient.put(path, TEST_DATA, UTF_8);
    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    final URI uri = mantaClient.getAsSignedURI(path, "GET", Instant.now().plus(Duration.ofHours(1)));
    final HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();

    try (final InputStream is = conn.getInputStream()) {
        conn.setReadTimeout(3000);//  w w  w . java 2s  . c o  m
        conn.connect();

        Assert.assertEquals(conn.getResponseCode(), HttpStatus.SC_OK);
        Assert.assertEquals(IOUtils.toString(is, UTF_8), TEST_DATA);
    } finally {
        conn.disconnect();
    }
}

From source file:com.netflix.genie.web.rpc.grpc.services.impl.v4.GRpcAgentFileStreamServiceImpl.java

/**
 * {@inheritDoc}/*from  w w w .j av  a  2 s.com*/
 */
@Override
public Optional<AgentFileResource> getResource(final String jobId, final Path relativePath, final URI uri) {

    final ControlStreamObserver streamObserver = this.jobIdControlStreamMap.get(jobId);
    if (streamObserver == null) {
        log.warn("Stream Record not found for job id: {}", jobId);
        return Optional.empty();
    }

    final JobDirectoryManifest manifest = streamObserver.manifestRef.get();
    if (manifest == null) {
        log.warn("Stream record for job id: {} does not have a manifest", jobId);
        return Optional.empty();
    }

    final JobDirectoryManifest.ManifestEntry manifestEntry = manifest.getEntry(relativePath.toString())
            .orElse(null);

    if (manifestEntry == null) {
        // File does not exist according to manifest
        log.warn("Requesting a file that does not exist in the manifest for job id: {}: ", jobId, relativePath);
        return Optional.of(AgentFileResourceImpl.forNonExistingResource());
    }

    // A unique ID for this file transfer
    final String fileTransferId = UUID.randomUUID().toString();

    // TODO: code upstream of here assumes files is requested in its entirety.
    // But rest of the code downstream actually treats everything as a range request.
    final int startOffset = 0;
    final int endOffset = Math.toIntExact(manifestEntry.getSize());

    // Allocate and park the buffer that will store the data in transit.
    final StreamBuffer buffer = new StreamBuffer();

    if (endOffset - startOffset == 0) {
        // When requesting an empty file (or a range of 0 bytes), short-circuit and just return an empty resource.
        buffer.closeForCompleted();
    } else {
        // Expecting some data. Track this stream and its buffer so incoming chunks can be appended.
        this.pendingTransferBuffersMap.put(fileTransferId, buffer);

        // Request file over control channel
        streamObserver.responseObserver.onNext(ServerControlMessage.newBuilder()
                .setServerFileRequest(ServerFileRequestMessage.newBuilder().setStreamId(fileTransferId)
                        .setRelativePath(relativePath.toString()).setStartOffset(startOffset)
                        .setEndOffset(endOffset).build())
                .build());

        // Schedule a timeout for this transfer to start (first chunk received)
        this.taskScheduler.schedule(() -> {
            final StreamBuffer b = pendingTransferBuffersMap.remove(fileTransferId);
            // Is this stream/buffer still in the 'pending' map?
            if (b != null) {
                b.closeForError(new TimeoutException("Timeout waiting for transfer to start"));
            }
        }, Instant.now().plusMillis(FILE_TRANSFER_BEGIN_TIMEOUT_MILLIS));
    }

    final AgentFileResource resource = AgentFileResourceImpl.forAgentFile(uri, manifestEntry.getSize(),
            manifestEntry.getLastModifiedTime(), Paths.get(manifestEntry.getPath()), jobId,
            buffer.getInputStream());

    return Optional.of(resource);
}

From source file:ai.susi.server.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {/*from w  w  w .  j av a2  s.c  o  m*/
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

private boolean isProvProfileExpired() throws IOSAppException {
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    Instant dateTime = Instant.from(formatter.parse(provProfile.getExpiration()));
    return dateTime.compareTo(Instant.now()) < 0;
}

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

/**
 * Updates the tag./*from  w ww.  j av  a 2  s .  c om*/
 * @param _groupId The id of the group containing the tag to change.
 * @param _tagUUID The uuid of the tag identifying it in the group.
 * @param _entity Data to change.
 */
@PUT
@TokenSecured
@Path("{taguuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putTag(@PathParam("groupid") int _groupId, @PathParam("taguuid") String _tagUUID,
        TagInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_tagUUID))
            || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    try {
        toUpdate = UUID.fromString(_tagUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITagController tagController = ControllerFactory.getTagController(manager);
    try {
        tagController.update(_groupId, toUpdate, _entity.getName(), updated);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The tag was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The tag has been " + "deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("The sent data would " + "conflict with saved tag."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

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

/**
 * Updates the unit.//from  w  w w  . j  a  v a 2  s  .c  o m
 * @param _groupId The id of the group containing the unit.
 * @param _unitUUID The existing Unit-UUID to update.
 * @param _entity The data for update.
 */
@PUT
@TokenSecured
@Path("{unituuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putUnit(@PathParam("groupid") int _groupId, @PathParam("unituuid") String _unitUUID,
        UnitInfo _entity) throws Exception {
    UUID toUpdate;
    try {
        toUpdate = UUID.fromString(_unitUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant changeDate;
    if (_entity.getLastChanged() == null)
        changeDate = Instant.now();
    else {
        changeDate = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(changeDate))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }
    if ((_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getUUID() != null && !_entity.getUUID().equals(_unitUUID)))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IUnitController unitController = ControllerFactory.getUnitController(manager);
    try {
        unitController.update(_groupId, toUpdate, _entity.getName(), changeDate);
    } catch (NotFoundException _e) {
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The unit to change " + "was not found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(
                new Error().withMessage("The unit to change was " + "not found since it has been deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "lead to a conflict with saved unit."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:sx.blah.discord.handle.impl.obj.Channel.java

@Override
public MessageHistory getMessageHistory(int messageCount) {
    if (messageCount <= messages.size()) { // we already have all of the wanted messages in the cache
        return new MessageHistory(messages.values().stream().sorted(new MessageComparator(true))
                .limit(messageCount).collect(Collectors.toList()));
    } else {//from  w w  w  .j a va  2 s  .  com
        List<IMessage> retrieved = new ArrayList<>(messageCount);
        AtomicLong lastMessage = new AtomicLong(DiscordUtils.getSnowflakeFromTimestamp(Instant.now()));
        int chunkSize = messageCount < MESSAGE_CHUNK_COUNT ? messageCount : MESSAGE_CHUNK_COUNT;

        while (retrieved.size() < messageCount) { // while we dont have messageCount messages
            IMessage[] chunk = getHistory(lastMessage.get(), chunkSize);

            if (chunk.length == 0)
                break;

            lastMessage.set(chunk[chunk.length - 1].getLongID());
            Collections.addAll(retrieved, chunk);
        }

        return new MessageHistory(
                retrieved.size() > messageCount ? retrieved.subList(0, messageCount) : retrieved);
    }
}

From source file:net.beaconpe.jraklib.server.Session.java

public void sendQueue() throws IOException {
    if (!sendQueue.packets.isEmpty()) {
        sendQueue.seqNumber = sendSeqNumber++;
        sendPacket(sendQueue);//from  ww w.  j a v a  2 s . c  om
        sendQueue.sendTime = Instant.now().toEpochMilli();
        recoveryQueue.put(sendQueue.seqNumber, sendQueue);
        sendQueue = new DataPackets.DATA_PACKET_4();
    }
}