Search in sources :

Example 76 with Period

use of org.joda.time.Period in project graylog2-server by Graylog2.

the class TimeBasedRotationStrategy method determineRotationPeriodAnchor.

/**
     * 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.
     *
     * 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
     */
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);
}
Also used : DateTimeFieldType(org.joda.time.DateTimeFieldType) Period(org.joda.time.Period) DateTimeField(org.joda.time.DateTimeField) DateTime(org.joda.time.DateTime)

Example 77 with Period

use of org.joda.time.Period in project uPortal by Jasig.

the class PortalEventDimensionPopulatorImplTest method populateDefaultDateDimensions.

@Test
public void populateDefaultDateDimensions() {
    final DateTime now = new DateTime(1325881376117l);
    final Period dimensionBuffer = Period.days(30);
    final DateTime oldestPortalEvent = now.minusDays(30);
    final DateTime newestPortalEvent = now;
    final DateTime dimensionStart = oldestPortalEvent.minus(dimensionBuffer);
    final DateTime dimensionEnd = newestPortalEvent.plus(dimensionBuffer);
    when(dateDimensionDao.getDateDimensionsBetween(any(DateMidnight.class), any(DateMidnight.class))).thenReturn(Collections.<DateDimension>emptyList());
    when(portalEventDao.getOldestPortalEventTimestamp()).thenReturn(oldestPortalEvent);
    when(portalEventDao.getOldestPortalEventTimestamp()).thenReturn(oldestPortalEvent);
    final AggregationIntervalInfo startIntervalInfo = mock(AggregationIntervalInfo.class);
    when(startIntervalInfo.getStart()).thenReturn(dimensionStart.year().roundFloorCopy());
    final AggregationIntervalInfo endIntervalInfo = mock(AggregationIntervalInfo.class);
    when(endIntervalInfo.getEnd()).thenReturn(dimensionStart.year().roundCeilingCopy());
    when(aggregationIntervalHelper.getIntervalInfo(AggregationInterval.YEAR, dimensionStart)).thenReturn(startIntervalInfo);
    when(aggregationIntervalHelper.getIntervalInfo(AggregationInterval.YEAR, dimensionEnd)).thenReturn(endIntervalInfo);
    when(eventAggregationManagementDao.getAcademicTermDetails()).thenReturn(Collections.<AcademicTermDetail>emptyList());
    when(eventAggregationManagementDao.getQuartersDetails()).thenReturn(EventDateTimeUtils.createStandardQuarters());
    portalEventDimensionPopulator.setDimensionBuffer(dimensionBuffer);
    portalEventDimensionPopulator.doPopulateDateDimensions();
    verify(dateDimensionDao).getDateDimensionsBetween(any(DateMidnight.class), any(DateMidnight.class));
    verify(dateDimensionDao, times(365)).createDateDimension(Matchers.<DateMidnight>anyObject(), anyInt(), anyString());
    verifyNoMoreInteractions(timeDimensionDao, dateDimensionDao);
}
Also used : DateMidnight(org.joda.time.DateMidnight) Period(org.joda.time.Period) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 78 with Period

use of org.joda.time.Period in project quorrabot by GloriousEggroll.

the class YouTubeAPIv3 method GetVideoLength.

public int[] GetVideoLength(String id) {
    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Start id=" + id);
    }
    JSONObject j = GetData(request_type.GET, "https://www.googleapis.com/youtube/v3/videos?id=" + id + "&key=" + apikey + "&part=contentDetails");
    if (j.getBoolean("_success")) {
        if (j.getInt("_http") == 200) {
            JSONArray a = j.getJSONArray("items");
            if (a.length() > 0) {
                JSONObject i = a.getJSONObject(0);
                JSONObject cd = i.getJSONObject("contentDetails");
                PeriodFormatter formatter = ISOPeriodFormat.standard();
                Period d = formatter.parsePeriod(cd.getString("duration"));
                //String d = cd.getString("duration").substring(2);
                int h, m, s;
                String hours = d.toStandardHours().toString().substring(2);
                h = Integer.parseInt(hours.substring(0, hours.indexOf("H")));
                String minutes = d.toStandardMinutes().toString().substring(2);
                m = Integer.parseInt(minutes.substring(0, minutes.indexOf("M")));
                String seconds = d.toStandardSeconds().toString().substring(2);
                s = Integer.parseInt(seconds.substring(0, seconds.indexOf("S")));
                /*
                     * if (d.contains("H")) { h =
                     * Integer.parseInt(d.substring(0, d.indexOf("H")));
                     *
                     * d = d.substring(0, d.indexOf("H")); }
                     *
                     * if (d.contains("M")) { m =
                     * Integer.parseInt(d.substring(0, d.indexOf("M")));
                     *
                     * d = d.substring(0, d.indexOf("M")); }
                     *
                     * s = Integer.parseInt(d.substring(0, d.indexOf("S")));
                     */
                if (Quorrabot.enableDebugging) {
                    com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Success");
                }
                return new int[] { h, m, s };
            } else {
                if (Quorrabot.enableDebugging) {
                    com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail");
                }
                return new int[] { 0, 0, 0 };
            }
        } else {
            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail2");
            }
            return new int[] { 0, 0, 0 };
        }
    }
    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail3");
    }
    return new int[] { 0, 0, 0 };
}
Also used : JSONObject(org.json.JSONObject) PeriodFormatter(org.joda.time.format.PeriodFormatter) JSONArray(org.json.JSONArray) Period(org.joda.time.Period)

Example 79 with Period

use of org.joda.time.Period in project joda-time by JodaOrg.

the class TestPeriodFormatterBuilder method testFormatPrefixRegEx2.

public void testFormatPrefixRegEx2() {
    PeriodFormatter f = builder.appendPrefix(new String[] { "^1$", "^.*$" }, new String[] { "Hour:", "Hours:" }).appendHours().toFormatter();
    assertEquals("Hours:5", f.print(PERIOD));
    assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
    Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("Hours:0", f.print(p));
    assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
Also used : Period(org.joda.time.Period)

Example 80 with Period

use of org.joda.time.Period in project joda-time by JodaOrg.

the class TestPeriodFormatterBuilder method testFormatSuffixRegEx1.

public void testFormatSuffixRegEx1() {
    PeriodFormatter f = builder.appendYears().appendSuffix(new String[] { "^1$", "^2$" }, new String[] { " year", " years" }).toFormatter();
    assertEquals("1 year", f.print(PERIOD));
    assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
    Period p2 = new Period(2, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("2 years", f.print(p2));
    assertEquals(7, f.getPrinter().calculatePrintedLength(p2, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(p2, Integer.MAX_VALUE, null));
    Period p0 = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("0 years", f.print(p0));
    assertEquals(7, f.getPrinter().calculatePrintedLength(p0, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(p0, Integer.MAX_VALUE, null));
}
Also used : Period(org.joda.time.Period)

Aggregations

Period (org.joda.time.Period)273 Test (org.junit.Test)102 DateTime (org.joda.time.DateTime)54 PeriodGranularity (io.druid.java.util.common.granularity.PeriodGranularity)40 Interval (org.joda.time.Interval)30 LongSumAggregatorFactory (io.druid.query.aggregation.LongSumAggregatorFactory)29 DefaultDimensionSpec (io.druid.query.dimension.DefaultDimensionSpec)20 Row (io.druid.data.input.Row)19 File (java.io.File)15 DefaultObjectMapper (io.druid.jackson.DefaultObjectMapper)12 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)10 Result (io.druid.query.Result)10 CountAggregatorFactory (io.druid.query.aggregation.CountAggregatorFactory)10 FinalizeResultsQueryRunner (io.druid.query.FinalizeResultsQueryRunner)8 QueryRunner (io.druid.query.QueryRunner)8 AggregatorFactory (io.druid.query.aggregation.AggregatorFactory)8 DimensionSpec (io.druid.query.dimension.DimensionSpec)8 MutablePeriod (org.joda.time.MutablePeriod)8 ExtractionDimensionSpec (io.druid.query.dimension.ExtractionDimensionSpec)7 DimFilterHavingSpec (io.druid.query.groupby.having.DimFilterHavingSpec)7