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:notaql.performance.PerformanceTest.java

public static void runTests() throws URISyntaxException, IOException {
    URI basePath = NotaQL.class.getResource(BASE_PATH).toURI();

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    FileSystem zipfs = FileSystems.newFileSystem(basePath, env);

    final List<Path> tests = Files.list(Paths.get(basePath)).filter(p -> p.toString().endsWith(".json"))
            .sorted((a, b) -> a.toString().compareTo(b.toString())).collect(Collectors.toList());

    List<String> csv = new LinkedList<>();

    for (Path test : tests) {
        if (testCase != null && !test.getFileName().toString().equals(testCase))
            continue;

        final List<JSONObject> transformations = readArray(test);

        csv.add(test.getFileName().toString());

        int i = 1;

        for (JSONObject transformation : transformations) {
            final String name = transformation.getString("name");
            final String notaqlTransformation = composeTransformation(transformation);

            if (!(inEngine == null && outEngine == null
                    || inEngine != null/*from  www . ja v  a 2  s .c  om*/
                            && transformation.getJSONObject("IN-ENGINE").getString("engine").equals(inEngine)
                    || outEngine != null && transformation.getJSONObject("OUT-ENGINE").getString("engine")
                            .equals(outEngine)))
                continue;

            System.out.println("Evaluation test (" + i++ + "/" + transformations.size() + "): "
                    + test.getFileName() + ": " + name);

            List<Duration> durations = new LinkedList<>();

            for (int j = 0; j < RUNS; j++) {
                clean(transformation);

                final Instant startTime = Instant.now();

                NotaQL.evaluate(notaqlTransformation);

                final Instant endTime = Instant.now();

                final Duration duration = Duration.between(startTime, endTime);

                durations.add(duration);

                System.out.println("Testrun(" + j + ") " + name + " took: " + duration);
            }

            System.out.println("!!=================================================================!!");

            System.out.println("Test " + name + " took: "
                    + durations.stream().map(Duration::toString).collect(Collectors.joining(", ")));

            System.out.println("Test " + name + " took millis: " + durations.stream()
                    .map(d -> Long.toString(d.toMillis())).collect(Collectors.joining(", ")));

            System.out.println("Test " + name + " took on average (millis): "
                    + durations.stream().mapToLong(Duration::toMillis).average());

            System.out.println("Test " + name + " took on average (ignoring first - millis): "
                    + durations.stream().skip(1).mapToLong(Duration::toMillis).average());

            System.out.println("!!=================================================================!!");

            csv.add(name);
            csv.add(durations.stream().map(d -> Long.toString(d.toMillis())).collect(Collectors.joining(",")));
        }

    }

    System.out.println(csv.stream().collect(Collectors.joining("\n")));
}

From source file:org.wso2.carbon.apimgt.tracing.TracingReporter.java

/**
 * Get the structured log message format
 *
 * @param timeStamp timeStamp Instant//from   ww w. j  a va2s  .c  o m
 * @param span      opentracing SpanData
 * @return structured log message format String
 * */
private String toStructuredMessage(Instant timeStamp, SpanData span) {
    try {
        StringWriter writer = new StringWriter();
        JsonGenerator generator = this.jsonFactory.createGenerator(writer);
        generator.writeStartObject();
        generator.writeNumberField(TracingConstants.LATENCY,
                Duration.between(span.startAt, timeStamp).toMillis());
        generator.writeStringField(TracingConstants.OPERATION_NAME, span.operationName);
        generator.writeObjectFieldStart(TracingConstants.TAGS);
        Iterator itr = span.tags.entrySet().iterator();

        Map.Entry map;
        Object value;
        while (itr.hasNext()) {
            map = (Map.Entry) itr.next();
            value = map.getValue();
            if (value instanceof String) {
                generator.writeStringField((String) map.getKey(), (String) value);
            } else if (value instanceof Number) {
                generator.writeNumberField((String) map.getKey(), ((Number) value).doubleValue());
            } else if (value instanceof Boolean) {
                generator.writeBooleanField((String) map.getKey(), (Boolean) value);
            }
        }
        generator.writeEndObject();
        generator.close();
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        log.error("Error in structured message", e);
        return null;
    }
}

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

/**
 * Scans all the APM's in NewRelic and establishes relationship to servers
 * that are hosting them. In this way we know what all servers are hosting 
 * a particular application.//from www. j  a v a 2 s  .  c  om
 * 
 */
private void scanApms() {
    Instant startTime = Instant.now();

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

    String cypher = "WITH {json} as data " + "UNWIND data.applications as app "
            + "MERGE (a:NewRelicApplication { nr_appId: toString(app.id), nr_accountId: {accountId}} ) "
            + "ON CREATE SET a.appName = app.name, a.lastReportedAt = app.last_reported_at, a.createTs = timestamp(), a.healthStatus = app.health_status, "
            + "a.reporting = app.reporting, a.language = app.language, a.updateTs = timestamp() "
            + "ON MATCH SET a.lastReportedAt = app.last_reported_at, a.reporting = app.reporting, a.healthStatus = app.health_status, a.updateTs = timestamp() "
            + "FOREACH ( sid IN app.links.servers | MERGE (s:NewRelicServer { nr_serverId: toString(sid), nr_accountId:{accountId} }) MERGE (a)-[:HOSTED_ON]->(s))";

    getProjector().getNeoRxClient().execCypher(cypher, "json", apps, "accountId",
            clientSupplier.get().getAccountId());

    Instant endTime = Instant.now();

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

}

From source file:org.commonjava.indy.ftest.core.AbstractIndyFunctionalTest.java

@SuppressWarnings("resource")
@Before//  w  w w  . ja v a 2s  . co m
public void start() throws Throwable {
    try {
        final long start = System.currentTimeMillis();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                long time = System.currentTimeMillis();
                System.out.printf("\n\n\nDate: %s\nElapsed: %s\n\n\n", new Date(time),
                        Duration.between(Instant.ofEpochMilli(start), Instant.ofEpochMilli(time)));
            }
        };

        new Timer().scheduleAtFixedRate(task, 0, 5000);

        Thread.currentThread().setName(getClass().getSimpleName() + "." + name.getMethodName());

        fixture = newServerFixture();
        fixture.start();

        if (!fixture.isStarted()) {
            final BootStatus status = fixture.getBootStatus();
            throw new IllegalStateException("server fixture failed to boot.", status.getError());
        }

        client = createIndyClient();
    } catch (Throwable t) {
        logger.error("Error initializing test", t);
        throw t;
    }
}

From source file:tibano.service.ParkService.java

@RequestMapping(path = "/getPaymentInfo")
PaymentInfo getPaymentInfo(@RequestParam(name = "areaId") Long areaId,
        @RequestParam(name = "licensePlate") String licensePlate) {
    ParkingTransaction pt = ptRepository.findOpenTransactionByAreaAndLicensePlate(areaId, licensePlate);
    if (pt != null) {
        Duration duration = Duration.between(pt.getStart(), LocalDateTime.now());
        Double amount = duration.getSeconds() * SEC_TARIF;
        BigDecimal bd = new BigDecimal(amount);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        Integer loyaltyPoints = 5 + Integer.valueOf(Double.valueOf(bd.doubleValue()).intValue());
        return new PaymentInfo(pt.getEnd(), amount, duration, loyaltyPoints);
    }// w  w  w .  j a v a 2 s  . c om
    return new PaymentInfo(null, Double.valueOf(0), Duration.ZERO, Integer.valueOf(0));
}

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

public void removeStalePools() {
    LOGGER.info("Checking for stale pools prefixed with {}", poolNamePrefix);
    client.getAllPools(true).stream().filter(pool -> pool.getName().startsWith(poolNamePrefix))
            .filter(pool -> !pool.getMembers().isPresent() || pool.getMembers().get().size() == 0)
            .filter(pool -> {/*from  ww w  . ja va 2  s  .c  o  m*/
                // Filter out non stale pools.
                final Optional<PoolDescription> description = PoolDescription
                        .fromJsonish(pool.getDescription());
                if (description.isPresent()) {
                    final Duration timeSinceModified = Duration.between(description.get().getModified(),
                            Instant.now());
                    return POOL_STALE_TIME.compareTo(timeSinceModified) < 0;
                }
                return false;
            }).forEach(pool -> safeDeletePool(pool.getName()));
}

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

private void scanAllRecordsByZone(List<String> zones) {

    Instant startTime = Instant.now();

    logger.info("Scanning all records in each available zones");

    for (String zone : zones) {
        logger.debug("Scanning all records in Dynect zone {} ", zone);

        ObjectNode response = getDynectClient().get("REST/AllRecord/" + zone);

        JsonNode recordsData = response.path("data");

        if (recordsData.isArray()) {
            recordsData.forEach(record -> {
                String recordFullName = record.asText();

                logger.debug("Scanning {} record for more information in {} zone", recordFullName, zone);
                ObjectNode recordResponse = getDynectClient().get(recordFullName);

                ObjectNode data = toRecordJson(recordResponse.get("data"));
                String recordId = Splitter.on("/").splitToList(recordFullName).get(5);

                String cypher = "MATCH (z:DynHostedZone {zoneName:{zone}})"
                        + "MERGE (m:DynHostedZoneRecord {recordId:{recordId}}) "
                        + "ON CREATE SET  m+={props}, m.createTs = timestamp(), m.updateTs=timestamp() "
                        + "ON MATCH SET m+={props}, m.updateTs=timestamp() " + "MERGE (z)-[:CONTAINS]->(m);";
                getProjector().getNeoRxClient().execCypher(cypher, "recordId", recordId, "props", data, "zone",
                        zone);//  w ww . ja  va  2s .c o  m
            });
        }
    }

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

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

@Override
public Optional<File> exportData() throws DataExportException {
    File exportFile = expandPlaceholders(config.getExportFile());
    if (exportFile == null) {
        log.info("No export file configured, data will not be exported");
        return Optional.empty();
    }//from w ww .  j  ava  2s. c o  m

    if (!exportFile.getName().toLowerCase().endsWith(ExportFileFormat.ZIP.getSuffix())) {
        log.error("Can only export to " + ExportFileFormat.ZIP + " format");
        return Optional.empty();
    }

    Instant startedAt = now();

    doExportDataTo(exportFile);

    log.info("Created {} ({}) in {} ms", exportFile, LogUtil.humanReadableByteCount(exportFile.length()),
            Duration.between(startedAt, now()).toMillis());
    return Optional.of(exportFile);
}

From source file:org.ng200.openolympus.controller.api.ContestTimerController.java

@RequestMapping("/api/contestTimeRemaining/{contest}")
public @ResponseBody Map<String, String> getTimeRemaining(@PathVariable("contest") final Contest contest,
        final Principal principal) {
    Assertions.resourceExists(contest);/*from   w w  w.ja  v  a  2  s . c  o  m*/

    Instant end = contest.getStartTime().toInstant();
    final boolean isInProcess = contest.getStartTime().before(java.util.Date.from(Instant.now()));
    if (isInProcess) {
        if (this.contestSecurityService.isSuperuser(principal)) {
            end = this.contestService.getContestEndIncludingAllTimeExtensions(contest);
        } else if (principal != null) {
            final User user = this.userRepository.findByUsername(principal.getName());
            if (user != null) {
                end = end.plusMillis(contest.getDuration())
                        .plusMillis(this.contestService.getTimeExtensions(contest, user));
            }
        }
    }
    if (principal != null) {
        this.contestService.getTimeExtensions(contest, this.userRepository.findByUsername(principal.getName()));
    }
    final Instant cur = Instant.now();
    if (end.isBefore(cur)) {
        return new HashMap<String, String>() {
            /**
             *
             */
            private static final long serialVersionUID = 5419629757758058933L;

            {
                this.put("timer", "00:00:00");
                this.put("status", "ended");
            }
        };
    }
    final Duration duration = Duration.between(cur, end);
    final DecimalFormat format = new DecimalFormat("00");
    final long hours = duration.toHours();
    final long minutes = duration.minusHours(hours).toMinutes();
    final long seconds = duration.minusHours(hours).minusMinutes(minutes).getSeconds();
    return new HashMap<String, String>() {
        /**
         *
         */
        private static final long serialVersionUID = -4698243010184691932L;

        {
            this.put("timer",
                    format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds));

            this.put("status", isInProcess ? "inProgress" : "notStartedYet");
        }
    };
}

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

public void start() throws IOException, InterruptedException {

    super.start();
    String source = "SystemProducerBench";

    int size = Integer.parseInt(cmd.getOptionValue(OPT_SHORT_MESSAGE_SIZE));
    RandomValueGenerator randGenerator = new RandomValueGenerator(System.currentTimeMillis());
    value = randGenerator.getNextString(size, size).getBytes();

    NoOpMetricsRegistry metricsRegistry = new NoOpMetricsRegistry();
    List<SystemStreamPartition> ssps = createSSPs(systemName, physicalStreamName, startPartition, endPartition);
    SystemProducer producer = factory.getProducer(systemName, config, metricsRegistry);
    producer.register(source);//  w ww  .ja v  a2s.co m
    producer.start();

    System.out.println("starting production at " + Instant.now());
    Instant startTime = Instant.now();
    for (int index = 0; index < totalEvents; index++) {
        SystemStreamPartition ssp = ssps.get(index % ssps.size());
        OutgoingMessageEnvelope messageEnvelope = createMessageEnvelope(ssp, index);
        producer.send(source, messageEnvelope);
    }

    System.out.println("Ending production at " + Instant.now());
    System.out.println(String.format("Event Rate is %s Messages/Sec",
            (totalEvents * 1000 / Duration.between(startTime, Instant.now()).toMillis())));

    producer.flush(source);

    System.out.println("Ending flush at " + Instant.now());
    System.out.println(String.format("Event Rate with flush is %s Messages/Sec",
            (totalEvents * 1000 / Duration.between(startTime, Instant.now()).toMillis())));
    producer.stop();
    System.exit(0);
}