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.netflix.genie.web.services.impl.LocalJobKillServiceImpl.java

private void killJobOnUnix(final int pid) throws GenieException {
    try {//from   w  w  w.j  a va  2s  . co  m
        // Ensure this process check can't be timed out
        final Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
        final ProcessChecker processChecker = new UnixProcessChecker(pid, this.executor, tomorrow);
        processChecker.checkProcess();
    } catch (final ExecuteException ee) {
        // This means the job was done already
        log.debug("Process with pid {} is already done", pid);
        return;
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to check process status for pid " + pid, ioe);
    }

    // TODO: Do we need retries?
    // This means the job client process is still running
    try {
        final CommandLine killCommand;
        if (this.runAsUser) {
            killCommand = new CommandLine("sudo");
            killCommand.addArgument("kill");
        } else {
            killCommand = new CommandLine("kill");
        }
        killCommand.addArguments(Integer.toString(pid));
        this.executor.execute(killCommand);
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to kill process " + pid, ioe);
    }
}

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

public void update(long time) throws IOException {
    if (!isActive && (lastUpdate + 10000) < time) { //10 second timeout
        disconnect("timeout");
        return;/*from  w w  w .  j  a v a  2 s.  c  o  m*/
    }
    isActive = false;

    if (!ACKQueue.isEmpty()) {
        ACK pk = new ACK();
        pk.packets = ACKQueue.stream().toArray(Integer[]::new);
        sendPacket(pk);
        ACKQueue.clear();
    }

    if (!NACKQueue.isEmpty()) {
        NACK pk = new NACK();
        pk.packets = NACKQueue.stream().toArray(Integer[]::new);
        sendPacket(pk);
        NACKQueue.clear();
    }

    if (!packetToSend.isEmpty()) {
        int limit = 16;
        for (int i = 0; i < packetToSend.size(); i++) {
            DataPacket pk = packetToSend.get(i);
            pk.sendTime = time;
            pk.encode();
            recoveryQueue.put(pk.seqNumber, pk);
            packetToSend.remove(pk);
            sendPacket(pk);
            if (limit-- <= 0) {
                break;
            }
        }
    }

    if (packetToSend.size() > WINDOW_SIZE) {
        packetToSend.clear();
    }

    if (needACK.values().size() > 0) {
        for (Integer i : needACK.keySet()) {
            Map<Integer, Integer> indexes = needACK.get(i);
            if (indexes.values().size() == 0) {
                needACK.remove(indexes);
                sessionManager.notifyACK(this, i);
            }
        }
    }

    for (Integer seq : recoveryQueue.keySet()) {
        DataPacket pk = recoveryQueue.get(seq);
        if (pk.sendTime < Instant.now().toEpochMilli() - 6000) { //If no ACK in 6 seconds, resend :)
            packetToSend.add(pk);
            recoveryQueue.remove(seq);
        } else {
            break;
        }
    }

    for (Integer seq : receivedWindow.keySet()) {
        if (seq < windowStart) {
            receivedWindow.remove(seq);
        } else {
            break;
        }
    }

    try {
        sendQueue();
    } catch (IOException e) {
        sessionManager.getLogger().notice("Failed to send queue: IOException: " + e.getMessage());
        throw new RuntimeException(e);
    }
}

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

private HttpEntityEnclosingRequestBase sign(HttpEntityEnclosingRequestBase request, String payload) {
    String method = "sign";
    Instant timestamp = Instant.now();
    String signature = getSigner(request, timestamp).payload(payload).signV1();
    logDebug(method, SIGNATURE_MSG, signature);
    addHeaders(request, timestamp, signature);
    request.setEntity(new StringEntity(payload, StandardCharsets.UTF_8));
    return request;
}

From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTask.java

/**
 * {@inheritDoc}//from   w w  w .  j a va2 s.  c  o  m
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final JobRequest jobRequest = jobExecEnv.getJobRequest();
        final String user = jobRequest.getUser();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobRequest.getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue."));
        log.info("Starting Job Kickoff Task for job {}", jobId);

        // At this point all contents are written to the run script and we call an explicit flush and close to write
        // the contents to the file before we execute it.
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new GenieServerException("Failed to execute job", e);
        }
        // Create user, if enabled
        if (isUserCreationEnabled) {
            createUser(user, jobRequest.getGroup().orElse(null));
        }
        final List<String> command = new ArrayList<>();

        // If the OS is linux use setsid to launch the process so that the entire process tree
        // is launched in process group id which is the same as the pid of the parent process
        if (SystemUtils.IS_OS_LINUX) {
            command.add("setsid");
        }

        // Set the ownership to the user and run as the user, if enabled
        if (isRunAsUserEnabled) {
            changeOwnershipOfDirectory(jobWorkingDirectory, user);

            // This is needed because the genie.log file is still generated as the user running Genie system.
            makeDirGroupWritable(jobWorkingDirectory + "/genie/logs");
            command.add("sudo");
            command.add("-u");
            command.add(user);
        }

        final String runScript = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_JOB_LAUNCHER_SCRIPT;
        command.add(runScript);

        // Cannot convert to executor because it does not provide an api to get process id.
        final ProcessBuilder pb = new ProcessBuilder(command).directory(jobExecEnv.getJobWorkingDir())
                .redirectOutput(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH))
                .redirectError(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH));

        //
        // Check if file can be executed. This is to fix issue where execution of the run script fails because
        // the file may be used by some other program
        //
        canExecute(runScript);
        try {
            final Process process = pb.start();
            final int processId = this.getProcessId(process);
            final Instant timeout = Instant.now().plus(
                    jobRequest.getTimeout().orElse(JobRequest.DEFAULT_TIMEOUT_DURATION), ChronoUnit.SECONDS);
            final JobExecution jobExecution = new JobExecution.Builder(this.hostname).withId(jobId)
                    .withProcessId(processId).withCheckDelay(jobExecEnv.getCommand().getCheckDelay())
                    .withTimeout(timeout).withMemory(jobExecEnv.getMemory()).build();
            context.put(JobConstants.JOB_EXECUTION_DTO_KEY, jobExecution);
        } catch (final IOException ie) {
            throw new GenieServerException("Unable to start command " + String.valueOf(command), ie);
        }
        log.info("Finished Job Kickoff Task for job {}", jobId);
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(JOB_KICKOFF_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:com.coinblesk.server.controller.PaymentController.java

License:asdf

@RequestMapping(value = "/signverify", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody//from  ww  w . ja  v a 2 s  .  c  om
public SignVerifyTO signVerify(@RequestBody SignVerifyTO request) {
    final String tag = "{signverify}";
    final Instant startTime = Instant.now();
    String clientPubKeyHex = "(UNKNOWN)";

    try {
        final NetworkParameters params = appConfig.getNetworkParameters();
        final Keys keys;
        final ECKey clientKey = ECKey.fromPublicOnly(request.publicKey());
        clientPubKeyHex = clientKey.getPublicKeyAsHex();
        final ECKey serverKey;
        final Transaction transaction;
        final List<TransactionSignature> clientSigs;

        // clear payeeSig since client sig does not cover it
        final TxSig payeeSigInput = request.payeeMessageSig();
        request.payeeMessageSig(null);
        final byte[] payeePubKey = request.payeePublicKey();
        request.payeePublicKey(null);

        // NFC has a hard limit of 245, thus we have no space for the date
        // yet.
        final SignVerifyTO error = ToUtils.checkInput(request, false);
        if (error != null) {
            LOG.info("{} - clientPubKey={} - input error - type={}", tag, clientPubKeyHex, error.type());
            return error;
        }

        LOG.debug("{} - clientPubKey={} - request", tag, clientPubKeyHex);
        keys = keyService.getByClientPublicKey(clientKey.getPubKey());
        if (keys == null || keys.clientPublicKey() == null || keys.serverPrivateKey() == null
                || keys.serverPublicKey() == null) {
            LOG.debug("{} - clientPubKey={} - KEYS_NOT_FOUND", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.KEYS_NOT_FOUND);
        }
        serverKey = ECKey.fromPrivateAndPrecalculatedPublic(keys.serverPrivateKey(), keys.serverPublicKey());

        if (keys.timeLockedAddresses().isEmpty()) {
            LOG.debug("{} - clientPubKey={} - ADDRESS_EMPTY", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.ADDRESS_EMPTY, serverKey);
        }

        /*
         * Got a transaction in the request - sign
         */
        if (request.transaction() != null) {
            transaction = new Transaction(params, request.transaction());
            LOG.debug("{} - clientPubKey={} - transaction from input: \n{}", tag, clientPubKeyHex, transaction);

            List<TransactionOutput> outputsToAdd = new ArrayList<>();
            // if amount to spend && address provided, add corresponding
            // output
            if (request.amountToSpend() > 0 && request.addressTo() != null && !request.addressTo().isEmpty()) {
                TransactionOutput txOut = transaction.addOutput(Coin.valueOf(request.amountToSpend()),
                        Address.fromBase58(params, request.addressTo()));
                outputsToAdd.add(txOut);
                LOG.debug("{} - added output={} to Tx={}", tag, txOut, transaction.getHash());
            }

            // if change amount is provided, we add an output to the most
            // recently created address of the client.
            if (request.amountChange() > 0) {
                Address changeAddress = keys.latestTimeLockedAddresses().toAddress(params);
                Coin changeAmount = Coin.valueOf(request.amountChange());
                TransactionOutput changeOut = transaction.addOutput(changeAmount, changeAddress);
                outputsToAdd.add(changeOut);
                LOG.debug("{} - added change output={} to Tx={}", tag, changeOut, transaction.getHash());
            }

            if (!outputsToAdd.isEmpty()) {
                outputsToAdd = BitcoinUtils.sortOutputs(outputsToAdd);
                transaction.clearOutputs();
                for (TransactionOutput to : outputsToAdd) {
                    transaction.addOutput(to);
                }
            }

        } else {
            LOG.debug("{} - clientPubKey={} - INPUT_MISMATCH", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.INPUT_MISMATCH, serverKey);
        }

        // check signatures
        if (request.signatures() == null || (request.signatures().size() != transaction.getInputs().size())) {
            LOG.debug(
                    "{} - clientPubKey={} - INPUT_MISMATCH - number of signatures ({}) != number of inputs ({})",
                    tag, clientPubKeyHex, request.signatures().size(), transaction.getInputs().size());
            return ToUtils.newInstance(SignVerifyTO.class, Type.INPUT_MISMATCH, serverKey);
        }

        clientSigs = SerializeUtils.deserializeSignatures(request.signatures());
        SignVerifyTO responseTO = txService.signVerifyTransaction(transaction, clientKey, serverKey,
                clientSigs);
        SerializeUtils.signJSON(responseTO, serverKey);

        // if we know the receiver, we create an additional signature with
        // the key of the payee.
        if (maybeAppendPayeeSignature(request, payeePubKey, payeeSigInput, responseTO)) {
            LOG.debug("{} - created additional signature for payee.", tag);
        } else {
            LOG.debug("{} - payee unknown (no additional signature)");
        }

        return responseTO;
    } catch (Exception e) {
        LOG.error("{} - clientPubKey={} - SERVER_ERROR: ", tag, clientPubKeyHex, e);
        return new SignVerifyTO().currentDate(System.currentTimeMillis()).type(Type.SERVER_ERROR)
                .message(e.getMessage());
    } finally {
        LOG.debug("{} - clientPubKey={} - finished in {} ms", tag, clientPubKeyHex,
                Duration.between(startTime, Instant.now()).toMillis());
    }
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

private void waitForHoverflyToStart() {
    final Instant now = Instant.now();
    Stream.generate(this::hoverflyHasStarted).peek(b -> {
        if (Duration.between(now, Instant.now()).getSeconds() > BOOT_TIMEOUT_SECONDS) {
            throw new IllegalStateException(
                    "Hoverfly has not become healthy within " + BOOT_TIMEOUT_SECONDS + " seconds");
        }/*from www .ja va2 s.  c  om*/
    }).anyMatch(b -> b.equals(true));
}

From source file:com.netflix.spinnaker.front50.model.SwiftStorageService.java

@Override
public long getLastModified(ObjectType objectType) {
    List<? extends SwiftObject> objects = getSwift().objects().list(containerName,
            ObjectListOptions.create().path(objectType.group));
    ZonedDateTime lastModified = Instant.now().atZone(ZoneOffset.UTC);
    for (SwiftObject o : objects) {
        ZonedDateTime timestamp = ZonedDateTime.parse(
                getSwift().objects().getMetadata(containerName, o.getName()).get("Last-Modified"),
                DateTimeFormatter.RFC_1123_DATE_TIME);
        if (timestamp.isBefore(lastModified)) {
            lastModified = timestamp;//from w w  w .jav  a  2 s  .  c  om
        }
    }
    return lastModified.toEpochSecond();
}

From source file:com.orange.cepheus.cep.SubscriptionManager.java

private void periodicSubscriptionTask() {

    Instant now = Instant.now();
    Instant nextSubscriptionTaskDate = now.plusMillis(subscriptionPeriodicity);
    logger.info("Launch of the periodic subscription task at {}", now.toString());

    // Futures will use the current subscription list.
    // So that they will not add old subscriptions to a new configuration.
    Subscriptions subscriptions = this.subscriptions;

    for (EventTypeIn eventType : eventTypeIns) {
        SubscribeContext subscribeContext = null;
        for (Provider provider : eventType.getProviders()) {

            boolean deadlineIsPassed = false;
            Instant subscriptionDate = provider.getSubscriptionDate();
            if (subscriptionDate != null) {
                Instant subscriptionEndDate = subscriptionDate.plus(Duration.parse(subscriptionDuration));
                // check if deadline is passed
                if (nextSubscriptionTaskDate.compareTo(subscriptionEndDate) >= 0) {
                    deadlineIsPassed = true;
                    String subscriptionId = provider.getSubscriptionId();
                    // if delay is passed then clear the subscription info in provider et suppress subscription
                    if (subscriptionId != null) {
                        subscriptions.removeSubscription(subscriptionId);
                        provider.setSubscriptionId(null);
                        provider.setSubscriptionDate(null);
                    }/*from  www  .  ja v a2  s. co  m*/
                }
            }
            //Send subscription if subscription is a new subscription or we do not receive a response (subscriptionDate is null)
            //Send subscription if deadline is passed
            if ((subscriptionDate == null) || deadlineIsPassed) {
                // lazy build body request only when the first request requires it
                if (subscribeContext == null) {
                    subscribeContext = buildSubscribeContext(eventType);
                }
                subscribeProvider(provider, subscribeContext, subscriptions);
            }
        }
    }
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepositoryTest.java

@Test
public void getAllRegistrationsWithExceptionTest() throws URISyntaxException, RegistrationPersistenceException {
    thrown.expect(RegistrationPersistenceException.class);
    Instant expirationDate = Instant.now().plus(1, ChronoUnit.DAYS);
    jdbcTemplate.update("insert into t_registrations(id,expirationDate,registerContext) values(?,?,?)", "12345",
            expirationDate.toString(), "aaaaaa");
    Map<String, Registration> registrations = registrationsRepository.getAllRegistrations();
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {/*from   w w  w . j a v  a2s .  com*/
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}