Example usage for java.time Duration parse

List of usage examples for java.time Duration parse

Introduction

In this page you can find the example usage for java.time Duration parse.

Prototype

public static Duration parse(CharSequence text) 

Source Link

Document

Obtains a Duration from a text string such as PnDTnHnMn.nS .

Usage

From source file:Main.java

public static void main(String[] args) {
    Duration duration = Duration.parse("PT20.345S");
    System.out.println(duration);

    duration = Duration.parse("PT15M");
    System.out.println(duration);

    duration = Duration.parse("PT10H");
    System.out.println(duration);

    duration = Duration.parse("P2D");
    System.out.println(duration);

    duration = Duration.parse("P2DT3H4M");
    System.out.println(duration);

    duration = Duration.parse("P2DT3H4M");
    System.out.println(duration);

    duration = Duration.parse("P-6H3M");
    System.out.println(duration);

    duration = Duration.parse("-P6H3M");
    System.out.println(duration);

    duration = Duration.parse("-P-6H+3M");
    System.out.println(duration);
}

From source file:Main.java

public static void main(String[] args) {
    System.out.println(Period.parse("P3Y6M4D"));
    System.out.println(Duration.parse("PT12H30M5S"));
}

From source file:dk.dma.ais.track.TargetFilter.java

TargetFilter(UriInfo uriInfo) {
    MultivaluedMap<String, String> query = uriInfo.getQueryParameters();
    if (query.containsKey("ttlLive")) {
        ttlLive = Duration.parse(query.getFirst("ttlLive")).getSeconds();
    }//from  w ww.  j  a va 2  s  . com
    if (query.containsKey("ttlSat")) {
        ttlSat = Duration.parse(query.getFirst("ttlSat")).getSeconds();
    }
    Collection<String> list = query.get("mmsi");
    if (list != null) {
        mmsis = new HashSet<String>(list);
    }
    List<String> geoStrs = query.get("geo");
    if (geoStrs != null) {
        geos = new ArrayList<>();
        for (String geoStr : geoStrs) {
            geos.add(getGeometry(geoStr));
        }
    }
}

From source file:org.openmhealth.data.generator.converter.StringToDurationConverter.java

@Override
public Duration convert(String source) {

    if (source == null) {
        return null;
    }/*from   www  .j  a  va  2  s. com*/

    return Duration.parse(source);
}

From source file:dk.dma.vessel.track.store.AisStoreClient.java

public List<PastTrackPos> getPastTrack(int mmsi, Integer minDist, Duration age) {

    // Determine URL
    age = age != null ? age : Duration.parse(pastTrackTtl);
    minDist = minDist == null ? Integer.valueOf(pastTrackMinDist) : minDist;
    ZonedDateTime now = ZonedDateTime.now();
    String from = now.format(DateTimeFormatter.ISO_INSTANT);
    ZonedDateTime end = now.minus(age);
    String to = end.format(DateTimeFormatter.ISO_INSTANT);
    String interval = String.format("%s/%s", to, from);
    String url = String.format("%s?mmsi=%d&interval=%s", aisViewUrl, mmsi, interval);

    final List<PastTrackPos> track = new ArrayList<>();
    try {//from w ww  . j  av a  2s .c om
        long t0 = System.currentTimeMillis();

        // TEST
        url = url + "&filter=" + URLEncoder.encode("(s.country not in (GBR)) & (s.region!=808)", "UTF-8");

        // Set up a few timeouts and fetch the attachment
        URLConnection con = new URL(url).openConnection();
        con.setConnectTimeout(10 * 1000); // 10 seconds
        con.setReadTimeout(60 * 1000); // 1 minute

        if (!StringUtils.isEmpty(aisAuthHeader)) {
            con.setRequestProperty("Authorization", aisAuthHeader);
        }

        try (InputStream in = con.getInputStream(); BufferedInputStream bin = new BufferedInputStream(in)) {
            AisReader aisReader = AisReaders.createReaderFromInputStream(bin);
            aisReader.registerPacketHandler(new Consumer<AisPacket>() {
                @Override
                public void accept(AisPacket p) {
                    AisMessage message = p.tryGetAisMessage();
                    if (message == null || !(message instanceof IVesselPositionMessage)) {
                        return;
                    }
                    VesselTarget target = new VesselTarget();
                    target.merge(p, message);
                    if (!target.checkValidPos()) {
                        return;
                    }
                    track.add(new PastTrackPos(target.getLat(), target.getLon(), target.getCog(),
                            target.getSog(), target.getLastPosReport()));
                }
            });
            aisReader.start();
            try {
                aisReader.join();
            } catch (InterruptedException e) {
                return null;
            }
        }
        LOG.info(String.format("Read %d past track positions in %d ms", track.size(),
                System.currentTimeMillis() - t0));
    } catch (IOException e) {
        LOG.error("Failed to make REST query: " + url);
        throw new InternalError("REST endpoint failed");
    }
    LOG.info("AisStore returned track with " + track.size() + " points");
    return PastTrack.downSample(track, minDist, age.toMillis());
}

From source file:com.liferay.jenkins.tools.DurationMatcher.java

protected int parseDuration(String[] optionValues) throws IllegalArgumentException {
    String joinedString = StringUtils.join(optionValues, "");
    String spacedString = StringUtils.join(optionValues, " ");

    try {//from   w  ww .  ja v a2  s.co  m
        return Integer.parseInt(joinedString);
    } catch (NumberFormatException e) {
        logger.debug("'{}' is not a numeric duration string", spacedString);
    }

    try {
        Duration durationObject = Duration.parse(joinedString);

        return (int) durationObject.toMillis();
    } catch (DateTimeParseException e) {
        logger.debug("'{}' is not an ISO-8601 duration string", spacedString);
    }

    try {
        String textDurationString = parseTextDuration(optionValues);

        Duration durationObject = Duration.parse(textDurationString);

        return (int) durationObject.toMillis();
    } catch (DateTimeParseException e) {
        logger.debug("'{}' is not a text duration string", spacedString);
    }

    throw new IllegalArgumentException("Unable to parse duration string '" + spacedString + "'");
}

From source file:com.hurence.logisland.connect.opc.CommonUtils.java

/**
 * Validate the tag configuration.//from  ww  w .  j a v  a 2 s . co m
 *
 * @param tags  the list of tag id.
 * @param freqs the list of tag sampling frequencies.
 * @param modes the list of tag streaming modes.
 * @throws IllegalArgumentException in case something is bad.
 */
public static final void validateTagConfig(List<String> tags, List<String> freqs, List<String> modes) {
    //validate
    if (tags == null || tags.isEmpty()) {
        throw new IllegalArgumentException("Tag id list should not be empty");
    }
    if (freqs == null || freqs.size() != tags.size()) {
        throw new IllegalArgumentException("You should provide exactly one sampling rate per tag id");
    }
    if (modes == null || modes.size() != tags.size()) {
        throw new IllegalArgumentException("You should provide exactly one streaming mode per tag id");
    }
    freqs.forEach(freq -> {
        try {
            if (StringUtils.isNotBlank(freq)) {
                Duration.parse(freq);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Unrecognized sampling rate: " + freq);
        }
    });
    modes.forEach(mode -> {
        try {
            if (StringUtils.isNotBlank(mode)) {
                StreamingMode.valueOf(mode);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Unrecognized streaming mode: " + mode);
        }
    });
}

From source file:com.querydsl.webhooks.GithubReviewWindow.java

@Bean
public PullRequestHandler reviewWindowHandler(Environment environment) {
    Duration defaultReviewWindow = Duration.parse(environment.getRequiredProperty("duration")); //duration is the default window
    Map<String, ScheduledFuture<?>> asyncTasks = Maps.newConcurrentMap();

    return payload -> {
        PullRequest pullRequest = payload.getPullRequest();
        Ref head = pullRequest.getHead();

        try {/*from w ww .j a va 2s .  c  o m*/
            GHRepository repository = github.getRepository(payload.getRepository().getFullName());
            Collection<GHLabel> labels = repository.getIssue(pullRequest.getNumber()).getLabels();

            Duration reviewTime = labels.stream().map(label -> "duration." + label.getName()) //for all duration.[label] properties
                    .map(environment::getProperty).filter(Objects::nonNull) //look for a Duration
                    .findFirst().map(Duration::parse).orElse(defaultReviewWindow); //if none found, use the default window

            ZonedDateTime creationTime = pullRequest.getCreatedAt();
            ZonedDateTime windowCloseTime = creationTime.plus(reviewTime);

            boolean windowPassed = now().isAfter(windowCloseTime);
            logger.info("creationTime({}) + reviewTime({}) = windowCloseTime({}), so windowPassed = {}",
                    creationTime, reviewTime, windowCloseTime, windowPassed);

            if (windowPassed) {
                completeAndCleanUp(asyncTasks, repository, head);
            } else {
                createPendingMessage(repository, head, reviewTime);

                ScheduledFuture<?> scheduledTask = taskScheduler.schedule(
                        () -> completeAndCleanUp(asyncTasks, repository, head),
                        Date.from(windowCloseTime.toInstant()));

                replaceCompletionTask(asyncTasks, scheduledTask, head);
            }
        } catch (IOException ex) {
            throw Throwables.propagate(ex);
        }
    };
}

From source file:com.epam.dlab.automation.test.TestCallable.java

private static Duration getDuration(String duration) {
    return Duration.parse("PT" + duration);
}

From source file:keywhiz.KeywhizConfig.java

public Duration getStatusCacheExpiry() {
    if ((statusCacheExpiry == null) || (statusCacheExpiry.isEmpty())) {
        // Default to 1 second
        return Duration.ofSeconds(1);
    }/* w w w  .  j  a  v  a 2 s.  c  om*/
    return Duration.parse(statusCacheExpiry);
}