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.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

@Override
public void run() {

    // Trust https urls 
    trustAll();//from ww w .j  a v a2s  .  c om

    // Get start count
    int stCnt = -3;
    stCnt = getMsLayerCount(this.msLayerUrl);
    int cnt1 = stCnt;

    if (stCnt < 0) {
        throw new UnsupportedOperationException("Couldn't get start count from BDS");
    }

    // Wait for count to increase by the right number of events
    int curCnt = -3;

    curCnt = getMsLayerCount(this.msLayerUrl);

    if (curCnt < 0) {
        throw new UnsupportedOperationException("Couldn't get count from BDS");
    }

    // if count stop increase for 30 seconds then exit
    int newCnt = curCnt;

    LocalDateTime et = LocalDateTime.now();
    LocalDateTime st = LocalDateTime.now();
    Boolean firstCountChange = true;

    LocalDateTime s1 = LocalDateTime.now();
    LocalDateTime s2 = LocalDateTime.now();

    int sampleRateCnt = stCnt + sampleInterval;

    while (curCnt < stCnt + numEvents) {
        newCnt = getMsLayerCount(this.msLayerUrl);

        //System.out.println(newCnt);
        if (newCnt < 0) {
            System.out.println("Couldn't get count from BDS");
        }

        if (newCnt > curCnt) {
            if (firstCountChange) {
                sampleRateCnt = newCnt + sampleInterval;
                st = LocalDateTime.now();
                s1 = st;
                firstCountChange = false;
            }
            curCnt = newCnt;
            et = LocalDateTime.now();
        }

        LocalDateTime et2 = LocalDateTime.now();
        Duration delta = Duration.between(et, et2);

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

        if (isSingle && curCnt > sampleRateCnt) {
            // Calculate the rate for the sample rates
            s2 = LocalDateTime.now();
            Duration tm = Duration.between(s1, s2);
            Double secnds = (double) tm.getSeconds() + tm.getNano() / 1000000000.0;
            int cntChg = curCnt - cnt1;
            cnt1 = curCnt;
            Double rt = (double) cntChg / secnds;
            sampleRateCnt = cnt1 + sampleInterval;
            s1 = s2;
            System.out.println(curCnt - stCnt + "," + rt);
            if (rt < 200.0) {
                this.num_events_read = curCnt - stCnt;
                throw new UnsupportedOperationException("Rate has dropped below 200 e/s");
            }
        }

        if (elapsed_seconds > 30.0) {
            // count hasn't changed for 30 seconds
            System.out.println("Features lost");
            System.out.println(curCnt);
            break;
        }

        try {
            // This delay was added to prevent calls from overloading map service
            Thread.sleep(100);

        } catch (InterruptedException ex) {
            Logger.getLogger(GetMapServiceCountRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

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

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

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

        int eventsRcvd = curCnt - stCnt;
        //System.out.println("Events received: " + eventsRcvd);
        this.average_read_per_second = (double) eventsRcvd / elapsed_seconds;
        this.num_events_read = eventsRcvd;
    }
}

From source file:no.digipost.api.useragreements.client.response.ResponseUtils.java

public static Optional<Duration> parseDelayDurationOfRetryAfterHeader(HttpResponse response, Clock clock) {
    return getValueOfFirstHeader(response, Headers.Retry_After).map(retryAfterValue -> {
        try {//from   w w w.  ja  va  2 s . c  o m
            long parsedSeconds = Long.parseLong(retryAfterValue);
            return Duration.ofSeconds(parsedSeconds);
        } catch (NumberFormatException secondsNotParseable) {
            try {
                Instant parsedInstant = RFC_1123_DATE_TIME.parse(retryAfterValue, Instant::from);
                return Duration.between(clock.instant(), parsedInstant);
            } catch (RuntimeException e) {
                e.addSuppressed(secondsNotParseable);
                throw e;
            }
        }
    });
}

From source file:org.wso2.carbon.uuf.internal.io.StaticResolver.java

public void serve(App app, HttpRequest request, HttpResponse response) {
    Path resourcePath;//from  www. ja v  a2  s.  c om
    ZonedDateTime lastModifiedDate;
    try {
        if (request.isComponentStaticResourceRequest()) {
            // /public/components/...
            resourcePath = resolveResourceInComponent(app, request.getUriWithoutContextPath());
        } else if (request.isThemeStaticResourceRequest()) {
            // /public/themes/...
            resourcePath = resolveResourceInTheme(app, request.getUriWithoutContextPath());
        } else {
            // /public/...
            response.setContent(STATUS_BAD_REQUEST, "Invalid static resource URI '" + request.getUri() + "'.");
            return;
        }
        lastModifiedDate = resourcesLastModifiedDates.computeIfAbsent(resourcePath, this::getLastModifiedDate);
    } catch (IllegalArgumentException e) {
        // Invalid/incorrect static resource URI.
        response.setContent(STATUS_BAD_REQUEST, e.getMessage());
        return;
    } catch (ResourceNotFoundException e) {
        // Static resource file does not exists.
        response.setContent(STATUS_NOT_FOUND, "Requested resource '" + request.getUri() + "' does not exists.");
        return;
    } catch (Exception e) {
        // FileOperationException, IOException or any other Exception that might occur.
        log.error("An error occurred when manipulating paths for request '" + request + "'.", e);
        response.setContent(STATUS_INTERNAL_SERVER_ERROR,
                "A server occurred while serving for static resource request '" + request + "'.");
        return;
    }

    if (lastModifiedDate == null) {
        /* Since we failed to read last modified date of 'resourcePath' file, we cannot set cache headers.
        Therefore just serve the file without any cache headers. */
        response.setStatus(STATUS_OK);
        response.setContent(resourcePath, getContentType(request, resourcePath));
        return;
    }
    ZonedDateTime ifModifiedSinceDate = getIfModifiedSinceDate(request);
    if ((ifModifiedSinceDate != null) && Duration.between(ifModifiedSinceDate, lastModifiedDate).isZero()) {
        // Resource is NOT modified since the last serve.
        response.setStatus(STATUS_NOT_MODIFIED);
        return;
    }

    setCacheHeaders(lastModifiedDate, response);
    response.setStatus(STATUS_OK);
    response.setContent(resourcePath, getContentType(request, resourcePath));
}

From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java

LocalDateTime addChangeData(final List<String> out, final HistoricalDataEntry entry,
        final TemporalChangeOutput temporalOutput, final LocalDateTime lastChangeDate) {
    out.add(entry.getFrom());/*from w w  w. java2 s  .com*/
    final LocalDateTime changeDate = entry.getChangeDate();
    if (temporalOutput == TIME || temporalOutput == BOTH) {
        out.add(localDateTimeToString(entry.getChangeDate()));
    }
    if (temporalOutput == DURATION || temporalOutput == BOTH) {
        final Duration duration = Duration.between(lastChangeDate, changeDate);
        final String dur = String.valueOf(duration.toMillis() /*/ MILLIS*/);
        out.add(dur);
    }
    out.add(entry.getTo());
    return changeDate;
}

From source file:dk.sublife.docker.integration.Container.java

/**
 * Wait for isUp method call is satisfied.
 *
 * @param timoutSeconds seconds before failing
 * @return true when service is available
 * @throws InterruptedException//from ww  w . j  av  a 2s . c om
 */
protected boolean waitFor(long timoutSeconds) throws Exception {
    final Instant start = Instant.now();
    final ContainerInfo inspect = inspect();
    final String name = inspect.name();
    final String image = inspect.config().image();

    if (LOGGER.isInfoEnabled() && !isUp) {
        LOGGER.info("Waiting for container is up: {}{}", image, name);
    }
    while (!isUp) {
        try {
            if (inspect().state().running()) {
                isUp = isUp();
                if (isUp) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Running post startup actions...");
                    }
                    if (!postStartup()) {
                        throw new RuntimeException("Post startup failed!");
                    }
                }
            } else {
                LOGGER.error("Container is not up: {}{}", image, name);
                logFromContainer();
                throw new RuntimeException("Container died.");
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
        }
        final long seconds = Duration.between(start, Instant.now()).getSeconds();
        if (seconds > timoutSeconds) {
            try {
                if (inspect().state().running()) {
                    LOGGER.error("Container is running but not up: {}{}", image, name);
                    logFromContainer();
                }
            } catch (final Exception e) {
                LOGGER.error("Error inspecting container!", e);
            }
            throw new RuntimeException("Wait time exceeded.");
        }
        Thread.sleep(5000);
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("container is up {}{}", image, name);
    }
    return true;
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

private void waitForHoverflyToStart() {
    final Instant now = Instant.now();
    Stream.generate(this::hoverflyHasStarted).peek(b -> {
        if (Duration.between(now, Instant.now()).getSeconds() > BOOT_TIMEOUT_SECONDS) {
            throw new IllegalStateException(
                    "Hoverfly has not become healthy within " + BOOT_TIMEOUT_SECONDS + " seconds");
        }/* www.  j  a  v  a  2  s.  co  m*/
    }).anyMatch(b -> b.equals(true));
}

From source file:com.seleniumtests.driver.screenshots.ScreenshotUtil.java

/**
 * Capture a picture//w w  w .  j  ava2 s  .c  o m
 * @param target      which picture to take, screen or page.
 * @param exportClass   The type of export to perform (File, ScreenShot, String, BufferedImage)
 * @param allWindows   if true, will take a screenshot for all windows (only available for browser capture)
 * @param force         force capture even if set to false in SeleniumTestContext. This allows PictureElement and ScreenZone to work
 * @return
 */
public <T extends Object> List<T> capture(Target target, Class<T> exportClass, boolean allWindows,
        boolean force) {

    if (!force && (SeleniumTestsContextManager.getThreadContext() == null || getOutputDirectory() == null
            || !SeleniumTestsContextManager.getThreadContext().getCaptureSnapshot())) {
        return new ArrayList<>();
    }

    List<NamedBufferedImage> capturedImages = new ArrayList<>();
    LocalDateTime start = LocalDateTime.now();

    if (target == Target.SCREEN && SeleniumTestsContextManager.isDesktopWebTest()) {
        // capture desktop
        capturedImages.add(new NamedBufferedImage(captureDesktop(), ""));
    } else if (target == Target.PAGE && SeleniumTestsContextManager.isWebTest()) {
        // capture web with scrolling
        removeAlert();
        capturedImages.addAll(captureWebPages(allWindows));
    } else if (target == Target.PAGE && SeleniumTestsContextManager.isAppTest()) {
        capturedImages.add(new NamedBufferedImage(capturePage(-1, -1), ""));
    } else {
        throw new ScenarioException(
                "Capturing page is only possible for web and application tests. Capturing desktop possible for desktop web tests only");
    }

    // back to page top
    try {
        if (target == Target.PAGE) {
            ((CustomEventFiringWebDriver) driver).scrollTop();
        }
    } catch (WebDriverException e) {
        // ignore errors here.
        // com.seleniumtests.it.reporter.TestTestLogging.testManualSteps() with HTMLUnit driver
        // org.openqa.selenium.WebDriverException: Can't execute JavaScript before a page has been loaded!
    }

    List<T> out = new ArrayList<>();
    for (NamedBufferedImage capturedImage : capturedImages) {
        if (capturedImage != null) {
            if (exportClass.equals(File.class)) {
                out.add((T) exportToFile(capturedImage.image));
            } else if (exportClass.equals(ScreenShot.class)) {
                out.add((T) exportToScreenshot(capturedImage.image, capturedImage.prefix,
                        Duration.between(start, LocalDateTime.now()).toMillis()));
            } else if (exportClass.equals(String.class)) {
                try {
                    out.add((T) ImageProcessor.toBase64(capturedImage.image));
                } catch (IOException e) {
                    logger.error("ScreenshotUtil: cannot write image");
                }
            } else if (exportClass.equals(BufferedImage.class)) {
                out.add((T) capturedImage.image);
            }
        }
    }

    return out;
}

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

/**
 * Parse from a partial ICAL string.//from ww w  . j ava2 s  .c  o m
 *
 * @param recurrenceString the string
 * @return a thing
 */
public static Recurrence parse(String recurrenceString) {
    if (recurrenceString == null)
        return null;

    Recurrence result = new Recurrence();

    // each major part will be on a separate line
    String[] parts = recurrenceString.split("\\n");

    // first one MUST be a "DTSTART;" or we're already fucked
    String working = checkAndStrip(DTSTART, parts[0]);
    result.startTime = LocalTime.parse(working, ICAL_DT);

    // if there are three parts, the second must be an end time
    if (parts.length == 3) {
        working = checkAndStrip(DTEND, parts[1]);
        LocalTime endsAt = LocalTime.parse(working, ICAL_DT);
        result.duration = Duration.between(result.startTime, endsAt);
    }

    // we always have a RRULE: first part is FREQ and if it's weekly, followed by BYDAY
    working = checkAndStrip(RRULE, parts[parts.length - 1]);
    parts = working.split(";");

    // the type is first
    working = checkAndStrip(FREQ, parts[0]);
    result.frequency = Frequency.valueOf(working);

    // if it's weekly, there's more
    if (result.frequency == Frequency.WEEKLY) {
        SortedSet<DayOfWeek> list = new TreeSet<>();

        working = checkAndStrip(BYDAY, parts[1]);
        for (String dayValue : working.split(",")) {
            for (DayOfWeek dow : DayOfWeek.values()) {
                if (dow.name().startsWith(dayValue)) {
                    list.add(dow);
                    break;
                }
            }
        }
        result.days = list;
    }

    return result;
}

From source file:com.omertron.slackbot.functions.scheduler.AbstractBotTask.java

/**
 * Calculate the time between "now" and the execution time.
 *
 * @param targetHour//ww  w  . j a va2s .  c  o m
 * @param targetMin
 * @param targetSec
 * @return
 */
private long computeNextDelay(int targetHour, int targetMin, int targetSec) {
    ZonedDateTime zonedNow = localeDateTime();
    ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec)
            .withNano(0);

    if (zonedNow.compareTo(zonedNextTarget) >= 0) {
        zonedNextTarget = zonedNextTarget.plusDays(1);
    }

    Duration duration = Duration.between(zonedNow, zonedNextTarget);

    // If we are scheduled within the next minute, then skip a day as we probably just ran fast
    if (duration.getSeconds() <= 60l) {
        zonedNextTarget = zonedNextTarget.plusDays(1);
        duration = Duration.between(zonedNow, zonedNextTarget);
    }

    return duration.getSeconds();
}

From source file:ai.grakn.engine.tasks.manager.multiqueue.Scheduler.java

/**
 * Schedule a task to be submitted to the work queue when it is supposed to be run
 * @param state state of the task/*from w ww  . j  av  a  2  s.c o m*/
 */
private void scheduleTask(TaskState state) {
    TaskSchedule schedule = state.schedule();
    long delay = Duration.between(Instant.now(), schedule.runAt()).toMillis();

    Runnable submit = () -> {
        markAsScheduled(state);
        sendToWorkQueue(state);
    };

    Optional<Duration> interval = schedule.interval();
    if (interval.isPresent()) {
        schedulingService.scheduleAtFixedRate(submit, delay, interval.get().toMillis(), MILLISECONDS);
    } else {
        schedulingService.schedule(submit, delay, MILLISECONDS);
    }
}