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:com.teradata.benchto.driver.BenchmarkProperties.java

public Optional<Duration> getTimeLimit() {
    if (timeLimit != null) {
        return Optional.of(Duration.parse(timeLimit));
    } else {/*w  ww  . j a v  a2s.c om*/
        return Optional.empty();
    }
}

From source file:com.creactiviti.piper.core.Worker.java

private long calculateTimeout(TaskExecution aTask) {
    if (aTask.getTimeout() != null) {
        return Duration.parse("PT" + aTask.getTimeout()).toMillis();
    }/* ww  w.  j a  v a 2 s.  c  o m*/
    return DEFAULT_TIME_OUT;
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.JwtCookieAuthBundle.java

@Override
public void run(C configuration, Environment environment) throws Exception {
    JwtCookieAuthConfiguration conf = configurationSupplier.apply(configuration);

    //build the key from the key factory if it was provided
    Key key = Optional.ofNullable(keySuppplier).map(k -> k.apply(configuration, environment)).orElseGet(() ->
    //else make a key from the seed if it was provided
    Optional.ofNullable(conf.getSecretSeed())
            .map(seed -> Hashing.sha256().newHasher().putString(seed, UTF_8).hash().asBytes())
            .map(k -> (Key) new SecretKeySpec(k, HS256.getJcaName()))
            //else generate a random key
            .orElseGet(getHmacSha256KeyGenerator()::generateKey));

    JerseyEnvironment jerseyEnvironment = environment.jersey();

    jerseyEnvironment.register(new AuthDynamicFeature(new JwtCookieAuthRequestFilter.Builder()
            .setCookieName(DEFAULT_COOKIE_NAME)
            .setAuthenticator(new JwtCookiePrincipalAuthenticator(key, deserializer))
            .setPrefix(JWT_COOKIE_PREFIX).setAuthorizer((Authorizer<P>) (P::isInRole)).buildAuthFilter()));
    jerseyEnvironment.register(new AuthValueFactoryProvider.Binder<>(principalType));
    jerseyEnvironment.register(RolesAllowedDynamicFeature.class);

    jerseyEnvironment.register(new JwtCookieAuthResponseFilter<>(principalType, serializer, DEFAULT_COOKIE_NAME,
            conf.isHttpsOnlyCookie(), key,
            Ints.checkedCast(Duration.parse(conf.getSessionExpiryVolatile()).getSeconds()),
            Ints.checkedCast(Duration.parse(conf.getSessionExpiryPersistent()).getSeconds())));

    jerseyEnvironment.register(DontRefreshSessionFilter.class);
}

From source file:de.metas.ui.web.dashboard.UserDashboardRepository.java

private KPI getKPIOrNull(final int WEBUI_KPI_ID) {
    if (WEBUI_KPI_ID <= 0) {
        return null;
    }//from w ww. j  av  a2  s  .c o m
    return kpisCache.getOrLoad(WEBUI_KPI_ID, () -> {
        final I_WEBUI_KPI kpiDef = InterfaceWrapperHelper.create(Env.getCtx(), WEBUI_KPI_ID, I_WEBUI_KPI.class,
                ITrx.TRXNAME_None);
        if (kpiDef == null) {
            return null;
        }

        final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(kpiDef);

        final String timeRangeStr = kpiDef.getES_TimeRange();
        final Duration timeRange = Check.isEmpty(timeRangeStr, true) ? Duration.ZERO
                : Duration.parse(timeRangeStr);

        return KPI.builder().setId(kpiDef.getWEBUI_KPI_ID())
                .setCaption(trls.getColumnTrl(I_WEBUI_KPI.COLUMNNAME_Name, kpiDef.getName()))
                .setDescription(trls.getColumnTrl(I_WEBUI_KPI.COLUMNNAME_Description, kpiDef.getDescription()))
                .setChartType(KPIChartType.forCode(kpiDef.getChartType()))
                .setFields(retrieveKPIFields(WEBUI_KPI_ID))
                //
                .setTimeRange(timeRange)
                //
                .setESSearchIndex(kpiDef.getES_Index()).setESSearchTypes(kpiDef.getES_Type())
                .setESQuery(kpiDef.getES_Query()).setElasticsearchClient(elasticsearchClient)
                //
                .build();
    });
}

From source file:com.orange.cepheus.cep.SubscriptionManager.java

private void periodicSubscriptionTask() {

    Instant now = Instant.now();
    Instant nextSubscriptionTaskDate = now.plusMillis(subscriptionPeriodicity);
    logger.info("Launch of the periodic subscription task at {}", now.toString());

    // Futures will use the current subscription list.
    // So that they will not add old subscriptions to a new configuration.
    Subscriptions subscriptions = this.subscriptions;

    for (EventTypeIn eventType : eventTypeIns) {
        SubscribeContext subscribeContext = null;
        for (Provider provider : eventType.getProviders()) {

            boolean deadlineIsPassed = false;
            Instant subscriptionDate = provider.getSubscriptionDate();
            if (subscriptionDate != null) {
                Instant subscriptionEndDate = subscriptionDate.plus(Duration.parse(subscriptionDuration));
                // check if deadline is passed
                if (nextSubscriptionTaskDate.compareTo(subscriptionEndDate) >= 0) {
                    deadlineIsPassed = true;
                    String subscriptionId = provider.getSubscriptionId();
                    // if delay is passed then clear the subscription info in provider et suppress subscription
                    if (subscriptionId != null) {
                        subscriptions.removeSubscription(subscriptionId);
                        provider.setSubscriptionId(null);
                        provider.setSubscriptionDate(null);
                    }//w  w w .ja va2 s . com
                }
            }
            //Send subscription if subscription is a new subscription or we do not receive a response (subscriptionDate is null)
            //Send subscription if deadline is passed
            if ((subscriptionDate == null) || deadlineIsPassed) {
                // lazy build body request only when the first request requires it
                if (subscribeContext == null) {
                    subscribeContext = buildSubscribeContext(eventType);
                }
                subscribeProvider(provider, subscribeContext, subscriptions);
            }
        }
    }
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private Duration parseVideoDuration(final String ffmpegOutput) throws IOException {
    final Pattern pattern = Pattern.compile("Duration: \\d\\d:\\d\\d:\\d\\d\\.\\d+");
    final Matcher matcher = pattern.matcher(ffmpegOutput);

    if (matcher.find()) {
        final String durationString = matcher.group();
        final String[] durationParts = durationString.substring("Duration: ".length()).split(":");
        final String hours = durationParts[0];
        final String minutes = durationParts[1];
        final String seconds = durationParts[2];
        return Duration.parse(String.format("PT%sH%sM%sS", hours, minutes, seconds));
    } else {//from   w ww.j  ava 2s.  c om
        throw new IOException("Video duration not found in FFmpeg output.");
    }
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * Check that an input string is loadable as a certain SPARQL data type, and tweak it if necessary.
 * Throws exception if not./*from   w  ww  .  j  ava 2 s .co  m*/
 * Expects to only get the last part of the type, e.g. "float"
 */
@SuppressWarnings("deprecation")
public static String validateDataType(String input, String expectedSparqlGraphType) throws Exception {

    //   from the XSD data types:
    //   string | boolean | decimal | int | integer | negativeInteger | nonNegativeInteger | 
    //   positiveInteger | nonPositiveInteger | long | float | double | duration | 
    //   dateTime | time | date | unsignedByte | unsignedInt | anySimpleType |
    //   gYearMonth | gYear | gMonthDay;

    //      added for the runtimeConstraint:
    //     NODE_URI

    /**
     *  Please keep the wiki up to date
     *  https://github.com/ge-semtk/semtk/wiki/Ingestion-type-handling
     */
    String ret = input;

    if (expectedSparqlGraphType.equalsIgnoreCase("string")) {

    } else if (expectedSparqlGraphType.equalsIgnoreCase("boolean")) {
        try {
            Boolean.parseBoolean(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("decimal")) {
        try {
            Double.parseDouble(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("int")) {
        try {
            Integer.parseInt(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("integer")) {
        try {
            Integer.parseInt(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("negativeInteger")) {
        try {
            int test = Integer.parseInt(input);
            if (test >= 0) {
                throw new Exception("value in model is negative integer. non-negative integer given as input");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("nonNegativeInteger")) {
        try {
            int test = Integer.parseInt(input);
            if (test < 0) {
                throw new Exception("value in model is nonnegative integer. negative integer given as input");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("positiveInteger")) {
        try {
            int test = Integer.parseInt(input);
            if (test <= 0) {
                throw new Exception("value in model is positive integer. integer <= 0 given as input");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("nonPositiveInteger")) {
        try {
            int test = Integer.parseInt(input);
            if (test > 0) {
                throw new Exception("value in model is nonpositive integer. integer > 0 given as input");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("long")) {
        try {
            long test = Long.parseLong(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("float")) {
        try {
            float test = Float.parseFloat(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("double")) {
        try {
            double test = Double.parseDouble(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("duration")) {
        // not sure how to check this one. this might not match the expectation from SADL
        try {
            Duration.parse(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("dateTime")) {
        try {
            return Utility.getSPARQLDateTimeString(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("time")) {
        try {
            Time.parse(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("date")) {
        try {
            return Utility.getSPARQLDateString(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("unsignedByte")) {
        try {
            Byte.parseByte(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("unsignedint")) {
        try {
            Integer.parseUnsignedInt(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("anySimpleType")) {
        // do nothing. 
    } else if (expectedSparqlGraphType.equalsIgnoreCase("gYearMonth")) {
        try {
            String[] all = input.split("-");
            // check them all
            if (all.length != 2) {
                throw new Exception("year-month did not have two parts.");
            }
            if (all[0].length() != 4 && all[1].length() != 2) {
                throw new Exception("year-month format was wrong. " + input + " given was not YYYY-MM");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("gYear")) {
        try {
            if (input.length() != 4) {
                throw new Exception("year-month format was wrong. " + input + " given was not YYYY-MM");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("gMonthDay")) {
        try {
            String[] all = input.split("-");
            // check them all
            if (all.length != 2) {
                throw new Exception("month-day did not have two parts.");
            }
            if (all[0].length() != 2 && all[1].length() != 2) {
                throw new Exception("month-day format was wrong. " + input + " given was not MM-dd");
            }
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause:" + e.getMessage());
        }
    } else if (expectedSparqlGraphType.equalsIgnoreCase("NODE_URI")) {
        try {
            // check that this looks like a URI
            URI uri = new URI(input);
        } catch (Exception e) {
            throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType
                    + "\" failed. assumed cause: " + e.getMessage());
        }

    }

    else {
        // assume it is cool for now.
    }

    return ret;
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

private static Duration parseVideoDuration(final String ffmpegOutput) throws IllegalArgumentException {
    final Pattern pattern = Pattern.compile("Duration: \\d\\d:\\d\\d:\\d\\d\\.\\d+");
    final Matcher matcher = pattern.matcher(ffmpegOutput);

    if (matcher.find()) {
        final String durationString = matcher.group();
        final String[] durationParts = durationString.substring("Duration: ".length()).split(":");
        final String hours = durationParts[0];
        final String minutes = durationParts[1];
        final String seconds = durationParts[2];

        return Duration.parse(String.format("PT%sH%sM%sS", hours, minutes, seconds));
    } else {/*from   www .j  av  a  2 s  .  c  o m*/
        throw new IllegalArgumentException("Video duration not found in FFmpeg output.");
    }
}

From source file:org.edgexfoundry.scheduling.ScheduleContext.java

private void parsePeriodAndDuration(String frequency) {

    int periodStart = frequency.indexOf('P');
    int timeStart = frequency.indexOf('T');
    String freq = frequency;/*from  w w  w .  j a  v a2  s. com*/

    this.period = Period.ZERO;
    this.duration = Duration.ZERO;

    // Parse out the period (date)
    try {
        // If there is a duration 'T', remove it
        if (timeStart != -1)
            freq = frequency.substring(periodStart, timeStart);
        this.period = Period.parse(freq);
    } catch (IndexOutOfBoundsException | DateTimeParseException e) {
        logger.error("parsePeriodAndDuration() failed to parse period from '" + freq + "'");
    }

    // Parse out the duration (time)
    try {
        // Make sure there is both a 'P' and 'T'
        if (periodStart != -1 && timeStart != -1) {
            freq = frequency.substring(timeStart, frequency.length());
            this.duration = Duration.parse("P" + freq);
        }
    } catch (IndexOutOfBoundsException | DateTimeParseException e) {
        logger.error("parsePeriodAndDuration() failed to parse duration from 'P" + freq + "'");
    }
}

From source file:org.hobbit.utils.rdf.RdfHelper.java

/**
 * Returns the object as {@link Duration} of the first triple that has the given
 * subject and predicate and that can be found in the given model.
 *
 * @param model//from ww w  .  j  a  v a 2 s.  co  m
 *            the model that should contain the triple
 * @param subject
 *            the subject of the triple. <code>null</code> works like a
 *            wildcard.
 * @param predicate
 *            the predicate of the triple. <code>null</code> works like a
 *            wildcard.
 * @return object of the triple as {@link Duration} or <code>null</code> if such
 *         a triple couldn't be found or the value can not be read as
 *         XSDDuration
 */
public static Duration getDurationValue(Model model, Resource subject, Property predicate) {
    if (model == null) {
        return null;
    }
    Literal literal = getLiteral(model, subject, predicate);
    if (literal != null) {
        try {
            return Duration.parse(literal.getString());
        } catch (Exception e) {
            // nothing to do
            LOGGER.debug("Couldn't parse \"" + literal.getString() + "\" as xsd:duration. Returning null.", e);
        }
    }
    return null;
}