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:com.yahoo.bard.webservice.web.DataApiRequest.java

License:Apache License

/**
 * Extracts the set of intervals from the api request.
 *
 * @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  ww  .ja  v a2  s  .c o m
protected static Set<Interval> generateIntervals(String apiIntervalQuery, Granularity granularity,
        DateTimeFormatter dateTimeFormatter) throws BadApiRequestException {
    Set<Interval> generated = new LinkedHashSet<>();
    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;
            DateTime now = new DateTime();
            //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) {
            LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, iae.getMessage()), iae);
            throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, iae.getMessage()), iae);
        }
    }
    return generated;
}

From source file:com.yandex.money.api.model.showcase.components.uicontrols.Date.java

License:Open Source License

private static DateTime parseWithPeriod(String dateTime, String period, boolean add,
        DateTimeFormatter formatter) {
    return parseWithPeriod(parse(dateTime, formatter), Period.parse(period), add);
}

From source file:controllers.AlertController.java

License:Apache License

private Alert convertToInternalAlert(final models.view.Alert viewAlert) throws IOException {
    try {//from   w ww.  j a v a 2 s  .  co m
        final DefaultAlert.Builder alertBuilder = new DefaultAlert.Builder().setCluster(viewAlert.getCluster())
                .setMetric(viewAlert.getMetric()).setName(viewAlert.getName())
                .setService(viewAlert.getService()).setStatistic(viewAlert.getStatistic());
        if (viewAlert.getValue() != null) {
            alertBuilder.setValue(convertToInternalQuantity(viewAlert.getValue()));
        }
        if (viewAlert.getId() != null) {
            alertBuilder.setId(UUID.fromString(viewAlert.getId()));
        }
        if (viewAlert.getContext() != null) {
            alertBuilder.setContext(Context.valueOf(viewAlert.getContext()));
        }
        if (viewAlert.getOperator() != null) {
            alertBuilder.setOperator(Operator.valueOf(viewAlert.getOperator()));
        }
        if (viewAlert.getPeriod() != null) {
            alertBuilder.setPeriod(Period.parse(viewAlert.getPeriod()));
        }
        if (viewAlert.getExtensions() != null) {
            alertBuilder.setNagiosExtension(
                    convertToInternalNagiosExtension(viewAlert.getExtensions()).orElse(null));
        }
        return alertBuilder.build();
        // CHECKSTYLE.OFF: IllegalCatch - Translate any failure to bad input.
    } catch (final RuntimeException e) {
        // CHECKSTYLE.ON: IllegalCatch
        throw new IOException(e);
    }
}

From source file:de.fraunhofer.iosb.ilt.sta.query.expression.constant.DurationConstant.java

License:Open Source License

public DurationConstant(String value) {
    super(Period.parse(value));
}

From source file:dk.dma.ais.view.rest.QueryParameterHelper.java

License:Apache License

private static Long findMinimumDurationMS(UriInfo info) {
    String dur = QueryParameterValidators.getParameter(info, "minDuration", null);
    return dur == null ? null : Period.parse(dur).toStandardSeconds().getSeconds() * 1000L;
}

From source file:eagle.security.userprofile.UserProfileAggregatorExecutor.java

License:Apache License

@Override
public void init() {
    aggregator = new UserActivityAggregatorImpl(Arrays.asList(cmdFeatures), Period.parse(this.granularity),
            site, this.safeWindowMs);
}

From source file:gobblin.data.management.copy.hive.filter.LookbackPartitionFilterGenerator.java

License:Apache License

public LookbackPartitionFilterGenerator(Properties properties) {
    Preconditions.checkArgument(properties.containsKey(PARTITION_COLUMN), ERROR_MESSAGE);
    Preconditions.checkArgument(properties.containsKey(LOOKBACK), ERROR_MESSAGE);
    Preconditions.checkArgument(properties.containsKey(DATETIME_FORMAT), ERROR_MESSAGE);

    this.partitionColumn = properties.getProperty(PARTITION_COLUMN);
    this.lookback = Period.parse(properties.getProperty(LOOKBACK));
    this.formatter = DateTimeFormat.forPattern(properties.getProperty(DATETIME_FORMAT));
}

From source file:gobblin.example.wikipedia.WikipediaExtractor.java

License:Apache License

private long createLowWatermarkForBootstrap(WorkUnitState state) throws IOException {
    String bootstrapPeriodString = state.getProp(BOOTSTRAP_PERIOD, DEFAULT_BOOTSTRAP_PERIOD);
    Period period = Period.parse(bootstrapPeriodString);
    DateTime startTime = DateTime.now().minus(period);

    try {// w  w w.j  a  v  a 2 s  . c o  m
        Queue<JsonElement> firstRevision = retrievePageRevisions(ImmutableMap.<String, String>builder()
                .putAll(this.baseQuery).put("rvprop", "ids").put("titles", this.requestedTitle)
                .put("rvlimit", "1").put("rvstart", WIKIPEDIA_TIMESTAMP_FORMAT.print(startTime))
                .put("rvdir", "newer").build());
        if (firstRevision.isEmpty()) {
            throw new IOException("Could not retrieve oldest revision, returned empty revisions list.");
        }
        return parseRevision(firstRevision.poll());
    } catch (URISyntaxException use) {
        throw new IOException(use);
    }

}

From source file:gobblin.runtime.embedded.EmbeddedGobblin.java

License:Apache License

/**
 * Set the timeout for the Gobblin job execution from ISO-style period.
 *///from  w ww  . j  a  va2s  . c  o m
public EmbeddedGobblin setJobTimeout(String timeout) {
    return setJobTimeout(Period.parse(timeout).getSeconds(), TimeUnit.SECONDS);
}

From source file:gobblin.runtime.embedded.EmbeddedGobblin.java

License:Apache License

/**
 * Set the timeout for launching the Gobblin job from ISO-style period.
 *///  w  w w  .j  a v  a2s  . co  m
public EmbeddedGobblin setLaunchTimeout(String timeout) {
    return setLaunchTimeout(Period.parse(timeout).getSeconds(), TimeUnit.SECONDS);
}