Example usage for java.time Duration between

List of usage examples for java.time Duration between

Introduction

In this page you can find the example usage for java.time Duration between.

Prototype

public static Duration between(Temporal startInclusive, Temporal endExclusive) 

Source Link

Document

Obtains a Duration representing the duration between two temporal objects.

Usage

From source file:ai.grakn.engine.tasks.manager.StandaloneTaskManager.java

@Override
public void addTask(TaskState taskState) {
    stateStorage.newState(taskState);//  w  w w  . java 2  s.c  o m

    // Schedule task to run.
    Instant now = Instant.now();
    TaskSchedule schedule = taskState.schedule();
    long delay = Duration.between(now, schedule.runAt()).toMillis();
    try {
        stateStorage.updateState(taskState.markScheduled());

        // Instantiate task.
        BackgroundTask task = taskState.taskClass().newInstance();

        ScheduledFuture<?> future = schedule.interval()
                .map(interval -> schedulingService.scheduleAtFixedRate(runTask(taskState.getId(), task, true),
                        delay, interval.toMillis(), MILLISECONDS))
                .orElseGet(() -> (ScheduledFuture) schedulingService
                        .schedule(runTask(taskState.getId(), task, false), delay, MILLISECONDS));

        instantiatedTasks.put(taskState.getId(), new Pair<>(future, task));
    } catch (Throwable throwable) {
        LOG.error(getFullStackTrace(throwable));
        stateStorage.updateState(taskState.markFailed(throwable));
        instantiatedTasks.remove(taskState.getId());
    }
}

From source file:org.lendingclub.mercator.bind.BindScanner.java

@SuppressWarnings("unchecked")
private void scanRecordSetByZone() {

    Instant startTime = Instant.now();

    List<String> zones = getBindClient().getZones();
    Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set");

    zones.forEach(zone -> {//from  w  w  w  . j a  v  a 2 s .  com

        logger.info("Scanning the zone {}", zone);
        Optional<List> recordsStream = getBindClient().getRecordsbyZone(zone);

        if (!recordsStream.get().isEmpty()) {

            logger.info("Found {} records in {} zone", recordsStream.get().size(), zone);
            recordsStream.get().forEach(record -> {
                String line = record.toString();

                if (!line.startsWith(";")) {

                    ResourceRecordSet<Map<String, Object>> dnsRecord = getRecord(line);

                    ObjectNode recordNode = dnsRecord.toJson();
                    String cypher = "MATCH (z:BindHostedZone {zoneName:{zone}}) "
                            + "MERGE (m:BindHostedZoneRecord {domainName:{dn}, type:{type}, zoneName:{zone}}) "
                            + "ON CREATE SET m.ttl={ttl}, m.class={class}, m+={props}, m.createTs = timestamp(), m.updateTs=timestamp() "
                            + "ON MATCH SET m+={props}, m.updateTs=timestamp() "
                            + "MERGE (z)-[:CONTAINS]->(m);";
                    getProjector().getNeoRxClient().execCypher(cypher, "dn", recordNode.get("name").asText(),
                            "type", recordNode.get("type").asText(), "ttl", recordNode.get("ttl").asText(),
                            "class", recordNode.get("class").asText(), "props", recordNode.get("rData"), "zone",
                            zone);

                }
            });
        } else {
            logger.error("Failed to obtain any records in {} zone", zone);
        }
    });

    Instant endTime = Instant.now();
    logger.info(" Took {} secs to project Bind records to Neo4j",
            Duration.between(startTime, endTime).getSeconds());
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ScpFileUploaderImpl.java

@Override
public void uploadFile(File file) throws FileUploadException {
    if (config.isUploadEnabled()) {
        Instant startedAt = now();
        log.info("Uploading {} to {}...", file.getName(), formatUploadTo(config));

        try {//from   w  w  w  .ja v a2 s . com
            SSHClient sshClient = createAuthenticatedSshClient();

            doUploadFile(sshClient, file);
            log.info("{} ({}) uploaded to {} in {} s", file.getName(),
                    LogUtil.humanReadableByteCount(file.length()), formatUploadTo(config),
                    Duration.between(startedAt, now()).getSeconds());
        } catch (IOException e) {
            throw new FileUploadException("Cannot upload " + file, e);
        }
    }
}

From source file:org.jgrades.security.service.UserDetailsServiceImpl.java

private boolean isCredentialsNotExpired(User user) {
    Set<JgRole> userRoles = userMgntService.getUserRoles(user);
    int expirationDaysForRole = getExpirationDays(getRoleWithHighestPriority(userRoles));
    if (expirationDaysForRole != 0) {
        LocalDateTime lastPasswordChangeTime = passwordDataRepository.getPasswordDataWithUser(user.getLogin())
                .getLastChange();/*from   w w w  .  j  a v  a2 s. c  o  m*/
        Duration duration = Duration.between(lastPasswordChangeTime, LocalDateTime.now());
        return duration.minusDays(expirationDaysForRole).isNegative();
    } else {
        return true;
    }
}

From source file:ro.cosu.vampires.client.executors.fork.ForkExecutor.java

@Override
public Result execute(Computation computation) {

    acquireResources();//from   ww w .  j  a va 2 s  . c om

    CommandLine commandLine = getCommandLine(computation.command());

    CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream();
    PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream);
    executor.setStreamHandler(handler);
    executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS));
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    LocalDateTime start = LocalDateTime.now();
    int exitCode;
    try {
        executor.execute(commandLine, resultHandler);
    } catch (IOException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    try {
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1;

    //TODO take different action for failed commands so we can collect the output (stderr or java exception)

    LocalDateTime stop = LocalDateTime.now();

    long duration = Duration.between(start, stop).toMillis();

    releaseResources();
    return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop))
            .output(collectingLogOutputStream.getLines()).build();

}

From source file:org.apache.samza.tools.benchmark.SystemConsumerWithSamzaBench.java

public void start() throws IOException, InterruptedException {
    super.start();
    MessageConsumer consumeFn = new MessageConsumer();
    StreamApplication app = appDesc -> {
        String systemFactoryName = new SystemConfig(config).getSystemFactory(systemName).get();
        GenericSystemDescriptor sd = new GenericSystemDescriptor(systemName, systemFactoryName);
        GenericInputDescriptor<Object> isd = sd.getInputDescriptor(streamId, new NoOpSerde<>());
        MessageStream<Object> stream = appDesc.getInputStream(isd);
        stream.map(consumeFn);/*from  ww w.j av a  2  s  .  co  m*/
    };
    ApplicationRunner runner = ApplicationRunners.getApplicationRunner(app, new MapConfig());

    runner.run();

    while (consumeFn.getEventsConsumed() < totalEvents) {
        Thread.sleep(10);
    }

    Instant endTime = Instant.now();

    runner.kill();

    System.out.println("\n*******************");
    System.out.println(String.format("Started at %s Ending at %s ", consumeFn.startTime, endTime));
    System.out.println(String.format("Event Rate is %s Messages/Sec ", (consumeFn.getEventsConsumed() * 1000
            / Duration.between(consumeFn.startTime, Instant.now()).toMillis())));

    System.out.println("Event Rate is "
            + consumeFn.getEventsConsumed() * 1000 / Duration.between(consumeFn.startTime, endTime).toMillis());
    System.out.println("*******************\n");

    System.exit(0);
}

From source file:se.crisp.codekvast.warehouse.file_import.ZipFileImporterImpl.java

@Override
@Transactional(rollbackFor = Exception.class)
public void importZipFile(File file) {
    log.debug("Importing {}", file);
    Instant startedAt = now();//w  w w  .  j  ava2  s  . c o  m

    ExportFileMetaInfo metaInfo = null;
    ImportDAO.ImportContext context = new ImportDAO.ImportContext();

    try (ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
            InputStreamReader reader = new InputStreamReader(zipInputStream, charset)) {

        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            ExportFileEntry exportFileEntry = ExportFileEntry.fromString(zipEntry.getName());
            log.debug("Reading {} ...", zipEntry.getName());

            switch (exportFileEntry) {
            case META_INFO:
                metaInfo = ExportFileMetaInfo.fromInputStream(zipInputStream);
                if (importDAO.isFileImported(metaInfo)) {
                    log.debug("{} with uuid {} has already been imported", file, metaInfo.getUuid());
                    return;
                }
                break;
            case APPLICATIONS:
                readApplications(reader, context);
                break;
            case METHODS:
                readMethods(reader, context);
                break;
            case JVMS:
                readJvms(reader, context);
                break;
            case INVOCATIONS:
                readInvocations(reader, context);
                break;
            }
        }
        if (metaInfo != null) {
            importDAO.recordFileAsImported(metaInfo,
                    ImportDAO.ImportStatistics.builder().importFile(file)
                            .fileSize(humanReadableByteCount(file.length()))
                            .processingTime(Duration.between(startedAt, now())).build());
        }
    } catch (IllegalArgumentException | IOException e) {
        log.error("Cannot import " + file, e);
    }
}

From source file:org.lendingclub.mercator.bind.BindScanner.java

private void scanZones() {

    Instant startTime = Instant.now();

    List<String> zones = getBindClient().getZones();

    zones.forEach(zone -> {/*from  w  w w .  ja  va 2  s . co m*/

        String cypher = "MERGE (m:BindHostedZone {zoneName:{zone}}) "
                + "ON CREATE SET m.createTs = timestamp(), m.updateTs=timestamp() "
                + "ON MATCH SET  m.updateTs=timestamp();";
        getProjector().getNeoRxClient().execCypher(cypher, "zone", zone);
    });
    Instant endTime = Instant.now();
    logger.info(" Took {} secs to project Bind Zone information to Neo4j",
            Duration.between(startTime, endTime).getSeconds());

}

From source file:de.lgblaumeiser.ptm.analysis.analyzer.HourComputer.java

private Duration calculatePresence(final LocalTime starttime, final LocalTime endtime) {
    return Duration.between(starttime, endtime);
}

From source file:com.gigglinggnus.controllers.CheckinController.java

private JSONArray getAppointments(User user, Term term, Clock clk) {
    Instant now = Instant.now(clk);
    //return a list of appointments in this term
    List<Appointment> appts = user.getAppointments().stream().filter(appt -> appt.getTerm().equals(term))
            .filter(appt -> !appt.isStudentCheckedIn()).collect(Collectors.toList());
    //sorted by distance to current time
    Collections.sort(appts,//from  ww w.  j a  va 2s .  c o  m
            (Appointment a1, Appointment a2) -> Duration.between(now, a1.getInterval().getStart()).abs()
                    .compareTo(Duration.between(now, a1.getInterval().getStart()).abs()));

    JSONArray json = new JSONArray();

    for (Appointment appt : appts) {
        String examId = appt.getExam().getExamId();
        String startTime = LocalDateTime.from(appt.getInterval().getStart().atZone(ZoneId.systemDefault()))
                .toString();
        String seatNum = appt.prettySeat();
        //write JSON
        JSONObject elem = new JSONObject();
        elem.put("exam", examId);
        elem.put("start", startTime);
        elem.put("seat", seatNum);
        json.put(elem);
    }
    return json;
}