Java Code Examples for org.joda.time.DateTime#plusHours()

The following examples show how to use org.joda.time.DateTime#plusHours() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SuplLppClient.java    From supl-client with Apache License 2.0 6 votes vote down vote up
private DateTime toGloTime(DateTime dateTime) {
  dateTime = dateTime.plus(TimeConstants.GPS_UTC_EPOCHS_OFFSET_MILLIS);
  int countLeapSec1 = getLeapSecond(dateTime);

  // The countLeapSec1 would produce the correct number of leap seconds except for an edge case
  // where a straddle leap second occurs (number of leap seconds now != number of leap seconds
  // after adjusting the time with the computed leap seconds). In such case, we need to add one to
  // the used leap second.
  DateTime gpsDateTimeMinusLeapSec = dateTime.minusSeconds(countLeapSec1);
  int countLeapSec2 = getLeapSecond(gpsDateTimeMinusLeapSec);

  gpsDateTimeMinusLeapSec = (countLeapSec1 == countLeapSec2)
      ? gpsDateTimeMinusLeapSec
      : gpsDateTimeMinusLeapSec.minusSeconds(countLeapSec2);

  gpsDateTimeMinusLeapSec.plusHours(TimeConstants.MOSCOW_UTC_TIME_OFFSET_HOURS);

  return gpsDateTimeMinusLeapSec;
}
 
Example 2
Source File: CronExpressionTest.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Test
public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception {
    CronExpression cron = new CronExpression("0 0 * * * *");
    DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(23);
}
 
Example 3
Source File: DateUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns the nearest date forward in time with the given hour of day,
 * with the minute, second and millisecond to zero. If the hour equals
 * the current hour of day, the next following day is used.
 *
 * @param hourOfDay the hour of the day.
 * @param now the date representing the current time, if null, the current
 *         time is used.
 * @return the nearest date forward in time with the given hour of day.
 */
public static Date getNextDate( int hourOfDay, Date now )
{
    now = now != null ? now : new Date();

    DateTime date = new DateTime( now ).plusHours( 1 );

    while ( date.getHourOfDay() != hourOfDay )
    {
        date = date.plusHours( 1 );
    }

    return date
        .withMinuteOfHour( 0 )
        .withSecondOfMinute( 0 )
        .withMillisOfSecond( 0 )
        .toDate();
}
 
Example 4
Source File: CronExpressionTest.java    From cron with Apache License 2.0 6 votes vote down vote up
@Test
public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception {
    CronExpression cron = new CronExpression("0 0 * * * *");
    DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(23);
}
 
Example 5
Source File: BusSearchTask.java    From android-app with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void onPostExecute(BusData busData){
    super.onPostExecute(busData);
    TimeZone tz = TimeZone.getTimeZone("America/Sao_Paulo");
    int offset = tz.getOffset(new Date().getTime())/1000/60/60;
    List<Bus> buses = busData.getBuses();
    for(int i=0; i<buses.size(); i++){
        Bus bus = buses.get(i);
        DateTime dt = new DateTime(bus.getTimestamp());
        dt = dt.plusHours(offset);
        bus.setTimestamp(dt.toDate());
        buses.set(i, bus);
    }
    busData.setBuses(buses);
    dialog.dismiss();

    BusDataReceptor receptor = (BusDataReceptor) context;
    receptor.retrieveBusData(busData);
}
 
Example 6
Source File: RegisterMailHandler.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@Override
public MailMessage handlerMailMessage(String email, User user) {

	CheckEmailDto dto = new CheckEmailDto();
	dto.setType(EmailConstant.EMAIL_USER_REGISTER);// 邮件类型
	dto.setEmailAddress(user.getEmail());// 邮件地址

	DateTime dateTime = new DateTime();
	dto.setNowTime(dateTime.toDate());// 当前时间
	dateTime = dateTime.plusHours(registerValidMailDate);
	dto.setLastTime(dateTime.toDate());// 链接过期时间
	dto.setUserId(user.getId());// 用户账号

	MailMessage mailMessage = new MailMessage(
			EmailConstant.EMAIL_USER_REGISTER_TITLE);
	mailMessage.put("register", dto.getNowTime());
	mailMessage.put("userName", user.getName());
	mailMessage.put("validTime", registerValidMailDate);
	mailMessage.setCheckEmailDto(dto);

	return mailMessage;
}
 
Example 7
Source File: DateTimePeriod.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source File: TagsITest.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void findTaggedGaugeBucketPointsWithSimpleTagQuery() throws Exception {
    String tenantId = "tagged-bucket-points";
    DateTime start = now();
    DateTime end = start.plusHours(2);

    MetricId<Double> metricId = new MetricId<>(tenantId, GAUGE, "m1");
    Metric<Double> metric = new Metric<>(metricId, asList(
            new DataPoint<>(start.getMillis(), 27.43, ImmutableMap.of("x", "1")),
            new DataPoint<>(start.plusMinutes(5).getMillis(), 32.05, ImmutableMap.of("x", "2")),
            new DataPoint<>(start.plusMinutes(10).getMillis(), 34.14, ImmutableMap.of("x", "2")),
            new DataPoint<>(start.plusMinutes(15).getMillis(), 29.73, ImmutableMap.of("x", "1")),
            new DataPoint<>(start.plusMinutes(20).getMillis(), 28.44, ImmutableMap.of("x", "3")),
            new DataPoint<>(start.plusMinutes(25).getMillis(), 51.91, ImmutableMap.of("x", "3"))));
    doAction(() -> metricsService.addDataPoints(GAUGE, Observable.just(metric)));

    Map<String, TaggedBucketPoint> actual = getOnNextEvents(
            () -> metricsService.findGaugeStats(metricId, ImmutableMap.of("x", "*"), start.getMillis(),
                    end.getMillis(), emptyList())).get(0);

    assertEquals(actual.size(), 3, "The number of buckets do not match");

    TaggedDataPointCollector collector = new TaggedDataPointCollector(ImmutableMap.of("x", "1"), emptyList());
    collector.increment(metric.getDataPoints().get(0));
    collector.increment(metric.getDataPoints().get(3));
    assertEquals(actual.get("x:1"), collector.toBucketPoint());

    collector = new TaggedDataPointCollector(ImmutableMap.of("x", "2"), emptyList());
    collector.increment(metric.getDataPoints().get(1));
    collector.increment(metric.getDataPoints().get(2));
    assertEquals(actual.get("x:2"), collector.toBucketPoint());

    collector = new TaggedDataPointCollector(ImmutableMap.of("x", "3"), emptyList());
    collector.increment(metric.getDataPoints().get(4));
    collector.increment(metric.getDataPoints().get(5));
    assertEquals(actual.get("x:3"), collector.toBucketPoint());
}
 
Example 9
Source File: DateTimePeriodDataUtilTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void fill() throws Exception {
    //
    // create a period of 4 hours
    //
    DateTime start = new DateTime(2009, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
    DateTimePeriod period = new DateTimeHour(start, start.plusHours(4));

    // fill an empty map
    TreeMap<DateTime, SampleData> emptyMap = new TreeMap<DateTime, SampleData>();
    DateTimePeriodDataUtil.fill(SampleData.class, emptyMap, period.toHours());

    SampleData[] result0 = emptyMap.values().toArray(new SampleData[0]);
    Assert.assertArrayEquals(new SampleData[] {
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 0, DateTimeZone.UTC), null),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 1, DateTimeZone.UTC), null),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 2, DateTimeZone.UTC), null),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 3, DateTimeZone.UTC), null)
    }, result0);

    // fill a partially completed map
    SampleData hour0 = new SampleData(DateTimePeriod.createHour(2009, 1, 1, 0, DateTimeZone.UTC), "hour0");
    SampleData hour2 = new SampleData(DateTimePeriod.createHour(2009, 1, 1, 2, DateTimeZone.UTC), "hour2");
    TreeMap<DateTime, SampleData> partialMap = new TreeMap<DateTime, SampleData>();
    partialMap.put(hour0.getPeriod().getStart(), hour0);
    partialMap.put(hour2.getPeriod().getStart(), hour2);
    DateTimePeriodDataUtil.fill(SampleData.class, partialMap, period.toHours());

    result0 = partialMap.values().toArray(new SampleData[0]);
    Assert.assertArrayEquals(new SampleData[] {
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 0, DateTimeZone.UTC), "hour0"),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 1, DateTimeZone.UTC), null),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 2, DateTimeZone.UTC), "hour2"),
        new SampleData(DateTimePeriod.createHour(2009, 1, 1, 3, DateTimeZone.UTC), null)
    }, result0);

}
 
Example 10
Source File: DateTimeParser.java    From blueflood with Apache License 2.0 5 votes vote down vote up
private DateTime updateDateTimeWithOffset(DateTime baseDateTime) {
    if (offset.equals(""))
        return baseDateTime;
    Pattern p = Pattern.compile("(-?\\d*)([a-z]*)");
    Matcher m = p.matcher(offset);
    if (!m.matches())
        return baseDateTime;

    int count = Integer.parseInt(m.group(1));
    String unit = m.group(2);

    DateTime dateTimeWithOffset = baseDateTime;
    if (unit.startsWith("s"))
        dateTimeWithOffset = baseDateTime.plusSeconds(count);
    else if (unit.startsWith("min"))
        dateTimeWithOffset = baseDateTime.plusMinutes(count);
    else if (unit.startsWith("h"))
        dateTimeWithOffset = baseDateTime.plusHours(count);
    else if (unit.startsWith("d"))
        dateTimeWithOffset = baseDateTime.plusDays(count);
    else if (unit.startsWith("mon"))
        dateTimeWithOffset = baseDateTime.plusMonths(count);
    else if (unit.startsWith("y"))
        dateTimeWithOffset = baseDateTime.plusYears(count);

    return dateTimeWithOffset;
}
 
Example 11
Source File: TagsITest.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void findTaggedCounterBucketPointsWithMultipleTagFilters() throws Exception {
    String tenantId = "multiple-tag-filter-counter-data-point-query";
    DateTime start = now();
    DateTime end = start.plusHours(2);

    MetricId<Long> metricId = new MetricId<>(tenantId, COUNTER, "C1");
    Metric<Long> metric = new Metric<>(metricId, asList(
            new DataPoint<>(start.getMillis(), 11L, ImmutableMap.of("x", "1", "y", "1", "z", "1")),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 13L, ImmutableMap.of("x", "2", "y", "2", "z", "2")),
            new DataPoint<>(start.plusMinutes(4).getMillis(), 14L, ImmutableMap.of("x", "3", "y", "2", "z", "3")),
            new DataPoint<>(start.plusMinutes(6).getMillis(), 15L,
                    ImmutableMap.of("x", "1", "y", "3", "z", "4"))));
    doAction(() -> metricsService.addDataPoints(COUNTER, Observable.just(metric)));

    Map<String, TaggedBucketPoint> actual = getOnNextEvents(
            () -> metricsService.findCounterStats(metricId, ImmutableMap.of("x", "*", "y", "2", "z", "2|3"),
                    start.getMillis(), end.getMillis(), Collections.emptyList())).get(0);
    assertEquals(actual.size(), 2);

    TaggedDataPointCollector collector = new TaggedDataPointCollector(
            ImmutableMap.of("x", "2", "y", "2", "z", "2"),
            emptyList());
    collector.increment(metric.getDataPoints().get(1));
    assertEquals(actual.get("x:2,y:2,z:2"), collector.toBucketPoint());

    collector = new TaggedDataPointCollector(ImmutableMap.of("x", "3", "y", "2", "z", "3"), emptyList());
    collector.increment(metric.getDataPoints().get(2));
    assertEquals(actual.get("x:3,y:2,z:3"), collector.toBucketPoint());
}
 
Example 12
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DateTime addTime(int tempRes, int increment, DateTime start) {
    
    DateTime d = null;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return d;
    
}
 
Example 13
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int addTimeSteps(int tempRes, int increment, DateTime start) {
    
    DateTime d;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return (int) (d.getMillis()/1000);
    
}
 
Example 14
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static Date getPurgeTimestamp(long startTime, long delay, TimeUnit unit) {
   long ms = TimeUnit.MILLISECONDS.convert(delay, unit);

   DateTime purgeTime = new DateTime(startTime + ms);
   if (purgeTime.getMinuteOfHour() != 0 || purgeTime.getSecondOfMinute() != 0 || purgeTime.getMillisOfSecond() != 0) {
      purgeTime = purgeTime.plusHours(1);
   }

   return purgeTime.withTime(purgeTime.getHourOfDay(), 0, 0, 0).toDate();
}
 
Example 15
Source File: TimeExpressionUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
     * 按某个时间单位添加时间
     * @param dateTime
     * @param n
     * @param timeUnit
     * @return
     */
    public static DateTime calculateTime(DateTime dateTime, int n, TimeUnit timeUnit) {

        DateTime addedDateTime = null;
        switch (timeUnit){
//            case SECOND:
//                addedDateTime = dateTime.plusSeconds(n);
//                break;
            case MINUTE:
                addedDateTime = dateTime.plusMinutes(n);
                break;
            case HOUR:
                addedDateTime = dateTime.plusHours(n);
                break;
            case DAY:
                addedDateTime = dateTime.plusDays(n);
                break;
            case WEEK:
                addedDateTime = dateTime.plusWeeks(n);
                break;
            case MONTH:
                addedDateTime = dateTime.plusMonths(n);
                break;
            case YEAR:
                addedDateTime = dateTime.plusYears(n);
                break;
        }

        return addedDateTime;
    }
 
Example 16
Source File: TestChronosController.java    From chronos with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testJobFuture() throws Exception {
  final DateTime now = new DateTime().withMillisOfSecond(0)
    .withSecondOfMinute(0).withZone(DateTimeZone.UTC);

  DateTime t1 = now.plusHours(1);
  JobSpec job1 = getTestJob("should be first");
  job1.setCronString(String.format("%d %d * * *",
                                   t1.getMinuteOfHour(),
                                   t1.getHourOfDay()));
  job1.setId(1L);

  JobSpec job2 = getTestJob("should be second");
  DateTime t2 = t1.plusMinutes(59);
  job2.setCronString(String.format("%d %d * * *",
                                   t2.getMinuteOfHour(),
                                   t2.getHourOfDay()));
  job2.setId(2L);

  List<JobSpec> jobs = new ArrayList<>();
  jobs.add(job2);
  jobs.add(job1);

  when(jobDao.getJobs()).thenReturn(jobs);

  List<FutureRunInfo> expected = new ArrayList<>();
  FutureRunInfo fri1 =
    new FutureRunInfo(job1.getName(),
      ChronosController.calcNextRunTime(now, job1));
  FutureRunInfo fri2 =
    new FutureRunInfo(job2.getName(),
      ChronosController.calcNextRunTime(now, job2));
  expected.add(fri1);
  expected.add(fri2);

  FutureRunInfo fri3 =
    new FutureRunInfo(job1.getName(),
      ChronosController.calcNextRunTime(fri2.getTime(), job1));
  FutureRunInfo fri4 =
    new FutureRunInfo(job2.getName(),
      ChronosController.calcNextRunTime(fri2.getTime(), job2));
  expected.add(fri3);
  expected.add(fri4);

  int limit = 4;
  assertEquals(expected, controller.getJobFuture(null, limit));
  MockHttpServletRequestBuilder jobsFutureReq =
    get(String.format("/api/jobs/future?limit=%d", limit));
  mockMvc.perform(jobsFutureReq)
    .andExpect(content().string(OM.writeValueAsString(expected)))
    .andExpect(status().isOk());

  when(jobDao.getJob(job1.getId())).thenReturn(job1);
  List<FutureRunInfo> expectedId = new ArrayList<>();
  expectedId.add(fri1);
  expectedId.add(fri3);

  limit = 2;
  MockHttpServletRequestBuilder jobsFutureIdReq =
    get(String.format("/api/jobs/future?limit=%d&id=%d", limit, job1.getId()));
  mockMvc.perform(jobsFutureIdReq)
    .andExpect(content().string(OM.writeValueAsString(expectedId)))
    .andExpect(status().isOk());
}
 
Example 17
Source File: AugmentBaseDataVisitor.java    From spork with Apache License 2.0 4 votes vote down vote up
Object GetLargerValue(Object v) {
    byte type = DataType.findType(v);

    if (type == DataType.BAG || type == DataType.TUPLE
            || type == DataType.MAP)
        return null;

    switch (type) {
    case DataType.CHARARRAY:
        return (String) v + "0";
    case DataType.BYTEARRAY:
        String str = ((DataByteArray) v).toString();
        str = str + "0";
        return new DataByteArray(str);
    case DataType.INTEGER:
        return Integer.valueOf((Integer) v + 1);
    case DataType.LONG:
        return Long.valueOf((Long) v + 1);
    case DataType.FLOAT:
        return Float.valueOf((Float) v + 1);
    case DataType.DOUBLE:
        return Double.valueOf((Double) v + 1);
    case DataType.BIGINTEGER:
        return ((BigInteger)v).add(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal)v).add(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.plusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.plusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.plusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.plusHours(1);
        } else {
            return dt.plusDays(1);
        }
    default:
        return null;
    }
}
 
Example 18
Source File: DatePartitionedAvroFileExtractorTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public void setUp() throws IOException {

  this.schema = new Schema.Parser().parse(AVRO_SCHEMA);

  //set up datetime objects
  DateTime now = new DateTime(TZ).minusHours(6);
  this.startDateTime =
      new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), now.getHourOfDay(), 30, 0, TZ);

  //create records, shift their timestamp by 1 minute
  DateTime recordDt = startDateTime;
  recordTimestamps[0] = recordDt.getMillis();
  recordDt = recordDt.plusHours(4);
  for (int i = 1; i < RECORD_SIZE; i++) {
    recordDt = recordDt.plusMinutes(1);
    recordTimestamps[i] = recordDt.getMillis();
  }

  // create dummy data partitioned by minutes
  State state = new State();
  state.setProp(TimeBasedAvroWriterPartitioner.WRITER_PARTITION_COLUMNS, PARTITION_COLUMN_NAME);
  state.setProp(ConfigurationKeys.WRITER_BUFFER_SIZE, ConfigurationKeys.DEFAULT_BUFFER_SIZE);
  state.setProp(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, ConfigurationKeys.LOCAL_FS_URI);
  state.setProp(ConfigurationKeys.WRITER_STAGING_DIR, STAGING_DIR);
  state.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, OUTPUT_DIR);
  state.setProp(ConfigurationKeys.WRITER_FILE_PATH, SOURCE_ENTITY);
  state.setProp(ConfigurationKeys.WRITER_FILE_NAME, FILE_NAME);
  state.setProp(TimeBasedWriterPartitioner.WRITER_PARTITION_PATTERN, DATE_PATTERN);
  state.setProp(TimeBasedWriterPartitioner.WRITER_PARTITION_PREFIX, PREFIX);
  state.setProp(TimeBasedWriterPartitioner.WRITER_PARTITION_SUFFIX, SUFFIX);
  state.setProp(ConfigurationKeys.WRITER_PARTITIONER_CLASS, TimeBasedAvroWriterPartitioner.class.getName());

  DataWriterBuilder<Schema, GenericRecord> builder = new AvroDataWriterBuilder()
      .writeTo(Destination.of(Destination.DestinationType.HDFS, state))
      .writeInFormat(WriterOutputFormat.AVRO)
      .withWriterId("writer-1")
      .withSchema(this.schema)
      .withBranches(1).forBranch(0);

  this.writer = new PartitionedDataWriter<Schema, GenericRecord>(builder, state);

  GenericRecordBuilder genericRecordBuilder = new GenericRecordBuilder(this.schema);
  for (int i = 0; i < RECORD_SIZE; i++) {
    genericRecordBuilder.set(PARTITION_COLUMN_NAME, recordTimestamps[i]);
    this.writer.writeEnvelope(new RecordEnvelope<>(genericRecordBuilder.build()));
  }

  this.writer.close();
  this.writer.commit();

}
 
Example 19
Source File: MultiSemesterEnrolmentReporter.java    From fenixedu-academic with GNU Lesser General Public License v3.0 3 votes vote down vote up
public void report(final int year, final int month, final int day, final int hour) {
    final DateTime enrolmentStartTime = new DateTime(year, month, day, hour, 0, 0, 0);
    final ExecutionSemester semester = ExecutionSemester.readByDateTime(enrolmentStartTime);
    final DateTime endTimeToReport = enrolmentStartTime.plusHours(hoursToReport);

    if (semester.getSemester().intValue() == semesterToReport) {
        semester.getCurriculumLineLogsSet().stream()

        .filter(l -> l instanceof EnrolmentLog)

        .filter(l -> !l.getDateDateTime().isBefore(enrolmentStartTime) && !l.getDateDateTime().isAfter(endTimeToReport))

        .sorted((l1, l2) -> l1.getDateDateTime().compareTo(l2.getDateDateTime()))

        .forEach(l -> process(semester, enrolmentStartTime, l));

        semester.getAssociatedExecutionCoursesSet().stream()

        .flatMap(ec -> ec.getCourseLoadsSet().stream())

        .flatMap(cl -> cl.getShiftsSet().stream())

        .flatMap(s -> s.getShiftEnrolmentsSet().stream())

        .map(se -> se.getCreatedOn())

        .filter(dt -> !dt.isBefore(enrolmentStartTime) && !dt.isAfter(endTimeToReport))

        .map(dt -> new Interval(enrolmentStartTime, dt).toDuration().getStandardSeconds())

        .forEach(seconds -> add(semester, seconds, new int[] { 0, 0, 1 }));
    }
}
 
Example 20
Source File: DatePlusHours.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void add_hours_to_date_in_java_with_joda () {

	DateTime newYearsEve = new DateTime(2012, 12, 31, 23, 0, 0, 0);
	DateTime newYearsDay = newYearsEve.plusHours(1);

	DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
	
	logger.info(newYearsEve.toString(fmt));
	logger.info(newYearsDay.toString(fmt));

	assertTrue(newYearsDay.isAfter(newYearsEve));
}