org.joda.time.DateTime

Here are the examples of the java api class org.joda.time.DateTime taken from open source projects.

1. TestDateTruncFunctions#testDateTrunc()

Project: drill
File: TestDateTruncFunctions.java
@Test
public void testDateTrunc() throws Exception {
    String query = "select " + "date_trunc('MINUTE', time '2:30:21.5') as TIME1, " + "date_trunc('SECOND', time '2:30:21.5') as TIME2, " + "date_trunc('HOUR', timestamp '1991-05-05 10:11:12.100') as TS1, " + "date_trunc('SECOND', timestamp '1991-05-05 10:11:12.100') as TS2, " + "date_trunc('MONTH', date '2011-2-2') as DATE1, " + "date_trunc('YEAR', date '2011-2-2') as DATE2 " + "from cp.`employee.json` where employee_id < 2";
    DateTime time1 = formatTime.parseDateTime("2:30:00.0");
    DateTime time2 = formatTime.parseDateTime("2:30:21.0");
    DateTime ts1 = formatTimeStamp.parseDateTime("1991-05-05 10:00:00.0");
    DateTime ts2 = formatTimeStamp.parseDateTime("1991-05-05 10:11:12.0");
    DateTime date1 = formatDate.parseDateTime("2011-02-01");
    DateTime date2 = formatDate.parseDateTime("2011-01-01");
    testBuilder().sqlQuery(query).unOrdered().baselineColumns("TIME1", "TIME2", "TS1", "TS2", "DATE1", "DATE2").baselineValues(time1, time2, ts1, ts2, date1, date2).go();
}

2. TestDateAndTimeZoneContext#testComputeTargetDateWithDayLightSaving()

Project: killbill
File: TestDateAndTimeZoneContext.java
@Test(groups = "fast")
public void testComputeTargetDateWithDayLightSaving() {
    final DateTime dateTime1 = new DateTime("2015-01-01T08:01:01.000Z");
    final DateTime dateTime2 = new DateTime("2015-09-01T08:01:01.000Z");
    final DateTime dateTime3 = new DateTime("2015-12-01T08:01:01.000Z");
    // Alaska Standard Time
    final DateTimeZone tz = DateTimeZone.forID("America/Juneau");
    internalCallContext.setReferenceDateTimeZone(tz);
    // Time zone is AKDT (UTC-8h) between March and November
    final DateTime referenceDateTimeWithDST = new DateTime("2015-09-01T08:01:01.000Z");
    final AccountDateAndTimeZoneContext tzContextWithDST = new DefaultAccountDateAndTimeZoneContext(referenceDateTimeWithDST, internalCallContext);
    assertEquals(tzContextWithDST.computeLocalDateFromFixedAccountOffset(dateTime1), new LocalDate("2015-01-01"));
    assertEquals(tzContextWithDST.computeLocalDateFromFixedAccountOffset(dateTime2), new LocalDate("2015-09-01"));
    assertEquals(tzContextWithDST.computeLocalDateFromFixedAccountOffset(dateTime3), new LocalDate("2015-12-01"));
    // Time zone is AKST (UTC-9h) otherwise
    final DateTime referenceDateTimeWithoutDST = new DateTime("2015-02-01T08:01:01.000Z");
    final AccountDateAndTimeZoneContext tzContextWithoutDST = new DefaultAccountDateAndTimeZoneContext(referenceDateTimeWithoutDST, internalCallContext);
    assertEquals(tzContextWithoutDST.computeLocalDateFromFixedAccountOffset(dateTime1), new LocalDate("2014-12-31"));
    assertEquals(tzContextWithoutDST.computeLocalDateFromFixedAccountOffset(dateTime2), new LocalDate("2015-08-31"));
    assertEquals(tzContextWithoutDST.computeLocalDateFromFixedAccountOffset(dateTime3), new LocalDate("2015-11-30"));
}

3. TestDateTimeFormatter#testZoneShortNameNearTransition()

Project: joda-time
File: TestDateTimeFormatter.java
// Ensure time zone name switches properly at the zone DST transition.
public void testZoneShortNameNearTransition() {
    DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK);
    DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK);
    DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK);
    DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK);
    DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S z");
    assertEquals("2005-10-30 01:00:00.0 EDT", fmt.print(inDST_1));
    assertEquals("2005-10-30 01:59:59.9 EDT", fmt.print(inDST_2));
    assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(onDST));
    assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(outDST));
    assertEquals("2005-10-30 02:00:01.0 EST", fmt.print(outDST_2));
}

4. TestDateTimeFormatter#testZoneNameNearTransition()

Project: joda-time
File: TestDateTimeFormatter.java
//-----------------------------------------------------------------------
// Ensure time zone name switches properly at the zone DST transition.
public void testZoneNameNearTransition() {
    DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK);
    DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK);
    DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK);
    DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK);
    DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S zzzz");
    assertEquals("2005-10-30 01:00:00.0 Eastern Daylight Time", fmt.print(inDST_1));
    assertEquals("2005-10-30 01:59:59.9 Eastern Daylight Time", fmt.print(inDST_2));
    assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(onDST));
    assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(outDST));
    assertEquals("2005-10-30 02:00:01.0 Eastern Standard Time", fmt.print(outDST_2));
}

5. TestDateTimeFormatter#testParseDateTime_chrono()

Project: joda-time
File: TestDateTimeFormatter.java
public void testParseDateTime_chrono() {
    DateTime expect = null;
    expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS);
    assertEquals(expect, g.withChronology(ISO_PARIS).parseDateTime("2004-06-09T10:20:30Z"));
    expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON);
    assertEquals(expect, g.withChronology(null).parseDateTime("2004-06-09T10:20:30Z"));
    expect = new DateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS);
    assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2547-06-09T10:20:30Z"));
    // zone is +00:09:21 in 1451
    expect = new DateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS);
    assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2004-06-09T10:20:30Z"));
}

6. TestDateTimeFormatter#testParseDateTime_offsetParsed()

Project: joda-time
File: TestDateTimeFormatter.java
public void testParseDateTime_offsetParsed() {
    DateTime expect = null;
    expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC);
    assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z"));
    expect = new DateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4));
    assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T06:20:30-04:00"));
    expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC);
    assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z"));
    expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS);
    assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z"));
}

7. RepairRunStatusMapper#map()

Project: cassandra-reaper
File: RepairRunStatusMapper.java
@Override
public RepairRunStatus map(int index, ResultSet r, StatementContext ctx) throws SQLException {
    long runId = r.getLong("id");
    String clusterName = r.getString("cluster_name");
    String keyspaceName = r.getString("keyspace_name");
    Collection<String> columnFamilies = ImmutableSet.copyOf((String[]) r.getArray("column_families").getArray());
    int segmentsRepaired = r.getInt("segments_repaired");
    int totalSegments = r.getInt("segments_total");
    RepairRun.RunState state = RepairRun.RunState.valueOf(r.getString("state"));
    DateTime startTime = RepairRunMapper.getDateTimeOrNull(r, "start_time");
    DateTime endTime = RepairRunMapper.getDateTimeOrNull(r, "end_time");
    String cause = r.getString("cause");
    String owner = r.getString("owner");
    String lastEvent = r.getString("last_event");
    DateTime creationTime = RepairRunMapper.getDateTimeOrNull(r, "creation_time");
    DateTime pauseTime = RepairRunMapper.getDateTimeOrNull(r, "pause_time");
    Double intensity = r.getDouble("intensity");
    RepairParallelism repairParallelism = RepairParallelism.valueOf(r.getString("repair_parallelism"));
    return new RepairRunStatus(runId, clusterName, keyspaceName, columnFamilies, segmentsRepaired, totalSegments, state, startTime, endTime, cause, owner, lastEvent, creationTime, pauseTime, intensity, repairParallelism);
}

8. CalendarEventVisualizer#createFollowingEntries()

Project: calendar-widget
File: CalendarEventVisualizer.java
private void createFollowingEntries(List<CalendarEntry> entryList, CalendarEntry dayOneEntry) {
    DateTime endDate = dayOneEntry.getEvent().getEndDate();
    if (endDate.isAfter(calendarContentProvider.getEndOfTimeRange())) {
        endDate = calendarContentProvider.getEndOfTimeRange();
    }
    DateTime thisDay = dayOneEntry.getStartDay().plusDays(1).withTimeAtStartOfDay();
    while (thisDay.isBefore(endDate)) {
        DateTime nextDay = thisDay.plusDays(1);
        CalendarEntry nextEntry = CalendarEntry.fromEvent(dayOneEntry.getEvent());
        nextEntry.setStartDate(thisDay);
        if (endDate.isAfter(nextDay)) {
            nextEntry.setEndDate(nextDay);
        } else {
            nextEntry.setEndDate(endDate);
        }
        entryList.add(nextEntry);
        thisDay = nextDay;
    }
}

9. CalendarEventVisualizer#setupDayOneEntry()

Project: calendar-widget
File: CalendarEventVisualizer.java
private CalendarEntry setupDayOneEntry(List<CalendarEntry> entryList, CalendarEvent event) {
    CalendarEntry dayOneEntry = CalendarEntry.fromEvent(event);
    DateTime firstDate = event.getStartDate();
    DateTime dayOfStartOfTimeRange = calendarContentProvider.getStartOfTimeRange().withTimeAtStartOfDay();
    if (!event.hasDefaultCalendarColor() && firstDate.isBefore(calendarContentProvider.getStartOfTimeRange()) && event.getEndDate().isAfter(calendarContentProvider.getStartOfTimeRange())) {
        if (event.isAllDay() || firstDate.isBefore(dayOfStartOfTimeRange)) {
            firstDate = dayOfStartOfTimeRange;
        }
    }
    DateTime today = DateUtil.now().withTimeAtStartOfDay();
    if (event.isActive() && firstDate.isBefore(today)) {
        firstDate = today;
    }
    dayOneEntry.setStartDate(firstDate);
    DateTime nextDay = dayOneEntry.getStartDay().plusDays(1);
    if (event.getEndDate().isAfter(nextDay)) {
        dayOneEntry.setEndDate(nextDay);
    }
    entryList.add(dayOneEntry);
    return dayOneEntry;
}

10. TabularViewHandler#generateTimeOnTimeComparisonRequest()

Project: pinot
File: TabularViewHandler.java
private TimeOnTimeComparisonRequest generateTimeOnTimeComparisonRequest(TabularViewRequest request) throws Exception {
    TimeOnTimeComparisonRequest comparisonRequest = new TimeOnTimeComparisonRequest();
    String collection = request.getCollection();
    DateTime baselineStart = request.getBaselineStart();
    DateTime baselineEnd = request.getBaselineEnd();
    DateTime currentStart = request.getCurrentStart();
    DateTime currentEnd = request.getCurrentEnd();
    comparisonRequest.setEndDateInclusive(true);
    Multimap<String, String> filters = request.getFilters();
    List<MetricExpression> metricExpressions = request.getMetricExpressions();
    comparisonRequest.setCollectionName(collection);
    comparisonRequest.setBaselineStart(baselineStart);
    comparisonRequest.setBaselineEnd(baselineEnd);
    comparisonRequest.setCurrentStart(currentStart);
    comparisonRequest.setCurrentEnd(currentEnd);
    comparisonRequest.setFilterSet(filters);
    comparisonRequest.setMetricExpressions(metricExpressions);
    comparisonRequest.setAggregationTimeGranularity(request.getTimeGranularity());
    return comparisonRequest;
}

11. DateEncoderTest#testHoliday()

Project: htm.java
File: DateEncoderTest.java
/**
     * look at holiday more carefully because of the smooth transition
     */
@Test
public void testHoliday() {
    //use of forced is not recommended, used here for readability, see ScalarEncoder
    DateEncoder e = DateEncoder.builder().holiday(5).forced(true).build();
    int[] holiday = new int[] { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 };
    int[] notholiday = new int[] { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
    int[] holiday2 = new int[] { 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 };
    DateTime d = new DateTime(2010, 12, 25, 4, 55);
    //System.out.println(String.format("1:%s", Arrays.toString(e.encode(d))));
    assertArrayEquals(holiday, e.encode(d));
    d = new DateTime(2008, 12, 27, 4, 55);
    //System.out.println(String.format("2:%s", Arrays.toString(e.encode(d))));
    assertArrayEquals(notholiday, e.encode(d));
    d = new DateTime(1999, 12, 26, 8, 0);
    //System.out.println(String.format("3:%s", Arrays.toString(e.encode(d))));
    assertArrayEquals(holiday2, e.encode(d));
    d = new DateTime(2011, 12, 24, 16, 0);
    //System.out.println(String.format("4:%s", Arrays.toString(e.encode(d))));
    assertArrayEquals(holiday2, e.encode(d));
}

12. LegacyMongoIndexRangeServiceTest#testFindAll()

Project: graylog2-server
File: LegacyMongoIndexRangeServiceTest.java
@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void testFindAll() throws Exception {
    final SortedSet<IndexRange> indexRanges = indexRangeService.findAll();
    final DateTime end0 = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
    final DateTime end1 = new DateTime(2015, 1, 2, 0, 0, 0, 0, DateTimeZone.UTC);
    final DateTime end2 = new DateTime(2015, 1, 3, 0, 0, 0, 0, DateTimeZone.UTC);
    final DateTime end99 = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
    assertThat(indexRanges).containsExactly(MongoIndexRange.create(new ObjectId("56250da2d400000000000001"), "graylog_0", EPOCH, end0, end0, 0), MongoIndexRange.create(new ObjectId("56250da2d400000000000099"), "graylog_99", EPOCH, end99, EPOCH, 0), MongoIndexRange.create(new ObjectId("56250da2d400000000000002"), "graylog_1", EPOCH, end1, end1, 1), MongoIndexRange.create(new ObjectId("56250da2d400000000000003"), "graylog_2", EPOCH, end2, end2, 2));
}

13. TestDateTimeFormatter#testParseDateTime_zone3()

Project: joda-time
File: TestDateTimeFormatter.java
public void testParseDateTime_zone3() {
    DateTimeFormatter h = new DateTimeFormatterBuilder().append(ISODateTimeFormat.date()).appendLiteral('T').append(ISODateTimeFormat.timeElementParser()).toFormatter();
    DateTime expect = null;
    expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON);
    assertEquals(expect, h.withZone(LONDON).parseDateTime("2004-06-09T10:20:30"));
    expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON);
    assertEquals(expect, h.withZone(null).parseDateTime("2004-06-09T10:20:30"));
    expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, PARIS);
    assertEquals(expect, h.withZone(PARIS).parseDateTime("2004-06-09T10:20:30"));
}

14. TestStringConverter#testGetInstantMillis_Object_Zone()

Project: joda-time
File: TestStringConverter.java
public void testGetInstantMillis_Object_Zone() throws Exception {
    DateTime dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, PARIS);
    assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+02:00", ISO_PARIS));
    dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, PARIS);
    assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501", ISO_PARIS));
    dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, LONDON);
    assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+01:00", ISO_LONDON));
    dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, LONDON);
    assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501", ISO_LONDON));
}

15. TestLenientChronology#testNearDstTransition()

Project: joda-time
File: TestLenientChronology.java
//-----------------------------------------------------------------------
//------------------------ Bug ------------------------------------------
//-----------------------------------------------------------------------
public void testNearDstTransition() {
    // This is just a regression test. Test case provided by Blair Martin.
    int hour = 23;
    DateTime dt;
    dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles")));
    // OK - no LenientChronology
    assertEquals(hour, dt.getHourOfDay());
    dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, LenientChronology.getInstance(ISOChronology.getInstance(DateTimeZone.forOffsetHours(-8))));
    // OK - no TZ ID
    assertEquals(hour, dt.getHourOfDay());
    dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, LenientChronology.getInstance(ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles"))));
    // Used to fail - hour was 22
    assertEquals(hour, dt.getHourOfDay());
}

16. DatabaseHandler#getGlucoseDatetimesByMonth()

Project: glucosio-android
File: DatabaseHandler.java
public List<String> getGlucoseDatetimesByMonth() {
    JodaTimeAndroid.init(mContext);
    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());
    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;
    ArrayList<String> finalMonths = new ArrayList<String>();
    // The number of months is at least 1 because current month is incomplete
    int monthsNumber = Months.monthsBetween(minDateTime, maxDateTime).getMonths() + 1;
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    for (int i = 0; i < monthsNumber; i++) {
        newDateTime = currentDateTime.plusMonths(1);
        finalMonths.add(inputFormat.format(newDateTime.toDate()));
        currentDateTime = newDateTime;
    }
    return finalMonths;
}

17. DatabaseHandler#getAverageGlucoseReadingsByMonth()

Project: glucosio-android
File: DatabaseHandler.java
public List<Integer> getAverageGlucoseReadingsByMonth() {
    JodaTimeAndroid.init(mContext);
    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());
    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;
    ArrayList<Integer> averageReadings = new ArrayList<Integer>();
    // The number of months is at least 1 since we do have average for the current week even if incomplete
    int monthsNumber = Months.monthsBetween(minDateTime, maxDateTime).getMonths() + 1;
    for (int i = 0; i < monthsNumber; i++) {
        newDateTime = currentDateTime.plusMonths(1);
        RealmResults<GlucoseReading> readings = realm.where(GlucoseReading.class).between("created", currentDateTime.toDate(), newDateTime.toDate()).findAll();
        averageReadings.add(((int) readings.average("reading")));
        currentDateTime = newDateTime;
    }
    return averageReadings;
}

18. DatabaseHandler#getGlucoseDatetimesByWeek()

Project: glucosio-android
File: DatabaseHandler.java
public List<String> getGlucoseDatetimesByWeek() {
    JodaTimeAndroid.init(mContext);
    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());
    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;
    ArrayList<String> finalWeeks = new ArrayList<String>();
    // The number of weeks is at least 1 since we do have average for the current week even if incomplete
    int weeksNumber = Weeks.weeksBetween(minDateTime, maxDateTime).getWeeks() + 1;
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    for (int i = 0; i < weeksNumber; i++) {
        newDateTime = currentDateTime.plusWeeks(1);
        finalWeeks.add(inputFormat.format(newDateTime.toDate()));
        currentDateTime = newDateTime;
    }
    return finalWeeks;
}

19. DatabaseHandler#getAverageGlucoseReadingsByWeek()

Project: glucosio-android
File: DatabaseHandler.java
/*    private ArrayList<Integer> getGlucoseReadingsForLastMonthAsArray(){
        Calendar calendar = Calendar.getInstance();
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String now = inputFormat.format(calendar.getTime());
        calendar.add(Calendar.MONTH, -1);
        String oneMonthAgo = inputFormat.format(calendar.getTime());


        String[] parameters = new String[] { oneMonthAgo, now } ;
        String[] columns = new String[] { "reading" };
        String whereString = "created_at between ? and ?";

        List<GlucoseReading> gReadings;
        ArrayList<Integer> readings = new ArrayList<Integer>();

        gReadings = GlucoseReading.getGlucoseReadings(whereString);
        int i;
        for (i=0; i < gReadings.size(); i++){
            readings.add(gReadings.get(i).getGlucoseReading());
        }

        return readings;
    }

    public Integer getAverageGlucoseReadingForLastMonth() {
        ArrayList<Integer> readings = getGlucoseReadingsForLastMonthAsArray();
        int sum = 0;
        int numberOfReadings = readings.size();
        for (int i=0; i < numberOfReadings; i++) {
            sum += readings.get(i);
        }
        if (numberOfReadings > 0){
            return Math.round(sum / numberOfReadings);
        } else {
            return 0;
        }
    }*/
public List<Integer> getAverageGlucoseReadingsByWeek() {
    JodaTimeAndroid.init(mContext);
    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());
    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;
    ArrayList<Integer> averageReadings = new ArrayList<Integer>();
    // The number of weeks is at least 1 since we do have average for the current week even if incomplete
    int weeksNumber = Weeks.weeksBetween(minDateTime, maxDateTime).getWeeks() + 1;
    for (int i = 0; i < weeksNumber; i++) {
        newDateTime = currentDateTime.plusWeeks(1);
        RealmResults<GlucoseReading> readings = realm.where(GlucoseReading.class).between("created", currentDateTime.toDate(), newDateTime.toDate()).findAll();
        averageReadings.add(((int) readings.average("reading")));
        currentDateTime = newDateTime;
    }
    return averageReadings;
}

20. RangeQueryBuilderTests#testRewriteDateToMatchAll()

Project: elasticsearch
File: RangeQueryBuilderTests.java
public void testRewriteDateToMatchAll() throws IOException {
    String fieldName = randomAsciiOfLengthBetween(1, 20);
    RangeQueryBuilder query = new RangeQueryBuilder(fieldName) {

        @Override
        protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException {
            return Relation.WITHIN;
        }
    };
    DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
    DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
    DateTime shardMinValue = new DateTime(2015, 3, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
    DateTime shardMaxValue = new DateTime(2015, 9, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
    query.from(queryFromValue);
    query.to(queryToValue);
    QueryShardContext queryShardContext = createShardContext();
    QueryBuilder rewritten = query.rewrite(queryShardContext);
    assertThat(rewritten, instanceOf(RangeQueryBuilder.class));
    RangeQueryBuilder rewrittenRange = (RangeQueryBuilder) rewritten;
    assertThat(rewrittenRange.fieldName(), equalTo(fieldName));
    assertThat(rewrittenRange.from(), equalTo(null));
    assertThat(rewrittenRange.to(), equalTo(null));
}

21. SyslogParser#parseRfc3164Time()

Project: datacollector
File: SyslogParser.java
/**
   * Parse the RFC3164 date format. This is trickier than it sounds because this
   * format does not specify a year so we get weird edge cases at year
   * boundaries. This implementation tries to "do what I mean".
   * @param ts RFC3164-compatible timestamp to be parsed
   * @return Typical (for Java) milliseconds since the UNIX epoch
   */
protected long parseRfc3164Time(String recordIdentifer, String msg, String ts) throws OnRecordErrorException {
    DateTime now = DateTime.now();
    int year = now.getYear();
    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        throw throwOnRecordErrorException(recordIdentifer, msg, Errors.SYSLOG_10, ts, e);
    }
    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    DateTime fixed = date.withYear(year);
    // flume clock is ahead or there is some latency, and the year rolled
    if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
        fixed = date.withYear(year - 1);
    // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
        fixed = date.withYear(year + 1);
    }
    date = fixed;
    return date.getMillis();
}

22. QueryAPIErrorResponseTest#testQueryColumnWithBothStartDateAndEndDate()

Project: lens
File: QueryAPIErrorResponseTest.java
@Test(dataProvider = "mediaTypeData")
public void testQueryColumnWithBothStartDateAndEndDate(MediaType mt) throws DatatypeConfigurationException {
    /* This test will have a col which has both start date and end date set */
    /* Col will be queried for a time range which does not fall in start date and end date */
    DateTime startDateOneJan2015 = new DateTime(2015, 01, 01, 0, 0, DateTimeZone.UTC);
    DateTime endDateThirtyJan2015 = new DateTime(2015, 01, 30, 23, 0, DateTimeZone.UTC);
    DateTime queryFromOneJan2014 = new DateTime(2014, 01, 01, 0, 0, DateTimeZone.UTC);
    DateTime queryTillThreeJan2014 = new DateTime(2014, 01, 03, 0, 0, DateTimeZone.UTC);
    final String expectedErrMsgSuffix = " can only be queried after Thursday, January 1, 2015 12:00:00 AM UTC and " + "before Friday, January 30, 2015 11:00:00 PM UTC. Please adjust the selected time range accordingly.";
    testColUnAvailableInTimeRange(Optional.of(startDateOneJan2015), Optional.of(endDateThirtyJan2015), queryFromOneJan2014, queryTillThreeJan2014, expectedErrMsgSuffix, mt);
}

23. TestDateUtils#testGetRelativeTimeSpanStringWithPreposition()

Project: joda-time-android
File: TestDateUtils.java
public void testGetRelativeTimeSpanStringWithPreposition() {
    Context ctx = getInstrumentation().getContext();
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1);
    LocalDate nextYear = today.plusYears(1);
    assertEquals("12:35", DateUtils.getRelativeTimeSpanString(ctx, today, false));
    assertEquals("at 12:35", DateUtils.getRelativeTimeSpanString(ctx, today, true));
    assertEquals("Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrow, false));
    assertEquals("on Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrow, true));
    assertEquals("10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYear, false));
    assertEquals("on 10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYear, true));
    DateTime todayDt = DateTime.now();
    DateTime tomorrowDt = todayDt.plusDays(1);
    DateTime nextYearDt = todayDt.plusYears(1);
    assertEquals("12:35", DateUtils.getRelativeTimeSpanString(ctx, todayDt, false));
    assertEquals("at 12:35", DateUtils.getRelativeTimeSpanString(ctx, todayDt, true));
    assertEquals("Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrowDt, false));
    assertEquals("on Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrowDt, true));
    assertEquals("10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYearDt, false));
    assertEquals("on 10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYearDt, true));
}

24. TimeBasedSubDirDatasetsFinder#folderWithinAllowedPeriod()

Project: gobblin
File: TimeBasedSubDirDatasetsFinder.java
/**
   * Return true iff input folder time is between compaction.timebased.min.time.ago and
   * compaction.timebased.max.time.ago.
   */
private boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) {
    DateTime currentTime = new DateTime(this.timeZone);
    PeriodFormatter periodFormatter = getPeriodFormatter();
    DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter);
    DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter);
    if (folderTime.isBefore(earliestAllowedFolderTime)) {
        log.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping", inputFolder, folderTime, earliestAllowedFolderTime));
        return false;
    } else if (folderTime.isAfter(latestAllowedFolderTime)) {
        log.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping", inputFolder, folderTime, latestAllowedFolderTime));
        return false;
    } else {
        return true;
    }
}

25. OverviewPresenterTest#ShouldAddZerosBetweenReadings_WhenAsked()

Project: glucosio-android
File: OverviewPresenterTest.java
@Test
public void ShouldAddZerosBetweenReadings_WhenAsked() throws Exception {
    DateTime now = DateTime.now();
    DateTime fiveDaysAgo = now.minusDays(5);
    when(dbMock.getLastMonthGlucoseReadings()).thenReturn(Arrays.asList(new GlucoseReading(12, "test", fiveDaysAgo.toDate(), ""), new GlucoseReading(21, "test", now.toDate(), "")));
    presenter.loadDatabase();
    final List<Integer> readings = presenter.getGlucoseReadings();
    DateTime minDateTime = DateTime.now().minusMonths(1).minusDays(15);
    assertThat(readings).hasSize(Days.daysBetween(minDateTime, now).getDays());
    assertThat(readings).containsSequence(12, 0, 0, 0, 0, 21);
}

26. ServerTimeRejectionPolicyFactoryTest#testAccept()

Project: druid
File: ServerTimeRejectionPolicyFactoryTest.java
@Test
public void testAccept() throws Exception {
    Period period = new Period("PT10M");
    RejectionPolicy rejectionPolicy = new ServerTimeRejectionPolicyFactory().create(period);
    DateTime now = new DateTime();
    DateTime past = now.minus(period).minus(100);
    DateTime future = now.plus(period).plus(100);
    Assert.assertTrue(rejectionPolicy.accept(now.getMillis()));
    Assert.assertFalse(rejectionPolicy.accept(past.getMillis()));
    Assert.assertFalse(rejectionPolicy.accept(future.getMillis()));
}

27. MessageTimeRejectionPolicyFactoryTest#testAccept()

Project: druid
File: MessageTimeRejectionPolicyFactoryTest.java
@Test
public void testAccept() throws Exception {
    Period period = new Period("PT10M");
    RejectionPolicy rejectionPolicy = new MessageTimeRejectionPolicyFactory().create(period);
    DateTime now = new DateTime();
    DateTime past = now.minus(period).minus(1);
    DateTime future = now.plus(period).plus(1);
    Assert.assertTrue(rejectionPolicy.accept(now.getMillis()));
    Assert.assertFalse(rejectionPolicy.accept(past.getMillis()));
    Assert.assertTrue(rejectionPolicy.accept(future.getMillis()));
    Assert.assertFalse(rejectionPolicy.accept(now.getMillis()));
}

28. FlexibleDateConverterTest#convertObeysTimeZone()

Project: graylog2-server
File: FlexibleDateConverterTest.java
@Test
public void convertObeysTimeZone() throws Exception {
    Converter c = new FlexibleDateConverter(ImmutableMap.<String, Object>of("time_zone", "+12:00"));
    final DateTime dateOnly = (DateTime) c.convert("2014-3-12");
    assertThat(dateOnly.getZone()).isEqualTo(DateTimeZone.forOffsetHours(12));
    Assertions.assertThat(dateOnly).isAfterOrEqualTo(new DateTime(2014, 3, 12, 0, 0, DateTimeZone.forOffsetHours(12))).isBefore(new DateTime(2014, 3, 13, 0, 0, DateTimeZone.forOffsetHours(12)));
    final DateTime dateTime = (DateTime) c.convert("2014-3-12 12:34");
    assertThat(dateTime.getZone()).isEqualTo(DateTimeZone.forOffsetHours(12));
    Assertions.assertThat(dateTime).isEqualTo(new DateTime(2014, 3, 12, 12, 34, DateTimeZone.forOffsetHours(12)));
    final DateTime textualDateTime = (DateTime) c.convert("Mar 12, 2014 2pm");
    assertThat(textualDateTime.getZone()).isEqualTo(DateTimeZone.forOffsetHours(12));
    Assertions.assertThat(textualDateTime).isEqualTo(new DateTime(2014, 3, 12, 14, 0, DateTimeZone.forOffsetHours(12)));
}

29. MongoIndexRangeTest#testJsonMapping()

Project: graylog2-server
File: MongoIndexRangeTest.java
@Test
public void testJsonMapping() throws Exception {
    String indexName = "test";
    DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    int calculationDuration = 42;
    MongoIndexRange indexRange = MongoIndexRange.create(indexName, begin, end, calculatedAt, calculationDuration);
    ObjectMapper objectMapper = new ObjectMapperProvider().get();
    String json = objectMapper.writeValueAsString(indexRange);
    Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
    assertThat((String) JsonPath.read(document, "$." + MongoIndexRange.FIELD_INDEX_NAME)).isEqualTo(indexName);
    assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_BEGIN)).isEqualTo(begin.getMillis());
    assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_END)).isEqualTo(end.getMillis());
    assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_CALCULATED_AT)).isEqualTo(calculatedAt.getMillis());
    assertThat((int) JsonPath.read(document, "$." + MongoIndexRange.FIELD_TOOK_MS)).isEqualTo(calculationDuration);
}

30. MongoIndexRangeTest#testCreate()

Project: graylog2-server
File: MongoIndexRangeTest.java
@Test
public void testCreate() throws Exception {
    String indexName = "test";
    DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    int calculationDuration = 42;
    MongoIndexRange indexRange = MongoIndexRange.create(indexName, begin, end, calculatedAt, calculationDuration);
    assertThat(indexRange.indexName()).isEqualTo(indexName);
    assertThat(indexRange.begin()).isEqualTo(begin);
    assertThat(indexRange.end()).isEqualTo(end);
    assertThat(indexRange.calculatedAt()).isEqualTo(calculatedAt);
    assertThat(indexRange.calculationDuration()).isEqualTo(calculationDuration);
}

31. MongoIndexRangeServiceTest#saveOverwritesExistingIndexRange()

Project: graylog2-server
File: MongoIndexRangeServiceTest.java
@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
public void saveOverwritesExistingIndexRange() throws Exception {
    final String indexName = "graylog";
    final DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    final DateTime end = new DateTime(2015, 1, 2, 0, 0, DateTimeZone.UTC);
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final IndexRange indexRangeBefore = MongoIndexRange.create(indexName, begin, end, now, 1);
    final IndexRange indexRangeAfter = MongoIndexRange.create(indexName, begin, end, now, 2);
    indexRangeService.save(indexRangeBefore);
    final IndexRange before = indexRangeService.get(indexName);
    assertThat(before.calculationDuration()).isEqualTo(1);
    indexRangeService.save(indexRangeAfter);
    final IndexRange after = indexRangeService.get(indexName);
    assertThat(after.calculationDuration()).isEqualTo(2);
}

32. MongoIndexRangeServiceTest#savePersistsIndexRange()

Project: graylog2-server
File: MongoIndexRangeServiceTest.java
@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
public void savePersistsIndexRange() throws Exception {
    final String indexName = "graylog";
    final DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    final DateTime end = new DateTime(2015, 1, 2, 0, 0, DateTimeZone.UTC);
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final IndexRange indexRange = MongoIndexRange.create(indexName, begin, end, now, 42);
    indexRangeService.save(indexRange);
    final IndexRange result = indexRangeService.get(indexName);
    assertThat(result.indexName()).isEqualTo(indexName);
    assertThat(result.begin()).isEqualTo(begin);
    assertThat(result.end()).isEqualTo(end);
    assertThat(result.calculatedAt()).isEqualTo(now);
    assertThat(result.calculationDuration()).isEqualTo(42);
}

33. EsIndexRangeTest#testJsonMapping()

Project: graylog2-server
File: EsIndexRangeTest.java
@Test
public void testJsonMapping() throws Exception {
    String indexName = "test";
    DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    int calculationDuration = 42;
    EsIndexRange indexRange = EsIndexRange.create(indexName, begin, end, calculatedAt, calculationDuration);
    ObjectMapper objectMapper = new ObjectMapperProvider().get();
    String json = objectMapper.writeValueAsString(indexRange);
    Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
    assertThat((String) JsonPath.read(document, "$." + EsIndexRange.FIELD_INDEX_NAME)).isEqualTo(indexName);
    assertThat((String) JsonPath.read(document, "$." + EsIndexRange.FIELD_BEGIN)).asString().isEqualTo(begin.toString());
    assertThat((String) JsonPath.read(document, "$." + EsIndexRange.FIELD_END)).isEqualTo(end.toString());
    assertThat((String) JsonPath.read(document, "$." + EsIndexRange.FIELD_CALCULATED_AT)).isEqualTo(calculatedAt.toString());
    assertThat((int) JsonPath.read(document, "$." + EsIndexRange.FIELD_TOOK_MS)).isEqualTo(calculationDuration);
}

34. EsIndexRangeTest#testCreate()

Project: graylog2-server
File: EsIndexRangeTest.java
@Test
public void testCreate() throws Exception {
    String indexName = "test";
    DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
    DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
    int calculationDuration = 42;
    EsIndexRange indexRange = EsIndexRange.create(indexName, begin, end, calculatedAt, calculationDuration);
    assertThat(indexRange.indexName()).isEqualTo(indexName);
    assertThat(indexRange.begin()).isEqualTo(begin);
    assertThat(indexRange.end()).isEqualTo(end);
    assertThat(indexRange.calculatedAt()).isEqualTo(calculatedAt);
    assertThat(indexRange.calculationDuration()).isEqualTo(calculationDuration);
}

35. SearchResource#restrictTimeRange()

Project: graylog2-server
File: SearchResource.java
protected org.graylog2.plugin.indexer.searches.timeranges.TimeRange restrictTimeRange(final org.graylog2.plugin.indexer.searches.timeranges.TimeRange timeRange) {
    final DateTime originalFrom = timeRange.getFrom();
    final DateTime to = timeRange.getTo();
    final DateTime from;
    final SearchesClusterConfig config = clusterConfigService.get(SearchesClusterConfig.class);
    if (config == null || Period.ZERO.equals(config.queryTimeRangeLimit())) {
        from = originalFrom;
    } else {
        final DateTime limitedFrom = to.minus(config.queryTimeRangeLimit());
        from = limitedFrom.isAfter(originalFrom) ? limitedFrom : originalFrom;
    }
    return AbsoluteRange.create(from, to);
}

36. MongoIndexRange#create()

Project: graylog2-server
File: MongoIndexRange.java
@JsonCreator
public static MongoIndexRange create(@JsonProperty("_id") @Id @Nullable ObjectId id, @JsonProperty(FIELD_INDEX_NAME) String indexName, @JsonProperty(FIELD_BEGIN) long beginMillis, @JsonProperty(FIELD_END) long endMillis, @JsonProperty(FIELD_CALCULATED_AT) long calculatedAtMillis, @JsonProperty(FIELD_TOOK_MS) int calculationDuration) {
    final DateTime begin = new DateTime(beginMillis, DateTimeZone.UTC);
    final DateTime end = new DateTime(endMillis, DateTimeZone.UTC);
    final DateTime calculatedAt = new DateTime(calculatedAtMillis, DateTimeZone.UTC);
    return new AutoValue_MongoIndexRange(id, indexName, begin, end, calculatedAt, calculationDuration);
}

37. PaymentAutomatonDAOHelper#buildNewPaymentTransactionModelDao()

Project: killbill
File: PaymentAutomatonDAOHelper.java
private PaymentTransactionModelDao buildNewPaymentTransactionModelDao(final UUID paymentId) {
    final DateTime createdDate = utcNow;
    final DateTime updatedDate = utcNow;
    final DateTime effectiveDate = utcNow;
    final String gatewayErrorCode = null;
    final String gatewayErrorMsg = null;
    return new PaymentTransactionModelDao(createdDate, updatedDate, paymentStateContext.getAttemptId(), paymentStateContext.getPaymentTransactionExternalKey(), paymentId, paymentStateContext.getTransactionType(), effectiveDate, TransactionStatus.UNKNOWN, paymentStateContext.getAmount(), paymentStateContext.getCurrency(), gatewayErrorCode, gatewayErrorMsg);
}

38. TestEntitlementDateHelper#testWithAccountInUtc()

Project: killbill
File: TestEntitlementDateHelper.java
@Test(groups = "fast")
public void testWithAccountInUtc() throws EntitlementApiException {
    final LocalDate initialDate = new LocalDate(2013, 8, 7);
    clock.setDay(initialDate.plusDays(1));
    Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
    final DateTime refererenceDateTime = new DateTime(2013, 1, 1, 15, 43, 25, 0, DateTimeZone.UTC);
    final DateTime targetDate = dateHelper.fromLocalDateAndReferenceTime(initialDate, refererenceDateTime, internalCallContext);
    final DateTime expectedDate = new DateTime(2013, 8, 7, 15, 43, 25, 0, DateTimeZone.UTC);
    Assert.assertEquals(targetDate, expectedDate);
}

39. DefaultSubscription#getBillingEndDate()

Project: killbill
File: DefaultSubscription.java
@Override
public LocalDate getBillingEndDate() {
    final DateTime futureOrCurrentEndDateForSubscription = getSubscriptionBase().getEndDate() != null ? getSubscriptionBase().getEndDate() : getSubscriptionBase().getFutureEndDate();
    final DateTime futureOrCurrentEndDateForBaseSubscription;
    if (getBasePlanSubscriptionBase() == null) {
        futureOrCurrentEndDateForBaseSubscription = null;
    } else {
        futureOrCurrentEndDateForBaseSubscription = getBasePlanSubscriptionBase().getEndDate() != null ? getBasePlanSubscriptionBase().getEndDate() : getBasePlanSubscriptionBase().getFutureEndDate();
    }
    final DateTime futureOrCurrentEndDate;
    if (futureOrCurrentEndDateForBaseSubscription != null && futureOrCurrentEndDateForBaseSubscription.isBefore(futureOrCurrentEndDateForSubscription)) {
        futureOrCurrentEndDate = futureOrCurrentEndDateForBaseSubscription;
    } else {
        futureOrCurrentEndDate = futureOrCurrentEndDateForSubscription;
    }
    return futureOrCurrentEndDate != null ? internalTenantContext.toLocalDate(futureOrCurrentEndDate, getSubscriptionBase().getStartDate()) : null;
}

40. TestVersionedCatalogLoader#testLoad()

Project: killbill
File: TestVersionedCatalogLoader.java
@Test(groups = "fast")
public void testLoad() throws IOException, SAXException, InvalidConfigException, JAXBException, TransformerException, URISyntaxException, CatalogApiException {
    final VersionedCatalog c = loader.loadDefaultCatalog(Resources.getResource("versionedCatalog").toString());
    Assert.assertEquals(c.size(), 3);
    final Iterator<StandaloneCatalogWithPriceOverride> it = c.iterator();
    DateTime dt = new DateTime("2011-01-01T00:00:00+00:00");
    Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
    dt = new DateTime("2011-02-02T00:00:00+00:00");
    Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
    dt = new DateTime("2011-03-03T00:00:00+00:00");
    Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
}

41. QueryAPIErrorResponseTest#testQueryColumnWithOnlyEndDate()

Project: lens
File: QueryAPIErrorResponseTest.java
@Test(dataProvider = "mediaTypeData")
public void testQueryColumnWithOnlyEndDate(MediaType mt) throws DatatypeConfigurationException {
    /* This test will have a col which has only end date set */
    /* Col will be queried for a time range which is after end date */
    DateTime endDateThirtyJan2015 = new DateTime(2015, 01, 30, 23, 0, DateTimeZone.UTC);
    DateTime queryFromOneJan2016 = new DateTime(2016, 01, 01, 0, 0, DateTimeZone.UTC);
    DateTime queryTillThreeJan2016 = new DateTime(2016, 01, 03, 0, 0, DateTimeZone.UTC);
    final String expectedErrMsgSuffix = " can only be queried before Friday, January 30, 2015 11:00:00 PM UTC. " + "Please adjust the selected time range accordingly.";
    testColUnAvailableInTimeRange(Optional.<DateTime>absent(), Optional.of(endDateThirtyJan2015), queryFromOneJan2016, queryTillThreeJan2016, expectedErrMsgSuffix, mt);
}

42. QueryAPIErrorResponseTest#testQueryColumnWithOnlyStartDate()

Project: lens
File: QueryAPIErrorResponseTest.java
@Test(dataProvider = "mediaTypeData")
public void testQueryColumnWithOnlyStartDate(MediaType mt) throws DatatypeConfigurationException {
    /* This test will have a col which has only start date set */
    /* Col will be queried for a time range which is before start date */
    DateTime startDateOneJan2015 = new DateTime(2015, 01, 01, 0, 0, DateTimeZone.UTC);
    DateTime queryFromOneJan2014 = new DateTime(2014, 01, 01, 0, 0, DateTimeZone.UTC);
    DateTime queryTillThreeJan2014 = new DateTime(2014, 01, 03, 0, 0, DateTimeZone.UTC);
    final String expectedErrMsgSuffix = " can only be queried after Thursday, January 1, 2015 12:00:00 AM UTC. " + "Please adjust the selected time range accordingly.";
    testColUnAvailableInTimeRange(Optional.of(startDateOneJan2015), Optional.<DateTime>absent(), queryFromOneJan2014, queryTillThreeJan2014, expectedErrMsgSuffix, mt);
}

43. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle4()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsAfterTransferForMigratedBundle4() throws Exception {
    // MIGRATE_ENTITLEMENT then MIGRATE_BILLING (both in the future)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateSubscriptionEventEffectiveDate = transferDate.plusDays(10);
    final DateTime migrateBillingEventEffectiveDate = migrateSubscriptionEventEffectiveDate.plusDays(20);
    final List<SubscriptionBaseEvent> events = transferBundle(migrateSubscriptionEventEffectiveDate, migrateBillingEventEffectiveDate, transferDate);
    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), migrateSubscriptionEventEffectiveDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getApiEventType(), ApiEventType.TRANSFER);
}

44. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle3()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsAfterTransferForMigratedBundle3() throws Exception {
    // MIGRATE_ENTITLEMENT then MIGRATE_BILLING (the latter in the future)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateSubscriptionEventEffectiveDate = transferDate.minusDays(10);
    final DateTime migrateBillingEventEffectiveDate = migrateSubscriptionEventEffectiveDate.plusDays(20);
    final List<SubscriptionBaseEvent> events = transferBundle(migrateSubscriptionEventEffectiveDate, migrateBillingEventEffectiveDate, transferDate);
    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getApiEventType(), ApiEventType.TRANSFER);
}

45. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle2()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsAfterTransferForMigratedBundle2() throws Exception {
    // MIGRATE_ENTITLEMENT and MIGRATE_BILLING at the same time (both in the past)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateSubscriptionEventEffectiveDate = transferDate.minusDays(10);
    final DateTime migrateBillingEventEffectiveDate = migrateSubscriptionEventEffectiveDate;
    final List<SubscriptionBaseEvent> events = transferBundle(migrateSubscriptionEventEffectiveDate, migrateBillingEventEffectiveDate, transferDate);
    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getApiEventType(), ApiEventType.TRANSFER);
}

46. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle1()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsAfterTransferForMigratedBundle1() throws Exception {
    // MIGRATE_ENTITLEMENT then MIGRATE_BILLING (both in the past)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateSubscriptionEventEffectiveDate = transferDate.minusDays(10);
    final DateTime migrateBillingEventEffectiveDate = migrateSubscriptionEventEffectiveDate.plusDays(1);
    final List<SubscriptionBaseEvent> events = transferBundle(migrateSubscriptionEventEffectiveDate, migrateBillingEventEffectiveDate, transferDate);
    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getApiEventType(), ApiEventType.TRANSFER);
}

47. TestDefaultSubscriptionTransferApi#testEventsForCancelledSubscriptionAfterTransfer()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsForCancelledSubscriptionAfterTransfer() throws Exception {
    final DateTime subscriptionStartTime = clock.getUTCNow();
    final DateTime subscriptionCancelTime = subscriptionStartTime.plusDays(1);
    final ImmutableList<ExistingEvent> existingEvents = ImmutableList.<ExistingEvent>of(createEvent(subscriptionStartTime, SubscriptionBaseTransitionType.CREATE), createEvent(subscriptionCancelTime, SubscriptionBaseTransitionType.CANCEL));
    final SubscriptionBuilder subscriptionBuilder = new SubscriptionBuilder();
    final DefaultSubscriptionBase subscription = new DefaultSubscriptionBase(subscriptionBuilder);
    final DateTime transferDate = subscriptionStartTime.plusHours(1);
    final List<SubscriptionBaseEvent> events = transferApi.toEvents(existingEvents, subscription, transferDate, internalCallContext);
    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getApiEventType(), ApiEventType.TRANSFER);
}

48. TestDefaultSubscriptionTransferApi#testEventsForCancelledSubscriptionBeforeTransfer()

Project: killbill
File: TestDefaultSubscriptionTransferApi.java
@Test(groups = "fast")
public void testEventsForCancelledSubscriptionBeforeTransfer() throws Exception {
    final DateTime subscriptionStartTime = clock.getUTCNow();
    final DateTime subscriptionCancelTime = subscriptionStartTime.plusDays(1);
    final ImmutableList<ExistingEvent> existingEvents = ImmutableList.<ExistingEvent>of(createEvent(subscriptionStartTime, SubscriptionBaseTransitionType.CREATE), createEvent(subscriptionCancelTime, SubscriptionBaseTransitionType.CANCEL));
    final SubscriptionBuilder subscriptionBuilder = new SubscriptionBuilder();
    final DefaultSubscriptionBase subscription = new DefaultSubscriptionBase(subscriptionBuilder);
    final DateTime transferDate = subscriptionStartTime.plusDays(10);
    final List<SubscriptionBaseEvent> events = transferApi.toEvents(existingEvents, subscription, transferDate, internalCallContext);
    Assert.assertEquals(events.size(), 0);
}

49. KafkaController#topicDetail()

Project: DCMonitor
File: KafkaController.java
@RequestMapping("/detail")
@ResponseBody
public Map<String, List<Event>> topicDetail(String topic, String consumer, String from, String to, Integer partitionId) {
    DateTime fromTime = null;
    DateTime toTime = null;
    DateTime now = new DateTime();
    try {
        fromTime = DateTime.parse(from, formatter);
    } catch (Exception e) {
        fromTime = now;
    }
    try {
        toTime = DateTime.parse(to, formatter);
    } catch (Exception e) {
        toTime = now;
    }
    if (from == null || to.equals(from)) {
        fromTime = toTime.minus(new Period(timeOffset));
    }
    partitionId = (partitionId == null) ? -1 : partitionId;
    return KafkaStats.getTrendConsumeInfos(consumer, topic, partitionId, fromTime, toTime);
}

50. DruidController#topicDetail()

Project: DCMonitor
File: DruidController.java
@RequestMapping("/detail")
@ResponseBody
public Map<String, List<Event>> topicDetail(String topic, String consumer, String from, String to, Integer partitionId) {
    DateTime fromDate = null;
    DateTime toDate = null;
    DateTime now = new DateTime();
    try {
        fromDate = DateTime.parse(from, formatter);
    } catch (Exception e) {
        fromDate = now;
    }
    try {
        toDate = DateTime.parse(to, formatter);
    } catch (Exception e) {
        toDate = now;
    }
    if (from == null || to.equals(from)) {
        fromDate = toDate.minus(new Period(timeOffset));
    }
    partitionId = (partitionId == null) ? -1 : partitionId;
    return KafkaStats.getTrendConsumeInfos(consumer, topic, partitionId, fromDate, toDate);
}

51. JodaDemo#convertFromString()

Project: cyfm
File: JodaDemo.java
@Test
public void convertFromString() {
    String dateString = "1978-06-01 12:10:08";
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    // ????????????,??????????T??
    DateTime dt1 = new DateTime("1978-06-01");
    assertThat(dt1.getYear()).isEqualTo(1978);
    DateTime dt2 = new DateTime("1978-06-01T12:10:08");
    assertThat(dt2.getYear()).isEqualTo(1978);
    // ????????Formatter
    DateTime dt3 = fmt.parseDateTime(dateString);
    assertThat(dt3.getYear()).isEqualTo(1978);
}

52. ExecutionTimeQuartzIntegrationTest#testNextExecutionProducingInvalidValues()

Project: cron-utils
File: ExecutionTimeQuartzIntegrationTest.java
/**
     * Issue #73: NextExecution not working as expected
     */
@Test
public void testNextExecutionProducingInvalidValues() {
    String cronText = "0 0 18 ? * MON";
    CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
    Cron cron = parser.parse(cronText);
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    DateTime now = DateTime.parse("2016-03-18T19:02:51.424+09:00");
    DateTime next = executionTime.nextExecution(now);
    DateTime nextNext = executionTime.nextExecution(next);
    assertEquals(DateTimeConstants.MONDAY, next.getDayOfWeek());
    assertEquals(DateTimeConstants.MONDAY, nextNext.getDayOfWeek());
    assertEquals(18, next.getHourOfDay());
    assertEquals(18, nextNext.getHourOfDay());
}

53. ExecutionTimeCustomDefinitionIntegrationTest#testCronExpressionAfterHalf()

Project: cron-utils
File: ExecutionTimeCustomDefinitionIntegrationTest.java
@Test
public void testCronExpressionAfterHalf() {
    CronDefinition cronDefinition = CronDefinitionBuilder.defineCron().withSeconds().and().withMinutes().and().withHours().and().withDayOfMonth().and().withMonth().and().withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).and().instance();
    CronParser parser = new CronParser(cronDefinition);
    Cron cron = parser.parse("*/30 * * * * *");
    DateTime startDateTime = new DateTime(2015, 8, 28, 12, 5, 44, 0);
    DateTime expectedDateTime = new DateTime(2015, 8, 28, 12, 6, 0, 0);
    ExecutionTime executionTime = ExecutionTime.forCron(cron);
    DateTime nextExecutionDateTime = executionTime.nextExecution(startDateTime);
    assertEquals(expectedDateTime, nextExecutionDateTime);
}

54. DateUtil#calculateDays()

Project: community-edition
File: DateUtil.java
/**
     * Calculate the number of days between start and end dates based on the <b>default</b> timezone.
     * If the end date is before the start date, the returned value is negative.
     *
     * @param startMs start date in milliseconds
     * @param endMs   end date in milliseconds
     * @return number days between
     */
public static int calculateDays(long startMs, long endMs) {
    DateTime startDateTime = new DateTime(startMs).withTimeAtStartOfDay();
    DateTime endDateTime = new DateTime(endMs).withTimeAtStartOfDay();
    int days;
    if (endDateTime.isBefore(startDateTime)) {
        Interval interval = new Interval(endDateTime, startDateTime);
        Period period = interval.toPeriod(PeriodType.days());
        days = 0 - period.getDays();
    } else {
        Interval interval = new Interval(startDateTime, endDateTime);
        Period period = interval.toPeriod(PeriodType.days());
        days = period.getDays();
    }
    return days;
}

55. DateTimeUtilTest#floorToSecond()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
@Test
public void floorToSecond() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 31, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest second
    //
    DateTime dt1 = DateTimeUtil.floorToSecond(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(6, dt1.getMonthOfYear());
    Assert.assertEquals(24, dt1.getDayOfMonth());
    Assert.assertEquals(23, dt1.getHourOfDay());
    Assert.assertEquals(30, dt1.getMinuteOfHour());
    Assert.assertEquals(31, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToSecond(null);
    Assert.assertNull(dt2);
}

56. DateTimeUtilTest#floorToMinute()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
@Test
public void floorToMinute() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 30, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest minute
    //
    DateTime dt1 = DateTimeUtil.floorToMinute(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(6, dt1.getMonthOfYear());
    Assert.assertEquals(24, dt1.getDayOfMonth());
    Assert.assertEquals(23, dt1.getHourOfDay());
    Assert.assertEquals(30, dt1.getMinuteOfHour());
    Assert.assertEquals(0, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToMinute(null);
    Assert.assertNull(dt2);
}

57. DateTimeUtilTest#floorToHour()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
@Test
public void floorToHour() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 30, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest hour
    //
    DateTime dt1 = DateTimeUtil.floorToHour(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(6, dt1.getMonthOfYear());
    Assert.assertEquals(24, dt1.getDayOfMonth());
    Assert.assertEquals(23, dt1.getHourOfDay());
    Assert.assertEquals(0, dt1.getMinuteOfHour());
    Assert.assertEquals(0, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToHour(null);
    Assert.assertNull(dt2);
}

58. DateTimeUtilTest#floorToDay()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
@Test
public void floorToDay() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 30, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest day
    //
    DateTime dt1 = DateTimeUtil.floorToDay(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(6, dt1.getMonthOfYear());
    Assert.assertEquals(24, dt1.getDayOfMonth());
    Assert.assertEquals(0, dt1.getHourOfDay());
    Assert.assertEquals(0, dt1.getMinuteOfHour());
    Assert.assertEquals(0, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToDay(null);
    Assert.assertNull(dt2);
}

59. DateTimeUtilTest#floorToMonth()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
@Test
public void floorToMonth() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 30, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest month
    //
    DateTime dt1 = DateTimeUtil.floorToMonth(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(6, dt1.getMonthOfYear());
    Assert.assertEquals(1, dt1.getDayOfMonth());
    Assert.assertEquals(0, dt1.getHourOfDay());
    Assert.assertEquals(0, dt1.getMinuteOfHour());
    Assert.assertEquals(0, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToMonth(null);
    Assert.assertNull(dt2);
}

60. DateTimeUtilTest#floorToYear()

Project: cloudhopper-commons
File: DateTimeUtilTest.java
/**
    @Test
    public void toMidnightUTCDateTime() throws Exception {
        // create a DateTime in the pacific timezone for June 24, 2009 at 11 PM
        DateTime dt = new DateTime(2009,6,24,23,30,30,0,DateTimeZone.forID("America/Los_Angeles"));
        logger.info("Local DateTime: " + dt);

        // just for making sure we're creating something interesting, let's
        // just convert this to UTC without using our utility function
        DateTime utcdt = dt.toDateTime(DateTimeZone.UTC);
        logger.info("DateTime -> UTC: " + utcdt);

        // convert this to be in the UTC timezone -- reset to midnight
        DateTime newdt = DateTimeUtil.toYearMonthDayUTC(dt);
        logger.debug("DateTime -> UTC (but with util): " + newdt);

        Assert.assertEquals(2009, newdt.getYear());
        Assert.assertEquals(6, newdt.getMonthOfYear());
        Assert.assertEquals(24, newdt.getDayOfMonth());
        Assert.assertEquals(0, newdt.getHourOfDay());
        Assert.assertEquals(0, newdt.getMinuteOfHour());
        Assert.assertEquals(0, newdt.getSecondOfMinute());
        Assert.assertEquals(0, newdt.getMillisOfSecond());
    }
     */
@Test
public void floorToYear() throws Exception {
    // create a reference datetime
    DateTime dt0 = new DateTime(2009, 6, 24, 23, 30, 30, 789, DateTimeZone.forID("America/Los_Angeles"));
    //
    // floor to nearest year
    //
    DateTime dt1 = DateTimeUtil.floorToYear(dt0);
    Assert.assertEquals(2009, dt1.getYear());
    Assert.assertEquals(1, dt1.getMonthOfYear());
    Assert.assertEquals(1, dt1.getDayOfMonth());
    Assert.assertEquals(0, dt1.getHourOfDay());
    Assert.assertEquals(0, dt1.getMinuteOfHour());
    Assert.assertEquals(0, dt1.getSecondOfMinute());
    Assert.assertEquals(0, dt1.getMillisOfSecond());
    Assert.assertEquals(DateTimeZone.forID("America/Los_Angeles"), dt1.getZone());
    //
    // floor null
    //
    DateTime dt2 = DateTimeUtil.floorToYear(null);
    Assert.assertNull(dt2);
}

61. ISOToYear#exec()

Project: pig
File: ISOToYear.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the month and day to 1 and the hour, minute, second and milliseconds to 0
    DateTime result = dt.monthOfYear().setCopy(1).dayOfMonth().setCopy(1).hourOfDay().setCopy(0).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

62. ISOToWeek#exec()

Project: pig
File: ISOToWeek.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the the day to 1, and the hour, minute, second and milliseconds to 0
    DateTime result = dt.dayOfWeek().setCopy(1).hourOfDay().setCopy(0).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

63. ISOToSecond#exec()

Project: pig
File: ISOToSecond.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the the second and milliseconds to 0
    DateTime result = dt.millisOfSecond().setCopy(0);
    return result.toString();
}

64. ISOToMonth#exec()

Project: pig
File: ISOToMonth.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the day to 1 and the hour, minute, second and milliseconds to 0
    DateTime result = dt.dayOfMonth().setCopy(1).hourOfDay().setCopy(0).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

65. ISOToMinute#exec()

Project: pig
File: ISOToMinute.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the the second and milliseconds to 0
    DateTime result = dt.secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

66. ISOToHour#exec()

Project: pig
File: ISOToHour.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the minute, second and milliseconds to 0
    DateTime result = dt.minuteOfHour().setCopy(0).secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

67. ISOToDay#exec()

Project: pig
File: ISOToDay.java
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTime dt = ISOHelper.parseDateTime(input);
    // Set the the hour, minute, second and milliseconds to 0
    DateTime result = dt.hourOfDay().setCopy(0).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0).millisOfSecond().setCopy(0);
    return result.toString();
}

68. FilterConstraintToQuery#buildLastModifiedDateCondition()

Project: zanata-server
File: FilterConstraintToQuery.java
private String buildLastModifiedDateCondition() {
    DateTime changedBeforeTime = constraints.getChangedBefore();
    DateTime changedAfterTime = constraints.getChangedAfter();
    if (changedBeforeTime == null && changedAfterTime == null) {
        return null;
    }
    String changedAfter = null;
    String changedBefore = null;
    if (changedAfterTime != null) {
        changedAfter = HqlCriterion.gt("tft.lastChanged", LastChangedAfter.placeHolder());
    }
    if (changedBeforeTime != null) {
        changedBefore = HqlCriterion.lt("tft.lastChanged", LastChangedBefore.placeHolder());
    }
    return QueryBuilder.and(changedAfter, changedBefore);
}

69. MomentUtilTest#momentWithLanguage()

Project: yobi
File: MomentUtilTest.java
@Test
public void momentWithLanguage() {
    // Given
    DateTime now = new DateTime();
    DateTime oneDayBefore = now.minusDays(1);
    // When
    JSInvocable invocable = MomentUtil.newMoment(oneDayBefore.getMillis(), "ko");
    String result = invocable.invoke("fromNow");
    // Then
    assertThat(result).isEqualTo("?? ?");
}

70. MomentUtilTest#moment()

Project: yobi
File: MomentUtilTest.java
@Test
public void moment() {
    // Given
    DateTime now = new DateTime();
    DateTime oneDayBefore = now.minusDays(1);
    // When
    JSInvocable invocable = MomentUtil.newMoment(oneDayBefore.getMillis());
    String result = invocable.invoke("fromNow");
    // Then
    assertThat(result).isEqualTo("a day ago");
}

71. JpaPortalEventStoreTest#testStoreSingleEvents()

Project: uPortal
File: JpaPortalEventStoreTest.java
@Test
public void testStoreSingleEvents() throws Exception {
    final DateTime startDate = DateTime.now().minusDays(1);
    final DateTime endDate = DateTime.now().plusDays(1);
    final List<PortalEvent> originalEvents = generateEvents();
    execute(new CallableWithoutResult() {

        @Override
        protected void callWithoutResult() {
            for (final PortalEvent event : originalEvents) {
                portalEventDao.storePortalEvent(event);
            }
        }
    });
    verifyGetEvents(originalEvents, startDate, endDate);
    verifyAggregateEvents(originalEvents, startDate, endDate);
    verifyAggregateEvents(Collections.<PortalEvent>emptyList(), startDate, endDate);
    deleteEvents(originalEvents, startDate, endDate);
    verifyGetEvents(Collections.<PortalEvent>emptyList(), startDate, endDate);
    verifyAggregateEvents(Collections.<PortalEvent>emptyList(), startDate, endDate);
}

72. AggregationIntervalHelperImplTest#testIntervalsBetweens()

Project: uPortal
File: AggregationIntervalHelperImplTest.java
@Test
public void testIntervalsBetweens() {
    DateTime start = new DateTime(2012, 2, 2, 2, 2, 2);
    DateTime end = start.plusYears(2);
    assertEquals(1052640, helper.getIntervalStartDateTimesBetween(AggregationInterval.MINUTE, start, end).size());
    assertEquals(210528, helper.getIntervalStartDateTimesBetween(AggregationInterval.FIVE_MINUTE, start, end).size());
    assertEquals(17544, helper.getIntervalStartDateTimesBetween(AggregationInterval.HOUR, start, end).size());
    assertEquals(731, helper.getIntervalStartDateTimesBetween(AggregationInterval.DAY, start, end).size());
    assertEquals(104, helper.getIntervalStartDateTimesBetween(AggregationInterval.WEEK, start, end).size());
    assertEquals(24, helper.getIntervalStartDateTimesBetween(AggregationInterval.MONTH, start, end).size());
    assertEquals(2, helper.getIntervalStartDateTimesBetween(AggregationInterval.YEAR, start, end).size());
    assertEquals(3, helper.getIntervalStartDateTimesBetween(AggregationInterval.ACADEMIC_TERM, start, end).size());
    assertEquals(8, helper.getIntervalStartDateTimesBetween(AggregationInterval.CALENDAR_QUARTER, start, end).size());
}

73. AggregationIntervalHelperImplTest#testIntervalsBetween()

Project: uPortal
File: AggregationIntervalHelperImplTest.java
@Test
public void testIntervalsBetween() {
    DateTime start = new DateTime(2012, 2, 2, 2, 2, 2);
    DateTime end = start.plusYears(2);
    assertEquals(1052640, helper.intervalsBetween(AggregationInterval.MINUTE, start, end));
    assertEquals(210528, helper.intervalsBetween(AggregationInterval.FIVE_MINUTE, start, end));
    assertEquals(17544, helper.intervalsBetween(AggregationInterval.HOUR, start, end));
    assertEquals(731, helper.intervalsBetween(AggregationInterval.DAY, start, end));
    assertEquals(104, helper.intervalsBetween(AggregationInterval.WEEK, start, end));
    assertEquals(24, helper.intervalsBetween(AggregationInterval.MONTH, start, end));
    assertEquals(2, helper.intervalsBetween(AggregationInterval.YEAR, start, end));
    assertEquals(3, helper.intervalsBetween(AggregationInterval.ACADEMIC_TERM, start, end));
    assertEquals(8, helper.intervalsBetween(AggregationInterval.CALENDAR_QUARTER, start, end));
}

74. ActivityController#getPopularSearchTerms()

Project: uPortal
File: ActivityController.java
private List<SearchInfo> getPopularSearchTerms() {
    DateTime end = new DateTime();
    DateTime begin = end.minusDays(1);
    final IEntityGroup everyone = GroupService.getRootGroup(IPerson.class);
    final AggregatedGroupMapping group = aggregatedGroupLookupDao.getGroupMapping(everyone.getKey());
    List<SearchRequestAggregationImpl> aggregations = searchRequestAggregationDao.getAggregations(begin, end, AggregationInterval.FIVE_MINUTE, group);
    Map<String, SearchInfo> resultBuilder = new HashMap<String, SearchInfo>();
    for (SearchRequestAggregationImpl aggregation : aggregations) {
        SearchInfo info = resultBuilder.get(aggregation.getSearchTerm());
        if (info == null) {
            info = new SearchInfo(aggregation.getSearchTerm(), aggregation.getCount());
            resultBuilder.put(aggregation.getSearchTerm(), info);
        } else {
            info.incrementCount(aggregation.getCount());
        }
    }
    List<SearchInfo> results = new ArrayList<SearchInfo>(resultBuilder.values());
    Collections.sort(results);
    Collections.reverse(results);
    return results.size() > 10 ? results.subList(0, 9) : results;
}

75. PortalEventSessionPurgerImpl#doPurgeEventSessions()

Project: uPortal
File: PortalEventSessionPurgerImpl.java
@Override
@AggrEventsTransactional
public EventProcessingResult doPurgeEventSessions() {
    if (!this.clusterLockService.isLockOwner(PURGE_EVENT_SESSION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + PURGE_EVENT_SESSION_LOCK_NAME + " must be owned by the current thread and server");
    }
    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao.getEventAggregatorStatus(ProcessingType.AGGREGATION, false);
    if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
        return new EventProcessingResult(0, null, null, true);
    }
    final DateTime lastEventDate = eventAggregatorStatus.getLastEventDate();
    final DateTime sessionPurgeDate = lastEventDate.minus(eventSessionDuration);
    final int purgeCount = eventSessionDao.purgeEventSessionsBefore(sessionPurgeDate);
    return new EventProcessingResult(purgeCount, null, sessionPurgeDate, true);
}

76. TemporalDotsApp#setup()

Project: unfolding
File: TemporalDotsApp.java
public void setup() {
    size(800, 600, OPENGL);
    smooth();
    map = new UnfoldingMap(this);
    map.zoomToLevel(2);
    MapUtils.createDefaultEventDispatcher(this, map);
    List<Feature> features = GeoRSSReader.loadDataGeoRSS(this, earthquakesURL);
    markers = MapUtils.createSimpleMarkers(features);
    // Earthquakes are ordered from latest to oldest
    startTime = new DateTime(features.get(features.size() - 1).getProperty("date"));
    endTime = new DateTime(features.get(0).getProperty("date"));
    currentTime = startTime.plus(0);
    println("Dates of earthquakes ranges from " + startTime + " to " + endTime);
}

77. AnimatedTemporalDotsApp#setup()

Project: unfolding
File: AnimatedTemporalDotsApp.java
public void setup() {
    size(900, 600, OPENGL);
    smooth();
    map = new UnfoldingMap(this);
    map.zoomToLevel(2);
    MapUtils.createMouseEventDispatcher(this, map);
    print("Loading earthquakes from web feed ... ");
    List<Feature> features = GeoRSSReader.loadDataGeoRSS(this, earthquakesURL);
    println("done.");
    markers = MapUtils.createSimpleMarkers(features);
    // Earthquakes are ordered from latest to oldest
    startTime = new DateTime(features.get(features.size() - 1).getProperty("date"));
    endTime = new DateTime(features.get(0).getProperty("date"));
    currentTime = startTime.plus(0);
    println("Dates of earthquakes ranges from " + startTime + " to " + endTime);
}

78. CsvTradesLoader#buildEmptyTicks()

Project: ta4j
File: CsvTradesLoader.java
/**
     * Builds a list of empty ticks.
     * @param beginTime the begin time of the whole period
     * @param endTime the end time of the whole period
     * @param duration the tick duration (in seconds)
     * @return the list of empty ticks
     */
private static List<Tick> buildEmptyTicks(DateTime beginTime, DateTime endTime, int duration) {
    List<Tick> emptyTicks = new ArrayList<Tick>();
    Period tickTimePeriod = Period.seconds(duration);
    DateTime tickEndTime = beginTime;
    do {
        tickEndTime = tickEndTime.plus(tickTimePeriod);
        emptyTicks.add(new Tick(tickTimePeriod, tickEndTime));
    } while (tickEndTime.isBefore(endTime));
    return emptyTicks;
}

79. TimeSeries#subseries()

Project: ta4j
File: TimeSeries.java
/**
     * Returns a new time series which is a view of a subset of the current series.
     * <p>
     * The new series has begin and end indexes which correspond to the bounds of the sub-set into the full series.<br>
     * The tick of the series are shared between the original time series and the returned one (i.e. no copy).
     * @param beginIndex the begin index (inclusive) of the time series
     * @param duration the duration of the time series
     * @return a constrained {@link TimeSeries time series} which is a sub-set of the current series
     */
public TimeSeries subseries(int beginIndex, Period duration) {
    // Calculating the sub-series interval
    DateTime beginInterval = getTick(beginIndex).getEndTime();
    DateTime endInterval = beginInterval.plus(duration);
    Interval subseriesInterval = new Interval(beginInterval, endInterval);
    // Checking ticks belonging to the sub-series (starting at the provided index)
    int subseriesNbTicks = 0;
    for (int i = beginIndex; i <= endIndex; i++) {
        // For each tick...
        DateTime tickTime = getTick(i).getEndTime();
        if (!subseriesInterval.contains(tickTime)) {
            // Tick out of the interval
            break;
        }
        // Tick in the interval
        // --> Incrementing the number of ticks in the subseries
        subseriesNbTicks++;
    }
    return subseries(beginIndex, beginIndex + subseriesNbTicks - 1);
}

80. InMemoryAggregateCounter#accumulateDayCounts()

Project: spring-analytics
File: InMemoryAggregateCounter.java
private static List<long[]> accumulateDayCounts(Map<Integer, long[]> fromDayCounts, DateTime start, DateTime end, int subSize) {
    List<long[]> days = new ArrayList<long[]>();
    Duration step = Duration.standardDays(1);
    long[] emptySubArray = new long[subSize];
    // Need to account for an interval which crosses days
    end = end.plusDays(1);
    for (DateTime now = start; now.isBefore(end); now = now.plus(step)) {
        int countsByDayKey = now.getYear() * 1000 + now.getDayOfYear();
        long[] dayCounts = fromDayCounts.get(countsByDayKey);
        if (dayCounts == null) {
            // Use an empty array if we don't have data
            dayCounts = emptySubArray;
        }
        days.add(dayCounts);
    }
    return days;
}

81. Schedule#getNextRuntime()

Project: azkaban
File: Schedule.java
private DateTime getNextRuntime(long scheduleTime, DateTimeZone timezone, ReadablePeriod period) {
    DateTime now = new DateTime();
    DateTime date = new DateTime(scheduleTime).withZone(timezone);
    int count = 0;
    while (!now.isBefore(date)) {
        if (count > 100000) {
            throw new IllegalStateException("100000 increments of period did not get to present time.");
        }
        if (period == null) {
            break;
        } else {
            date = date.plus(period);
        }
        count += 1;
    }
    return date;
}

82. BasicTimeChecker#calculateNextCheckTime()

Project: azkaban
File: BasicTimeChecker.java
private long calculateNextCheckTime() {
    DateTime date = new DateTime(nextCheckTime).withZone(timezone);
    int count = 0;
    while (!date.isAfterNow()) {
        if (count > 100000) {
            throw new IllegalStateException("100000 increments of period did not get to present time.");
        }
        if (period == null) {
            break;
        } else {
            date = date.plus(period);
        }
        count += 1;
        if (!skipPastChecks) {
            continue;
        }
    }
    return date.getMillis();
}

83. Schedule#getNextRuntime()

Project: azkaban
File: Schedule.java
private DateTime getNextRuntime(long scheduleTime, DateTimeZone timezone, ReadablePeriod period) {
    DateTime now = new DateTime();
    DateTime date = new DateTime(scheduleTime).withZone(timezone);
    int count = 0;
    while (!now.isBefore(date)) {
        if (count > 100000) {
            throw new IllegalStateException("100000 increments of period did not get to present time.");
        }
        if (period == null) {
            break;
        } else {
            date = date.plus(period);
        }
        count += 1;
    }
    return date;
}

84. OrganizationResourceImpl#getResponseStatsPerPlan()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getResponseStatsPerPlan(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public ResponseStatsPerPlanBean getResponseStatsPerPlan(String organizationId, String apiId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getResponseStatsPerPlan(organizationId, apiId, version, from, to);
}

85. OrganizationResourceImpl#getResponseStatsPerClient()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getResponseStatsPerClient(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public ResponseStatsPerClientBean getResponseStatsPerClient(String organizationId, String apiId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getResponseStatsPerClient(organizationId, apiId, version, from, to);
}

86. OrganizationResourceImpl#getResponseStatsSummary()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getResponseStatsSummary(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public ResponseStatsSummaryBean getResponseStatsSummary(String organizationId, String apiId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getResponseStatsSummary(organizationId, apiId, version, from, to);
}

87. OrganizationResourceImpl#getResponseStats()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getResponseStats(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.metrics.HistogramIntervalType, java.lang.String, java.lang.String)
     */
@Override
public ResponseStatsHistogramBean getResponseStats(String organizationId, String apiId, String version, HistogramIntervalType interval, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    if (interval == null) {
        interval = HistogramIntervalType.day;
    }
    validateMetricRange(from, to);
    validateTimeSeriesMetric(from, to, interval);
    return metrics.getResponseStats(organizationId, apiId, version, interval, from, to);
}

88. OrganizationResourceImpl#getUsagePerPlan()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getUsagePerPlan(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public UsagePerPlanBean getUsagePerPlan(String organizationId, String apiId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getUsagePerPlan(organizationId, apiId, version, from, to);
}

89. OrganizationResourceImpl#getUsagePerClient()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getUsagePerClient(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public UsagePerClientBean getUsagePerClient(String organizationId, String apiId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getUsagePerClient(organizationId, apiId, version, from, to);
}

90. OrganizationResourceImpl#getUsage()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getUsage(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.metrics.HistogramIntervalType, java.lang.String, java.lang.String)
     */
@Override
public UsageHistogramBean getUsage(String organizationId, String apiId, String version, HistogramIntervalType interval, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.apiView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    if (interval == null) {
        interval = HistogramIntervalType.day;
    }
    validateMetricRange(from, to);
    validateTimeSeriesMetric(from, to, interval);
    return metrics.getUsage(organizationId, apiId, version, interval, from, to);
}

91. OrganizationResourceImpl#getClientUsagePerApi()

Project: apiman
File: OrganizationResourceImpl.java
/**
     * @see io.apiman.manager.api.rest.contract.IOrganizationResource#getClientUsagePerApi(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public ClientUsagePerApiBean getClientUsagePerApi(String organizationId, String clientId, String version, String fromDate, String toDate) throws NotAuthorizedException, InvalidMetricCriteriaException {
    if (!securityContext.hasPermission(PermissionType.clientView, organizationId))
        throw ExceptionFactory.notAuthorizedException();
    if (fromDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "fromDate"));
    }
    if (toDate == null) {
        //$NON-NLS-1$ //$NON-NLS-2$
        throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("MissingOrInvalidParam", "toDate"));
    }
    DateTime from = parseFromDate(fromDate);
    DateTime to = parseToDate(toDate);
    validateMetricRange(from, to);
    return metrics.getClientUsagePerApi(organizationId, clientId, version, from, to);
}

92. JdbcMetricsAccessorTest#testGetClientUsagePerApi()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getClientUsagePerApi(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetClientUsagePerApi() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    ClientUsagePerApiBean usage = accessor.getClientUsagePerApi("TestOrg", "TestClient", "1.0", from, to);
    Map<String, Long> expectedData = new HashMap<>();
    expectedData.put("TestApi", 15L);
    expectedData.put("OtherApi", 4L);
    Assert.assertEquals(expectedData, usage.getData());
}

93. JdbcMetricsAccessorTest#testGetResponseStatsPerPlan()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getResponseStatsPerPlan(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetResponseStatsPerPlan() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    ResponseStatsPerPlanBean stats = accessor.getResponseStatsPerPlan("TestOrg", "TestApi", "1.0", from, to);
    ResponseStatsDataPoint dataPoint = stats.getData().get("Gold");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(8, dataPoint.getTotal());
    Assert.assertEquals(1, dataPoint.getFailures());
    Assert.assertEquals(1, dataPoint.getErrors());
    dataPoint = stats.getData().get("Silver");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(10, dataPoint.getTotal());
    Assert.assertEquals(2, dataPoint.getFailures());
    Assert.assertEquals(0, dataPoint.getErrors());
}

94. JdbcMetricsAccessorTest#testGetResponseStatsPerClient()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getResponseStatsPerClient(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetResponseStatsPerClient() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    ResponseStatsPerClientBean stats = accessor.getResponseStatsPerClient("TestOrg", "TestApi", "1.0", from, to);
    ResponseStatsDataPoint dataPoint = stats.getData().get("TestClient");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(16, dataPoint.getTotal());
    Assert.assertEquals(3, dataPoint.getFailures());
    Assert.assertEquals(1, dataPoint.getErrors());
    dataPoint = stats.getData().get("OtherClient");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(2, dataPoint.getTotal());
    Assert.assertEquals(0, dataPoint.getFailures());
    Assert.assertEquals(0, dataPoint.getErrors());
}

95. JdbcMetricsAccessorTest#testGetResponseStatsSummary()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getResponseStatsSummary(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetResponseStatsSummary() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    ResponseStatsSummaryBean stats = accessor.getResponseStatsSummary("TestOrg", "TestApi", "1.0", from, to);
    Assert.assertEquals(18, stats.getTotal());
    Assert.assertEquals(3, stats.getFailures());
    Assert.assertEquals(1, stats.getErrors());
}

96. JdbcMetricsAccessorTest#testGetUsagePerPlan()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getUsagePerPlan(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetUsagePerPlan() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    UsagePerPlanBean usage = accessor.getUsagePerPlan("TestOrg", "TestApi", "1.0", from, to);
    Map<String, Long> expectedData = new HashMap<>();
    expectedData.put("Silver", 10L);
    expectedData.put("Gold", 8L);
    Assert.assertEquals(expectedData, usage.getData());
}

97. JdbcMetricsAccessorTest#testGetUsagePerClient()

Project: apiman
File: JdbcMetricsAccessorTest.java
/**
     * Test for {@link JdbcMetricsAccessor#getUsagePerClient(String, String, String, DateTime, DateTime)}
     */
@Test
public void testGetUsagePerClient() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);
    DateTime from = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-02-01T00:00:00Z");
    DateTime to = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime("2016-03-01T00:00:00Z");
    UsagePerClientBean usage = accessor.getUsagePerClient("TestOrg", "TestApi", "1.0", from, to);
    Map<String, Long> expectedData = new HashMap<>();
    expectedData.put("TestClient", 16L);
    expectedData.put("OtherClient", 2L);
    Assert.assertEquals(expectedData, usage.getData());
}

98. DateTimePeriod#toMonths()

Project: cloudhopper-commons
File: DateTimePeriod.java
/**
     * Converts this period to a list of month periods.  Partial months will not be
     * included.  For example, a period of "2009" will return a list
     * of 12 months - one for each month in 2009.  On the other hand, a period
     * of "January 20, 2009" would return an empty list since partial
     * months are not included.
     * @return A list of month periods contained within this period
     */
public List<DateTimePeriod> toMonths() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();
    // default "current" month to start datetime
    DateTime currentStart = getStart();
    // calculate "next" month
    DateTime nextStart = currentStart.plusMonths(1);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeMonth(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusMonths(1);
    }
    return list;
}

99. DateTimePeriod#toDays()

Project: cloudhopper-commons
File: DateTimePeriod.java
/**
     * Converts this period to a list of day periods.  Partial days will not be
     * included.  For example, a period of "January 2009" will return a list
     * of 31 days - one for each day in January.  On the other hand, a period
     * of "January 20, 2009 13:00-59" would return an empty list since partial
     * days are not included.
     * @return A list of day periods contained within this period
     */
public List<DateTimePeriod> toDays() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();
    // default "current" day to start datetime
    DateTime currentStart = getStart();
    // calculate "next" day
    DateTime nextStart = currentStart.plusDays(1);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeDay(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusDays(1);
    }
    return list;
}

100. DateTimePeriod#toHours()

Project: cloudhopper-commons
File: DateTimePeriod.java
/**
     * Converts this period to a list of hour periods.  Partial hours will not be
     * included.  For example, a period of "January 20, 2009" will return a list
     * of 24 hours - one for each hour on January 20, 2009.  On the other hand,
     * a period of "January 20, 2009 13:10" would return an empty list since partial
     * hours are not included.
     * @return A list of hour periods contained within this period
     */
public List<DateTimePeriod> toHours() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();
    // default "current" hour to start datetime
    DateTime currentStart = getStart();
    // calculate "next" hour
    DateTime nextStart = currentStart.plusHours(1);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeHour(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusHours(1);
    }
    return list;
}