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:org.ulyssis.ipp.publisher.Score.java

public Score(Snapshot snapshot, boolean publicScore) {
    Config config = Config.getCurrentConfig();
    Instant now = Instant.now();
    this.time = now.toEpochMilli();
    this.lap = config.getTrackLength();
    this.update = snapshot.getUpdateFrequency();
    this.teams = new TreeSet<>();
    this.status = snapshot.getStatus();
    this.message = snapshot.getStatusMessage();
    TeamStates teamStates = publicScore ? snapshot.getPublicTeamStates() : snapshot.getTeamStates();
    for (org.ulyssis.ipp.config.Team team : config.getTeams()) {
        Optional<TeamState> teamState = teamStates.getStateForTeam(team.getTeamNb());
        if (teamState.isPresent()) {
            TeamState t = teamState.get();
            double speed = t.getPredictedSpeed();
            if (Double.isNaN(speed)) {
                teams.add(new Team(lap, team.getTeamNb(), team.getName(), 0, 0, 0, 0));
            } else {
                TagSeenEvent lastEvent = t.getLastTagSeenEvent().get();
                Instant lastTime = t.getLastTagSeenEvent().get().getTime();
                double elapsedSeconds = Duration.between(lastTime, now).toMillis() / 1000D;
                double previousReaderPosition = config.getReader(lastEvent.getReaderId()).getPosition();
                double nonLimitedPosition = previousReaderPosition + elapsedSeconds * speed;
                double position = nonLimitedPosition;
                if (position > config.getTrackLength())
                    position = config.getTrackLength();
                teams.add(new Team(lap, team.getTeamNb(), team.getName(), t.getNbLaps(),
                        position / config.getTrackLength(), nonLimitedPosition / config.getTrackLength(),
                        speed));/*  w w w  .  j  a  v  a  2 s  .  c o  m*/
            }
        } else {
            teams.add(new Team(lap, team.getTeamNb(), team.getName(), 0, 0, 0, 0));
        }
    }
}

From source file:org.ulyssis.ipp.snapshot.TeamState.java

public TeamState addTagSeenEvent(Snapshot snapshot, TagSeenEvent event) {
    int newTagFragmentCount = tagFragmentCount;
    double newSpeed = Double.NaN;
    double newPredictedSpeed = Double.NaN;
    int lastEventId = 0;
    if (lastTagSeenEvent.isPresent()) {
        TagSeenEvent lastEvent = lastTagSeenEvent.get();
        if (lastEvent.getReaderId() == event.getReaderId()
                && Duration.between(lastEvent.getTime(), event.getTime()).minusSeconds(MIN_TIME_BETWEEN_UPDATES)
                        .isNegative()) {
            LOG.info("Rejecting event because a tag for this team passed less than {} seconds ago",
                    MIN_TIME_BETWEEN_UPDATES);
            return this;
        }/*www.  java 2  s  .com*/
        lastEventId = lastEvent.getReaderId();
    }
    int diff = (event.getReaderId() - lastEventId);
    if (diff < 0) {
        diff = Config.getCurrentConfig().getNbReaders() + diff;
    } else if (diff == 0 && (lastTagSeenEvent.isPresent() || // TODO: Refactor this fustercluck of comparisons
            (snapshot.getStartTime().isBefore(event.getTime())
                    && !Duration.between(snapshot.getStartTime(), event.getTime())
                            .minusSeconds(MIN_TIME_BETWEEN_UPDATES).isNegative()))) {
        diff = Config.getCurrentConfig().getNbReaders();
    }
    newTagFragmentCount += diff;
    List<ReaderConfig> readers = Config.getCurrentConfig().getReaders();
    double distance = 0;
    if (lastTagSeenEvent.isPresent()) {
        for (int i = tagFragmentCount; i < newTagFragmentCount; i++) {
            int j = i % Config.getCurrentConfig().getNbReaders();
            int k = (i + 1) % Config.getCurrentConfig().getNbReaders();
            if (k > j) {
                distance += readers.get(k).getPosition() - readers.get(j).getPosition();
            } else if (j > k) {
                assert k == 0;
                distance += Config.getCurrentConfig().getTrackLength() - readers.get(j).getPosition();
            } else {
                // This can happen when there is only one reader.
                distance += Config.getCurrentConfig().getTrackLength();
            }
        }
        double time = Duration.between(lastTagSeenEvent.get().getTime(), event.getTime()).toMillis() / 1000D;
        newSpeed = distance / time;
        if (Double.isNaN(predictedSpeed)) {
            newPredictedSpeed = newSpeed;
        } else {
            newPredictedSpeed = newSpeed * ALPHA + predictedSpeed * (1 - ALPHA);
        }
    } else if (snapshot.getStartTime().isBefore(event.getTime())
            && !Duration.between(snapshot.getStartTime(), event.getTime())
                    .minusSeconds(MIN_TIME_BETWEEN_UPDATES).isNegative()) {
        double time = Duration.between(snapshot.getStartTime(), event.getTime()).toMillis() / 1000D;
        distance = readers.get(event.getReaderId()).getPosition();
        newSpeed = distance / time;
        if (Double.isNaN(predictedSpeed)) {
            newPredictedSpeed = newSpeed;
        } else {
            newPredictedSpeed = newSpeed * ALPHA + predictedSpeed * (1 - ALPHA);
        }
    }
    return new TeamState(Optional.of(event), newTagFragmentCount, newSpeed, newPredictedSpeed);
}

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

private void scanAlertPolicies() {

    Instant startTime = Instant.now();

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

    String cypher = "WITH {json} as data " + "UNWIND data.policies as policy "
            + "MERGE ( s:NewRelicAlertPolicy { nr_policyId: toString(policy.id), nr_accountId:{accountId} } ) "
            + "ON CREATE SET s.name = policy.name, s.policyCreatedTs = policy.created_at, s.policyUpdatedTs = policy.updated_at, "
            + "s.createTs = timestamp(), s.updateTs = timestamp() "
            + "ON MATCH SET s.policyUpdatedTs = policy.updated_at, s.updateTs = timestamp() ";

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

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

From source file:org.dcache.ftp.door.GFtpPerfMarker.java

private double calculateBandwidth(long byteCount) {
    long delta = byteCount - _stripeBytesTransferred;
    Instant now = Instant.now();
    Duration elapsed = Duration.between(lastUpdated, now);
    lastUpdated = now;//w w  w .  ja v  a 2 s.  c o  m
    double elapsedSeconds = (double) elapsed.getNano() / SECONDS.getDuration().toNanos() + elapsed.getSeconds();
    return delta / elapsedSeconds;
}

From source file:org.openmhealth.shim.misfit.MisfitShim.java

@Override
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final MisfitDataTypes misfitDataType;
    try {/*from   ww w  .j  a  v  a 2  s .  c o m*/
        misfitDataType = MisfitDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    // TODO don't truncate dates
    OffsetDateTime now = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();

    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    if (Duration.between(startDateTime, endDateTime).toDays() > MAX_DURATION_IN_DAYS) {
        endDateTime = startDateTime.plusDays(MAX_DURATION_IN_DAYS - 1); // TODO when refactoring, break apart queries
    }

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL);

    for (String pathSegment : Splitter.on("/").split(misfitDataType.getEndPoint())) {
        uriBuilder.pathSegment(pathSegment);
    }

    uriBuilder.queryParam("start_date", startDateTime.toLocalDate()) // TODO convert ODT to LocalDate properly
            .queryParam("end_date", endDateTime.toLocalDate()).queryParam("detail", true); // added to all endpoints to support summaries

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriBuilder.build().encode().toUri(), JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // FIXME figure out how to handle this
        logger.error("A request for Misfit data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {

        MisfitDataPointMapper<?> dataPointMapper;

        switch (misfitDataType) {
        case ACTIVITIES:
            dataPointMapper = physicalActivityMapper;
            break;
        case SLEEP:
            dataPointMapper = sleepDurationMapper;
            break;
        case STEPS:
            dataPointMapper = stepCountMapper;
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {
        return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody()));
    }
}

From source file:org.wso2.carbon.apimgt.core.util.APIUtils.java

public static boolean isTimeStampsEquals(Temporal date1, Temporal date2) {
    if (date1 == null && date2 == null) {
        return true;
    } else {//w  w  w . ja v  a 2 s .  co m
        return Duration.between(date1, date2).toMillis() < 1000L;
    }
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingGenerator.java

private void writeConferenceSolution(int dayListSize, int roomListSize) {
    int labTimeslotCount = (int) timeslotOptions.stream()
            .filter(pair -> Duration.between(pair.getLeft(), pair.getRight()).toMinutes() >= 120).count();
    int labRoomCount = roomListSize / 5;
    labTalkCount = (dayListSize * labTimeslotCount) * labRoomCount;

    int timeslotListSize = dayListSize * timeslotOptions.size();
    int talkListSize = (dayListSize * (timeslotOptions.size() - labTimeslotCount))
            * (roomListSize - labRoomCount) + labTalkCount;
    int speakerListSize = talkListSize * 2 / 3;

    String fileName = talkListSize + "talks-" + timeslotListSize + "timeslots-" + roomListSize + "rooms";
    File outputFile = new File(outputDir, fileName + "." + solutionFileIO.getOutputFileExtension());
    ConferenceSolution solution = createConferenceSolution(fileName, timeslotListSize, roomListSize,
            speakerListSize, talkListSize);
    solutionFileIO.write(solution, outputFile);
}

From source file:org.openhab.binding.openuv.internal.handler.OpenUVBridgeHandler.java

public @Nullable OpenUVResult getUVData(String latitude, String longitude, @Nullable String altitude) {
    StringBuilder urlBuilder = new StringBuilder(BASE_URL).append("?lat=").append(latitude).append("&lng=")
            .append(longitude);/*from w  ww . j  a va2  s .co m*/

    if (altitude != null) {
        urlBuilder.append("&alt=").append(altitude);
    }
    String errorMessage = null;
    try {
        String jsonData = HttpUtil.executeUrl("GET", urlBuilder.toString(), header, null, null,
                REQUEST_TIMEOUT);
        OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
        if (uvResponse.getError() == null) {
            updateStatus(ThingStatus.ONLINE);
            return uvResponse.getResult();
        } else {
            errorMessage = uvResponse.getError();
        }
    } catch (IOException e) {
        errorMessage = e.getMessage();
    }

    if (errorMessage.startsWith(ERROR_QUOTA_EXCEEDED)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);
        LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);

        logger.warn("Quota Exceeded, going OFFLINE for today, will retry at : {} ", tomorrowMidnight);
        scheduler.schedule(this::initiateConnexion,
                Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);

    } else if (errorMessage.startsWith(ERROR_WRONG_KEY)) {
        logger.error("Error occured during API query : {}", errorMessage);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
    }
    return null;
}

From source file:org.darkware.wpman.util.TimeWindow.java

/**
 * Fetch a time offset to a random moment within the time window.
 *
 * @return A number of seconds to a moment that is within the time window.
 *///from   w ww.  ja v a2 s .c  om
public Duration getRandomOffset() {
    return Duration.between(LocalDateTime.now(), this.getRandomMoment());
}

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Run the reader. Reader implements runnable, so that we can
 * do this in its own thread.//from w ww .  j a v  a2 s. com
 */
@Override
public void run() {
    LOG.info("Spinning up reader!");
    ReaderConfig.Type type = Config.getCurrentConfig().getReader(options.getId()).getType();
    if (type == ReaderConfig.Type.LLRP) {
        initSpeedway();
        if (!speedwayInitialized) {
            shutdownHook();
            return;
        }
    } else if (type == ReaderConfig.Type.SIMULATOR) {
        initSimulator();
    }
    Thread commandThread = new Thread(commandProcessor);
    commandThread.start();
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTED_UP,
            String.format("Started up reader %s!", options.getId())));
    try {
        while (!Thread.currentThread().isInterrupted()) {
            Duration maxUpdateInterval = Duration.ofMillis(Config.getCurrentConfig().getMaxUpdateInterval());
            if (maxUpdateInterval.minus(Duration.between(lastUpdate, Instant.now())).isNegative()) {
                lastUpdate = Instant.now();
                LOG.warn("No update received in {} seconds!", maxUpdateInterval.getSeconds());
                statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NO_UPDATES,
                        String.format("No update received in %s seconds!", maxUpdateInterval.getSeconds())));
            }
            Thread.sleep(1000L);
        }
    } catch (InterruptedException e) {
        // We don't care about this exception
    }
    commandProcessor.stop();
    commandThread.interrupt();
    try {
        commandThread.join();
    } catch (InterruptedException ignored) {
    }
    shutdownHook();
}