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:com.joyent.manta.client.multipart.JobsMultipartManagerIT.java

public void canUploadSmallMultipartString() throws IOException {
    String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" };

    StringBuilder combined = new StringBuilder();
    for (String p : parts) {
        combined.append(p);/*from w  ww . j  av  a 2 s. c  o  m*/
    }

    final String name = uploadName("can-upload-small-multipart-string");
    final String path = testPathPrefix + name;

    final JobsMultipartUpload upload = multipart.initiateUpload(path);
    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);

        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    Instant start = Instant.now();
    multipart.complete(upload, uploadedParts);

    multipart.waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
        fail("Completion operation didn't succeed within timeout");
        return null;
    });
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);

    assertEquals(status, MantaMultipartStatus.COMPLETED);

    assertEquals(mantaClient.getAsString(path), combined.toString(),
            "Manta combined string doesn't match expectation: " + multipart.findJob(upload));

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000);
}

From source file:org.lendingclub.mercator.newrelic.NewRelicScanner.java

/**
 * Scans all the servers ( reporting and non-reporting ) in NewRelic.
 * /*from   w  w  w  .j  a  v a 2 s.  c o m*/
 */
private void scanServers() {

    Instant startTime = Instant.now();

    ObjectNode servers = getNewRelicClient().getServers();
    Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set");

    String cypher = "WITH {json} as data " + "UNWIND data.servers as server "
            + "MERGE ( s:NewRelicServer { nr_serverId: toString(server.id), nr_accountId:{accountId} } ) "
            + "ON CREATE SET s.name = server.name, s.host = server.host, s.healthStatus = server.health_status, s.reporting = server.reporting, "
            + "s.lastReportedAt = server.last_reported_at, s.createTs = timestamp(), s.updateTs = timestamp() "
            + "ON MATCH SET s.name = server.name, s.host = server.host, s.healthStatus = server.health_status, s.reporting = server.reporting, "
            + "s.lastReportedAt = server.last_reported_at, s.updateTs = timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "json", servers, "accountId",
            clientSupplier.get().getAccountId());
    Instant endTime = Instant.now();

    logger.info("Updating neo4j with the latest information about {} NewRelic Servers took {} secs",
            servers.get("servers").size(), Duration.between(startTime, endTime).getSeconds());
}

From source file:com.seleniumtests.uipage.htmlelements.GenericPictureElement.java

/**
 * Search the picture in the screenshot taken by Robot or WebDriver
 * Robot is used in Desktop mode//from w  w w.j av  a2 s .  co m
 * WebDriver is used in mobile, because Robot is not available for mobile platforms
 * 
 */
public void findElement() {

    LocalDateTime start = LocalDateTime.now();

    File screenshotFile = getScreenshotFile();

    if (screenshotFile == null) {
        throw new WebDriverException("Screenshot does not exist");
    }

    // for desktop search, without reference image, do not search
    if (detector != null) {
        detector.setSceneImage(screenshotFile);
        detector.detectExactZoneWithScale();
        detectedObjectRectangle = detector.getDetectedRectangle();
        pictureSizeRatio = detector.getSizeRatio();
    } else {
        detectedObjectRectangle = new Rectangle(0, 0, 0, 0);
        pictureSizeRatio = 1.0;
    }
    actionDuration = Duration.between(start, LocalDateTime.now()).toMillis();

    doAfterPictureSearch();
}

From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.java

public void canUploadSmallMultipartString() throws IOException {
    String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" };

    StringBuilder combined = new StringBuilder();
    for (String p : parts) {
        combined.append(p);/*from w w  w.ja va 2s.  co m*/
    }

    final String name = uploadName("can-upload-small-multipart-string");
    final String path = testPathPrefix + name;

    final EncryptedMultipartUpload<JobsMultipartUpload> upload = multipart.initiateUpload(path);
    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);

        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    Instant start = Instant.now();
    multipart.complete(upload, uploadedParts);

    multipart.getWrapped().waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
        fail("Completion operation didn't succeed within timeout");
        return null;
    });
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);

    assertEquals(status, MantaMultipartStatus.COMPLETED);

    assertEquals(mantaClient.getAsString(path), combined.toString(),
            "Manta combined string doesn't match expectation: " + multipart.getWrapped().findJob(upload));

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000);
}

From source file:com.teradata.benchto.driver.execution.ExecutionDriver.java

private boolean isTimeLimitEnded() {
    Optional<Duration> timeLimit = properties.getTimeLimit();
    return timeLimit.isPresent() && timeLimit.get().compareTo(Duration.between(startTime, nowUtc())) < 0;
}

From source file:org.lendingclub.mercator.dynect.DynectScanner.java

private List<String> scanZones() {

    Instant startTime = Instant.now();

    logger.info("Scanning all zones in Dynect");
    ObjectNode response = getDynectClient().get("REST/Zone/");

    JsonNode zoneData = response.path("data");
    List<String> zonesList = new ArrayList<String>();

    if (zoneData.isArray()) {
        zoneData.forEach(zone -> {/*from   ww w .java  2s. c  o  m*/

            String zoneNode = zone.asText();
            String zoneName = Splitter.on("/").splitToList(zoneNode).get(3);
            zonesList.add(zoneName);
        });
    }

    logger.info("Scanning {} zones in Dynect to get more details", zonesList.size());

    for (String zone : zonesList) {
        response = getDynectClient().get("REST/Zone/" + zone);
        logger.debug("Scanning {} zone", zone);

        ObjectNode n = toZoneJson(response.get("data"));
        Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set");
        String cypher = "MERGE (m:DynHostedZone {zoneName:{zone}}) "
                + "ON CREATE SET  m+={props}, m.createTs = timestamp(), m.updateTs=timestamp() "
                + "ON MATCH SET m+={props}, m.updateTs=timestamp();";
        getProjector().getNeoRxClient().execCypher(cypher, "zone", zone, "props", n);
    }

    Instant endTime = Instant.now();
    logger.info("Updating neo4j with the latest information of all {} zones from Dynect took {} secs",
            zonesList.size(), Duration.between(startTime, endTime).getSeconds());

    return zonesList;
}

From source file:org.thevortex.lighting.jinks.robot.Recurrence.java

/**
 * Determine if the target is within the boundaries of this event.
 *
 * @param target the target time/date//from www  . j  a  va  2s.c  o m
 * @return {@code true} if the target is after the start time and within the duration; {@code false} if outside
 * the duration and/or there is no duration
 */
public boolean within(TemporalAccessor target) {
    if (duration == null)
        return false;

    LocalTime lt = LocalTime.from(target);
    return duration != null && lt.isAfter(startTime)
            && (Duration.between(startTime, lt).compareTo(duration) < 0);
}

From source file:org.wallride.service.PostService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }/*from  w ww  .  j  a va 2s.  co  m*/
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:nu.yona.server.analysis.service.AnalysisEngineService.java

private Duration determineDeviceTimeOffset(AppActivitiesDto appActivities) {
    Duration offset = Duration.between(ZonedDateTime.now(), appActivities.getDeviceDateTime());
    return (offset.abs().compareTo(DEVICE_TIME_INACCURACY_MARGIN) > 0) ? offset : Duration.ZERO; // Ignore if less than 10
    // seconds// w  w w.  java2 s .  co  m
}

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

private void doReadCsv(InputStreamReader reader, String what, Function<String[], Boolean> lineProcessor) {
    CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
    int count = 0;
    Instant startedAt = now();//from   w  w  w .j a v  a 2 s  .c o  m
    for (String[] columns : csvReader) {
        if (lineProcessor.apply(columns)) {
            count += 1;

            if (count % 1000 == 0) {
                log.debug("Imported {} {}...", count, what);
            }
        }
    }
    if (count > 0) {
        log.debug("Imported {} {} in {} ms", count, what, Duration.between(startedAt, now()).toMillis());
    }
}