Example usage for org.joda.time Period toStandardDuration

List of usage examples for org.joda.time Period toStandardDuration

Introduction

In this page you can find the example usage for org.joda.time Period toStandardDuration.

Prototype

public Duration toStandardDuration() 

Source Link

Document

Converts this period to a duration assuming a 7 day week, 24 hour day, 60 minute hour and 60 second minute.

Usage

From source file:org.apache.hadoop.hive.druid.json.KafkaSupervisorIOConfig.java

License:Apache License

@JsonCreator
public KafkaSupervisorIOConfig(@JsonProperty("topic") String topic, @JsonProperty("replicas") Integer replicas,
        @JsonProperty("taskCount") Integer taskCount, @JsonProperty("taskDuration") Period taskDuration,
        @JsonProperty("consumerProperties") Map<String, String> consumerProperties,
        @JsonProperty("startDelay") Period startDelay, @JsonProperty("period") Period period,
        @JsonProperty("useEarliestOffset") Boolean useEarliestOffset,
        @JsonProperty("completionTimeout") Period completionTimeout,
        @JsonProperty("lateMessageRejectionPeriod") Period lateMessageRejectionPeriod,
        @JsonProperty("earlyMessageRejectionPeriod") Period earlyMessageRejectionPeriod,
        @JsonProperty("skipOffsetGaps") Boolean skipOffsetGaps) {
    this.topic = Preconditions.checkNotNull(topic, "topic");
    this.consumerProperties = Preconditions.checkNotNull(consumerProperties, "consumerProperties");
    Preconditions.checkNotNull(consumerProperties.get(BOOTSTRAP_SERVERS_KEY),
            StringUtils.format("consumerProperties must contain entry for [%s]", BOOTSTRAP_SERVERS_KEY));

    this.replicas = replicas != null ? replicas : 1;
    this.taskCount = taskCount != null ? taskCount : 1;
    this.taskDuration = defaultDuration(taskDuration, "PT1H");
    this.startDelay = defaultDuration(startDelay, "PT5S");
    this.period = defaultDuration(period, "PT30S");
    this.useEarliestOffset = useEarliestOffset != null ? useEarliestOffset : false;
    this.completionTimeout = defaultDuration(completionTimeout, "PT30M");
    //noinspection Guava
    this.lateMessageRejectionPeriod = lateMessageRejectionPeriod == null ? Optional.absent()
            : Optional.of(lateMessageRejectionPeriod.toStandardDuration());
    //noinspection Guava
    this.earlyMessageRejectionPeriod = earlyMessageRejectionPeriod == null ? Optional.absent()
            : Optional.of(earlyMessageRejectionPeriod.toStandardDuration());
    this.skipOffsetGaps = skipOffsetGaps != null ? skipOffsetGaps : false;
}

From source file:org.apache.tamaya.jodatime.DurationConverter.java

License:Apache License

@Override
public Duration convert(String value, ConversionContext context) {
    String trimmed = Objects.requireNonNull(value).trim();
    context.addSupportedFormats(getClass(), "PTa.bS");
    context.addSupportedFormats(getClass(), "PdDThHmMsS");
    context.addSupportedFormats(getClass(), "ddThh:mm:ss");
    try {/*ww w. j  ava 2  s .  c o  m*/
        return Duration.parse(value);
    } catch (Exception e) {
        ConversionContext subContext = new ConversionContext.Builder(context.getConfiguration(),
                context.getKey(), context.getTargetType()).setValues(context.getValues()).build();
        Period period = null;
        if (value.startsWith("P")) {
            period = periodConverter.convert("P0Y0M0W" + value.substring(1), subContext);
        }
        if (period == null) {
            period = periodConverter.convert("P0000-00-" + value, subContext);
        }
        if (period != null) {
            return period.toStandardDuration();
        }
    }
    return null;
}

From source file:org.cook_e.cook_e.ui.StepDialogFragment.java

License:Open Source License

/**
 * Called when the user presses the positive (OK) button
 *
 * @return true to dismiss the dialog, false to continue displaying it
 *//*from  ww w.j a  v  a 2  s .c o m*/
private boolean onOkPressed() {
    final String description = mDescriptionField.getText().toString();
    final String durationString = mDurationField.getText().toString();
    final String ingredientsString = mIngredientsField.getText().toString();

    // Check required fields
    if (description.isEmpty()) {
        mDescriptionField.setError("Please enter a description");
        return false;
    }
    if (durationString.isEmpty()) {
        mDurationField.setError("Please enter a time");
        return false;
    }

    try {
        // Try to parse duration
        final Period period = mFormatter.parsePeriod(durationString);
        final Duration duration = period.toStandardDuration();

        // Parse ingredients
        final List<String> ingredients = ingredientsString.isEmpty() ? Collections.<String>emptyList()
                : Arrays.asList(ingredientsString.split("\n"));

        final Step step = new Step(ingredients, description, duration);

        // Pass the step to the parent
        ((StepEditListener) getActivity()).stepEditingFinished(step);
        return true;
    } catch (IllegalArgumentException e) {
        mDurationField.setError("Invalid time format");
        return false;
    } catch (UnsupportedOperationException e) {
        mDurationField.setError("Enter a time less than 1 month");
        return false;
    }
}

From source file:org.fao.geonet.domain.ISODate.java

License:Open Source License

public static String parseISODateTimes(String input1, String input2) {
    DateTimeFormatter dto = ISODateTimeFormat.dateTime();
    PeriodFormatter p = ISOPeriodFormat.standard();
    DateTime odt1;/*from w w w.j a v a  2  s. c om*/
    String odt = "";

    // input1 should be some sort of ISO time
    // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        DateTime idt = parseBasicOrFullDateTime(input1);
        odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
        odt = odt1.toString();

    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return DEFAULT_DATE_TIME;
    }

    if (input2 == null || input2.equals(""))
        return odt;

    // input2 can be an ISO time as for input1 but also an ISO time period
    // eg. -P3D or P3D - if an ISO time period then it must be added to the
    // DateTime generated for input1 (odt1)
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        boolean minus = false;
        if (input2.startsWith("-P")) {
            input2 = input2.substring(1);
            minus = true;
        }

        if (input2.startsWith("P")) {
            Period ip = p.parsePeriod(input2);
            DateTime odt2;
            if (!minus)
                odt2 = odt1.plus(ip.toStandardDuration().getMillis());
            else
                odt2 = odt1.minus(ip.toStandardDuration().getMillis());
            odt = odt + "|" + odt2.toString();
        } else {
            DateTime idt = parseBasicOrFullDateTime(input2);
            DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
            odt = odt + "|" + odt2.toString();
        }
    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return odt + "|" + DEFAULT_DATE_TIME;
    }

    return odt;
}

From source file:org.fao.geonet.util.JODAISODate.java

License:Open Source License

public static String parseISODateTimes(String input1, String input2) {
    DateTimeFormatter dto = ISODateTimeFormat.dateTime();
    PeriodFormatter p = ISOPeriodFormat.standard();
    DateTime odt1;/*from ww w. ja v a2s .  c om*/
    String odt = "";

    // input1 should be some sort of ISO time 
    // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        DateTime idt = parseBasicOrFullDateTime(input1);
        odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
        odt = odt1.toString();

    } catch (Exception e) {
        e.printStackTrace();
        return dt;
    }

    if (input2 == null || input2.equals(""))
        return odt;

    // input2 can be an ISO time as for input1 but also an ISO time period
    // eg. -P3D or P3D - if an ISO time period then it must be added to the
    // DateTime generated for input1 (odt1)
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        boolean minus = false;
        if (input2.startsWith("-P")) {
            input2 = input2.substring(1);
            minus = true;
        }

        if (input2.startsWith("P")) {
            Period ip = p.parsePeriod(input2);
            DateTime odt2;
            if (!minus)
                odt2 = odt1.plus(ip.toStandardDuration().getMillis());
            else
                odt2 = odt1.minus(ip.toStandardDuration().getMillis());
            odt = odt + "|" + odt2.toString();
        } else {
            DateTime idt = parseBasicOrFullDateTime(input2);
            DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
            odt = odt + "|" + odt2.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return odt + "|" + dt;
    }

    return odt;
}

From source file:org.graylog.plugin.filter.dns.DnsResolverFilter.java

License:Apache License

@Inject
public DnsResolverFilter(@Named("dns_resolver_timeout") Period resolverTimeout,
        @Named("dns_resolver_run_before_extractors") boolean shouldRunBeforeExtractors,
        @Named("dns_resolver_enabled") boolean enabled, MetricRegistry metricRegistry) {
    this.shouldRunBeforeExtractors = shouldRunBeforeExtractors;
    this.enabled = enabled;
    timeout = resolverTimeout.toStandardDuration().getMillis();
    timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("dns-resolver-thread-%d").build()));
    this.resolveTime = metricRegistry.timer(name(DnsResolverFilter.class, "resolveTime"));
    this.resolveTimeouts = metricRegistry.meter(name(DnsResolverFilter.class, "resolveTimeouts"));
}

From source file:org.jbpm.process.core.timer.DateTimeUtils.java

License:Apache License

public static long parseDuration(String durationStr) {
    if (isPeriod(durationStr)) {
        Period p = ISOPeriodFormat.standard().parsePeriod(durationStr);
        return p.toStandardDuration().getMillis();
    } else {/*w  ww  . j  av a  2 s. c  om*/
        return TimeUtils.parseTimeString(durationStr);
    }
}

From source file:org.jbpm.process.core.timer.DateTimeUtils.java

License:Apache License

public static long[] parseRepeatableDateTime(String dateTimeStr) {
    long[] result = new long[3];
    if (isRepeatable(dateTimeStr)) {

        String[] parsed = parseISORepeatable(dateTimeStr);
        String repeats = parsed[0];
        String delayIn = parsed[1];
        String periodIn = parsed[2];

        DateTime startAtDelay = ISODateTimeFormat.dateTimeParser().parseDateTime(delayIn);
        Duration startAtDelayDur = new Duration(System.currentTimeMillis(), startAtDelay.getMillis());
        if (startAtDelayDur.getMillis() <= 0) {
            // need to introduce delay to allow all initialization
            startAtDelayDur = Duration.standardSeconds(1);
        }//from w  ww  . j a v  a  2 s  .  co m
        Period period = ISOPeriodFormat.standard().parsePeriod(periodIn);
        result[0] = Long.parseLong(repeats.length() == 0 ? "-1" : repeats);
        result[1] = startAtDelayDur.getMillis();
        result[2] = period.toStandardDuration().getMillis();

        return result;
    } else {

        int index = dateTimeStr.indexOf("###");
        if (index != -1) {
            String period = dateTimeStr.substring(index + 3);
            String delay = dateTimeStr.substring(0, index);
            result = new long[] { TimeUtils.parseTimeString(delay), TimeUtils.parseTimeString(period) };

            return result;
        }
        result = new long[] { TimeUtils.parseTimeString(dateTimeStr) };
        return result;
    }
}

From source file:org.kalypso.model.rcm.RainfallGenerationOp.java

License:Open Source License

/**
 * Check if all timeseries that get combined here have the same timestep<br/>
 * Necessary, because the timestep of the combined timeseries is the timestep of the first timseries.
 *//* w  ww .  j ava2s . c o  m*/
private static void checkCombinedTimestep(final IObservation[] observations) throws CoreException {
    Period combinedTimestep = null;
    for (final IObservation observation : observations) {
        final Period currentTimestep = MetadataHelper.getTimestep(observation.getMetadataList());

        final boolean hasValues = hasValues(observation);
        if (currentTimestep == null && hasValues) {
            final IStatus status = new Status(IStatus.ERROR, KalypsoModelRcmActivator.PLUGIN_ID,
                    Messages.getString("RainfallGenerationOp_5")); //$NON-NLS-1$
            throw new CoreException(status);
        }

        if (combinedTimestep != null) {
            final Duration currentDuration = currentTimestep.toStandardDuration();
            final Duration combinedDuration = combinedTimestep.toStandardDuration();
            if (!currentDuration.equals(combinedDuration)) {
                final String message = String.format(Messages.getString("RainfallGenerationOp_6"), //$NON-NLS-1$
                        combinedTimestep, currentTimestep);
                final IStatus status = new Status(IStatus.ERROR, KalypsoModelRcmActivator.PLUGIN_ID, message);
                throw new CoreException(status);
            }
        }

        combinedTimestep = currentTimestep;
    }
}

From source file:org.ldp4j.application.data.Literals.java

License:Apache License

private static <T> DurationLiteral coherceDuration(T value) {
    DurationLiteral duration = null;//from   w  ww.j  a  v  a2 s. co  m
    if (value instanceof Duration) {
        duration = of((Duration) value);
    } else if (value instanceof javax.xml.datatype.Duration) {
        duration = of((javax.xml.datatype.Duration) value);
    } else if (value instanceof String) {
        try {
            Period period = ISOPeriodFormat.standard().parsePeriod((String) value);
            duration = of(period.toStandardDuration());
        } catch (Exception e) {
            throw new DatatypeCohercionException(value, Datatypes.DURATION, e);
        }
    } else {
        throw new DatatypeCohercionException(value, Datatypes.DURATION);
    }
    return duration;
}