Example usage for org.joda.time Period parse

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

Introduction

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

Prototype

@FromString
public static Period parse(String str) 

Source Link

Document

Parses a Period from the specified string.

Usage

From source file:ca.phon.session.io.xml.v12.XMLSessionReader_v12.java

License:Open Source License

private Participant copyParticipant(SessionFactory factory, ParticipantType pt, DateTime sessionDate) {
    final Participant retVal = factory.createParticipant();

    retVal.setId(pt.getId());/*from  w w  w.  java  2s . co m*/
    retVal.setName(pt.getName());

    final XMLGregorianCalendar bday = pt.getBirthday();
    if (bday != null) {
        final DateTime bdt = new DateTime(bday.getYear(), bday.getMonth(), bday.getDay(), 12, 0);
        retVal.setBirthDate(bdt);

        // calculate age up to the session date
        final Period period = new Period(bdt, sessionDate);
        retVal.setAgeTo(period);
    }

    final Duration ageDuration = pt.getAge();
    if (ageDuration != null) {
        // convert to period
        final Period age = Period.parse(ageDuration.toString());
        retVal.setAge(age);
    }

    retVal.setEducation(pt.getEducation());
    retVal.setGroup(pt.getGroup());

    String langs = "";
    for (String lang : pt.getLanguage())
        langs += (langs.length() > 0 ? ", " : "") + lang;
    retVal.setLanguage(langs);

    if (pt.getSex() == SexType.MALE)
        retVal.setSex(Sex.MALE);
    else if (pt.getSex() == SexType.FEMALE)
        retVal.setSex(Sex.FEMALE);
    else
        retVal.setSex(Sex.UNSPECIFIED);

    ParticipantRole prole = ParticipantRole.fromString(pt.getRole());
    if (prole == null)
        prole = ParticipantRole.TARGET_CHILD;
    retVal.setRole(prole);

    retVal.setSES(pt.getSES());

    return retVal;
}

From source file:com.almende.timecontrol.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 . j a va  2s. c om
 * 
 * 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
 */
public static final Measure<BigDecimal, Duration> parsePeriodOrMeasure(final String measure) {
    if (measure == 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 org.threeten.bp.Duration temp = org.threeten.bp.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())),
                            TimeControl.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);
            final Period joda = Period.parse(measure);
            result = DecimalMeasure.valueOf(BigDecimal.valueOf(joda.toStandardDuration().getMillis()),
                    TimeControl.MILLIS);
            // LOG.trace(
            // "Parsed '{}' using Joda to JSR-275 measure/unit: {}",
            // measure, result);
            return result;
        }
    }
}

From source file:com.arpnetworking.clusteraggregator.client.AggClientConnection.java

License:Apache License

private Optional<AggregatedData> getAggData(final Messages.LegacyAggRecord aggRecord) {
    try {/*from w  w  w .  jav  a 2s.  c  o  m*/
        long sampleCount = 1;
        if (aggRecord.hasRawSampleCount()) {
            sampleCount = aggRecord.getRawSampleCount();
        } else if (aggRecord.getStatisticSamplesCount() > 0) {
            sampleCount = aggRecord.getStatisticSamplesCount();
        }

        final Period period = Period.parse(aggRecord.getPeriod());
        DateTime periodStart;
        if (aggRecord.hasPeriodStart()) {
            periodStart = DateTime.parse(aggRecord.getPeriodStart());
        } else {
            periodStart = DateTime.now().withTime(DateTime.now().getHourOfDay(), 0, 0, 0);
            while (periodStart.plus(period).isBeforeNow()) {
                periodStart = periodStart.plus(period);
            }
        }

        final Optional<Statistic> statisticOptional = _statisticFactory
                .createStatistic(aggRecord.getStatistic());
        if (!statisticOptional.isPresent()) {
            _log.error(String.format("Unsupported statistic %s", aggRecord.getStatistic()));
            return Optional.absent();
        }

        return Optional.of(new AggregatedData.Builder().setHost(_hostName.get())
                .setFQDSN(new FQDSN.Builder().setCluster(_clusterName.get()).setService(aggRecord.getService())
                        .setMetric(aggRecord.getMetric()).setStatistic(statisticOptional.get()).build())
                .setPeriod(Period.parse(aggRecord.getPeriod())).setStart(periodStart)
                .setPopulationSize(sampleCount)
                .setSamples(sampleizeDoubles(aggRecord.getStatisticSamplesList(), Optional.<Unit>absent()))
                .setValue(new Quantity(aggRecord.getStatisticValue(), Optional.<Unit>absent())).build());
        // CHECKSTYLE.OFF: IllegalCatch - The legacy parsing can throw a variety of runtime exceptions
    } catch (final RuntimeException e) {
        // CHECKSTYLE.ON: IllegalCatch
        _log.error("Caught an error parsing legacy agg record", e);
        return Optional.absent();
    }
}

From source file:com.arpnetworking.clusteraggregator.client.AggClientConnection.java

License:Apache License

private Optional<AggregatedData> getAggData(final Messages.AggregationRecord aggRecord) {
    final Optional<Statistic> statisticOptional = _statisticFactory.createStatistic(aggRecord.getStatistic());
    if (!statisticOptional.isPresent()) {
        _log.error(String.format("Unsupported statistic %s", aggRecord.getStatistic()));
        return Optional.absent();
    }//from  w ww . j a  v  a 2s. c o  m
    final Optional<Unit> recordUnit;
    if (Strings.isNullOrEmpty(aggRecord.getUnit())) {
        recordUnit = Optional.absent();
    } else {
        recordUnit = Optional.fromNullable(Unit.valueOf(aggRecord.getUnit()));
    }
    final Quantity quantity = new Quantity(aggRecord.getStatisticValue(), recordUnit);
    return Optional.of(new AggregatedData.Builder().setHost(_hostName.get())
            .setFQDSN(new FQDSN.Builder().setService(aggRecord.getService()).setMetric(aggRecord.getMetric())
                    .setCluster(_clusterName.get()).setStatistic(statisticOptional.get()).build())
            .setPeriod(Period.parse(aggRecord.getPeriod())).setStart(DateTime.parse(aggRecord.getPeriodStart()))
            .setPopulationSize(aggRecord.getPopulationSize())
            .setSamples(sampleizeDoubles(aggRecord.getSamplesList(), recordUnit)).setValue(quantity).build());
}

From source file:com.brienwheeler.svc.users.impl.ForgottenPasswordService.java

License:Open Source License

@Required
public void setExpirationPeriod(String expirationPeriod) {
    this.expirationPeriod = Period.parse(expirationPeriod);
}

From source file:com.claresco.tinman.json.XapiResultJson.java

License:Open Source License

@Override
public XapiResult deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {
    JsonObject theResult = JsonUtility.convertJsonElementToJsonObject(arg0);

    XapiScore theScore = JsonUtility.delegateDeserialization(arg2,
            JsonUtility.findJsonElementWithKey(theResult, "score"), XapiScore.class);
    Boolean theSuccess = JsonUtility.getElementAsBool(theResult, "success");
    Boolean theCompletion = JsonUtility.getElementAsBool(theResult, "completion");
    String theResponse = JsonUtility.getElementAsString(theResult, "response");
    String theStringDuration = JsonUtility.getElementAsString(theResult, "duration");

    Period thePeriodDuration = null;
    Duration theDuration = null;/* w w  w. jav a2 s.c o  m*/
    try {
        if (theStringDuration != null) {
            thePeriodDuration = Period.parse(theStringDuration);
            theDuration = thePeriodDuration.toStandardDuration();
        }
    } catch (IllegalArgumentException e) {
        throw new XapiBadResultException("Invalid Duration");
    }

    XapiExtension theExtension = null;
    if (JsonUtility.hasElement(theResult, "extensions")) {
        theExtension = JsonUtility.delegateDeserialization(arg2, JsonUtility.get(theResult, "extensions"),
                XapiExtension.class);
    }

    XapiResult theResultObject = new XapiResult(theScore, theSuccess, theCompletion, theResponse, theDuration,
            theExtension);

    if (theResultObject.isEmpty()) {
        return null;
    }

    return theResultObject;
}

From source file:com.ibm.common.activitystreams.util.Converters.java

License:Apache License

/**
 * Method tryParseDuration./*w w  w  . j a va  2s  . c o  m*/
 * @param input String
 * @return Duration
 */
private static Duration tryParseDuration(String input) {
    try {
        return Period.parse(input).toDurationFrom(DateTime.now());
    } catch (Throwable t) {
        return null;
    }
}

From source file:com.ibm.common.activitystreams.util.Converters.java

License:Apache License

/**
 * Method tryParsePeriod.// ww  w  .j  av  a  2s .co  m
 * @param input String
 * @return Period
 */
private static Period tryParsePeriod(String input) {
    try {
        return Period.parse(input);
    } catch (Throwable t) {
        return null;
    }
}

From source file:com.thinkbiganalytics.metadata.api.sla.WithinSchedule.java

License:Apache License

public WithinSchedule(String cronExpression, String period) throws ParseException {
    this.cronExpression = new CronExpression(cronExpression);
    this.period = Period.parse(period);
    this.cronString = cronExpression;
    this.periodString = period;
}

From source file:com.yahoo.bard.webservice.web.apirequest.ApiRequestImpl.java

License:Apache License

/**
 * Extracts the set of intervals from the api request.
 *
 * @param now The 'now' for which time macros will be relatively calculated
 * @param apiIntervalQuery  API string containing the intervals in ISO 8601 format, values separated by ','.
 * @param granularity  The granularity to generate the date based on period or macros.
 * @param dateTimeFormatter  The formatter to parse date time interval segments
 *
 * @return Set of jodatime interval objects.
 * @throws BadApiRequestException if the requested interval is not found.
 *///  w  w w .j a v a 2 s  .  com
protected static List<Interval> generateIntervals(DateTime now, String apiIntervalQuery,
        Granularity granularity, DateTimeFormatter dateTimeFormatter) throws BadApiRequestException {
    try (TimedPhase timer = RequestLog.startTiming("GeneratingIntervals")) {
        List<Interval> generated = new ArrayList<>();
        if (apiIntervalQuery == null || apiIntervalQuery.equals("")) {
            LOG.debug(INTERVAL_MISSING.logFormat());
            throw new BadApiRequestException(INTERVAL_MISSING.format());
        }
        List<String> apiIntervals = Arrays.asList(apiIntervalQuery.split(","));
        // Split each interval string into the start and stop instances, parse them, and add the interval to the
        // list

        for (String apiInterval : apiIntervals) {
            String[] split = apiInterval.split("/");

            // Check for both a start and a stop
            if (split.length != 2) {
                String message = "Start and End dates are required.";
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, message));
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, message));
            }

            try {
                String start = split[0].toUpperCase(Locale.ENGLISH);
                String end = split[1].toUpperCase(Locale.ENGLISH);
                //If start & end intervals are period then marking as invalid interval.
                //Becacuse either one should be macro or actual date to generate an interval
                if (start.startsWith("P") && end.startsWith("P")) {
                    LOG.debug(INTERVAL_INVALID.logFormat(start));
                    throw new BadApiRequestException(INTERVAL_INVALID.format(apiInterval));
                }

                Interval interval;
                //If start interval is period, then create new interval with computed end date
                //possible end interval could be next,current, date
                if (start.startsWith("P")) {
                    interval = new Interval(Period.parse(start),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                    //If end string is period, then create an interval with the computed start date
                    //Possible start & end string could be a macro or an ISO 8601 DateTime
                } else if (end.startsWith("P")) {
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            Period.parse(end));
                } else {
                    //start and end interval could be either macros or actual datetime
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                }

                // Zero length intervals are invalid
                if (interval.toDuration().equals(Duration.ZERO)) {
                    LOG.debug(INTERVAL_ZERO_LENGTH.logFormat(apiInterval));
                    throw new BadApiRequestException(INTERVAL_ZERO_LENGTH.format(apiInterval));
                }
                generated.add(interval);
            } catch (IllegalArgumentException iae) {
                // Handle poor JodaTime message (special case)
                String internalMessage = iae.getMessage().equals("The end instant must be greater the start")
                        ? "The end instant must be greater than the start instant"
                        : iae.getMessage();
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, internalMessage), iae);
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, internalMessage),
                        iae);
            }
        }
        return generated;
    }
}