Example usage for org.joda.time Period Period

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

Introduction

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

Prototype

public Period(Object period) 

Source Link

Document

Creates a period by converting or copying from another object.

Usage

From source file:io.github.benas.jpopulator.randomizers.joda.DefaultJodaPeriodRandomizer.java

License:Open Source License

@Override
public Period getRandomValue() {
    return new Period(Math.abs(ConstantsUtil.RANDOM.nextInt()));
}

From source file:io.github.benas.randombeans.randomizers.jodatime.JodaTimePeriodRandomizer.java

License:Open Source License

@Override
public Period getRandomValue() {
    return new Period(Math.abs(Constants.RANDOM.nextInt()));
}

From source file:io.imply.tranquility.JavaExample.java

License:Apache License

public static void main(String[] args) {
    final String indexService = "druid/overlord"; // Your overlord's druid.service
    final String discoveryPath = "/druid/discovery"; // Your overlord's druid.discovery.curator.path
    final String dataSource = "foo";
    final List<String> dimensions = ImmutableList.of("bar", "qux");
    final List<AggregatorFactory> aggregators = ImmutableList.of(new CountAggregatorFactory("cnt"),
            new LongSumAggregatorFactory("baz", "baz"));

    // Tranquility needs to be able to extract timestamps from your object type (in this case, Map<String, Object>).
    final Timestamper<Map<String, Object>> timestamper = new Timestamper<Map<String, Object>>() {
        @Override/*w  ww  .ja va 2  s  . com*/
        public DateTime timestamp(Map<String, Object> theMap) {
            return new DateTime(theMap.get("timestamp"));
        }
    };

    // Tranquility uses ZooKeeper (through Curator) for coordination.
    final CuratorFramework curator = CuratorFrameworkFactory.builder().connectString("zk.example.com:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000, 20, 30000)).build();
    curator.start();

    // The JSON serialization of your object must have a timestamp field in a format that Druid understands. By default,
    // Druid expects the field to be called "timestamp" and to be an ISO8601 timestamp.
    final TimestampSpec timestampSpec = new TimestampSpec("timestamp", "auto", null);

    // Tranquility needs to be able to serialize your object type to JSON for transmission to Druid. By default this is
    // done with Jackson. If you want to provide an alternate serializer, you can provide your own via ```.objectWriter(...)```.
    // In this case, we won't provide one, so we're just using Jackson.
    final Tranquilizer<Map<String, Object>> druidService = DruidBeams.builder(timestamper).curator(curator)
            .discoveryPath(discoveryPath).location(DruidLocation.create(indexService, dataSource))
            .timestampSpec(timestampSpec)
            .rollup(DruidRollup.create(DruidDimensions.specific(dimensions), aggregators,
                    QueryGranularity.MINUTE))
            .tuning(ClusteredBeamTuning.builder().segmentGranularity(Granularity.HOUR)
                    .windowPeriod(new Period("PT10M")).partitions(1).replicants(1).build())
            .buildTranquilizer();

    druidService.start();

    try {
        // Build a sample event to send; make sure we use a current date
        Map<String, Object> obj = ImmutableMap.<String, Object>of("timestamp", new DateTime().toString(), "bar",
                "barVal", "baz", 3);

        // Send event to Druid:
        final Future<BoxedUnit> future = druidService.send(obj);

        // Wait for confirmation:
        Await.result(future);
    } catch (Exception e) {
        log.warn(e, "Failed to send message");
    } finally {
        // Close objects:
        druidService.stop();
        curator.close();
    }
}

From source file:io.mandrel.common.unit.TimeValue.java

License:Apache License

public String format() {
    Period period = new Period(millis());
    return defaultFormatter.print(period);
}

From source file:io.mandrel.common.unit.TimeValue.java

License:Apache License

public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}

From source file:jamel.markets.labor.EmploymentContract.java

License:Open Source License

/**
 * Creates a new employment contract.//from  w w w.  j  a  va2  s .  c o m
 * 
 * @param abstractJobOfferer
 *            the employer.
 * @param employee
 *            the employee.
 * @param wage
 *            the wage.
 * @param term
 *            the term.
 */
public EmploymentContract(Cycle cycle, Employer employer, Worker employee, long wage) {
    super(cycle, new Period(Math.abs(new JamelRandom().nextInt())).plus(MINDURATION));
    this.employer = employer;
    if (!employee.isUnemployed()) {
        throw new IllegalArgumentException("Employee is already employed!");
    }
    this.employee = employee;
    this.wage = wage;
}

From source file:jp.furplag.util.time.JodaPrettifier.java

License:Apache License

/**
 * Return the prettified String if the period includes specified moment.
 *
 * <pre>/*from w  w  w .  j  a va  2 s. co  m*/
 * prettify(DateTime.now().minusHours(1), null, null, null, null) = "one hour ago." prettify(DateTime.now(), DateTime.now().plusYears(1), null, null, null) = "one year ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withDays(1)) = "one hour ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withMinites(10)) =
 * DateTime.now().withZone(DateTimeZone.UTC).minusHours(1).toString(DateTimeFormat.forStyle("-M"))
 *
 * <pre>
 *
 * @param then the datetime object, null means current date-time.
 * @param reference the moment of a starting point ( {@link org.joda.time.ReadableInstant} and {@link Long} specifiable ). Use {@code DateTime.now()} as a start point if {@code reference} is null.
 * @param locale the language for Localization ( {@code String} and {@code Locale} specifiable ). Use ROOT if {@code locale} is null.
 * @param limit if the moment is in the specified period, return prettified String ( {@code Period} and {@code Interval} specifiable ). Prettify all, if null.
 * @return the prettified String if the period includes specified moment. In other situation, return stringified date-time.
 */
public static String prettify(final Object then, final Object reference, final Locale locale,
        final DateTimeZone zone, final Object limit) {
    DateTime temporary = DateTimeUtils.toDT(then, zone, true);
    if (temporary == null)
        return StringUtils.EMPTY;
    DateTime ref = DateTimeUtils.toDT(reference, temporary.getZone(), true);
    if (ref == null)
        return doPrettify(temporary, null, locale);
    if (ref.isEqual(temporary))
        ref = ref.plusMillis(1);
    if (limit == null)
        return doPrettify(temporary, ref, locale);
    Interval limitter = null;
    if (Interval.class.equals(limit))
        limitter = (Interval) limit;
    if (limit instanceof Period) {
        limitter = new Interval(ref.minus((Period) limit), ref.plusMillis(1).plus((Period) limit));
    }
    if (limit instanceof BaseSingleFieldPeriod) {
        limitter = new Interval(ref.minus(new Period(limit)), ref.plusMillis(1).plus(new Period(limit)));
    }
    if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(limit.getClass()), Double.class, Float.class)) {
        limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref),
                toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref));
    } else if (BigDecimal.class.equals(limit.getClass())) {
        if (NumberUtils.compareTo((BigDecimal) limit, NumberUtils.down(limit)) == 0) {
            limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)),
                    ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1));
        } else {
            limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref),
                    toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref));
        }
    } else if (Number.class.isAssignableFrom(ClassUtils.primitiveToWrapper(limit.getClass()))) {
        limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)),
                ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1));
    }
    if (DateTime.class.equals(limit.getClass())) {
        limitter = new Interval(ref.minus(((DateTime) limit).getMillis()),
                ref.plus(((DateTime) limit).getMillis() + 1L));
    }
    if (Boolean.class.equals(limit.getClass())) {
        limitter = new Interval(temporary.minusMillis(1),
                ((Boolean) limit) ? temporary.plusMillis(1) : temporary.minusMillis(1));
    }
    if (limitter == null)
        return doPrettify(temporary, ref, locale);
    if (limitter.contains(temporary))
        return doPrettify(temporary, ref, locale);

    return toDT(temporary, GJChronology.getInstance(temporary.getZone()))
            .toString(DateTimeFormat.forStyle(isToday(temporary, temporary.getZone()) ? "-M" : "MS")
                    .withLocale(locale == null ? Locale.ROOT : locale));
}

From source file:model.SqlInterface.java

/**
 * Return all entries filtered by the date of interest.
 * // www .j  ava2s . c o  m
 * @param date The date to get entries for.
 * 
 * @return Array of strings containing all the TimeLord entries for 'date'.
 * 
 * @throws SQLException
 */
public String[][] getEntriesByDate(String date) throws SQLException {
    taskCount = 0;

    ResultSet rs = statementHandler.executeQuery("select * from timelord where date = '" + date + "';");

    int tmpCounter = 0;
    while (rs.next()) {
        tmpCounter++;
    }

    String[][] tableData = new String[tmpCounter][6];

    rs = statementHandler.executeQuery("select * from timelord where date = '" + date + "';");

    while (rs.next()) {
        DateTime start = new DateTime(rs.getObject("start"));
        tableData[taskCount][0] = Time.getFormattedTime(start);

        DateTime stop = new DateTime(rs.getObject("stop"));
        tableData[taskCount][1] = Time.getFormattedTime(stop);

        Period period = new Period(rs.getObject("delta"));
        tableData[taskCount][2] = Time.displayDelta(period);

        tableData[taskCount][3] = rs.getString("jira");
        tableData[taskCount][4] = rs.getString("description");
        tableData[taskCount][5] = rs.getString("date");

        taskCount++;
    }

    rs.close();

    return tableData;
}

From source file:model.SqlInterface.java

/**
 * Use this method to get all the values from the database corresponding to
 * the given JIRA project for the time period specified.
 * //ww  w .ja v a2s .  co  m
 * @param startDate The start date of the period to report on.
 * @param interval The length of time from the start date to report on.
 * @param jiraCode The Jira issue to report on.
 * 
 * @return ArrayList where each entry is an array containing the
 *         contents of each row from the database that was found: date,
 *         start, stop, delta, jira, description, dayTally.
 */
public Object[][] generateReport(DateTime startDate, Period interval, String jiraCode) {
    int taskCount = 0;
    String[][] tableData = null;

    MutableDateTime start = startDate.toMutableDateTime();
    // Need mutable to perform arithmetic
    MutableDateTime end = startDate.plus(interval).toMutableDateTime();
    // Only have 'isBefore' so add one day to make it equivalent to
    // 'isBeforeOrOnThisDay'
    end.addDays(1);

    ResultSet rs;
    try {
        rs = statementHandler.executeQuery("select * from timelord where date = '"
                + Time.getReferableDate(start.toDateTime()) + "' and jira = '" + jiraCode + "';");

        while (rs.next()) {
            taskCount++;
        }
        rs = statementHandler.executeQuery("select * from timelord where date = '"
                + Time.getReferableDate(start.toDateTime()) + "' and jira = '" + jiraCode + "';");

        tableData = new String[taskCount][6];

        taskCount = 0;
        while (start.isBefore(end)) {
            while (rs.next()) {
                tableData[taskCount][0] = Time.getFormattedDate(new DateTime(rs.getObject("start")));
                tableData[taskCount][1] = Time.getFormattedTime(new DateTime(rs.getObject("start")));
                tableData[taskCount][2] = Time.getFormattedTime(new DateTime(rs.getObject("stop")));
                tableData[taskCount][3] = Time.displayDelta(new Period(rs.getObject("delta")));
                tableData[taskCount][4] = rs.getString("jira");
                tableData[taskCount][5] = rs.getString("description");

                taskCount++;
            }
            start.addDays(1);
        }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return tableData;
}

From source file:net.acesinc.data.json.generator.log.TranquilityLogger.java

public TranquilityLogger(Map<String, Object> props) {
    this.jsonUtils = new JsonUtils();
    this.mapper = new ObjectMapper();

    this.indexService = (String) props.get(OVERLORD_NAME_PROP_NAME);
    this.firehosePattern = (String) props.get(FIREHOSE_PATTERN_PROP_NAME);
    this.discoveryPath = (String) props.get(DISCOVERY_PATH_PROP_NAME);
    this.dataSourceName = (String) props.get(DATASOURCE_NAME_PROP_NAME);
    this.dimensionNames = (String) props.get(DIMENSIONS_PROP_NAME);
    this.geoSpatialDims = (String) props.get(GEOSPATIAL_DIMENSIONS_PROP_NAME);
    this.timestampName = (String) props.get(TIMESTAMP_NAME_PROP_NAME);
    this.timestampFormat = (String) props.getOrDefault(TIMESTAMP_FORMAT_PROP_NAME, "auto");
    this.segmentGranularity = ((String) props.getOrDefault(SEGMENT_GRANULARITY_PROP_NAME, "hour"))
            .toUpperCase();/*  ww w  . j  a v  a  2  s  .c o  m*/
    this.queryGranularity = ((String) props.getOrDefault(QUERY_GRANULARITY_PROP_NAME, "minute")).toUpperCase();
    this.zookeeperHost = (String) props.get(ZOOKEEPER_HOST_PROP_NAME);
    this.zookeeperPort = (Integer) props.get(ZOOKEEPER_PORT_PROP_NAME);
    this.flatten = (Boolean) props.getOrDefault(FLATTEN_PROP_NAME, true);
    this.sync = (Boolean) props.getOrDefault(SYNC_PROP_NAME, false);

    dimensions = new ArrayList<>();
    if (dimensionNames != null && !dimensionNames.isEmpty()) {
        String[] dims = dimensionNames.split(",");
        for (String s : dims) {
            dimensions.add(s.trim());
        }
    }
    if (dimensions.isEmpty()) {
        log.debug("Configuring Tranquility with Schemaless ingestion");
        druidDimensions = DruidDimensions.schemaless();
    } else {
        log.debug("Configuring Tranqulity with the following dimensions: " + dimensions.toString());
        druidDimensions = DruidDimensions.specific(dimensions);
    }

    List<String> geoDims = new ArrayList<>();
    if (geoSpatialDims != null && !geoSpatialDims.isEmpty()) {
        String[] dims = geoSpatialDims.split(",");
        for (String s : dims) {
            geoDims.add(s.trim());
        }
    }
    if (!geoDims.isEmpty()) {
        log.debug("Adding Geospatial Dimensions: " + geoDims.toString());
        druidDimensions = druidDimensions
                .withSpatialDimensions(Lists.newArrayList(DruidSpatialDimension.multipleField("geo", geoDims)));
    }

    aggregators = ImmutableList.<AggregatorFactory>of(new CountAggregatorFactory("events"));

    // Tranquility needs to be able to extract timestamps from your object type (in this case, Map<String, Object>).
    timestamper = new Timestamper<Map<String, Object>>() {
        @Override
        public DateTime timestamp(Map<String, Object> theMap) {
            return new DateTime(theMap.get(timestampName));
        }
    };

    // Tranquility uses ZooKeeper (through Curator) for coordination.
    curator = CuratorFrameworkFactory.builder().connectString(zookeeperHost + ":" + zookeeperPort.toString())
            .retryPolicy(new ExponentialBackoffRetry(1000, 20, 30000)).build();
    curator.start();

    // The JSON serialization of your object must have a timestamp field in a format that Druid understands. By default,
    // Druid expects the field to be called "timestamp" and to be an ISO8601 timestamp.
    log.debug("Confiuring Tranqulity Timestamp Spec with { name: " + timestampName + ", format: "
            + timestampFormat + " }");
    timestampSpec = new TimestampSpec(timestampName, timestampFormat);

    // Tranquility needs to be able to serialize your object type to JSON for transmission to Druid. By default this is
    // done with Jackson. If you want to provide an alternate serializer, you can provide your own via ```.objectWriter(...)```.
    // In this case, we won't provide one, so we're just using Jackson.
    log.debug("Creating Druid Beam for DataSource [ " + dataSourceName + " ]");
    druidService = DruidBeams.builder(timestamper).curator(curator).discoveryPath(discoveryPath)
            .location(DruidLocation.create(indexService, firehosePattern, dataSourceName))
            .timestampSpec(timestampSpec)
            .rollup(DruidRollup.create(druidDimensions, aggregators,
                    QueryGranularity.fromString(queryGranularity)))
            .tuning(ClusteredBeamTuning.builder().segmentGranularity(Granularity.valueOf(segmentGranularity))
                    .windowPeriod(new Period("PT10M")).partitions(1).replicants(1).build())
            .buildJavaService();

}