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.lendingclub.mercator.newrelic.NewRelicScanner.java

private void scanAlertConditions() {

    Instant startTime = Instant.now();

    String cypher = "MATCH ( p: NewRelicAlertPolicy { nr_accountId:{accountId} }) return p;";
    List<JsonNode> alertPolicies = getProjector().getNeoRxClient().execCypherAsList(cypher, "accountId",
            clientSupplier.get().getAccountId());

    // for each policy get the alert conditions attached      
    alertPolicies.forEach(alert -> {//from w w w  . j a  v a2 s. c o  m

        String policyId = alert.path("nr_policyId").asText();

        if (!Strings.isNullOrEmpty(policyId)) {
            ObjectNode alertConditions = clientSupplier.get().getAlertConditionForPolicy(policyId);

            // create relationship between policy and conditions
            // create relationship betwen condition and entities ( servers / apm )            

            String conditionsCypher = "WITH {json} as data " + "UNWIND data.conditions as condition "
                    + "MATCH (p: NewRelicAlertPolicy {nr_policyId: {policyId}, nr_accountId:{accountId}}) "
                    + "MERGE ( c:NewRelicAlertCondition { nr_conditionId: toString(condition.id), nr_accountId: {accountId} }) "
                    + "ON CREATE SET c.type = condition.type, c.name = condition.name, c.enabled = condition.enabled, "
                    + "c.metricType = condition.metric, c.createTs = timestamp(), c.updateTs = timestamp() "
                    + "ON MATCH SET c.updateTs = timestamp(), c.enabled = condition.enabled, c.type = condition.type "
                    + "MERGE (c)-[:BELONGS_TO]->(p) "
                    + "with c,condition, CASE WHEN c.type = 'servers_metric' then [1] ELSE [] END AS aps_var, "
                    + "CASE WHEN c.type = 'apm_app_metric' then [1] ELSE [] END AS apm_var "
                    + "FOREACH ( s IN aps_var | FOREACH(sid in condition.entities | MERGE (s:NewRelicServer { nr_serverId:sid, nr_accountId:{accountId} }) MERGE (s)-[:ATTACHED_TO]->(c))) "
                    + "FOREACH ( m IN apm_var | FOREACH(mid in condition.entities | MERGE (m:NewRelicApplication { nr_appId:mid, nr_accountId:{accountId} }) MERGE (m)-[:ATTACHED_TO]->(c))) ";

            getProjector().getNeoRxClient().execCypher(conditionsCypher, "json", alertConditions, "policyId",
                    policyId, "accountId", clientSupplier.get().getAccountId());
        }
    });

    Instant endTime = Instant.now();
    logger.info("Updating neo4j with the latest information about NewRelic alert conditions took {} secs",
            Duration.between(startTime, endTime).getSeconds());
}

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

private ZonedDateTime ensureMinimumDurationOneMinute(ActivityPayload payload) {
    Duration duration = Duration.between(payload.startTime, payload.endTime);
    if (duration.compareTo(ONE_MINUTE) < 0) {
        return payload.startTime.plus(ONE_MINUTE);
    }// w  ww  . j a  v  a 2 s.co m
    return payload.endTime;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.JWTSecurityHandler.java

private long computeScheduledDelay(LocalDateTime expiration) {
    long upperLimit = Math.max(leeway - 5L, 5L);
    // random delay in seconds [3, (leeway - 5)]
    long delayFromExpiration = random.nextLong(3L, upperLimit);
    Duration duration = Duration.between(getNow(), expiration);
    return duration.getSeconds() + delayFromExpiration;
}

From source file:com.teradata.benchto.service.BenchmarkService.java

public Duration getSuccessfulExecutionAge(String uniqueName) {
    Timestamp ended = benchmarkRunRepo.findTimeOfLatestSuccessfulExecution(uniqueName);
    if (ended == null) {
        return Duration.ofDays(Integer.MAX_VALUE);
    }/*from   w  ww . j av a2s. c  o  m*/
    ZonedDateTime endedAsZDT = ZonedDateTime.of(ended.toLocalDateTime(), ZoneId.systemDefault());
    return Duration.between(endedAsZDT, currentDateTime());
}

From source file:org.eclipse.winery.repository.rest.resources.MainResource.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Imports the given CSAR (sent by simplesinglefileupload.jsp)")
@ApiResponses(value = {/* w  w w .ja va  2s .  c o m*/
        @ApiResponse(code = 200, message = "success", responseHeaders = @ResponseHeader(description = "If the CSAR could be partially imported, the points where it failed are returned in the body")) })
// @formatter:off
public Response importCSAR(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("overwrite") @ApiParam(value = "true: content of CSAR overwrites existing content. false (default): existing content is kept") Boolean overwrite,
        @FormDataParam("validate") @ApiParam(value = "true: validates the hash of the manifest file with the one stored in the accountability layer") Boolean validate,
        @Context UriInfo uriInfo) {
    LocalDateTime start = LocalDateTime.now();
    // @formatter:on
    CsarImporter importer = new CsarImporter();
    CsarImportOptions options = new CsarImportOptions();
    options.setOverwrite((overwrite != null) && overwrite);
    options.setAsyncWPDParsing(false);
    options.setValidate((validate != null) && validate);
    ImportMetaInformation importMetaInformation;
    try {
        importMetaInformation = importer.readCSAR(uploadedInputStream, options);
    } catch (Exception e) {
        return Response.serverError().entity("Could not import CSAR").entity(e.getMessage()).build();
    }
    if (importMetaInformation.errors.isEmpty()) {
        if (options.isValidate()) {

            return Response.ok(importMetaInformation, MediaType.APPLICATION_JSON).build();
        } else if (Objects.nonNull(importMetaInformation.entryServiceTemplate)) {
            URI url = uriInfo.getBaseUri()
                    .resolve(RestUtils.getAbsoluteURL(importMetaInformation.entryServiceTemplate));
            LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
            return Response.created(url).build();
        } else {
            LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
            return Response.noContent().build();
        }
    } else {
        LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
        // In case there are errors, we send them as "bad request"
        return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON)
                .entity(importMetaInformation).build();
    }
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Attempts to parse a (typically recurring) time  
 * @param human_readable_duration - Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#)
 * @param base_date - for relative date, locks the date to this origin (mainly for testing in this case?)
 * @return the machine readable duration, or an error
 *///w  ww  .j  av a2 s  .c o  m
public static Validation<String, Duration> getDuration(final String human_readable_duration,
        Optional<Date> base_date) {
    // There's a few different cases:
    // - the validation from getTimePeriod
    // - a slightly more complicated version <N><p> where <p> == period from the above
    // - use Natty for more complex expressions

    final Validation<String, ChronoUnit> first_attempt = getTimePeriod(human_readable_duration);
    if (first_attempt.isSuccess()) {
        return Validation
                .success(Duration.of(first_attempt.success().getDuration().getSeconds(), ChronoUnit.SECONDS));
    } else { // Slightly more complex version
        final Matcher m = date_parser.matcher(human_readable_duration);
        if (m.matches()) {
            final Validation<String, Duration> candidate_ret = getTimePeriod(m.group(2)).map(cu -> {
                final LocalDateTime now = LocalDateTime.now();
                return Duration.between(now, now.plus(Integer.parseInt(m.group(1)), cu));
            });

            if (candidate_ret.isSuccess())
                return candidate_ret;
        }
    }
    // If we're here then try Natty
    final Date now = base_date.orElse(new Date());
    return getSchedule(human_readable_duration, Optional.of(now)).map(d -> {
        final long duration = d.getTime() - now.getTime();
        return Duration.of(duration, ChronoUnit.MILLIS);
    });
}

From source file:org.ulyssis.ipp.ui.widgets.TeamPanel.java

private void updateCharts() {
    Instant now = Instant.now();
    Instant anHourAgo = now.minus(Duration.ofHours(1L));
    try (Connection connection = Database.createConnection(EnumSet.of(Database.ConnectionFlags.READ_ONLY))) {
        List<Event> events = Event.loadFrom(connection, anHourAgo);
        if (events.size() == 0) {
            LOG.warn("No events");
            return;
        }/*w w  w.j a v  a  2 s  .c  o m*/
        Snapshot snapshot = Snapshot.loadForEvent(connection, events.get(0)).get(); // If it's not there, this is a fatal error
        List<Optional<Instant>> eventTimes = new ArrayList<>();
        List<List<TagSeenEvent>> eventLists = new ArrayList<>();
        for (int i = 0; i < config.getNbReaders(); i++) {
            eventTimes.add(Optional.empty());
            eventLists.add(new ArrayList<>());
        }
        for (int i = 1; i < events.size(); ++i) {
            Event event = events.get(i);
            snapshot = event.apply(snapshot);
            if (event instanceof TagSeenEvent && !event.isRemoved()) { // TODO(Roel): Well, we can't actually remove it, right?
                final TagSeenEvent tagSeenEvent = (TagSeenEvent) event;
                Optional<Integer> teamNb = snapshot.getTeamTagMap().tagToTeam(tagSeenEvent.getTag());
                if (teamNb.isPresent() && teamNb.get().equals(team.getTeamNb())) {
                    // TODO(Roel): This hack is kind of dirty. In fact, all of this
                    //             code is kind of dirty.
                    if (eventTimes.get(tagSeenEvent.getReaderId()).isPresent()) {
                        if (Duration.between(eventTimes.get(tagSeenEvent.getReaderId()).get(), event.getTime())
                                .toMillis() <= 30_000) {
                            continue;
                        }
                    }
                    eventTimes.get(tagSeenEvent.getReaderId()).ifPresent(lastTime -> {
                        try {
                            eventLists.get(tagSeenEvent.getReaderId()).add(tagSeenEvent);
                        } catch (Exception e) {
                            LOG.error("Exception", e);
                        }
                    });
                    eventTimes.set(tagSeenEvent.getReaderId(), Optional.of(event.getTime()));
                }
            }
        }
        for (int i = 0; i < config.getNbReaders(); i++) {
            List<TagSeenEvent> eventList = eventLists.get(i);
            List<TagSeenEvent> shortenedEventList = new ArrayList<>();
            if (eventList.size() > 40) {
                for (int j = eventList.size() - 40; j < eventList.size(); j++) {
                    shortenedEventList.add(eventList.get(j));
                }
            } else {
                shortenedEventList = eventList;
            }
            itemModels.get(i).setEvents(anHourAgo, shortenedEventList);
        }
    } catch (SQLException e) {
        LOG.error("Couldn't fetch events", e);
    } catch (IOException e) {
        LOG.error("Error processing events", e);
    }
}

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

private long getTotalPageableItems(UserAnonymizedDto userAnonymized, ChronoUnit timeUnit) {
    long activityMemoryDays = yonaProperties.getAnalysisService().getActivityMemory().toDays();
    Optional<LocalDateTime> oldestGoalCreationTime = userAnonymized.getOldestGoalCreationTime();
    long activityRecordedDays = oldestGoalCreationTime.isPresent()
            ? (Duration.between(oldestGoalCreationTime.get(), TimeUtil.utcNow()).toDays() + 1)
            : 0;/*from www .  ja v  a2s.c  o m*/
    long totalDays = Math.min(activityRecordedDays, activityMemoryDays);
    switch (timeUnit) {
    case WEEKS:
        return (long) Math.ceil((double) totalDays / 7);
    case DAYS:
        return totalDays;
    default:
        throw new IllegalArgumentException("timeUnit should be weeks or days");
    }
}

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

private void canUploadMultipartBinary(final long sizeInMb, final int noOfParts) throws IOException {
    final long size = sizeInMb * 1024L * 1024L;

    File[] parts = new File[noOfParts];

    for (int i = 0; i < noOfParts; i++) {
        parts[i] = createTemporaryDataFile(size, 1);
    }// ww  w. jav a2 s  . c  om

    final File expectedFile = concatenateFiles(parts);
    final byte[] expectedMd5 = md5(expectedFile);

    final String name = uploadName("can-upload-5mb-multipart-binary");
    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++) {
        File 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.stream());
    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);

    MantaObjectResponse head = mantaClient.head(path);
    byte[] remoteMd5 = head.getMd5Bytes();

    if (!Arrays.equals(remoteMd5, expectedMd5)) {
        StringBuilder builder = new StringBuilder();
        builder.append("MD5 values do not match - job id: ").append(multipart.findJob(upload));
        fail(builder.toString());
    }

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

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

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

@Override
public void registerRenewer(X509MaterialParameter parameter) {
    if (!isHopsTLSEnabled()) {
        return;/*from  www  .ja va  2 s .co m*/
    }
    if (!renewalTasks.containsKey(parameter.getApplicationId())) {
        LocalDateTime now = DateUtils.getNow();
        LocalDateTime expirationDate = DateUtils.unixEpoch2LocalDateTime(parameter.getExpiration());

        Duration validityPeriod = Duration.between(now, expirationDate);
        Duration delay = validityPeriod.minus(amountOfTimeToSubstractFromExpiration, renewalUnitOfTime);

        ScheduledFuture renewTask = renewalExecutorService
                .schedule(createCertificateRenewerTask(parameter.getApplicationId(), parameter.appUser,
                        parameter.cryptoMaterialVersion), delay.getSeconds(), TimeUnit.SECONDS);
        renewalTasks.put(parameter.getApplicationId(), renewTask);
    }
}