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:de.loercher.localpress.integration.GeoAndRatingITest.java

@Test
public void testAddArticle() {
    String nowString = "2015-10-12T08:00+02:00[Europe/Berlin]";
    ZonedDateTime now = new DateTimeConverter().fromString(nowString);

    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(nowString);
    Instant instant = now.toInstant();
    Instant fir = Instant.now();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("UserID", "ulf");

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, headers);

    RestTemplate template = new RestTemplate();
    ResponseEntity<Map> result = template.postForEntity("http://52.29.77.191:8080/localpress/feedback", request,
            Map.class);

    Instant afterRating = Instant.now();

    GeoBaseEntity.EntityBuilder builder = new GeoBaseEntity.EntityBuilder();
    GeoBaseEntity entity = builder.author("ulf")
            .coordinates(Arrays.asList(new Coordinate[] { new Coordinate(50.1, 8.4) }))
            .timestamp(now.toEpochSecond()).content("abc.de").title("mein titel").user("ulf").build();

    HttpEntity<GeoBaseEntity> second = new HttpEntity<>(entity, headers);
    System.out.println(result.getBody().get("articleID"));

    template.put("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"), second);

    Instant afterGeoPut = Instant.now();

    result = template.getForEntity("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"),
            Map.class);

    Instant afterGeoGet = Instant.now();

    assertEquals("User ID has changed over time!", "ulf", result.getBody().get("user"));
    assertEquals("Content URL has changed over time!", "abc.de", result.getBody().get("content"));

    DateTimeConverter conv = new DateTimeConverter();

    Duration first = Duration.between(fir, afterRating);
    Duration sec = Duration.between(afterRating, afterGeoPut);
    Duration third = Duration.between(afterGeoPut, afterGeoGet);

    System.out.println("Begin: " + conv.toString(now));
    System.out.println("Time until POST to rating: " + new Double(first.toMillis()) / 1000);
    System.out.println("Time until PUT to geo: " + new Double(sec.toMillis()) / 1000);
    System.out.println("Time until GET to geo: " + new Double(third.toMillis()) / 1000);
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java

void hillClimbing(Solution solution) {
    logger.info(/*from  www  .j  a va 2s  .com*/
            String.format("---------- Starting hill climbing for instance %s ----------", solution.getId()));
    Technology technology = solverChecker.enforceSolverSettings(solution.getLstSolutions());

    List<SolutionPerJob> lst = solution.getLstSolutions();
    Stream<SolutionPerJob> strm = settings.isParallel() ? lst.parallelStream() : lst.stream();
    AtomicLong executionTime = new AtomicLong();
    boolean overallSuccess = strm.map(s -> {
        Instant first = Instant.now();
        boolean success = hillClimbing(s, technology);
        Instant after = Instant.now();
        executionTime.addAndGet(Duration.between(first, after).toMillis());
        return success;
    }).reduce(true, Boolean::logicalAnd);

    if (!overallSuccess)
        stateHandler.sendEvent(Events.STOP);
    else {
        solution.setEvaluated(false);
        evaluator.evaluate(solution);

        Phase phase = new Phase();
        phase.setId(PhaseID.OPTIMIZATION);
        phase.setDuration(executionTime.get());
        solution.addPhase(phase);
    }
}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate, String data_file) {

    BufferedReader br = null;/*from w w w  .j  ava 2  s.  c om*/
    ArrayList<String> lines = new ArrayList<>();
    LocalDateTime st = null;

    try {

        // Read the file into String array
        br = new BufferedReader(new FileReader(data_file));

        String line = null;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }

        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        int i = 0;
        int j = 0;

        while (i < numEvents) {
            i++;
            j++;
            if (j >= lines.size()) {
                j = 0;
            }
            line = lines.get(j) + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            os.write(line.getBytes());
            os.flush();

        }

        LocalDateTime et = LocalDateTime.now();
        if (st != null) {
            et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        sckt.close();
        os = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate) {
    Random rnd = new Random();
    BufferedReader br = null;/*ww  w. j  a v a2s .c  o m*/
    LocalDateTime st = null;

    try {
        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();
        //PrintWriter sckt_out = new PrintWriter(os, true);

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        while (cnt < numEvents) {
            cnt += 1;
            LocalDateTime ct = LocalDateTime.now();
            String dtg = ct.toString();
            Double lat = 180 * rnd.nextDouble() - 90.0;
            Double lon = 360 * rnd.nextDouble() - 180.0;
            String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + ","
                    + lat.toString() + "\"," + cnt.toString() + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            if (cnt % 1000 == 0) {
                //System.out.println(cnt);
            }

            //sckt_out.write(line);
            os.write(line.getBytes());
            os.flush();

        }

        if (st != null) {
            LocalDateTime et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        //sckt_out.close();
        sckt.close();
        os = null;
        //sckt_out = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:org.openmhealth.shim.misfit.mapper.MisfitSleepDurationDataPointMapper.java

@Override
public Optional<DataPoint<SleepDuration>> asDataPoint(JsonNode sleepNode) {

    // The sleep details array contains segments corresponding to whether the user was awake, sleeping lightly,
    // or sleeping restfully for the duration of that segment. To discount the awake segments, we have to deduct
    // their duration from the total sleep duration.
    JsonNode sleepDetailsNode = asRequiredNode(sleepNode, "sleepDetails");

    long awakeDurationInSec = 0;

    OffsetDateTime previousSegmentStartDateTime = null;
    Long previousSegmentType = null;

    for (JsonNode sleepDetailSegmentNode : sleepDetailsNode) {

        OffsetDateTime startDateTime = asRequiredOffsetDateTime(sleepDetailSegmentNode, "datetime");
        Long value = asRequiredLong(sleepDetailSegmentNode, "value");

        // if the user was awake, add it to the awake tally
        if (previousSegmentType != null && previousSegmentType == AWAKE_SEGMENT_TYPE) {
            awakeDurationInSec += Duration.between(previousSegmentStartDateTime, startDateTime).getSeconds();
        }/* ww  w .  j  a v a2s .  c o  m*/

        previousSegmentStartDateTime = startDateTime;
        previousSegmentType = value;
    }

    // checking if the segment array is empty this way avoids compiler confusion later
    if (previousSegmentType == null) {
        throw new JsonNodeMappingException(
                format("The Misfit sleep node '%s' has no sleep details.", sleepNode));
    }

    // to calculate the duration of last segment, first determine the overall end time
    OffsetDateTime startDateTime = asRequiredOffsetDateTime(sleepNode, "startTime");
    Long totalDurationInSec = asRequiredLong(sleepNode, "duration");
    OffsetDateTime endDateTime = startDateTime.plusSeconds(totalDurationInSec);

    if (previousSegmentType == AWAKE_SEGMENT_TYPE) {
        awakeDurationInSec += Duration.between(previousSegmentStartDateTime, endDateTime).getSeconds();
    }

    Long sleepDurationInSec = totalDurationInSec - awakeDurationInSec;

    if (sleepDurationInSec == 0) {
        return Optional.empty();
    }

    SleepDuration measure = new SleepDuration.Builder(new DurationUnitValue(SECOND, sleepDurationInSec))
            .setEffectiveTimeFrame(ofStartDateTimeAndEndDateTime(startDateTime, endDateTime)).build();

    String externalId = asOptionalString(sleepNode, "id").orElse(null);
    Boolean sensed = asOptionalBoolean(sleepNode, "autoDetected").orElse(null);

    return Optional.of(newDataPoint(measure, RESOURCE_API_SOURCE_NAME, externalId, sensed));
}

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

public void start() throws IOException, InterruptedException {
    super.start();
    SystemAdmin systemAdmin = factory.getAdmin(systemName, config);
    SystemStreamMetadata ssm = systemAdmin.getSystemStreamMetadata(Collections.singleton(physicalStreamName))
            .get(physicalStreamName);//from   w  w w . ja  va2  s .c om

    NoOpMetricsRegistry metricsRegistry = new NoOpMetricsRegistry();
    Set<SystemStreamPartition> ssps = createSSPs(systemName, physicalStreamName, startPartition, endPartition);
    SystemConsumer consumer = factory.getConsumer(systemName, config, metricsRegistry);
    for (SystemStreamPartition ssp : ssps) {
        consumer.register(ssp,
                ssm.getSystemStreamPartitionMetadata().get(ssp.getPartition()).getOldestOffset());
    }

    consumer.start();

    System.out.println("starting consumption at " + Instant.now());
    Instant startTime = Instant.now();
    int numEvents = 0;
    while (numEvents < totalEvents) {
        Map<SystemStreamPartition, List<IncomingMessageEnvelope>> pollResult = consumer.poll(ssps, 2000);
        numEvents += pollResult.values().stream().mapToInt(List::size).sum();
    }

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

From source file:com.serphacker.serposcope.models.base.Run.java

public long getDurationMs() {
    if (started == null || finished == null) {
        return 0;
    }/* w  w w  .  j  a v a  2s.c om*/
    return Math.abs(Duration.between(started, finished).toMillis());
}

From source file:keywhiz.auth.cookie.AuthenticatedEncryptedCookieFactory.java

/**
 * Produces a cookie string for a given value and expiration.
 *
 * @param value value of new cookie./*from  ww w. ja  va 2 s  .com*/
 * @param expiration expiration time of cookie.
 * @return serialized cookie with given value and expiration.
 */
public NewCookie cookieFor(String value, ZonedDateTime expiration) {
    long maxAge = Duration.between(ZonedDateTime.now(clock), expiration).getSeconds();

    HttpCookie cookie = new HttpCookie(config.getName(), value, config.getDomain(), config.getPath(), maxAge,
            config.isHttpOnly(), config.isSecure());

    Response response = new Response(null, null);
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.services.PerformanceSolverProxy.java

@Cacheable(value = it.polimi.diceH2020.SPACE4CloudWS.main.Configurator.CACHE_NAME, keyGenerator = it.polimi.diceH2020.SPACE4CloudWS.main.Configurator.SPJ_KEYGENERATOR)
public Pair<Optional<Double>, Long> evaluate(@NonNull SolutionPerJob solPerJob) {
    Instant first = Instant.now();
    logger.info("Cache missing. Evaluation with " + performanceSolver.getClass().getSimpleName() + ".");
    Optional<Double> optionalResult = performanceSolver.evaluate(solPerJob);
    Instant after = Instant.now();
    return new ImmutablePair<>(optionalResult, Duration.between(first, after).toMillis());
}

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

@RequestMapping(value = "", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody//from   w ww  .  j  ava2 s . co  m
public VersionTO version(@RequestBody VersionTO input) {
    final String tag = "{version}";
    final Instant startTime = Instant.now();

    try {
        final String serverVersion = getServerVersion();
        final BitcoinNet serverNetwork = appConfig.getBitcoinNet();
        final String clientVersion = input.clientVersion();
        final BitcoinNet clientNetwork = input.bitcoinNet();

        if (clientVersion == null || clientVersion.isEmpty() || clientNetwork == null) {
            return new VersionTO().type(Type.INPUT_MISMATCH);
        }

        final boolean isSupported = isVersionSupported(clientVersion) && isNetworkSupported(clientNetwork);
        LOG.debug("{} - serverVersion={}, serverNetwork={}, clientVersion={}, clientNetwork={}, isSupported={}",
                tag, serverVersion, serverNetwork, clientVersion, clientNetwork, isSupported);

        return new VersionTO().bitcoinNet(serverNetwork).setSupported(isSupported).setSuccess();
    } catch (Exception e) {
        LOG.error("{} - failed with exception: ", tag, e);
        return new VersionTO().type(Type.SERVER_ERROR).message(e.getMessage());
    } finally {
        LOG.debug("{} - finished in {} ms", tag, Duration.between(startTime, Instant.now()).toMillis());
    }
}