Here are the examples of the java api class org.joda.time.DateTime taken from open source projects.
1. TestDateTruncFunctions#testDateTrunc()
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 licensepublic 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 licensepublic 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. QueryAPIErrorResponseTest#testQueryColumnWithBothStartDateAndEndDate()
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); }
8. SyslogParser#parseRfc3164Time()
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(); }
9. RangeQueryBuilderTests#testRewriteDateToMatchAll()
View licensepublic 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)); }
10. 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; }
11. DatabaseHandler#getGlucoseDatetimesByWeek()
View licensepublic 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; }
12. DatabaseHandler#getAverageGlucoseReadingsByMonth()
View licensepublic 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; }
13. DatabaseHandler#getGlucoseDatetimesByMonth()
View licensepublic 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; }
14. 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()); }
15. TestStringConverter#testGetInstantMillis_Object_Zone()
View licensepublic 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)); }
16. TestDateTimeFormatter#testParseDateTime_zone3()
View licensepublic 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")); }
17. 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)); }
18. DateEncoderTest#testHoliday()
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)); }
19. TabularViewHandler#generateTimeOnTimeComparisonRequest()
View licenseprivate 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; }
20. CalendarEventVisualizer#setupDayOneEntry()
View licenseprivate 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; }
21. CalendarEventVisualizer#createFollowingEntries()
View licenseprivate 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; } }
22. 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); }
23. PaymentAutomatonDAOHelper#buildNewPaymentTransactionModelDao()
View licenseprivate 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); }
24. TestDateUtils#testGetRelativeTimeSpanStringWithPreposition()
View licensepublic 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)); }
25. 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; } }
26. 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); }
27. 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())); }
28. 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())); }
29. 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))); }
30. 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); }
31. 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); }
32. 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); }
33. 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); }
34. 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); }
35. 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); }
36. SearchResource#restrictTimeRange()
View licenseprotected 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); }
37. 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); }
38. 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); }
39. DefaultSubscription#getBillingEndDate()
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; }
40. 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()); }
41. QueryAPIErrorResponseTest#testQueryColumnWithOnlyEndDate()
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); }
42. QueryAPIErrorResponseTest#testQueryColumnWithOnlyStartDate()
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); }
43. 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); }
44. 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); }
45. 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); }
46. 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); }
47. 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); }
48. KafkaController#topicDetail()
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); }
49. DruidController#topicDetail()
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); }
50. JodaDemo#convertFromString()
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); }
51. 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()); }
52. 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); }
53. 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); }
54. DateUtil#calculateDays()
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; }
55. 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); }
56. 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); }
57. 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); }
58. 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); }
59. 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); }
60. 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); }
61. ISOToYear#exec()
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(); }
62. ISOToWeek#exec()
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(); }
63. ISOToSecond#exec()
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(); }
64. ISOToMonth#exec()
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. ISOToMinute#exec()
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(); }
66. ISOToHour#exec()
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(); }
67. ISOToDay#exec()
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(); }
68. BuyZoneModel#sell()
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; }
69. BuyZoneModel#buy()
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; }
70. BenchmarkResultScannerTest#countFailureOnly()
View license@Ignore @Test public void countFailureOnly() throws Exception { File resultsFile = new File("/Programming/jmeter-maven-plugin/data1.xml"); ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, DO_NOT_COUNT_FAILURES); System.out.println("Benchmark new FailureScanner implementation - failure only"); final DateTime start = DateTime.now(); System.out.println("Start time is " + start); fileScanner.parseResultFile(resultsFile); final DateTime finish = DateTime.now(); System.out.println("Finish time is " + finish); Duration duration = new Duration(start, finish); System.out.println("Total time taken: " + duration.toStandardSeconds().getSeconds()); System.out.println("PASSED: " + fileScanner.getSuccessCount()); System.out.println("FAILED: " + fileScanner.getFailureCount()); }
71. BenchmarkResultScannerTest#countSuccessOnly()
View license@Ignore @Test public void countSuccessOnly() throws Exception { File resultsFile = new File("/Programming/jmeter-maven-plugin/data1.xml"); ResultScanner fileScanner = new ResultScanner(DO_NOT_COUNT_SUCCESSES, COUNT_FAILURES); System.out.println("Benchmark new FailureScanner implementation - success only"); final DateTime start = DateTime.now(); System.out.println("Start time is " + start); fileScanner.parseResultFile(resultsFile); final DateTime finish = DateTime.now(); System.out.println("Finish time is " + finish); Duration duration = new Duration(start, finish); System.out.println("Total time taken: " + duration.toStandardSeconds().getSeconds()); System.out.println("PASSED: " + fileScanner.getSuccessCount()); System.out.println("FAILED: " + fileScanner.getFailureCount()); }
72. BenchmarkResultScannerTest#countSuccessAndFailure()
View license@Ignore @Test public void countSuccessAndFailure() throws Exception { File resultsFile = new File("/Programming/jmeter-maven-plugin/data1.xml"); ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES); System.out.println("Benchmark new FailureScanner implementation"); final DateTime start = DateTime.now(); System.out.println("Start time is " + start); fileScanner.parseResultFile(resultsFile); final DateTime finish = DateTime.now(); System.out.println("Finish time is " + finish); Duration duration = new Duration(start, finish); System.out.println("Total time taken: " + duration.toStandardSeconds().getSeconds()); System.out.println("PASSED: " + fileScanner.getSuccessCount()); System.out.println("FAILED: " + fileScanner.getFailureCount()); }
73. IntermediateEventTest#testIntermediateCatchEventTimerDateISO()
View license@Test(timeout = 10000) public void testIntermediateCatchEventTimerDateISO() throws Exception { CountDownProcessEventListener countDownListener = new CountDownProcessEventListener("timer", 1); KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-IntermediateCatchEventTimerDateISO.bpmn2"); ksession = createKnowledgeSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new DoNothingWorkItemHandler()); ksession.addEventListener(countDownListener); HashMap<String, Object> params = new HashMap<String, Object>(); DateTime now = new DateTime(System.currentTimeMillis()); now.plus(2000); params.put("date", now.toString()); ProcessInstance processInstance = ksession.startProcess("IntermediateCatchEvent", params); assertProcessInstanceActive(processInstance); // now wait for 1 second for timer to trigger countDownListener.waitTillCompleted(); assertProcessInstanceFinished(processInstance, ksession); }
74. IntermediateEventTest#testTimerBoundaryEventDateISO()
View license@Test(timeout = 10000) public void testTimerBoundaryEventDateISO() throws Exception { CountDownProcessEventListener countDownListener = new CountDownProcessEventListener("TimerEvent", 1); KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-TimerBoundaryEventDateISO.bpmn2"); ksession = createKnowledgeSession(kbase); ksession.addEventListener(countDownListener); ksession.getWorkItemManager().registerWorkItemHandler("MyTask", new DoNothingWorkItemHandler()); HashMap<String, Object> params = new HashMap<String, Object>(); DateTime now = new DateTime(System.currentTimeMillis()); now.plus(2000); params.put("date", now.toString()); ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent", params); assertProcessInstanceActive(processInstance); countDownListener.waitTillCompleted(); ksession = restoreSession(ksession, true); assertProcessInstanceFinished(processInstance, ksession); }
75. DateUtil#getAliasesForDateRange()
View licensepublic static Set<String> getAliasesForDateRange(String starDate, String endDate, String prefix) throws ParseException { DateTime start = null; DateTime end = null; DateTimeFormatter df = ISODateTimeFormat.dateTimeNoMillis(); try { start = df.parseDateTime(starDate); } catch (Exception e) { } if (start == null) { start = determineDateTime(starDate); } if (endDate != null) { try { end = df.parseDateTime(endDate); } catch (Exception e) { } if (end == null) end = determineDateTime(endDate); } return getAliasesForDateRange(start, end, prefix); }
76. InstagramAbstractProvider#updateUserInfoList()
View license/** * Add default start and stop points if necessary. */ private void updateUserInfoList() { UsersInfo usersInfo = this.config.getUsersInfo(); if (usersInfo.getDefaultAfterDate() == null && usersInfo.getDefaultBeforeDate() == null) { return; } DateTime defaultAfterDate = usersInfo.getDefaultAfterDate(); DateTime defaultBeforeDate = usersInfo.getDefaultBeforeDate(); for (User user : usersInfo.getUsers()) { if (defaultAfterDate != null && user.getAfterDate() == null) { user.setAfterDate(defaultAfterDate); } if (defaultBeforeDate != null && user.getBeforeDate() == null) { user.setBeforeDate(defaultBeforeDate); } } }
77. ValueFilterDateRangeLength#parseRange()
View licenseprotected Interval parseRange(String rangeString) { int sepIndex = rangeString.indexOf(dateSep); if (sepIndex <= 0 || sepIndex + 1 == rangeString.length()) { throw new IllegalArgumentException("Failed to parse date range: " + rangeString); } DateTimeFormatter dtf = DateTimeFormat.forPattern(dateFormat); DateTime beg = dtf.parseDateTime(rangeString.substring(0, sepIndex)); DateTime end = dtf.parseDateTime(rangeString.substring(sepIndex + 1, rangeString.length())); return new Interval(beg, end); }
78. SearchResourceTest#restrictTimeRangeReturnsLimitedTimeRange()
View license@Test public void restrictTimeRangeReturnsLimitedTimeRange() { when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault().toBuilder().queryTimeRangeLimit(queryLimitPeriod).build()); final DateTime from = new DateTime(2015, 1, 15, 12, 0, DateTimeZone.UTC); final DateTime to = from.plus(queryLimitPeriod.multipliedBy(2)); final TimeRange timeRange = AbsoluteRange.create(from, to); final TimeRange restrictedTimeRange = searchResource.restrictTimeRange(timeRange); assertThat(restrictedTimeRange).isNotNull(); assertThat(restrictedTimeRange.getFrom()).isEqualTo(to.minus(queryLimitPeriod)); assertThat(restrictedTimeRange.getTo()).isEqualTo(to); }
79. SearchResourceTest#restrictTimeRangeReturnsGivenTimeRangeIfNoLimitHasBeenSet()
View license@Test public void restrictTimeRangeReturnsGivenTimeRangeIfNoLimitHasBeenSet() { when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault().toBuilder().queryTimeRangeLimit(Period.ZERO).build()); final SearchResource resource = new SearchResource(searches, clusterConfigService) { }; final DateTime from = new DateTime(2015, 1, 15, 12, 0, DateTimeZone.UTC); final DateTime to = from.plusYears(1); final TimeRange timeRange = AbsoluteRange.create(from, to); final TimeRange restrictedTimeRange = resource.restrictTimeRange(timeRange); assertThat(restrictedTimeRange).isNotNull(); assertThat(restrictedTimeRange.getFrom()).isEqualTo(from); assertThat(restrictedTimeRange.getTo()).isEqualTo(to); }
80. SearchResourceTest#restrictTimeRangeReturnsGivenTimeRangeWithinLimit()
View license@Test public void restrictTimeRangeReturnsGivenTimeRangeWithinLimit() { when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault().toBuilder().queryTimeRangeLimit(queryLimitPeriod).build()); final DateTime from = new DateTime(2015, 1, 15, 12, 0, DateTimeZone.UTC); final DateTime to = from.plusHours(1); final TimeRange timeRange = AbsoluteRange.create(from, to); final TimeRange restrictedTimeRange = searchResource.restrictTimeRange(timeRange); assertThat(restrictedTimeRange).isNotNull(); assertThat(restrictedTimeRange.getFrom()).isEqualTo(from); assertThat(restrictedTimeRange.getTo()).isEqualTo(to); }
81. DateConverterTest#convertObeysTimeZone()
View license@Test public void convertObeysTimeZone() throws Exception { final DateTimeZone timeZone = DateTimeZone.forOffsetHours(12); final Converter c = new DateConverter(config("YYYY-MM-dd HH:mm:ss", timeZone.toString())); final DateTime dateOnly = (DateTime) c.convert("2014-03-12 10:00:00"); assertThat(dateOnly.getZone()).isEqualTo(timeZone); Assertions.assertThat(dateOnly).isEqualTo(new DateTime(2014, 3, 12, 10, 0, 0, timeZone)).isBefore(new DateTime(2014, 3, 13, 10, 0, 0, timeZone)); final DateTime dateTime = (DateTime) c.convert("2014-03-12 12:34:00"); assertThat(dateTime.getZone()).isEqualTo(timeZone); Assertions.assertThat(dateTime).isEqualTo(new DateTime(2014, 3, 12, 12, 34, 0, timeZone)); }
82. MongoIndexRangeServiceTest#testHandleIndexReopening()
View license@Test @UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void testHandleIndexReopening() throws Exception { final DateTime begin = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC); final DateTime end = new DateTime(2016, 1, 15, 0, 0, DateTimeZone.UTC); when(indices.timestampStatsOfIndex("graylog_3")).thenReturn(TimestampStats.create(begin, end)); localEventBus.post(IndicesReopenedEvent.create(Collections.singleton("graylog_3"))); final SortedSet<IndexRange> indexRanges = indexRangeService.find(begin, end); assertThat(indexRanges).hasSize(1); assertThat(indexRanges.first().indexName()).isEqualTo("graylog_3"); assertThat(indexRanges.first().begin()).isEqualTo(begin); assertThat(indexRanges.first().end()).isEqualTo(end); }
83. MongoIndexRangeServiceTest#calculateRangeReturnsIndexRange()
View license@Test @UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void calculateRangeReturnsIndexRange() throws Exception { final String index = "graylog"; final DateTime min = new DateTime(2015, 1, 1, 1, 0, DateTimeZone.UTC); final DateTime max = new DateTime(2015, 1, 1, 5, 0, DateTimeZone.UTC); when(indices.timestampStatsOfIndex(index)).thenReturn(TimestampStats.create(min, max)); final IndexRange indexRange = indexRangeService.calculateRange(index); assertThat(indexRange.indexName()).isEqualTo(index); assertThat(indexRange.begin()).isEqualTo(min); assertThat(indexRange.end()).isEqualTo(max); Assertions.assertThat(indexRange.calculatedAt()).isEqualToIgnoringHours(DateTime.now(DateTimeZone.UTC)); }
84. MongoIndexRangeServiceTest#findReturnsIndexRangesWithinGivenRange()
View license/** * Test the following constellation: * <pre> * [- index range -] * [- graylog_1 -][- graylog_2 -][- graylog_3 -][- graylog_4 -][- graylog_5 -] * </pre> */ @Test @UsingDataSet(locations = "MongoIndexRangeServiceTest-distinct.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void findReturnsIndexRangesWithinGivenRange() throws Exception { final DateTime begin = new DateTime(2015, 1, 2, 12, 0, DateTimeZone.UTC); final DateTime end = new DateTime(2015, 1, 4, 12, 0, DateTimeZone.UTC); final SortedSet<IndexRange> indexRanges = indexRangeService.find(begin, end); assertThat(indexRanges).containsExactly(MongoIndexRange.create(new ObjectId("55e0261a0cc6980000000002"), "graylog_2", new DateTime(2015, 1, 2, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), 42), MongoIndexRange.create(new ObjectId("55e0261a0cc6980000000003"), "graylog_3", new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), 42), MongoIndexRange.create(new ObjectId("55e0261a0cc6980000000004"), "graylog_4", new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 5, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 5, 0, 0, DateTimeZone.UTC), 42)); }
85. EsIndexRangeServiceTest#findReturnsIndexRangesWithinGivenRange()
View license/** * Test the following constellation: * <pre> * [- index range -] * [- graylog_1 -][- graylog_2 -][- graylog_3 -][- graylog_4 -][- graylog_5 -] * </pre> */ @Test @UsingDataSet(locations = "EsIndexRangeServiceTest-distinct.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void findReturnsIndexRangesWithinGivenRange() throws Exception { final DateTime begin = new DateTime(2015, 1, 2, 12, 0, DateTimeZone.UTC); final DateTime end = new DateTime(2015, 1, 4, 12, 0, DateTimeZone.UTC); final SortedSet<IndexRange> indexRanges = indexRangeService.find(begin, end); assertThat(indexRanges).containsExactly(EsIndexRange.create("graylog_2", new DateTime(2015, 1, 2, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), 42), EsIndexRange.create("graylog_3", new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), 42), EsIndexRange.create("graylog_4", new DateTime(2015, 1, 4, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 5, 0, 0, DateTimeZone.UTC), new DateTime(2015, 1, 5, 0, 0, DateTimeZone.UTC), 42)); }
86. OverviewPresenterTest#ShouldSortReadingsChronologically_WhenAsked()
View license@Test public void ShouldSortReadingsChronologically_WhenAsked() throws Exception { DateTime now = DateTime.now(); DateTime twoDaysAgo = now.minusDays(2); when(dbMock.getLastMonthGlucoseReadings()).thenReturn(Arrays.asList(new GlucoseReading(33, "test", now.toDate(), ""), new GlucoseReading(11, "test", twoDaysAgo.toDate(), ""))); presenter.loadDatabase(); final List<Integer> readings = presenter.getGlucoseReadings(); assertThat(readings).containsSequence(11, 0, 33); }
87. RangeQueryBuilderTests#testRewriteDateToSame()
View licensepublic void testRewriteDateToSame() throws IOException { String fieldName = randomAsciiOfLengthBetween(1, 20); RangeQueryBuilder query = new RangeQueryBuilder(fieldName) { @Override protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException { return Relation.INTERSECTS; } }; DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); query.from(queryFromValue); query.to(queryToValue); QueryShardContext queryShardContext = createShardContext(); QueryBuilder rewritten = query.rewrite(queryShardContext); assertThat(rewritten, sameInstance(query)); }
88. 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()); }
89. SimpleValidateQueryIT#testExplainDateRangeInQueryString()
View license// Issue #3629 public void testExplainDateRangeInQueryString() { assertAcked(prepareCreate("test").setSettings(Settings.builder().put(indexSettings()).put("index.number_of_shards", 1))); String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1)); String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1)); client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get(); refresh(); ValidateQueryResponse response = client().admin().indices().prepareValidateQuery().setQuery(queryStringQuery("past:[now-2M/d TO now/d]")).setRewrite(true).get(); assertNoFailures(response); assertThat(response.getQueryExplanation().size(), equalTo(1)); assertThat(response.getQueryExplanation().get(0).getError(), nullValue()); DateTime twoMonthsAgo = new DateTime(DateTimeZone.UTC).minusMonths(2).withTimeAtStartOfDay(); DateTime now = new DateTime(DateTimeZone.UTC).plusDays(1).withTimeAtStartOfDay().minusMillis(1); assertThat(response.getQueryExplanation().get(0).getExplanation(), equalTo("past:[" + twoMonthsAgo.getMillis() + " TO " + now.getMillis() + "]")); assertThat(response.isValid(), equalTo(true)); }
90. StreamMeetupComTask#getUpfrontReservationTime()
View license// -1 (in past), 1d, 4d, 1w, 2w, 1m, 2m, - private String getUpfrontReservationTime(Long dateInMillis) { DateTime now = new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"))); DateTime event = new DateTime(dateInMillis, DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"))); Duration duration = new Duration(now, event); if (duration.getMillis() < 0) { return "-1"; } else if (duration.getStandardSeconds() < 86400) { return "1d"; } else if (duration.getStandardDays() < 4) { return "4d"; } else if (duration.getStandardDays() < 7) { return "1w"; } else if (duration.getStandardDays() < 14) { return "2w"; } else if (duration.getStandardDays() < 28) { return "4w"; } else if (duration.getStandardDays() < 56) { return "8w"; } else { return "-"; } }
91. HCatProcessTest#getDatesList()
View licensepublic static List<String> getDatesList(String startDate, String endDate, String datePattern, int skipMinutes) { DateTime startDateJoda = new DateTime(TimeUtil.oozieDateToDate(startDate)); DateTime endDateJoda = new DateTime(TimeUtil.oozieDateToDate(endDate)); DateTimeFormatter formatter = DateTimeFormat.forPattern(datePattern); LOGGER.info("generating data between " + formatter.print(startDateJoda) + " and " + formatter.print(endDateJoda)); List<String> dates = new ArrayList<>(); dates.add(formatter.print(startDateJoda)); while (!startDateJoda.isAfter(endDateJoda)) { startDateJoda = startDateJoda.plusMinutes(skipMinutes); dates.add(formatter.print(startDateJoda)); } return dates; }
92. BaseInterval#getInterval()
View licensepublic static Interval getInterval(long millis, Period period, Type type) { final DateTime currentTime = new DateTime(millis); final DateTime intervalStart; switch(type) { case DAY: intervalStart = currentTime.withTimeAtStartOfDay(); break; case WEEK: intervalStart = currentTime.weekOfWeekyear().roundFloorCopy(); break; case MONTH: intervalStart = currentTime.dayOfMonth().withMinimumValue().withTimeAtStartOfDay(); break; case YEAR: intervalStart = currentTime.withMonthOfYear(1).withDayOfMonth(1).withTimeAtStartOfDay(); break; default: throw new IllegalArgumentException("Type " + type + " is not supported."); } return new Interval(intervalStart, period); }
93. TwilightTest#NoonTest()
View license@Test public void NoonTest() { provider.setNextSunrise(new DateTime(2013, 11, 20, 5, 0)); provider.setNextSunset(new DateTime(2013, 11, 20, 17, 0)); DateTime noon = new DateTime(2013, 11, 21, 12, 0); //System.out.println(provider.getNextSunrise().toString() +" - "+ provider.getNextSunset() +" - "+ noon); GenericEvent twAtNoon = twu.prepareEvent(noon); Assert.assertEquals("300", twAtNoon.getProperty("beforeSunset")); Assert.assertEquals("", twAtNoon.getProperty("afterSunset")); Assert.assertEquals("", twAtNoon.getProperty("isSunset")); Assert.assertEquals("", twAtNoon.getProperty("isSunrise")); Assert.assertEquals("420", twAtNoon.getProperty("afterSunrise")); Assert.assertEquals("", twAtNoon.getProperty("beforeSunrise")); noon = new DateTime(2013, 11, 21, 12, 1); // System.out.println(provider.getNextSunrise().toString() +" - "+ provider.getNextSunset() +" - "+ noon); twAtNoon = twu.prepareEvent(noon); Assert.assertEquals("299", twAtNoon.getProperty("beforeSunset")); Assert.assertEquals("", twAtNoon.getProperty("afterSunset")); Assert.assertEquals("", twAtNoon.getProperty("isSunset")); Assert.assertEquals("", twAtNoon.getProperty("isSunrise")); Assert.assertEquals("421", twAtNoon.getProperty("afterSunrise")); Assert.assertEquals("", twAtNoon.getProperty("beforeSunrise")); }
94. TwilightTest#sunriseTest()
View license@Test public void sunriseTest() { provider.setNextSunrise(new DateTime(2013, 11, 20, 5, 0)); provider.setNextSunset(new DateTime(2013, 11, 20, 17, 0)); DateTime sunrise = new DateTime(2013, 11, 20, 5, 0); GenericEvent twAtSunrise = twu.prepareEvent(sunrise); Assert.assertEquals("720", twAtSunrise.getProperty("beforeSunset")); Assert.assertEquals("", twAtSunrise.getProperty("afterSunset")); Assert.assertEquals("", twAtSunrise.getProperty("isSunset")); Assert.assertEquals("true", twAtSunrise.getProperty("isSunrise")); Assert.assertEquals("", twAtSunrise.getProperty("afterSunrise")); Assert.assertEquals("", twAtSunrise.getProperty("beforeSunrise")); sunrise = new DateTime(2013, 11, 20, 5, 1); twAtSunrise = twu.prepareEvent(sunrise); Assert.assertEquals("719", twAtSunrise.getProperty("beforeSunset")); Assert.assertEquals("", twAtSunrise.getProperty("afterSunset")); Assert.assertEquals("", twAtSunrise.getProperty("isSunset")); Assert.assertEquals("", twAtSunrise.getProperty("isSunrise")); Assert.assertEquals("1", twAtSunrise.getProperty("afterSunrise")); Assert.assertEquals("", twAtSunrise.getProperty("beforeSunrise")); }
95. TwilightTest#sunsetTest()
View license@Test public void sunsetTest() { provider.setNextSunrise(new DateTime(2013, 11, 20, 5, 0)); provider.setNextSunset(new DateTime(2013, 11, 20, 17, 0)); DateTime sunset = new DateTime(2013, 11, 23, 17, 0); GenericEvent twAtSunset = twu.prepareEvent(sunset); Assert.assertEquals("", twAtSunset.getProperty("beforeSunset")); Assert.assertEquals("", twAtSunset.getProperty("afterSunset")); Assert.assertEquals("true", twAtSunset.getProperty("isSunset")); Assert.assertEquals("", twAtSunset.getProperty("isSunrise")); Assert.assertEquals("720", twAtSunset.getProperty("afterSunrise")); Assert.assertEquals("", twAtSunset.getProperty("beforeSunrise")); DateTime postSunset = new DateTime(2013, 11, 23, 17, 1); GenericEvent twPostSunset = twu.prepareEvent(postSunset); Assert.assertEquals("", twPostSunset.getProperty("beforeSunset")); Assert.assertEquals("1", twPostSunset.getProperty("afterSunset")); Assert.assertEquals("", twPostSunset.getProperty("isSunset")); Assert.assertEquals("", twPostSunset.getProperty("isSunrise")); Assert.assertEquals("", twPostSunset.getProperty("afterSunrise")); Assert.assertEquals("719", twPostSunset.getProperty("beforeSunrise")); }
96. TestOverdueCheckNotifier#test()
View license@Test(groups = "slow") public void test() throws Exception { final UUID accountId = new UUID(0L, 1L); final Account account = Mockito.mock(Account.class); Mockito.when(account.getId()).thenReturn(accountId); final DateTime now = clock.getUTCNow(); final DateTime readyTime = now.plusMillis(2000); final OverdueCheckNotificationKey notificationKey = new OverdueCheckNotificationKey(accountId); checkPoster.insertOverdueNotification(accountId, readyTime, OverdueCheckNotifier.OVERDUE_CHECK_NOTIFIER_QUEUE, notificationKey, internalCallContext); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); await().atMost(5, SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mockDispatcher.getEventCount() == 1; } }); Assert.assertEquals(mockDispatcher.getEventCount(), 1); Assert.assertEquals(mockDispatcher.getLatestAccountId(), accountId); }
97. BlockingCalculator#addDisabledDuration()
View licenseprivate void addDisabledDuration(final List<DisabledDuration> result, final BlockingState firstBlocking, @Nullable final BlockingState firstNonBlocking) { final DisabledDuration lastOne; if (!result.isEmpty()) { lastOne = result.get(result.size() - 1); } else { lastOne = null; } final DateTime startDate = firstBlocking.getEffectiveDate(); final DateTime endDate = firstNonBlocking == null ? null : firstNonBlocking.getEffectiveDate(); if (lastOne != null && lastOne.getEnd().compareTo(startDate) == 0) { lastOne.setEnd(endDate); } else if (endDate == null || Days.daysBetween(startDate, endDate).getDays() >= 1) { // Don't disable for periods less than a day (see https://github.com/killbill/killbill/issues/267) result.add(new DisabledDuration(startDate, endDate)); } }
98. TestBillingApi#createSubscriptionCreationEvent()
View licenseprivate DateTime createSubscriptionCreationEvent(final Plan nextPlan, final PlanPhase nextPhase) throws CatalogApiException { final DateTime now = clock.getUTCNow(); final DateTime then = now.minusDays(1); final PriceList nextPriceList = catalog.findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now); final EffectiveSubscriptionInternalEvent t = new MockEffectiveSubscriptionEvent(eventId, subId, bunId, then, now, null, null, null, null, EntitlementState.ACTIVE, nextPlan.getName(), nextPhase.getName(), nextPriceList.getName(), 1L, SubscriptionBaseTransitionType.CREATE, 1, null, 1L, 2L, null); effectiveSubscriptionTransitions.add(t); return now; }
99. TestEntitlementDateHelper#testIsBeforeOrEqualsToday()
View license@Test(groups = "fast") public void testIsBeforeOrEqualsToday() { clock.setTime(new DateTime(2013, 8, 7, 3, 28, 10, 0, DateTimeZone.UTC)); final DateTimeZone timeZoneUtcMinus8 = DateTimeZone.forOffsetHours(-8); Mockito.when(account.getTimeZone()).thenReturn(timeZoneUtcMinus8); internalCallContext.setReferenceDateTimeZone(account.getTimeZone()); final DateTime inputDateEquals = new DateTime(2013, 8, 6, 23, 28, 10, 0, timeZoneUtcMinus8); // Check that our input date is greater than now assertTrue(inputDateEquals.compareTo(clock.getUTCNow()) > 0); // And yet since the LocalDate match the function returns true final DateTime referenceDateTimeThatDoesNotMatter = new DateTime(); assertTrue(dateHelper.isBeforeOrEqualsToday(inputDateEquals, referenceDateTimeThatDoesNotMatter, timeZoneUtcMinus8, internalCallContext)); }
100. StaticEmailAlertSender#buildStreamDetailsURL()
View licenseprotected String buildStreamDetailsURL(URI baseUri, AlertCondition.CheckResult checkResult, Stream stream) { // Return an informational message if the web interface URL hasn't been set if (baseUri == null || isNullOrEmpty(baseUri.getHost())) { return "Please configure 'transport_email_web_interface_url' in your Graylog configuration file."; } int time = 5; if (checkResult.getTriggeredCondition().getParameters().get("time") != null) { time = (int) checkResult.getTriggeredCondition().getParameters().get("time"); } DateTime dateAlertEnd = checkResult.getTriggeredAt(); DateTime dateAlertStart = dateAlertEnd.minusMinutes(time); String alertStart = Tools.getISO8601String(dateAlertStart); String alertEnd = Tools.getISO8601String(dateAlertEnd); return baseUri + "/streams/" + stream.getId() + "/messages?rangetype=absolute&from=" + alertStart + "&to=" + alertEnd + "&q=*"; }