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:gobblin.runtime.embedded.EmbeddedGobblin.java

License:Apache License

/**
 * Set the timeout for shutting down the Gobblin instance driver after the job is done from ISO-style period.
 *//*from   ww  w  .  j  ava2  s . co  m*/
public EmbeddedGobblin setShutdownTimeout(String timeout) {
    return setShutdownTimeout(Period.parse(timeout).getSeconds(), TimeUnit.SECONDS);
}

From source file:google.registry.tools.params.DurationParameter.java

License:Open Source License

@Override
public Duration convert(String value) {
    return Period.parse(value).toStandardDuration();
}

From source file:google.registry.xml.PeriodAdapter.java

License:Open Source License

@Nullable
@Override
public Period unmarshal(@Nullable String periodString) {
    return isNullOrEmpty(periodString) ? null : Period.parse(periodString);
}

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}./* ww  w .j av a2 s. 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
 */
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.query.IntervalChunkingQueryRunner.java

License:Apache License

private Period getChunkPeriod(Query<T> query) {
    String p = query.getContextValue(QueryContextKeys.CHUNK_PERIOD, "P0D");
    return Period.parse(p);
}

From source file:jobs.YoutubeJob.java

License:Open Source License

public static YouTubeVideo getDetails(YouTubeVideo youVideo, String videoID) {
    //String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/"+videoID;

    // Logger.info("Getting duration for " + videoID);

    try {/*from   w  w  w . j a  v  a2 s. co  m*/
        YouTube.Videos.List listVideosRequest = youtube.videos().list("contentDetails").setId(videoID);

        listVideosRequest.setKey(key);
        VideoListResponse listResponse = listVideosRequest.execute();

        List<Video> videoList = listResponse.getItems();
        if (videoList.isEmpty()) {
            System.out.println("Can't find a video with ID: " + videoID);
            return null;
        }

        // Extract the snippet from the video resource.
        Video video = videoList.get(0);
        // Logger.info(video.toString());
        // VideoFileDetails details = video.getFileDetails();
        //Logger.info("Details" + details);
        // Logger.info("CD" + video.getContentDetails());
        // Logger.info("String duration" + video.getContentDetails().getDuration());

        int boo = Period.parse(video.getContentDetails().getDuration()).toStandardSeconds().getSeconds(); // Milliseconds

        //Logger.info("Long duration" + boo);
        // int duration = 3000; //details.getDurationMs().intValue();
        //youVideo.bitrateBps = video.getFileDetails().getBitrateBps().longValue();

        youVideo.duration = boo;
        youVideo.save();

        return youVideo;

    } catch (Exception e) {
        Logger.info("Exception: " + e.getMessage());
        e.printStackTrace();
    }
    return youVideo;
}

From source file:org.activiti.engine.impl.calendar.DueDateBusinessCalendar.java

License:Apache License

@Override
public Date resolveDuedate(String duedate, int maxIterations) {
    try {/*w w  w  . j  av  a2  s.c  o  m*/
        // check if due period was specified
        if (duedate.startsWith("P")) {
            return DateTime.now().plus(Period.parse(duedate)).toDate();
        }

        return DateTime.parse(duedate).toDate();

    } catch (Exception e) {
        throw new ActivitiException("couldn't resolve duedate: " + e.getMessage(), e);
    }
}

From source file:org.angnysa.yaba.dao.impl.FileTransactionDefinitionDao.java

License:Open Source License

private XStream newXStream() {
    XStream xs = new XStream();

    xs.alias("transaction", TransactionDefinition.class);
    xs.alias("date", LocalDate.class);

    xs.useAttributeFor(TransactionDefinition.class, "id");
    xs.useAttributeFor(TransactionDefinition.class, "label");
    xs.useAttributeFor(TransactionDefinition.class, "date");
    xs.useAttributeFor(TransactionDefinition.class, "period");
    xs.useAttributeFor(TransactionDefinition.class, "end");
    xs.useAttributeFor(TransactionDefinition.class, "amount");

    xs.registerConverter(new SingleValueConverter() {

        @Override/*from w w  w .j av a 2s . c o  m*/
        public boolean canConvert(@SuppressWarnings("rawtypes") Class c) {
            return c.equals(LocalDate.class);
        }

        @Override
        public String toString(Object obj) {
            return ((LocalDate) obj).toString();
        }

        @Override
        public Object fromString(String str) {
            return LocalDate.parse(str);
        }
    });

    xs.registerConverter(new SingleValueConverter() {

        @Override
        public boolean canConvert(@SuppressWarnings("rawtypes") Class c) {
            return c.equals(ReadablePeriod.class);
        }

        @Override
        public String toString(Object obj) {
            return ((ReadablePeriod) obj).toString();
        }

        @Override
        public Object fromString(String str) {
            return Period.parse(str);
        }
    });

    return xs;
}

From source file:org.apache.drill.exec.record.metadata.PrimitiveColumnMetadata.java

License:Apache License

/**
 * Converts value in string literal form into Object instance based on {@link MinorType} value.
 * Returns null in case of error during parsing or unsupported type.
 *
 * @param value value in string literal form
 * @return Object instance//from   ww  w .j  av a  2 s.  co m
 */
private Object valueFromString(String value) {
    if (value == null) {
        return null;
    }
    try {
        switch (type) {
        case INT:
            return Integer.parseInt(value);
        case BIGINT:
            return Long.parseLong(value);
        case FLOAT4:
            return Float.parseFloat(value);
        case FLOAT8:
            return Double.parseDouble(value);
        case VARDECIMAL:
            return new BigDecimal(value);
        case BIT:
            return Boolean.parseBoolean(value);
        case VARCHAR:
        case VARBINARY:
            return value;
        case TIME:
            DateTimeFormatter timeFormatter = formatValue == null
                    ? DateTimeFormatter.ISO_TIME.withZone(ZoneOffset.UTC)
                    : DateTimeFormatter.ofPattern(formatValue);
            return LocalTime.parse(value, timeFormatter);
        case DATE:
            DateTimeFormatter dateFormatter = formatValue == null
                    ? DateTimeFormatter.ISO_DATE.withZone(ZoneOffset.UTC)
                    : DateTimeFormatter.ofPattern(formatValue);
            return LocalDate.parse(value, dateFormatter);
        case TIMESTAMP:
            DateTimeFormatter dateTimeFormatter = formatValue == null
                    ? DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC)
                    : DateTimeFormatter.ofPattern(formatValue);
            return ZonedDateTime.parse(value, dateTimeFormatter);
        case INTERVAL:
        case INTERVALDAY:
        case INTERVALYEAR:
            return Period.parse(value);
        default:
            logger.warn("Unsupported type {} for default value {}, ignore and return null", type, value);
            return null;
        }
    } catch (IllegalArgumentException | DateTimeParseException e) {
        logger.warn("Error while parsing type {} default value {}, ignore and return null", type, value, e);
        return null;
    }
}

From source file:org.apache.druid.data.input.parquet.simple.ParquetGroupConverter.java

License:Apache License

/**
 * Convert a primitive group field to a "ingestion friendly" java object
 *
 * @return "ingestion ready" java object, or null
 *//*from   w ww. j a v a2s.  c o m*/
@Nullable
private static Object convertPrimitiveField(Group g, int fieldIndex, int index, boolean binaryAsString) {
    PrimitiveType pt = (PrimitiveType) g.getType().getFields().get(fieldIndex);
    OriginalType ot = pt.getOriginalType();

    try {
        if (ot != null) {
            // convert logical types
            switch (ot) {
            case DATE:
                long ts = g.getInteger(fieldIndex, index) * MILLIS_IN_DAY;
                return ts;
            case TIME_MICROS:
                return g.getLong(fieldIndex, index);
            case TIME_MILLIS:
                return g.getInteger(fieldIndex, index);
            case TIMESTAMP_MICROS:
                return TimeUnit.MILLISECONDS.convert(g.getLong(fieldIndex, index), TimeUnit.MICROSECONDS);
            case TIMESTAMP_MILLIS:
                return g.getLong(fieldIndex, index);
            case INTERVAL:
                /*
                INTERVAL is used for an interval of time. It must annotate a fixed_len_byte_array of length 12.
                This array stores three little-endian unsigned integers that represent durations at different
                granularities of time. The first stores a number in months, the second stores a number in days,
                and the third stores a number in milliseconds. This representation is independent of any particular
                timezone or date.
                        
                Each component in this representation is independent of the others. For example, there is no
                requirement that a large number of days should be expressed as a mix of months and days because there is
                not a constant conversion from days to months.
                        
                The sort order used for INTERVAL is undefined. When writing data, no min/max statistics should be
                 saved for this type and if such non-compliant statistics are found during reading, they must be ignored.
                 */
                Binary intervalVal = g.getBinary(fieldIndex, index);
                IntBuffer intBuf = intervalVal.toByteBuffer().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
                int months = intBuf.get(0);
                int days = intBuf.get(1);
                int millis = intBuf.get(2);
                StringBuilder periodBuilder = new StringBuilder("P");
                if (months > 0) {
                    periodBuilder.append(months).append("M");
                }
                if (days > 0) {
                    periodBuilder.append(days).append("D");
                }
                if (periodBuilder.length() > 1) {
                    Period p = Period.parse(periodBuilder.toString());
                    Duration d = p.toStandardDuration().plus(millis);
                    return d;
                } else {
                    return new Duration(millis);
                }
            case INT_8:
            case INT_16:
            case INT_32:
                return g.getInteger(fieldIndex, index);
            case INT_64:
                return g.getLong(fieldIndex, index);
            // todo: idk wtd about unsigned
            case UINT_8:
            case UINT_16:
            case UINT_32:
                return g.getInteger(fieldIndex, index);
            case UINT_64:
                return g.getLong(fieldIndex, index);
            case DECIMAL:
                /*
                  DECIMAL can be used to annotate the following types:
                    int32: for 1 <= precision <= 9
                    int64: for 1 <= precision <= 18; precision < 10 will produce a warning
                    fixed_len_byte_array: precision is limited by the array size. Length n can
                      store <= floor(log_10(2^(8*n - 1) - 1)) base-10 digits
                    binary: precision is not limited, but is required. The minimum number of bytes to store
                      the unscaled value should be used.
                 */
                int precision = pt.asPrimitiveType().getDecimalMetadata().getPrecision();
                int scale = pt.asPrimitiveType().getDecimalMetadata().getScale();
                switch (pt.getPrimitiveTypeName()) {
                case INT32:
                    return new BigDecimal(g.getInteger(fieldIndex, index));
                case INT64:
                    return new BigDecimal(g.getLong(fieldIndex, index));
                case FIXED_LEN_BYTE_ARRAY:
                case BINARY:
                    Binary value = g.getBinary(fieldIndex, index);
                    return convertBinaryToDecimal(value, precision, scale);
                default:
                    throw new RE(
                            "Unknown 'DECIMAL' type supplied to primitive conversion: %s (this should never happen)",
                            pt.getPrimitiveTypeName());
                }
            case UTF8:
            case ENUM:
            case JSON:
                return g.getString(fieldIndex, index);
            case LIST:
            case MAP:
            case MAP_KEY_VALUE:
            case BSON:
            default:
                throw new RE("Non-primitive supplied to primitive conversion: %s (this should never happen)",
                        ot.name());
            }
        } else {
            // fallback to handling the raw primitive type if no logical type mapping
            switch (pt.getPrimitiveTypeName()) {
            case BOOLEAN:
                return g.getBoolean(fieldIndex, index);
            case INT32:
                return g.getInteger(fieldIndex, index);
            case INT64:
                return g.getLong(fieldIndex, index);
            case FLOAT:
                return g.getFloat(fieldIndex, index);
            case DOUBLE:
                return g.getDouble(fieldIndex, index);
            case INT96:
                Binary tsBin = g.getInt96(fieldIndex, index);
                return convertInt96BinaryToTimestamp(tsBin);
            case FIXED_LEN_BYTE_ARRAY:
            case BINARY:
                Binary bin = g.getBinary(fieldIndex, index);
                byte[] bytes = bin.getBytes();
                if (binaryAsString) {
                    return StringUtils.fromUtf8(bytes);
                } else {
                    return bytes;
                }
            default:
                throw new RE("Unknown primitive conversion: %s", pt.getPrimitiveTypeName());
            }
        }
    } catch (Exception ex) {
        return null;
    }
}