Example usage for org.joda.time DateTimeField get

List of usage examples for org.joda.time DateTimeField get

Introduction

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

Prototype

public abstract int get(long instant);

Source Link

Document

Get the value of this field from the milliseconds.

Usage

From source file:de.openali.odysseus.chart.ext.base.axisrenderer.DateTimeTickCalculator.java

License:Open Source License

private long getFirstRollValue(final IDateTimeAxisField axisField, final long start, final long end) {
    final DateTimeZone jodaTZ = DateTimeZone.forTimeZone(KalypsoCorePlugin.getDefault().getTimeZone());
    final DateTimeField field = axisField.getFieldType().getField(GregorianChronology.getInstance(jodaTZ));
    final long firstRoll = field.roundFloor(start);
    if (firstRoll + end - start <= start)
        // out of range, precision too small so we return without adjustment
        // maybe try roundCeil instead
        return start;
    final int fieldValue = field.get(firstRoll);
    if (fieldValue == 0)
        return firstRoll;

    final int[] beginners = axisField.getBeginners();
    for (int i = 1; i < beginners.length; i++) {
        if (fieldValue < beginners[i]) {
            return field.add(firstRoll, beginners[i - 1] - fieldValue);
        }/*from  w  w w.jav  a  2 s .  c om*/
    }

    return field.add(firstRoll, -fieldValue);
}

From source file:net.danlew.android.joda.ZoneInfoCompiler.java

License:Apache License

static int parseMonth(String str) {
    DateTimeField field = ISOChronology.getInstanceUTC().monthOfYear();
    return field.get(field.set(0, str, Locale.ENGLISH));
}

From source file:net.danlew.android.joda.ZoneInfoCompiler.java

License:Apache License

static int parseDayOfWeek(String str) {
    DateTimeField field = ISOChronology.getInstanceUTC().dayOfWeek();
    return field.get(field.set(0, str, Locale.ENGLISH));
}

From source file:org.graylog2.indexer.rotation.strategies.TimeBasedRotationStrategy.java

License:Open Source License

/**
 * Determines the starting point ("anchor") for a period.
 *
 * To produce repeatable rotation points in time, the period is "snapped" to a "grid" of time.
 * For example, an hourly index rotation would be anchored to the last full hour, instead of happening at whatever minute
 * the first rotation was started./* w ww .  j a va2  s .c  o m*/
 *
 * This "snapping" is done accordingly with the other parts of a period.
 *
 * For highly irregular periods (those that do not have a small zero component)
 *
 * @param period the rotation period
 * @return the anchor DateTime to calculate rotation periods from
 */
protected static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) {
    final Period normalized = period.normalizedStandard();
    int years = normalized.getYears();
    int months = normalized.getMonths();
    int weeks = normalized.getWeeks();
    int days = normalized.getDays();
    int hours = normalized.getHours();
    int minutes = normalized.getMinutes();
    int seconds = normalized.getSeconds();

    if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        throw new IllegalArgumentException("Invalid rotation period specified");
    }

    // find the largest non-zero stride in the period. that's our anchor type. statement order matters here!
    DateTimeFieldType largestStrideType = null;
    if (seconds > 0)
        largestStrideType = secondOfMinute();
    if (minutes > 0)
        largestStrideType = minuteOfHour();
    if (hours > 0)
        largestStrideType = hourOfDay();
    if (days > 0)
        largestStrideType = dayOfMonth();
    if (weeks > 0)
        largestStrideType = weekOfWeekyear();
    if (months > 0)
        largestStrideType = monthOfYear();
    if (years > 0)
        largestStrideType = year();
    if (largestStrideType == null) {
        throw new IllegalArgumentException("Could not determine rotation stride length.");
    }

    final DateTime anchorTime = MoreObjects.firstNonNull(lastAnchor, Tools.nowUTC());

    final DateTimeField field = largestStrideType.getField(anchorTime.getChronology());
    // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836
    int periodValue = normalized.get(largestStrideType.getDurationType());
    final long fieldValue = field.roundFloor(anchorTime.getMillis());

    final int fieldValueInUnit = field.get(fieldValue);
    if (periodValue == 0) {
        // https://github.com/Graylog2/graylog2-server/issues/836
        log.warn(
                "Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!");
        periodValue = 1;
    }
    final long difference = (fieldValueInUnit % periodValue);
    final long newValue = field.add(fieldValue, -1 * difference);
    return new DateTime(newValue, DateTimeZone.UTC);
}

From source file:org.graylog2.indexer.rotation.TimeBasedRotationStrategy.java

License:Open Source License

/**
 * Determines the starting point ("anchor") for a period.
 *
 * To produce repeatable rotation points in time, the period is "snapped" to a "grid" of time.
 * For example, an hourly index rotation would be anchored to the last full hour, instead of happening at whatever minute
 * the first rotation was started./*from w ww . ja va  2s  .  c o  m*/
 *
 * This "snapping" is done accordingly with the other parts of a period.
 *
 * For highly irregular periods (those that do not have a small zero component)
 *
 * @param period the rotation period
 * @return the anchor DateTime to calculate rotation periods from
 */
protected static DateTime determineRotationPeriodAnchor(Period period) {
    final Period normalized = period.normalizedStandard();
    int years = normalized.getYears();
    int months = normalized.getMonths();
    int weeks = normalized.getWeeks();
    int days = normalized.getDays();
    int hours = normalized.getHours();
    int minutes = normalized.getMinutes();
    int seconds = normalized.getSeconds();

    if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        throw new IllegalArgumentException("Invalid rotation period specified");
    }

    // find the largest non-zero stride in the period. that's our anchor type. statement order matters here!
    DateTimeFieldType largestStrideType = null;
    if (seconds > 0)
        largestStrideType = secondOfMinute();
    if (minutes > 0)
        largestStrideType = minuteOfHour();
    if (hours > 0)
        largestStrideType = hourOfDay();
    if (days > 0)
        largestStrideType = dayOfMonth();
    if (weeks > 0)
        largestStrideType = weekOfWeekyear();
    if (months > 0)
        largestStrideType = monthOfYear();
    if (years > 0)
        largestStrideType = year();
    if (largestStrideType == null) {
        throw new IllegalArgumentException("Could not determine rotation stride length.");
    }

    final DateTime now = Tools.iso8601();

    final DateTimeField field = largestStrideType.getField(now.getChronology());
    // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836
    int periodValue = normalized.get(largestStrideType.getDurationType());
    final long fieldValue = field.roundFloor(now.getMillis());

    final int fieldValueInUnit = field.get(fieldValue);
    if (periodValue == 0) {
        // https://github.com/Graylog2/graylog2-server/issues/836
        log.warn(
                "Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!");
        periodValue = 1;
    }
    final long difference = (fieldValueInUnit % periodValue);
    final long newValue = field.add(fieldValue, -1 * difference);
    return new DateTime(newValue, DateTimeZone.UTC);
}

From source file:org.nfsdb.examples.reporting.DailyPriceAverageExample.java

License:Apache License

public static void main(String[] args) throws JournalException, IOException {
    if (args.length != 1) {
        System.out.println("Usage: " + DailyPriceAverageExample.class.getName() + " <path>");
        System.exit(1);/*w w w .  j  a  va2 s  .c o m*/
    }
    String journalLocation = args[0];

    try (JournalFactory factory = new JournalFactory(ModelConfiguration.CONFIG.build(journalLocation))) {

        // delete existing quote journal
        Files.delete(new File(factory.getConfiguration().getJournalBase(), Quote.class.getName()));

        int count = 10000000;
        long t = System.nanoTime();

        // get some data in :)
        try (JournalWriter<Quote> w = factory.writer(Quote.class)) {
            QuoteGenerator.generateQuoteData(w, count, 90);
        }

        System.out.println("Created " + count + " records in "
                + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t) + "ms");

        try (Journal<Quote> journal = factory.reader(Quote.class).select("ask", "timestamp")) {
            count = 0;
            t = System.nanoTime();
            final String symbol = "BP.L";
            // create query builder to search for all records with key (sym) = "BP.L"
            final QueryAllBuilder<Quote> builder = journal.query().all().withKeys(symbol);
            final DateTimeField dayOfYear = ISOChronology.getInstanceUTC().dayOfYear();

            // state
            int previousDay = -1;
            double avgSum = 0;
            int avgCount = 0;

            try (JournalPrinter printer = new JournalPrinter()) {

                // tell printer the types of objects we'll be producing
                printer.types(String.class, DateTime.class, double.class);
                // add fields to out output
                // in this example we are using scalar values, so we have same number of fields as there are types.
                // fields not declared here won't be printed.
                printer.v(0).h("Symbol").v(1).h("Date").v(2).h("avg(Ask)");
                // tell printer the appender we want to use, appender is anything implementing com.nfsdb.journal.printer.appender.Appender interface.
                printer.setAppender(StdOutAppender.INSTANCE);

                // print out header
                printer.header();

                // out result set is all chronologically ordered quotes for symbol BP.L
                // so this loop leverages data order by printing out result when
                // day of year changes
                for (Quote q : builder.asResultSet().bufferedIterator()) {
                    int thisDay = dayOfYear.get(q.getTimestamp());
                    if (thisDay != previousDay) {
                        if (previousDay != -1) {
                            printer.out(
                                    symbol, Dates.utc().withDayOfYear(previousDay).withHourOfDay(0)
                                            .withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0),
                                    avgSum / avgCount);
                        }
                        avgCount = 1;
                        avgSum = q.getTimestamp();
                        previousDay = thisDay;
                    } else {
                        avgCount++;
                        avgSum += q.getTimestamp();
                    }
                    count++;
                }

                if (previousDay != -1) {
                    printer.out(symbol, Dates.utc().withDayOfYear(previousDay).withHourOfDay(0)
                            .withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0),
                            avgSum / avgCount);
                }
            }
            System.out.println("Read " + count + " records in "
                    + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t) + "ms");
        }
    }
}