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:com.tkmtwo.timex.WallClock.java

License:Apache License

/**
 * Returns a copy of this <code>WallClock</code> minus
 * the specified <code>Period</code>.
 * <p>/*from   w  w w  . j  a  va  2s.  c  om*/
 *
 * <code>Period.toStandardDuration()</code> is used
 * to calculate seconds.
 * <p>
 *
 * @param p an <code>Period</code> representing the amount of time
 * @return a <code>WallClock</code> value
 */
public WallClock minus(Period p) {
    checkNotNull(p, "Need a Period.");
    return minus(p.toStandardDuration());
}

From source file:com.worktoken.engine.TimeExpression.java

License:Apache License

/**
 * Calculates alarm date for time duration elements
 *
 * @return Alarm date or null, if alarm date is in the past
 *///w ww .  j a  va  2  s  .  com
public Date calculateDurationAlarmDate() {
    DateTime now = new DateTime();
    if (endDate != null) {
        return endDate;
    }
    Date start;
    if (startDate != null) {
        start = startDate;
    } else if (duration != null) {
        start = now.toDate();
    } else {
        throw new IllegalStateException("Invalid duration definition");
    }
    Period period = new Period(duration);
    Duration dur = period.toStandardDuration();
    DateTime alarm;
    if (dur.getStandardSeconds() > 24 * 60 * 60) {
        alarm = new DateTime(start).plus(period);
    } else {
        alarm = new DateTime(start).plus(dur);
    }
    if (alarm.isBefore(now)) {
        return null;
    }
    return alarm.toDate();
}

From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

License:Open Source License

/**
 * Sets the scheme./*from   ww w  .j  av a2 s.c  om*/
 * 
 * @param scheme the scheme
 * 
 * @return the file system options
 * 
 * @throws MotuException the motu exception
 */
public FileSystemOptions setSchemeOpts(String scheme, String host) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("setSchemeOpts(String, String) - start");
    }

    if (Organizer.isNullOrEmpty(scheme)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("setSchemeOpts(String, String) - end");
        }
        return opts;
    }

    if (opts == null) {
        opts = new FileSystemOptions();
    }

    FileSystemConfigBuilder fscb = null;
    MotuConfigFileSystemWrapper<Boolean> wrapperBoolean = new MotuConfigFileSystemWrapper<Boolean>();
    MotuConfigFileSystemWrapper<Period> wrapperPeriod = new MotuConfigFileSystemWrapper<Period>();
    MotuConfigFileSystemWrapper<String> wrapperString = new MotuConfigFileSystemWrapper<String>();

    try {
        try {
            fscb = standardFileSystemManager.getFileSystemConfigBuilder(scheme);
        } catch (FileSystemException e) {
            LOG.error("setSchemeOpts(String)", e);

            fscb = standardFileSystemManager.getFileSystemConfigBuilder(VFSManager.DEFAULT_SCHEME);
        }

        if (fscb instanceof FtpFileSystemConfigBuilder) {
            FtpFileSystemConfigBuilder ftpFscb = (FtpFileSystemConfigBuilder) fscb;
            Boolean userDirIsRoot = wrapperBoolean.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_FTPUSERDIRISROOT);
            if (userDirIsRoot != null) {
                ftpFscb.setUserDirIsRoot(opts, userDirIsRoot);
            } else {
                ftpFscb.setUserDirIsRoot(opts, false);
            }

            Boolean passiveMode = wrapperBoolean.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_FTPPASSIVEMODE);
            ;
            if (passiveMode != null) {
                ftpFscb.setPassiveMode(opts, passiveMode);
            }
            Period dataTimeOut = wrapperPeriod.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_FTPDATATIMEOUT);
            if (dataTimeOut != null) {
                long value = dataTimeOut.toStandardDuration().getMillis();
                if (value > Integer.MAX_VALUE) {
                    throw new MotuException(String.format(
                            "Motu Configuration : sftp timeout value is too large '%ld' milliseconds. Max is '%d'",
                            value, Integer.MAX_VALUE));
                }
                if (value > 0) {
                    ftpFscb.setDataTimeout(opts, (int) value);
                }
            }
        }

        if (fscb instanceof HttpFileSystemConfigBuilder) {
            HttpFileSystemConfigBuilder httpFscb = (HttpFileSystemConfigBuilder) fscb;

            Boolean isUseProxy = wrapperBoolean.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_USEHTTPPROXY);
            if ((isUseProxy != null) && (isUseProxy)) {
                String proxyHost = wrapperString.getFieldValue(host,
                        MotuConfigFileSystemWrapper.PROP_HTTPPROXYHOST);
                String proxyPort = wrapperString.getFieldValue(host,
                        MotuConfigFileSystemWrapper.PROP_HTTPPROXYPORT);
                httpFscb.setProxyHost(opts, proxyHost);
                httpFscb.setProxyPort(opts, Integer.parseInt(proxyPort));
            }

        }

        if (fscb instanceof SftpFileSystemConfigBuilder) {
            SftpFileSystemConfigBuilder sftpFscb = (SftpFileSystemConfigBuilder) fscb;

            Boolean userDirIsRoot = wrapperBoolean.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_SFTPUSERDIRISROOT);
            if (userDirIsRoot != null) {
                sftpFscb.setUserDirIsRoot(opts, userDirIsRoot);
            } else {
                sftpFscb.setUserDirIsRoot(opts, false);
            }

            String strictHostKeyChecking = wrapperString.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_STRICTHOSTKEYCHECKING);
            if (strictHostKeyChecking != null) {
                sftpFscb.setStrictHostKeyChecking(opts, strictHostKeyChecking);
            }

            Period SftpSessionTimeOut = wrapperPeriod.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_SFTPSESSIONTIMEOUT);
            if (SftpSessionTimeOut != null) {
                long value = SftpSessionTimeOut.toStandardDuration().getMillis();
                if (value > Integer.MAX_VALUE) {
                    throw new MotuException(String.format(
                            "Motu Configuration : sftp timeout value is too large '%ld' milliseconds. Max is '%d'",
                            value, Integer.MAX_VALUE));
                }
                if (value > 0) {
                    sftpFscb.setTimeout(opts, (int) value);
                }
            }

            Boolean isUseProxy = wrapperBoolean.getFieldValue(host,
                    MotuConfigFileSystemWrapper.PROP_USESFTPPROXY);
            if ((isUseProxy != null) && (isUseProxy)) {
                String proxyHost = wrapperString.getFieldValue(host,
                        MotuConfigFileSystemWrapper.PROP_SFTPPROXYHOST);
                String proxyPort = wrapperString.getFieldValue(host,
                        MotuConfigFileSystemWrapper.PROP_SFTPPROXYPORT);
                sftpFscb.setProxyHost(opts, proxyHost);
                sftpFscb.setProxyPort(opts, Integer.parseInt(proxyPort));
            }

        }

    } catch (FileSystemException e) {
        LOG.error("setSchemeOpts(String, String)", e);

        throw new MotuException("Error in VFSManager#setScheme", e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("setSchemeOpts(String, String) - end");
    }
    return opts;
}

From source file:io.coala.time.TimeSpan.java

License:Apache License

/**
 * Parse duration as {@link DecimalMeasure JSR-275} measure (e.g.
 * {@code "123 ms"}) or as ISO Period with
 * {@link org.threeten.bp.Duration#parse(CharSequence) JSR-310} or
 * {@link Period#parse(String) Joda}./*from  w w w.  ja v a 2  s  . c  o m*/
 * 
 * Examples of ISO period:
 * 
 * <pre>
 *    "PT20.345S" -> parses as "20.345 seconds"
 *    "PT15M"     -> parses as "15 minutes" (where a minute is 60 seconds)
 *    "PT10H"     -> parses as "10 hours" (where an hour is 3600 seconds)
 *    "P2D"       -> parses as "2 days" (where a day is 24 hours or 86400 seconds)
 *    "P2DT3H4M"  -> parses as "2 days, 3 hours and 4 minutes"
 *    "P-6H3M"    -> parses as "-6 hours and +3 minutes"
 *    "-P6H3M"    -> parses as "-6 hours and -3 minutes"
 *    "-P-6H+3M"  -> parses as "+6 hours and -3 minutes"
 * </pre>
 * 
 * @param measure the {@link String} representation of a duration
 * @return
 * 
 * @see org.threeten.bp.Duration#parse(String)
 * @see org.joda.time.format.ISOPeriodFormat#standard()
 * @see DecimalMeasure
 */
protected static final Measure<BigDecimal, Duration> parsePeriodOrMeasure(final String measure) {
    if (measure == null)
        return null;//throw new NullPointerException();
    DecimalMeasure<Duration> result;
    try {
        result = DecimalMeasure.valueOf(measure + " ");
        // LOG.trace("Parsed '{}' as JSR-275 measure/unit: {}", measure,
        // result);
        return result;
    } catch (final Exception a) {
        // LOG.trace("JSR-275 failed, try JSR-310", e);
        try {
            // final long millis = Period.parse(measure).getMillis();
            // return DecimalMeasure.valueOf(BigDecimal.valueOf(millis),
            // SI.MILLI(SI.SECOND));
            final java.time.Duration temp = java.time.Duration.parse(measure);
            result = temp.getNano() == 0
                    ? DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds()), SI.SECOND)
                    : DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds())
                            .multiply(BigDecimal.TEN.pow(9)).add(BigDecimal.valueOf(temp.getNano())),
                            Units.NANOS);
            // LOG.trace(
            // "Parsed '{}' using JSR-310 to JSR-275 measure/unit: {}",
            // measure, result);
            return result;
        } catch (final Exception e) {
            // LOG.trace("JSR-275 and JSR-310 failed, try Joda", e);
            try {
                final Period joda = Period.parse(measure);
                result = DecimalMeasure.valueOf(BigDecimal.valueOf(joda.toStandardDuration().getMillis()),
                        Units.MILLIS);
                // LOG.trace(
                // "Parsed '{}' using Joda to JSR-275 measure/unit: {}",
                // measure, result);
                return result;
            } catch (final Exception j) {
                return Thrower.throwNew(IllegalArgumentException.class,
                        "Could not parse duration or period from: {}"
                                + ", JSR-275: {}, JSR-310: {}, Joda-time: {}",
                        measure, a.getMessage(), e.getMessage(), j.getMessage());
            }
        }
    }
}

From source file:io.druid.client.HttpServerInventoryViewConfig.java

License:Apache License

@JsonCreator
public HttpServerInventoryViewConfig(@JsonProperty("serverTimeout") Period serverTimeout,
        @JsonProperty("serverUnstabilityTimeout") Period serverUnstabilityTimeout,
        @JsonProperty("numThreads") Integer numThreads) {
    this.serverTimeout = serverTimeout != null ? serverTimeout.toStandardDuration().getMillis()
            : TimeUnit.MINUTES.toMillis(4);

    this.serverUnstabilityTimeout = serverUnstabilityTimeout != null
            ? serverUnstabilityTimeout.toStandardDuration().getMillis()
            : TimeUnit.MINUTES.toMillis(1);

    this.numThreads = numThreads != null ? numThreads.intValue() : 5;

    Preconditions.checkArgument(this.serverTimeout > 0, "server timeout must be > 0 ms");
    Preconditions.checkArgument(this.numThreads > 1, "numThreads must be > 1");
}

From source file:io.druid.indexing.common.config.TaskStorageConfig.java

License:Apache License

@JsonCreator
public TaskStorageConfig(@JsonProperty("recentlyFinishedThreshold") Period period) {
    if (period != null) {
        this.recentlyFinishedThreshold = period.toStandardDuration();
    }/*w  w  w  .j av a 2 s . co  m*/
}

From source file:io.druid.indexing.jdbc.supervisor.JDBCSupervisorIOConfig.java

License:Apache License

@JsonCreator
public JDBCSupervisorIOConfig(@JsonProperty("table") String table, @JsonProperty("user") String user,
        @JsonProperty("password") String password, @JsonProperty("connectURI") String connectURI,
        @JsonProperty("driverClass") String driverClass, @JsonProperty("replicas") Integer replicas,
        @JsonProperty("taskCount") Integer taskCount, @JsonProperty("taskDuration") Period taskDuration,
        @JsonProperty("startDelay") Period startDelay, @JsonProperty("period") Period period,
        @JsonProperty("completionTimeout") Period completionTimeout,
        @JsonProperty("lateMessageRejectionPeriod") Period lateMessageRejectionPeriod,
        @JsonProperty("jdbcOffsets") JDBCOffsets jdbcOffsets, @JsonProperty("query") String query,
        @JsonProperty("columns") List<String> columns, @JsonProperty("interval") int interval) {
    this.table = Preconditions.checkNotNull(table, "table");
    this.user = Preconditions.checkNotNull(user, "user");
    this.password = Preconditions.checkNotNull(password, "password");
    this.connectURI = Preconditions.checkNotNull(connectURI, "jdbc:derby:memory:myDB;create=true");
    this.driverClass = Preconditions.checkNotNull(driverClass, "org.apache.derby.jdbc.EmbeddedDriver");
    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.completionTimeout = defaultDuration(completionTimeout, "PT30M");
    this.lateMessageRejectionPeriod = lateMessageRejectionPeriod == null ? Optional.<Duration>absent()
            : Optional.of(lateMessageRejectionPeriod.toStandardDuration());
    this.jdbcOffsets = jdbcOffsets;
    this.query = query;
    this.columns = columns;
    this.interval = interval;
}

From source file:io.druid.indexing.kafka.supervisor.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("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");
    this.lateMessageRejectionPeriod = lateMessageRejectionPeriod == null ? Optional.<Duration>absent()
            : Optional.of(lateMessageRejectionPeriod.toStandardDuration());
    this.skipOffsetGaps = skipOffsetGaps != null ? skipOffsetGaps : false;
}

From source file:io.druid.query.IntervalChunkingQueryRunner.java

License:Apache License

@Override
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) {
    final Period chunkPeriod = getChunkPeriod(query);
    if (chunkPeriod.toStandardDuration().getMillis() == 0) {
        return baseRunner.run(query, responseContext);
    }/* www  .j  av a  2  s . co  m*/

    List<Interval> chunkIntervals = Lists.newArrayList(FunctionalIterable.create(query.getIntervals())
            .transformCat(new Function<Interval, Iterable<Interval>>() {
                @Override
                public Iterable<Interval> apply(Interval input) {
                    return splitInterval(input, chunkPeriod);
                }
            }));

    if (chunkIntervals.size() <= 1) {
        return baseRunner.run(query, responseContext);
    }

    return Sequences.concat(Lists.newArrayList(
            FunctionalIterable.create(chunkIntervals).transform(new Function<Interval, Sequence<T>>() {
                @Override
                public Sequence<T> apply(Interval singleInterval) {
                    return new AsyncQueryRunner<T>(
                            //Note: it is assumed that toolChest.mergeResults(..) gives a query runner that is
                            //not lazy i.e. it does most of its work on call to run() method
                            toolChest.mergeResults(new MetricsEmittingQueryRunner<T>(emitter,
                                    new Function<Query<T>, ServiceMetricEvent.Builder>() {
                                        @Override
                                        public ServiceMetricEvent.Builder apply(Query<T> input) {
                                            return toolChest.makeMetricBuilder(input);
                                        }
                                    }, baseRunner, "query/intervalChunk/time",
                                    ImmutableMap.of("chunkInterval", singleInterval.toString()))
                                            .withWaitMeasuredFromNow()),
                            executor, queryWatcher)
                                    .run(query.withQuerySegmentSpec(
                                            new MultipleIntervalSegmentSpec(Arrays.asList(singleInterval))),
                                            responseContext);
                }
            })));
}

From source file:io.druid.query.TimewarpOperator.java

License:Apache License

/**
 *
 * @param dataInterval interval containing the actual data
 * @param period time will be offset by a multiple of the given period
 *               until there is at least a full period ending within the data interval
 * @param origin origin to be used to align time periods
 *               (e.g. to determine on what day of the week a weekly period starts)
 *///  w w  w.j  a v  a2  s  .c  om
@JsonCreator
public TimewarpOperator(@JsonProperty("dataInterval") Interval dataInterval,
        @JsonProperty("period") Period period, @JsonProperty("origin") DateTime origin) {
    this.originMillis = origin.getMillis();
    this.dataInterval = dataInterval;
    // this will fail for periods that do not map to millis (e.g. P1M)
    this.periodMillis = period.toStandardDuration().getMillis();
}