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
Source File: TestDateTruncFunctions.java
View license
@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. TestDateTimeFormatter#testParseDateTime_offsetParsed()

View license
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"));
}

3. TestDateTimeFormatter#testParseDateTime_chrono()

View license
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"));
}

4. TestDateTimeFormatter#testZoneNameNearTransition()

View license
//-----------------------------------------------------------------------
// 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#testZoneShortNameNearTransition()

View license
// 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));
}

6. TestDateAndTimeZoneContext#testComputeTargetDateWithDayLightSaving()

View license
@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"));
}

7. CalendarEventVisualizer#setupDayOneEntry()

View license
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;
}

8. CalendarEventVisualizer#createFollowingEntries()

View license
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. RepairRunStatusMapper#map()

View license
@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);
}

10. SyslogParser#parseRfc3164Time()

Project: datacollector
Source File: SyslogParser.java
View license
/**
   * 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();
}

11. RangeQueryBuilderTests#testRewriteDateToMatchAll()

View license
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));
}

12. DatabaseHandler#getAverageGlucoseReadingsByWeek()

View license
/*    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;
}

13. DatabaseHandler#getGlucoseDatetimesByWeek()

View license
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;
}

14. DatabaseHandler#getAverageGlucoseReadingsByMonth()

View license
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;
}

15. DatabaseHandler#getGlucoseDatetimesByMonth()

View license
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;
}

16. LegacyMongoIndexRangeServiceTest#testFindAll()

View license
@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));
}

17. DateEncoderTest#testHoliday()

Project: htm.java
Source File: DateEncoderTest.java
View license
/**
     * 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));
}

18. TestLenientChronology#testNearDstTransition()

View license
//-----------------------------------------------------------------------
//------------------------ 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());
}

19. TestStringConverter#testGetInstantMillis_Object_Zone()

Project: joda-time
Source File: TestStringConverter.java
View license
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));
}

20. TestDateTimeFormatter#testParseDateTime_zone3()

View license
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"));
}

21. QueryAPIErrorResponseTest#testQueryColumnWithBothStartDateAndEndDate()

Project: lens
Source File: QueryAPIErrorResponseTest.java
View license
@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);
}

22. TabularViewHandler#generateTimeOnTimeComparisonRequest()

Project: pinot
Source File: TabularViewHandler.java
View license
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;
}

23. DateTimeUtilTest#floorToYear()

View license
/**
    @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);
}

24. DateTimeUtilTest#floorToMonth()

View license
@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);
}

25. DateTimeUtilTest#floorToDay()

View license
@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);
}

26. DateTimeUtilTest#floorToHour()

View license
@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);
}

27. DateTimeUtilTest#floorToMinute()

View license
@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);
}

28. DateTimeUtilTest#floorToSecond()

View license
@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);
}

29. DateUtil#calculateDays()

Project: community-edition
Source File: DateUtil.java
View license
/**
     * 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;
}

30. ExecutionTimeCustomDefinitionIntegrationTest#testCronExpressionAfterHalf()

View license
@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);
}

31. ExecutionTimeQuartzIntegrationTest#testNextExecutionProducingInvalidValues()

View license
/**
     * 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());
}

32. JodaDemo#convertFromString()

Project: cyfm
Source File: JodaDemo.java
View license
@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);
}

33. DruidController#topicDetail()

Project: DCMonitor
Source File: DruidController.java
View license
@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);
}

34. KafkaController#topicDetail()

Project: DCMonitor
Source File: KafkaController.java
View license
@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);
}

35. MessageTimeRejectionPolicyFactoryTest#testAccept()

View license
@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()));
}

36. ServerTimeRejectionPolicyFactoryTest#testAccept()

View license
@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()));
}

37. OverviewPresenterTest#ShouldAddZerosBetweenReadings_WhenAsked()

View license
@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);
}

38. TimeBasedSubDirDatasetsFinder#folderWithinAllowedPeriod()

View license
/**
   * 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;
    }
}

39. MongoIndexRange#create()

View license
@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);
}

40. SearchResource#restrictTimeRange()

Project: graylog2-server
Source File: SearchResource.java
View license
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);
}

41. EsIndexRangeTest#testCreate()

View license
@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);
}

42. EsIndexRangeTest#testJsonMapping()

View license
@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);
}

43. MongoIndexRangeServiceTest#savePersistsIndexRange()

View license
@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);
}

44. MongoIndexRangeServiceTest#saveOverwritesExistingIndexRange()

View license
@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);
}

45. MongoIndexRangeTest#testCreate()

View license
@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);
}

46. MongoIndexRangeTest#testJsonMapping()

View license
@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);
}

47. FlexibleDateConverterTest#convertObeysTimeZone()

View license
@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)));
}

48. TestDateUtils#testGetRelativeTimeSpanStringWithPreposition()

View license
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));
}

49. TestVersionedCatalogLoader#testLoad()

View license
@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());
}

50. DefaultSubscription#getBillingEndDate()

Project: killbill
Source File: DefaultSubscription.java
View license
@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;
}

51. TestEntitlementDateHelper#testWithAccountInUtc()

View license
@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);
}

52. PaymentAutomatonDAOHelper#buildNewPaymentTransactionModelDao()

View license
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);
}

53. TestDefaultSubscriptionTransferApi#testEventsForCancelledSubscriptionBeforeTransfer()

View license
@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);
}

54. TestDefaultSubscriptionTransferApi#testEventsForCancelledSubscriptionAfterTransfer()

View license
@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);
}

55. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle1()

View license
@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);
}

56. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle2()

View license
@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);
}

57. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle3()

View license
@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);
}

58. TestDefaultSubscriptionTransferApi#testEventsAfterTransferForMigratedBundle4()

View license
@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);
}

59. QueryAPIErrorResponseTest#testQueryColumnWithOnlyStartDate()

Project: lens
Source File: QueryAPIErrorResponseTest.java
View license
@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);
}

60. QueryAPIErrorResponseTest#testQueryColumnWithOnlyEndDate()

Project: lens
Source File: QueryAPIErrorResponseTest.java
View license
@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);
}

61. ISOToDay#exec()

Project: pig
Source File: ISOToDay.java
View license
@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();
}

62. ISOToHour#exec()

Project: pig
Source File: ISOToHour.java
View license
@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();
}

63. ISOToMinute#exec()

Project: pig
Source File: ISOToMinute.java
View license
@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();
}

64. ISOToMonth#exec()

Project: pig
Source File: ISOToMonth.java
View license
@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. ISOToSecond#exec()

Project: pig
Source File: ISOToSecond.java
View license
@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();
}

66. ISOToWeek#exec()

Project: pig
Source File: ISOToWeek.java
View license
@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();
}

67. ISOToYear#exec()

Project: pig
Source File: ISOToYear.java
View license
@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();
}

68. JdbcMetricsAccessorTest#testGetUsagePerClient()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

69. JdbcMetricsAccessorTest#testGetUsagePerPlan()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

70. JdbcMetricsAccessorTest#testGetResponseStatsSummary()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

71. JdbcMetricsAccessorTest#testGetResponseStatsPerClient()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

72. JdbcMetricsAccessorTest#testGetResponseStatsPerPlan()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

73. JdbcMetricsAccessorTest#testGetClientUsagePerApi()

Project: apiman
Source File: JdbcMetricsAccessorTest.java
View license
/**
     * 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());
}

74. OrganizationResourceImpl#getClientUsagePerApi()

View license
/**
     * @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);
}

75. OrganizationResourceImpl#getUsage()

View license
/**
     * @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);
}

76. OrganizationResourceImpl#getUsagePerClient()

View license
/**
     * @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);
}

77. OrganizationResourceImpl#getUsagePerPlan()

View license
/**
     * @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);
}

78. OrganizationResourceImpl#getResponseStats()

View license
/**
     * @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);
}

79. OrganizationResourceImpl#getResponseStatsSummary()

View license
/**
     * @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);
}

80. OrganizationResourceImpl#getResponseStatsPerClient()

View license
/**
     * @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);
}

81. OrganizationResourceImpl#getResponseStatsPerPlan()

View license
/**
     * @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);
}

82. Schedule#getNextRuntime()

Project: azkaban
Source File: Schedule.java
View license
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;
}

83. BasicTimeChecker#calculateNextCheckTime()

Project: azkaban
Source File: BasicTimeChecker.java
View license
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();
}

84. Schedule#getNextRuntime()

Project: azkaban
Source File: Schedule.java
View license
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;
}

85. BuyZoneModel#buy()

Project: bateman
Source File: BuyZoneModel.java
View license
@Override
public boolean buy(DateTime time, Session session) {
    if (session.inMarket(time)) {
        return false;
    }
    BigDecimal open = asset.getTimeSeries().openOnDay(time);
    BigDecimal current = asset.priceAt(time);
    BigDecimal increase = current.subtract(open);
    final DateTime midnight = time.toDateMidnight().toDateTime();
    final DateTime nextDay = midnight.plusDays(1);
    boolean tradedToday = (Collections2.filter(session.getTrades(), new Predicate<Trade>() {

        @Override
        public boolean apply(Trade trade) {
            return trade.getOpen().compareTo(midnight) > 0 && trade.getClose().compareTo(nextDay) < 0;
        }
    })).size() > 0;
    return !tradedToday && increase.compareTo(buyTrigger) >= 0;
}

86. BuyZoneModel#sell()

Project: bateman
Source File: BuyZoneModel.java
View license
@Override
public boolean sell(DateTime time, Session session) {
    if (!session.inMarket(time)) {
        return false;
    }
    BigDecimal open = asset.getTimeSeries().openOnDay(time);
    DateTime buyDate = session.lastTrade().getOpen();
    BigDecimal buyPrice = asset.priceAt(buyDate);
    BigDecimal current = asset.priceAt(time);
    BigDecimal difference = current.subtract(buyPrice);
    // exit if at end of day, if our sell trigger threshold is reached,
    // or if we hit our stop loss
    DateTime endOfDay = asset.getTimeSeries().closeOnDay(time);
    boolean atEndOfDay = time.compareTo(endOfDay) >= 0;
    boolean thresholdReached = difference.compareTo(sellTrigger) >= 0;
    boolean stopLossReached = buyPrice.subtract(current).compareTo(stopLoss) >= 0;
    return atEndOfDay || thresholdReached || stopLossReached;
}

87. QuoteCollectionTest#testConvertQuoteToTimeSeries()

Project: bateman
Source File: QuoteCollectionTest.java
View license
public void testConvertQuoteToTimeSeries() throws Exception {
    DateTime open = new DateTime();
    DateTime later = open.plusMinutes(1);
    List<Quote> quotes = Arrays.asList(new Quote(open, 60, new BigDecimal(1.0), new BigDecimal(1.2), new BigDecimal(0.9), new BigDecimal(1.1), 42), new Quote(later, 60, new BigDecimal(1.3), new BigDecimal(1.8), new BigDecimal(0.7), new BigDecimal(1.5), 43));
    QuoteCollection collection = new QuoteCollection();
    TreeMap<DateTime, BigDecimal> prices = new TreeMap<DateTime, BigDecimal>();
    prices.put(open, BigDecimal.ONE);
    prices.put(later, new BigDecimal(1.3));
    TimeSeries expResult = new TimeSeries(prices);
    TimeSeries result = collection.convertQuoteToTimeSeries(quotes);
    assertEquals(expResult.getPrices().get(open), result.getPrices().get(open));
    assertEquals(expResult.getPrices().get(later), result.getPrices().get(later));
}

88. EventElasticSearchIOTest#testRangeOnlySearch()

View license
@Test
public void testRangeOnlySearch() throws Exception {
    Map<String, List<String>> query = new HashMap<String, List<String>>();
    final int eventCountToCapture = TENANT_RANGE_EVENTS_NUM / 2;
    final int secondsDelta = 10;
    DateTime fromDateTime = new DateTime().minusSeconds(RANGE_STEP_IN_SECONDS * eventCountToCapture - secondsDelta);
    query.put(Event.fromParameterName, Arrays.asList(Long.toString(fromDateTime.getMillis())));
    List<Map<String, Object>> results = searchIO.search(TENANT_RANGE, query);
    Assert.assertEquals(eventCountToCapture, results.size());
    DateTime untilDateTime = new DateTime().minusSeconds(RANGE_STEP_IN_SECONDS * eventCountToCapture - secondsDelta);
    query.clear();
    query.put(Event.untilParameterName, Arrays.asList(Long.toString(untilDateTime.getMillis())));
    results = searchIO.search(TENANT_RANGE, query);
    Assert.assertEquals(eventCountToCapture, results.size());
    query.clear();
    fromDateTime = new DateTime().minusSeconds(RANGE_STEP_IN_SECONDS * 2 - secondsDelta);
    untilDateTime = new DateTime().minusSeconds(RANGE_STEP_IN_SECONDS - secondsDelta);
    query.put(Event.fromParameterName, Arrays.asList(Long.toString(fromDateTime.getMillis())));
    query.put(Event.untilParameterName, Arrays.asList(Long.toString(untilDateTime.getMillis())));
    results = searchIO.search(TENANT_RANGE, query);
    Assert.assertEquals(1, results.size());
}

89. MultidayEventTest#testThreeDaysEvent()

View license
/**  https://github.com/plusonelabs/calendar-widget/issues/184#issuecomment-142671469 */
public void testThreeDaysEvent() {
    DateTime friday = new DateTime(2015, 9, 18, 0, 0);
    DateTime sunday = friday.plusDays(2);
    CalendarEvent event = new CalendarEvent();
    event.setEventId(++eventId);
    event.setTitle("Leader's weekend");
    event.setStartDate(friday.plusHours(19));
    event.setEndDate(sunday.plusHours(15));
    assertSundayEntryAt(event, sunday, friday.plusHours(14));
    assertSundayEntryAt(event, sunday, friday.plusDays(1).plusHours(14));
    assertSundayEntryAt(event, sunday, friday.plusDays(2).plusHours(14));
}

90. DateUtil#now()

Project: calendar-widget
Source File: DateUtil.java
View license
/**
     * Usually returns real "now", but may be #setNow to some other time for testing purposes
     */
public static DateTime now() {
    DateTime nowSetAt;
    DateTime now;
    do {
        nowSetAt = mNowSetAt;
        now = mNow;
    } while (// Ensure concurrent consistency
    nowSetAt != mNowSetAt);
    if (now == null) {
        return DateTime.now();
    } else {
        long diffL = DateTime.now().getMillis() - nowSetAt.getMillis();
        int diff = 0;
        if (diffL > 0 && diffL < Integer.MAX_VALUE) {
            diff = (int) diffL;
        }
        return new DateTime(now).plusMillis(diff);
    }
}

91. DateTimePeriod#toFiveMinutes()

View license
/**
     * Converts this period to a list of five minute periods.  Partial five minute periods will not be
     * included.  For example, a period of "January 20, 2009 7 to 8 AM" will return a list
     * of 12 five minute periods - one for each 5 minute block of time 0, 5, 10, 15, etc.
     * On the other hand, a period of "January 20, 2009 at 13:04" would return an empty list since partial
     * five minute periods are not included.
     * @return A list of five minute periods contained within this period
     */
public List<DateTimePeriod> toFiveMinutes() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();
    // default "current" five minutes to start datetime
    DateTime currentStart = getStart();
    // calculate "next" five minutes
    DateTime nextStart = currentStart.plusMinutes(5);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeFiveMinutes(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusMinutes(5);
    }
    return list;
}

92. DateTimePeriod#toHours()

View license
/**
     * 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;
}

93. DateTimePeriod#toDays()

View license
/**
     * 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;
}

94. DateTimePeriod#toMonths()

View license
/**
     * 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;
}

95. DateTimePeriod#toYears()

View license
/**
     * Converts this period to a list of year periods.  Partial years will not be
     * included.  For example, a period of "2009-2010" will return a list
     * of 2 years - one for 2009 and one for 2010.  On the other hand, a period
     * of "January 2009" would return an empty list since partial
     * years are not included.
     * @return A list of year periods contained within this period
     */
public List<DateTimePeriod> toYears() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();
    // default "current" year to start datetime
    DateTime currentStart = getStart();
    // calculate "next" year
    DateTime nextStart = currentStart.plusYears(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 DateTimeYear(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusYears(1);
    }
    return list;
}

96. Issue55UnexpectedExecutionTimes#testOnceEveryThreeDaysNoInstantsWithinTwoDays()

View license
/** Test. */
@Test
public void testOnceEveryThreeDaysNoInstantsWithinTwoDays() {
    System.out.println();
    System.out.println("TEST1 - expecting 0 instants");
    DateTime startTime = new DateTime(0, DateTimeZone.UTC);
    final DateTime endTime = startTime.plusDays(2);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("0 0 */3 * ?");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    List<Instant> instants = getInstants(executionTime, startTime, endTime);
    System.out.println("instants.size() == " + instants.size());
    System.out.println("instants: " + instants);
    assertEquals(0, instants.size());
}

97. Issue55UnexpectedExecutionTimes#testOnceAMonthTwelveInstantsInYear()

View license
/** Test. */
@Test
public void testOnceAMonthTwelveInstantsInYear() {
    System.out.println();
    System.out.println("TEST2 - expecting 12 instants");
    DateTime startTime = new DateTime(0, DateTimeZone.UTC);
    final DateTime endTime = startTime.plusDays(365);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("0 12 L * ?");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    List<Instant> instants = getInstants(executionTime, startTime, endTime);
    System.out.println("instants.size() == " + instants.size());
    System.out.println("instants: " + instants);
    assertEquals(12, instants.size());
}

98. ExecutionTimeCustomDefinitionIntegrationTest#testCronExpressionBetweenDayOfWeekValueGeneratorCorrectFirstDayOfMonth()

View license
/**
     * Test for issue #57
     * https://github.com/jmrozanec/cron-utils/issues/57
     * Reported case: BetweenDayOfWeekValueGenerator does not work for the first day of a month in some cases.
     * Expected: first day of month should be returned ok
     */
@Test
public void testCronExpressionBetweenDayOfWeekValueGeneratorCorrectFirstDayOfMonth() {
    CronDefinition cronDefinition = CronDefinitionBuilder.defineCron().withMinutes().and().withHours().and().withDayOfMonth().supportsL().supportsW().and().withMonth().and().withDayOfWeek().withMondayDoWValue(1).withValidRange(1, 7).supportsHash().supportsL().and().withYear().and().lastFieldOptional().instance();
    CronParser parser = new CronParser(cronDefinition);
    Cron cron = parser.parse("30 3 * * MON-FRI");
    DateTime sameDayBeforeEventStartDateTime = DateTime.parse("1970-01-01T00:00:00.000-03:00");
    assertEquals(1, ExecutionTime.forCron(cron).nextExecution(sameDayBeforeEventStartDateTime).getDayOfMonth());
    DateTime sameDayAfterEventStartDateTime = DateTime.parse("1970-01-01T12:00:00.000-03:00");
    assertEquals(2, ExecutionTime.forCron(cron).nextExecution(sameDayAfterEventStartDateTime).getDayOfMonth());
}

99. ExecutionTimeQuartzIntegrationTest#testDoesNotIgnoreMonthOrDayOfWeek()

View license
/**
     * Test for issue #9
     * https://github.com/jmrozanec/cron-utils/issues/9
     * Reported case: If you write a cron expression that contains a month or day of week, nextExection() ignores it.
     * Expected: should not ignore month or day of week field
     */
@Test
public void testDoesNotIgnoreMonthOrDayOfWeek() {
    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
    CronParser cronParser = new CronParser(cronDefinition);
    //seconds, minutes, hours, dayOfMonth, month, dayOfWeek
    ExecutionTime executionTime = ExecutionTime.forCron(cronParser.parse("0 11 11 11 11 ?"));
    DateTime now = new DateTime(2015, 4, 15, 0, 0, 0);
    DateTime whenToExecuteNext = executionTime.nextExecution(now);
    assertEquals(2015, whenToExecuteNext.getYear());
    assertEquals(11, whenToExecuteNext.getMonthOfYear());
    assertEquals(11, whenToExecuteNext.getDayOfMonth());
    assertEquals(11, whenToExecuteNext.getHourOfDay());
    assertEquals(11, whenToExecuteNext.getMinuteOfHour());
    assertEquals(0, whenToExecuteNext.getSecondOfMinute());
}

100. ExecutionTimeUnixIntegrationTest#testCorrectMonthScaleForNextExecution1()

View license
/**
     * Issue #59: Incorrect next execution time for "month" and "day of week"
     * Considers Month in range 0-11 instead of 1-12
     */
@Test
public void testCorrectMonthScaleForNextExecution1() {
    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    CronParser parser = new CronParser(cronDefinition);
    //m,h,dom,M,dow
    String crontab = "* * */3 */4 */5";
    Cron cron = parser.parse(crontab);
    ExecutionTime executionTime = ExecutionTime.forCron(cron);
    DateTime scanTime = DateTime.parse("2015-12-10T16:32:56.586-08:00");
    DateTime nextExecutionTime = executionTime.nextExecution(scanTime);
    //DoW: 0-6 -> 0, 5 (sunday, friday)
    //DoM: 1-31 -> 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31
    //M: 1-12 -> 1, 5, 9
    assertEquals(DateTime.parse("2016-01-01T00:00:00.000-08:00"), nextExecutionTime);
}