예제 #1
0
 private DateTime ensureSameDate(
     DateTime date,
     int years,
     int monthsOfYear,
     int dayOfMonth,
     int hoursOfDay,
     int minutesOfHour,
     int secondsOfMinute,
     DateTimeZone timeZone) {
   if (date.getSecondOfMinute() != secondsOfMinute) {
     date = date.plusSeconds(secondsOfMinute - date.getSecondOfMinute());
   }
   if (date.getMinuteOfHour() != minutesOfHour) {
     date = date.plusMinutes(minutesOfHour - date.getMinuteOfHour());
   }
   if (date.getHourOfDay() != hoursOfDay) {
     date = date.plusHours(hoursOfDay - date.getHourOfDay());
   }
   if (date.getDayOfMonth() != dayOfMonth) {
     date = date.plusDays(dayOfMonth - date.getDayOfMonth());
   }
   if (date.getMonthOfYear() != monthsOfYear) {
     date = date.plusMonths(monthsOfYear - date.getMonthOfYear());
   }
   if (date.getYear() != years) {
     date = date.plusYears(years - date.getYear());
   }
   return date;
 }
예제 #2
0
  @Test
  public void test_aggregationByHour() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 1, 2, 20, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime minute = startDate; minute.isBefore(endDate); minute = minute.plusMinutes(10)) {
      group.addDataPoint(new LongDataPoint(minute.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setSampling(new Sampling(1, TimeUnit.HOURS));
    aggregator.setAlignSampling(false);

    DataPointGroup dayCount = aggregator.aggregate(group);

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(6L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(6L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(2L));

    assertThat(dayCount.hasNext(), is(false));
  }
예제 #3
0
  @Test
  public void shouldNotMakeACallWhenCurrentTimeIsConfiguredMinutesMoreThanScheduledTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID,
        NOW.plusMinutes(16).toDate(),
        TIMES_SENT,
        TOTAL_TIMES_TO_SEND,
        RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService, never()).initiateCall(callRequestArgumentCaptor.capture());
  }
예제 #4
0
  @Test
  public void shouldMarkDoseAsNotRecordedWhenCurrentTimeIsConfiguredMinutesMoreThanScheduledTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID,
        NOW.plusMinutes(16).toDate(),
        TIMES_SENT,
        TOTAL_TIMES_TO_SEND,
        RETRY_INTERVAL);

    verify(dailyPillReminderAdherenceService)
        .recordDosageAdherenceAsNotCaptured(
            PATIENT_DOC_ID, "pillRegimenId", dose, DosageStatus.NOT_RECORDED, now);
  }
예제 #5
0
  private void initTime() {

    DateTime current = new DateTime();
    inTime = current.minusMinutes(1);
    // 有效期30分钟
    expireTime = current.plusMinutes(30);
  }
예제 #6
0
  @Test(groups = "slow")
  public void testBasic() throws InterruptedException {
    final String ownerId = UUID.randomUUID().toString();

    final String notificationKey = UUID.randomUUID().toString();
    final DateTime effDt = new DateTime();
    final Notification notif =
        new DefaultNotification(
            "testBasic",
            hostname,
            notificationKey.getClass().getName(),
            notificationKey,
            accountId,
            effDt);
    dao.insertNotification(notif);

    Thread.sleep(1000);
    final DateTime now = new DateTime();
    final List<Notification> notifications =
        dao.getReadyNotifications(now.toDate(), hostname, 3, "testBasic");
    assertNotNull(notifications);
    assertEquals(notifications.size(), 1);

    Notification notification = notifications.get(0);
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    assertEquals(notification.getOwner(), null);
    assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.AVAILABLE);
    assertEquals(notification.getNextAvailableDate(), null);

    final DateTime nextAvailable = now.plusMinutes(5);
    final int res =
        dao.claimNotification(
            ownerId, nextAvailable.toDate(), notification.getId().toString(), now.toDate());
    assertEquals(res, 1);
    dao.insertClaimedHistory(ownerId, now.toDate(), notification.getId().toString());

    notification = fetchNotification(notification.getId().toString());
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    assertEquals(notification.getOwner(), ownerId);
    assertEquals(
        notification.getProcessingState(), PersistentQueueEntryLifecycleState.IN_PROCESSING);
    validateDate(notification.getNextAvailableDate(), nextAvailable);

    dao.clearNotification(notification.getId().toString(), ownerId);

    notification = fetchNotification(notification.getId().toString());
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    // assertEquals(notification.getOwner(), null);
    assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.PROCESSED);
    validateDate(notification.getNextAvailableDate(), nextAvailable);
  }
  @Test
  public void shouldBuildCallSummaryWithEmptyCallFlowDetailsWhenCallLogDoesNotHaveAnyFlows() {
    DateTime callStartTime = DateUtil.now();
    CallLog callLog = new CallLog();
    callLog.setStartTime(callStartTime);
    callLog.setEndTime(callStartTime.plusMinutes(1));

    CallLogSummary logSummary =
        new CallLogSummaryBuilder(allPatients, new Patients(allPatients.getAll()), allIVRLanguages)
            .build(callLog);
    assertNotNull(logSummary.getFlowDetailsMap());
  }
예제 #8
0
  @Test
  public void shouldReturnCallFlowDuration() {
    callEventView = new CallEventView(new CallEvent(IVREvent.GotDTMF.toString()));
    callFlowGroupView = new CallFlowGroupView("flow", callEventView);
    DateTime flowStartTime = DateUtil.now();

    callFlowGroupView.setFlowStartTime(flowStartTime);
    callFlowGroupView.setFlowEndTime(flowStartTime.plusMinutes(2).plusSeconds(3));

    assertEquals(123, callFlowGroupView.getFlowDuration());
    assertEquals("flow", callFlowGroupView.toString());
  }
예제 #9
0
 /**
  * @param from
  * @param to
  * @param offsetMinutes
  * @return
  */
 private Pair<Set<LocalTime>, Set<LocalTime>> getTimeOptions(
     DateTime from, DateTime to, int offsetMinutes) {
   Set<LocalTime> first = new TreeSet<LocalTime>();
   Set<LocalTime> second = new TreeSet<LocalTime>();
   if (from == null || to == null) {
     return new Pair<Set<LocalTime>, Set<LocalTime>>(first, second);
   }
   LocalTime startTime = from.toLocalTime();
   from = from.plusMinutes(offsetMinutes);
   int minuteInterval = from.getMinuteOfHour() % 15;
   from = from.plusMinutes(minuteInterval == 0 ? 0 : 15 - minuteInterval);
   while (!from.isAfter(to)) {
     LocalTime nextTime = from.toLocalTime();
     if (!nextTime.isAfter(startTime)) {
       second.add(nextTime);
     } else {
       first.add(nextTime);
     }
     from = from.plusMinutes(15);
   }
   return new Pair<Set<LocalTime>, Set<LocalTime>>(first, second);
 }
 @Test
 public void shouldValidateValidCallLogRecord() {
   DateTime now = ISODateTimeUtil.nowInTimeZoneUTC();
   DateTime tenMinutesAddedToNow = now.plusMinutes(10);
   CallLogRecord callLogRecord =
       new CallLogRecord(
           UUID.randomUUID(),
           1,
           CallLogRecordType.LESSON.name(),
           now.toString(),
           tenMinutesAddedToNow.toString());
   List<ValidationError> validationErrors = callLogRecord.validate();
   assertThat(validationErrors.size(), Is.is(0));
 }
예제 #11
0
  /** test to determine if the antenna would track through a pole during a pass */
  @Test
  public final void poleIsPassed() {
    final TLE tle = new TLE(LEO_TLE);

    Assert.assertTrue(!tle.isDeepspace());

    try {
      final PassPredictor passPredictor = new PassPredictor(tle, GROUND_STATION);
      DateTime cal = new DateTime(DATE_2009_01_05T07_00_00Z);

      boolean northFound = false;
      boolean southFound = false;

      for (int minute = 0; minute < 60 * 24 * 7; minute++) {
        final long startTime = cal.toDate().getTime();
        if (northFound && southFound) {
          break;
        }
        final SatPassTime passTime = passPredictor.nextSatPass(cal.toDate());
        final long endTime = passTime.getEndTime().getTime();
        final String polePassed = passTime.getPolePassed();
        if (!polePassed.equals(NONE)) {
          if (!northFound && polePassed.equals(NORTH)) {
            Assert.assertEquals(
                "2009-01-05T07:42:45+0000, north",
                String.format(STRING_PAIR, TZ_FORMAT.format(passTime.getStartTime()), polePassed));
            northFound = true;

            minute += (int) ((endTime - startTime) / 60000);
          } else if (!southFound && polePassed.equals("south")) {
            Assert.assertEquals(
                "2009-01-06T07:03:20+0000, south",
                String.format(STRING_PAIR, TZ_FORMAT.format(passTime.getStartTime()), polePassed));
            southFound = true;

            minute += (int) ((endTime - startTime) / 60000);
          }
        }

        cal = cal.plusMinutes(minute);
      }
    } catch (final InvalidTleException e) {
      Assert.fail(INVALID_TLE_EXCEPTION_WAS_THROWN);
    } catch (final SatNotFoundException snfe) {
      Assert.fail(SAT_NOT_FOUND_EXCEPTION_WAS_THROWN);
    }
  }
  @Test
  public void testResetSanity() throws IOException {

    IncrementalIndex index = indexCreator.createIndex();
    DateTime t = DateTime.now();
    Interval interval = new Interval(t.minusMinutes(1), t.plusMinutes(1));

    index.add(
        new MapBasedInputRow(
            t.minus(1).getMillis(),
            Lists.newArrayList("billy"),
            ImmutableMap.<String, Object>of("billy", "hi")));
    index.add(
        new MapBasedInputRow(
            t.minus(1).getMillis(),
            Lists.newArrayList("sally"),
            ImmutableMap.<String, Object>of("sally", "bo")));

    IncrementalIndexStorageAdapter adapter = new IncrementalIndexStorageAdapter(index);

    for (boolean descending : Arrays.asList(false, true)) {
      Sequence<Cursor> cursorSequence =
          adapter.makeCursors(
              new SelectorFilter("sally", "bo"), interval, QueryGranularity.NONE, descending);

      Cursor cursor =
          Sequences.toList(Sequences.limit(cursorSequence, 1), Lists.<Cursor>newArrayList()).get(0);
      DimensionSelector dimSelector;

      dimSelector = cursor.makeDimensionSelector(new DefaultDimensionSpec("sally", "sally"));
      Assert.assertEquals("bo", dimSelector.lookupName(dimSelector.getRow().get(0)));

      index.add(
          new MapBasedInputRow(
              t.minus(1).getMillis(),
              Lists.newArrayList("sally"),
              ImmutableMap.<String, Object>of("sally", "ah")));

      // Cursor reset should not be affected by out of order values
      cursor.reset();

      dimSelector = cursor.makeDimensionSelector(new DefaultDimensionSpec("sally", "sally"));
      Assert.assertEquals("bo", dimSelector.lookupName(dimSelector.getRow().get(0)));
    }
  }
예제 #13
0
  @Test
  public void shouldBeAbleToOutputNiceTimeDeltaForDatesInTheFuture() throws Exception {
    final DateTime now = new DateTime();

    DateTime fiveMinutesFromNow = now.plusMinutes(5).plusSeconds(5);
    assertEquals("5 minutes", dateFormatter.timeSince(fiveMinutesFromNow.toDate()));

    DateTime twoDaysFromNow = now.plusDays(2).plusHours(1);
    assertEquals("2 days", dateFormatter.timeSince(twoDaysFromNow.toDate()));

    DateTime oneWeekFromNow = now.plusWeeks(1).plusHours(1);
    assertEquals("1 week", dateFormatter.timeSince(oneWeekFromNow.toDate()));

    DateTime twoWeeksFromNow = now.plusWeeks(2).plusHours(1);
    assertEquals("2 weeks", dateFormatter.timeSince(twoWeeksFromNow.toDate()));

    DateTime sixMonthsFromNow = now.plusMonths(6).plusHours(1);
    assertEquals("6 months", dateFormatter.timeSince(sixMonthsFromNow.toDate()));
  }
예제 #14
0
  @Test(groups = "fast")
  public void testBasicClockOperations() throws Exception {
    final ClockMock clock = new ClockMock();

    final DateTime startingTime = new DateTime(DateTimeZone.UTC);
    // Lame, but required due to the truncation magic
    Awaitility.await()
        .atMost(1001, MILLISECONDS)
        .until(
            new Callable<Boolean>() {
              @Override
              public Boolean call() throws Exception {
                return clock.getUTCNow().isAfter(startingTime);
              }
            });

    clock.setTime(new DateTime(2012, 5, 1, 1, 2, 3, DateTimeZone.UTC));
    Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 5, 1));
    final DateTime utcNowAfterSetTime = clock.getUTCNow();
    Assert.assertEquals(utcNowAfterSetTime.getHourOfDay(), 1);
    Assert.assertEquals(utcNowAfterSetTime.getMinuteOfHour(), 2);
    Assert.assertEquals(utcNowAfterSetTime.getSecondOfMinute(), 3);

    clock.addDays(1);
    Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 5, 2));

    clock.addMonths(1);
    Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 6, 2));

    clock.addYears(1);
    Assert.assertEquals(clock.getUTCToday(), new LocalDate(2013, 6, 2));

    clock.setDay(new LocalDate(2045, 12, 12));
    Assert.assertEquals(clock.getUTCToday(), new LocalDate(2045, 12, 12));

    clock.resetDeltaFromReality();
    Assert.assertTrue(clock.getUTCNow().isAfter(startingTime));
    Assert.assertTrue(clock.getUTCNow().isBefore(startingTime.plusMinutes(1)));
  }
예제 #15
0
  public static void main(String[] args) {
    //
    // Creates an instance of current DateTime which represents the
    // current date time.
    //
    DateTime dateTime = new DateTime();
    System.out.println("DateTime = " + dateTime);

    //
    // Plus some hours, minutes, and seconds to the original DateTime.
    //
    System.out.println("Plus 1 hour is " + dateTime.plusHours(1));
    System.out.println("Plus 10 minutes is " + dateTime.plusMinutes(10));
    System.out.println("Plus 60 seconds is " + dateTime.plusSeconds(60));

    //
    // Minus some hours, minutes, and seconds to the original DateTime.
    //
    System.out.println("Minus 1 hour is " + dateTime.minusHours(1));
    System.out.println("Minus 10 minutes is " + dateTime.minusMinutes(10));
    System.out.println("Minus 60 seconds is " + dateTime.minusSeconds(60));
  }
예제 #16
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public void initialize(InputSplit split, TaskAttemptContext context)
      throws IOException, InterruptedException {
    this.split = (EtlSplit) split;
    this.context = context;

    if (context instanceof Mapper.Context) {
      mapperContext = (Context) context;
    }

    this.skipSchemaErrors = EtlInputFormat.getEtlIgnoreSchemaErrors(context);

    if (EtlInputFormat.getKafkaMaxPullHrs(context) != -1) {
      this.maxPullHours = EtlInputFormat.getKafkaMaxPullHrs(context);
    } else {
      this.endTimeStamp = Long.MAX_VALUE;
    }

    if (EtlInputFormat.getKafkaMaxPullMinutesPerTask(context) != -1) {
      DateTime now = new DateTime();
      this.maxPullTime =
          now.plusMinutes(EtlInputFormat.getKafkaMaxPullMinutesPerTask(context)).getMillis();
    } else {
      this.maxPullTime = Long.MAX_VALUE;
    }

    if (EtlInputFormat.getKafkaMaxHistoricalDays(context) != -1) {
      int maxDays = EtlInputFormat.getKafkaMaxHistoricalDays(context);
      beginTimeStamp = (new DateTime()).minusDays(maxDays).getMillis();
    } else {
      beginTimeStamp = 0;
    }

    this.totalBytes = this.split.getLength();

    System.out.println("Finished executing the initialize part");
  }
예제 #17
0
  /**
   * 计算指定时间之后的日期
   *
   * @param date 待计算时间
   * @param random 待计算数
   * @param timeType 时间类型枚举
   * @see org.codingsills.modules.utils.DateKit.TimeType
   * @return Date
   */
  public static Date nextDate(Date date, int random, TimeType timeType) {
    Date nextDate = null;
    if (date == null) {
      return nextDate;
    }
    DateTime dateTime = fromDate(date);
    random = Math.abs(random);
    switch (timeType.getCode()) {
      case "Y":
        nextDate = dateTime.plusYears(random).toDate();
        break;
      case "M":
        nextDate = dateTime.plusMonths(random).toDate();
        break;
      case "W":
        nextDate = dateTime.plusWeeks(random).toDate();
        break;
      case "D":
        nextDate = dateTime.plusDays(random).toDate();
        break;
      case "H":
        nextDate = dateTime.plusHours(random).toDate();
        break;
      case "MIN":
        nextDate = dateTime.plusMinutes(random).toDate();
        break;
      case "S":
        nextDate = dateTime.plusSeconds(random).toDate();
        break;
      case "MS":
        nextDate = dateTime.plusMillis(random).toDate();
        break;
      default:
        break;
    }

    return nextDate;
  }
예제 #18
0
  @Test
  public void shouldProperlyApplyManipulations() throws Exception {
    String string = "ala-has-a-cat";
    DateTime now = DateUtil.now();
    String toString = now.toString();
    String toStringWithPattern = now.toString("yyyy-MM-dd");
    KeyEvaluator keyEvaluator = new KeyEvaluator(null);

    String pastDate = "2015-05-15";
    String timeZone =
        new DateTime(pastDate)
            .toString("Z"); // Figure out the correct time zone for the given date and locale

    assertEquals("lower_case", keyEvaluator.manipulate("tolower", "LOWER_CASE"));
    assertEquals("UPPER_CASE", keyEvaluator.manipulate("toupper", "upper_case"));
    assertEquals("Capitalize", keyEvaluator.manipulate("capitalize", "capitalize"));
    assertEquals("My+sample+message", keyEvaluator.manipulate("urlencode", "My sample message"));
    assertEquals("37%2365%4078%2490", keyEvaluator.manipulate("URLEncode", "37#65@78$90"));
    assertEquals("67890", keyEvaluator.manipulate("substring(5)", "1234567890"));
    assertEquals("67", keyEvaluator.manipulate("substring(5,7)", "1234567890"));
    assertEquals(string, keyEvaluator.manipulate("join(-)", "ala has a cat"));
    assertEquals("ala", keyEvaluator.manipulate("split(-,0)", string));
    assertEquals("cat", keyEvaluator.manipulate("split(-,3)", string));
    assertEquals(
        pastDate + " 11:32 " + timeZone,
        keyEvaluator.manipulate("parseDate(yyyy/dd/MM hh:mm)", "2015/15/05 11:32"));
    assertEquals(toStringWithPattern, keyEvaluator.manipulate("datetime(yyyy-MM-dd)", toString));
    assertEquals(now.plusDays(1).toString(), keyEvaluator.manipulate("plusDays(1)", toString));
    assertEquals(now.minusDays(1).toString(), keyEvaluator.manipulate("minusDays(1)", toString));
    assertEquals(now.plusHours(2).toString(), keyEvaluator.manipulate("plusHours(2)", toString));
    assertEquals(now.minusHours(2).toString(), keyEvaluator.manipulate("minusHours(2)", toString));
    assertEquals(
        now.plusMinutes(20).toString(), keyEvaluator.manipulate("plusMinutes(20)", toString));
    assertEquals(
        now.minusMinutes(20).toString(), keyEvaluator.manipulate("minusMinutes(20)", toString));
  }
 public synchronized DateTime addMinute() {
   systemDate = systemDate.plusMinutes(1);
   return systemDate;
 }
예제 #20
0
  @Test
  public void testBilling() throws Exception {
    Vendor vendor =
        new Vendor(null)
            .setBillingFlat(200)
            .setBillingRate(50)
            .setBillingFlat2HrSoc(220)
            .setBillingRate2HrSoc(70)
            .setBillingFlat2HrRoc(210)
            .setBillingRate2HrRoc(60);
    Patient patient = new Patient(null).setVendor(vendor);
    Nurse nurse = new Nurse(null);
    DateTime timeIn = DateTime.now().minusHours(2);
    DateTime timeOut = DateTime.now();
    Appointment appointment =
        new Appointment(null)
            .setPatient(patient)
            .setNurse(nurse)
            .setStart(DateTime.now())
            .setTimeInD(timeIn)
            .setTimeOutD(timeOut);
    assertEquals(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager), appointment.getBillingType());
    assertEquals(2.0, appointment.getLoggedHours(), 0.0);
    assertEquals(220.0, appointment.getBillingFlat(), 0.0);
    assertEquals(0.0, appointment.getBilledHours(), 0.0);
    assertEquals(70.0, appointment.getBillingRate(), 0.0);
    assertEquals(220.0, appointment.getBillingTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusHours(1));
    assertEquals(GenData.ACCOUNTING_TYPE_HOURLY.get(entityManager), appointment.getBillingType());
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(0.0, appointment.getBillingFlat(), 0.0);
    assertEquals(50.0, appointment.getBillingRate(), 0.0);
    assertEquals(150.0, appointment.getBillingTotal(), 0.0);

    appointment.setBillingType(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager), appointment.getBillingType());
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(200.0, appointment.getBillingFlat(), 0.0);
    assertEquals(0.0, appointment.getBilledHours(), 0.0);
    assertEquals(0.0, appointment.getBillingRate(), 0.0);
    assertEquals(200.0, appointment.getBillingTotal(), 0.0);

    appointment.setTimeInD(timeIn.plusMinutes(105));
    appointment.setBillingType(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager), appointment.getBillingType());
    assertEquals(.25, appointment.getLoggedHours(), 0.0);
    assertEquals(200.0, appointment.getBillingFlat(), 0.0);
    assertEquals(0.0, appointment.getBilledHours(), 0.0);
    assertEquals(0.0, appointment.getBillingRate(), 0.0);
    assertEquals(200.0, appointment.getBillingTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusHours(1));
    appointment.setBillingType(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager), appointment.getBillingType());
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(220.0, appointment.getBillingFlat(), 0.0);
    assertEquals(1.0, appointment.getBilledHours(), 0.0);
    assertEquals(70.0, appointment.getBillingRate(), 0.0);
    assertEquals(290.0, appointment.getBillingTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusMinutes(30));
    appointment.setBillingType(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager), appointment.getBillingType());
    assertEquals(2.5, appointment.getLoggedHours(), 0.0);
    assertEquals(210.0, appointment.getBillingFlat(), 0.0);
    assertEquals(.5, appointment.getBilledHours(), 0.0);
    assertEquals(60.0, appointment.getBillingRate(), 0.0);
    assertEquals(240.0, appointment.getBillingTotal(), 0.0);

    appointment.setTimeInD(timeIn.plusMinutes(30));
    appointment.setBillingType(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager), appointment.getBillingType());
    assertEquals(1.5, appointment.getLoggedHours(), 0.0);
    assertEquals(210.0, appointment.getBillingFlat(), 0.0);
    assertEquals(0.0, appointment.getBilledHours(), 0.0);
    assertEquals(60.0, appointment.getBillingRate(), 0.0);
    assertEquals(210.0, appointment.getBillingTotal(), 0.0);

    appointment.setPropertyValue("TIME_IN", "20:10");
    appointment.setPropertyValue("TIME_OUT", "03:10");
    appointment.setBillingType(GenData.ACCOUNTING_TYPE_HOURLY.get(entityManager));
    assertEquals(7, appointment.getLoggedHours(), 0.0);
    assertEquals(0.0, appointment.getBillingFlat(), 0.0);
    assertEquals(7, appointment.getBilledHours(), 0.0);
    assertEquals(50.0, appointment.getBillingRate(), 0.0);
    assertEquals(350.0, appointment.getBillingTotal(), 0.0);
  }
예제 #21
0
  @Test
  public void testPayroll() throws Exception {
    Vendor vendor = new Vendor(entityManager);
    Patient patient = new Patient(entityManager).setVendor(vendor);
    Nurse nurse =
        new Nurse(entityManager)
            .setPayFlat(100)
            .setPayRate(40)
            .setPayFlat2HrSoc(95)
            .setPayRate2HrSoc(60)
            .setPayFlat2HrRoc(90)
            .setPayRate2HrRoc(50);
    DateTime timeIn = DateTime.now().minusHours(2);
    DateTime timeOut = DateTime.now();
    Appointment appointment =
        new Appointment(entityManager)
            .setPatient(patient)
            .setNurse(nurse)
            .setStart(DateTime.now())
            .setTimeInD(timeIn)
            .setTimeOutD(timeOut);
    assertEquals(2.0, appointment.getLoggedHours(), 0.0);
    assertEquals(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager), appointment.getPayingType());
    assertEquals(95.0, appointment.getPayFlat(), 0.0);
    assertEquals(0.0, appointment.getPayHours(), 0.0);
    assertEquals(60.0, appointment.getPayRate(), 0.0);
    assertEquals(95.0, appointment.getPaymentTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusHours(1));
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(GenData.ACCOUNTING_TYPE_HOURLY.get(entityManager), appointment.getPayingType());
    assertEquals(0.0, appointment.getPayFlat(), 0.0);
    assertEquals(40.0, appointment.getPayRate(), 0.0);
    assertEquals(3.0, appointment.getPayHours(), 0.0);
    assertEquals(120.0, appointment.getPaymentTotal(), 0.0);

    appointment.setPayingType(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager), appointment.getPayingType());
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(100.0, appointment.getPayFlat(), 0.0);
    assertEquals(0.0, appointment.getPayHours(), 0.0);
    assertEquals(0.0, appointment.getPayRate(), 0.0);
    assertEquals(100.0, appointment.getPaymentTotal(), 0.0);

    appointment.setTimeInD(timeIn.plusMinutes(105));
    appointment.setPayingType(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_FIXED.get(entityManager), appointment.getPayingType());
    assertEquals(.25, appointment.getLoggedHours(), 0.0);
    assertEquals(100.0, appointment.getPayFlat(), 0.0);
    assertEquals(0.0, appointment.getPayHours(), 0.0);
    assertEquals(0.0, appointment.getPayRate(), 0.0);
    assertEquals(100.0, appointment.getPaymentTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusHours(1));
    appointment.setPayingType(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_SOC_2HR.get(entityManager), appointment.getPayingType());
    assertEquals(3.0, appointment.getLoggedHours(), 0.0);
    assertEquals(95.0, appointment.getPayFlat(), 0.0);
    assertEquals(1.0, appointment.getPayHours(), 0.0);
    assertEquals(60.0, appointment.getPayRate(), 0.0);
    assertEquals(155.0, appointment.getPaymentTotal(), 0.0);

    appointment.setTimeInD(timeIn.minusMinutes(30));
    appointment.setPayingType(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager), appointment.getPayingType());
    assertEquals(2.5, appointment.getLoggedHours(), 0.0);
    assertEquals(90.0, appointment.getPayFlat(), 0.0);
    assertEquals(.5, appointment.getPayHours(), 0.0);
    assertEquals(50.0, appointment.getPayRate(), 0.0);
    assertEquals(115.0, appointment.getPaymentTotal(), 0.0);

    appointment.setTimeInD(timeIn.plusMinutes(30));
    appointment.setPayingType(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager));
    assertEquals(GenData.ACCOUNTING_TYPE_ROC_2HR.get(entityManager), appointment.getPayingType());
    assertEquals(1.5, appointment.getLoggedHours(), 0.0);
    assertEquals(90.0, appointment.getPayFlat(), 0.0);
    assertEquals(0.0, appointment.getPayHours(), 0.0);
    assertEquals(50.0, appointment.getPayRate(), 0.0);
    assertEquals(90.0, appointment.getPaymentTotal(), 0.0);
  }
예제 #22
0
 public static Date plusMinutes(Date date, int numberOfMinutes) {
   if (date == null) date = new Date();
   DateTime dt = new DateTime(date);
   return dt.plusMinutes(numberOfMinutes).toDate();
 }
예제 #23
0
 public static String computeTime(String dateString, String val, String timeUnit) {
   DateTime date = new DateTime();
   int value = 0;
   boolean isLong = false;
   if (!Strings.isEmpty(val) && !Strings.isEmpty(dateString) && !Strings.isEmpty(timeUnit)) {
     if (dateString.substring(dateString.indexOf("T") + 1, dateString.length()).length() == 0) {
       dateString = dateString + DEFAULT_TIME_FORMAT;
     }
     date = new DateTime(dateString);
     if (val.indexOf(".") > 0) {
       val = val.substring(0, val.indexOf("."));
     }
     Long l = new Long(val);
     if ((l.longValue() < 0 && -l.longValue() > 32768)
         || (l.longValue() > 0 && l.longValue() > 32768)) {
       isLong = true;
     }
     if (!isLong) {
       value = Integer.parseInt(val);
     }
     if (!Strings.isEmpty(timeUnit)) {
       if (timeUnit.equals("d")) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusDays(value);
           } else {
             date = date.minusDays(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 24 * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 24 * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(HOUR)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusHours(value);
           } else {
             date = date.minusHours(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(MIN)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusMinutes(value);
           } else {
             date = date.minusMinutes(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(SEC)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusSeconds(value);
           } else {
             date = date.minusSeconds(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 1000);
           } else {
             date = date.plus(l.longValue() * 1000);
           }
         }
       }
     }
   }
   return FormatUtils.formatDateTimeToISO(date.toDate());
 }
 public synchronized DateTime addMinutes(int minutes) {
   systemDate = systemDate.plusMinutes(minutes);
   return systemDate;
 }
  @Execute
  public void nextRecord() throws IOException {
    ensureOpen();
    if (tCurrent == null) {
      tPrevious = null;
      tCurrent = tStart.trim();
      expectedTimestamp = formatter.parseDateTime(tCurrent);
    } else {

      tPrevious = tCurrent;
      expectedTimestamp = expectedTimestamp.plusMinutes(tTimestep);
      tCurrent = expectedTimestamp.toString(formatter);
    }
    outData = new HashMap<Integer, double[]>();

    int columnCount = table.getColumnCount();
    List<Integer> idList = new ArrayList<Integer>();
    List<Integer> idCountList = new ArrayList<Integer>();
    int count = 0;
    Integer previousIdInteger = null;
    for (int i = 2; i <= columnCount; i++) {
      String id = table.getColumnInfo(i).get(idfield);
      try {
        Integer idInteger = Integer.valueOf(id);
        idList.add(idInteger);
        if (previousIdInteger == null) {
          count++;
        } else {
          if (idInteger.intValue() == previousIdInteger.intValue()) {
            count++;
          } else {
            idCountList.add(count);
            count = 1;
          }
        }
        if (i == columnCount) {
          idCountList.add(count);
        }
        previousIdInteger = idInteger;
      } catch (Exception e) {
        throw new ModelsIllegalargumentException(
            "The id value doesn't seem to be an integer.", this.getClass().getSimpleName(), pm);
      }
    }

    if (rowsIterator.hasNext()) {
      String[] row = getExpectedRow(rowsIterator, expectedTimestamp);

      int idCountIndex = 0;
      for (int i = 2; i < row.length; i++) {
        Integer id = idList.get(i - 2);
        Integer idCount = idCountList.get(idCountIndex);
        double[] values = outData.get(id);
        if (values == null) {
          values = new double[idCount];
          outData.put(id, values);
        }
        for (int j = 0; j < idCount; j++, i++) {
          if (row[i] == null || row[i].length() == 0) {
            values[j] = novalue;
          } else {
            String valueStr = row[i].trim();
            if (valueStr.equals(fileNovalue)) {
              values[j] = novalue;
            } else {
              values[j] = Double.parseDouble(valueStr);
            }
          }
        }
        idCountIndex++;
        i--;
      }
    } else {
      outData = null;
    }

    // time ran out
    if (tEnd != null && tCurrent.equals(tEnd)) {
      doProcess = false;
    }
    // data ran out
    if (!rowsIterator.hasNext()) {
      doProcess = false;
    }
  }
예제 #26
0
 @Override
 public void addMsg(String msgText) {
   DateTime now = new DateTime();
   tellChatter(new ChatMsg(now, now.plusMinutes(30), msgText));
   scheduleRemoval();
 }
예제 #27
0
  /**
   * @Title: getOpenTimeByOrderDate @Description: 返回营业时间段
   *
   * @param:
   * @return: String[]
   */
  @Override
  public String[] getOpenTimeByOrderDate(Date orderDate, String restaurantUuid, int type) {
    int pickupInterval = 20;
    int deliveryInterval = 45;

    // Get the restaurant's local time.
    // TODO: This assumes users are in the same time zone as the restaurant!!
    Restaurants restaurant = restaurantsDao.getRestaurantsByUuid(restaurantUuid);
    double latitude = restaurant.getRestaurantLat();
    double longitude = restaurant.getRestaurantLng();
    Date originalAdjustedDate = GoogleTimezoneAPIUtil.getLocalDateTime(latitude, longitude);
    DateTime originalAdjustedDateTime = new DateTime(originalAdjustedDate);

    System.out.println("local time: " + originalAdjustedDate.toString());
    System.out.println("order day: " + orderDate.toString());

    try {
      // 注释掉的是之前做的开始时间结束时间都减少15分钟的方案, 现在是不减时间的
      String orderDateStr = new SimpleDateFormat("yyyy-MM-dd").format(orderDate);

      // If the request's date is before the restaurant's local date, return null.
      if (orderDate.before(
          new SimpleDateFormat("yyyy-MM-dd")
              .parse(originalAdjustedDateTime.toString("yyyy-MM-dd")))) {
        return null;
      }

      // Create a string to store the available times.
      StringBuffer buffer = new StringBuffer();
      String startStr = "";

      // Get the times the restaurant is open for the request's date.
      DateTime orderDateTime = new DateTime(orderDate);
      int week = orderDateTime.getDayOfWeek();
      List<OpenTime> list = openTimeDao.getOpenTime(restaurantUuid, type, week);
      for (OpenTime openTime : list) {
        // If the request's date matches the restaurant's local date, use the restaurant's local
        // time as the start time.
        // Otherwise, use the restaurant's start time as the start time.
        String startTime = openTime.getStarttime();
        String endTime = openTime.getEndtime();
        if (orderDate.equals(originalAdjustedDate)) {
          startTime = originalAdjustedDateTime.toString("HH:mm");
        }

        DateTime nowDateTime = originalAdjustedDateTime;

        // 现在时间加半小时在开门时间之后
        if (originalAdjustedDate.after(
            new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(orderDateStr + " " + startTime))) {

          if (type == GlobalConstant.TYPE_PICKUP) {
            nowDateTime = nowDateTime.plusMinutes(pickupInterval);
          } else if (type == GlobalConstant.TYPE_DELIVERY) {
            nowDateTime = nowDateTime.plusMinutes(deliveryInterval);
          } else {
            //// calendar.setTime(new Date());
          }

          // Apply hour offset to get to the current time zone
          int currentH = nowDateTime.getHourOfDay();
          int currentM = nowDateTime.getMinuteOfHour();

          System.out.println("  Time: " + currentH + ":" + currentM);

          if (currentM > 0 && currentM <= 15) {
            startStr = currentH + ":15";
          } else if (currentM > 15 && currentM <= 30) {
            startStr = currentH + ":30";
          } else if (currentM > 30 && currentM <= 45) {
            startStr = currentH + ":45";
          } else if (currentM > 45 && currentM <= 59) {
            currentH += 1;
            startStr = currentH + ":00";
          } else {
            startStr = currentH + ":15";
          }
        } else {
          int startH = Integer.parseInt(startTime.split(":")[0]);
          int startM = Integer.parseInt(startTime.split(":")[1]);
          startStr = startH + ":" + startM;
        }
        Date start = new SimpleDateFormat("HH:mm").parse(startStr);
        DateTime startDateTime = new DateTime(start);

        // Add a case for 00:00.
        if (startTime.equals("00:00") && orderDate.after(originalAdjustedDate)) {
          buffer.append("00:00,");
        }

        // Loop through all possible times of the day, ignoring midnight.
        while (!(getDateFromDateTime(startDateTime)
            .after(new SimpleDateFormat("HH:mm").parse(endTime)))) {
          String openTimeToAppend =
              new SimpleDateFormat("HH:mm").format(getDateFromDateTime(startDateTime));
          if (!openTimeToAppend.equals("00:00")) {
            buffer.append(openTimeToAppend + ",");
          }
          startDateTime = startDateTime.plusMinutes(15);
        }

        // Add a case for 24:00, since it gets parsed to be 00:00.
        if (endTime.equals("24:00")) {
          buffer.append("24:00,");
        }
      }
      String[] strs = buffer.toString().split(",");
      // 去除可能存在的重复
      List<String> list1 = new ArrayList<String>();
      for (String str : strs) {
        if (!list1.contains(str)) {
          list1.add(str);
        }
      }
      return (String[]) list1.toArray(new String[list1.size()]);
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
예제 #28
0
  /**
   * If date is not match, will return next closest match. If date is match, will return this date.
   *
   * @param date - reference DateTime instance - never null;
   * @return DateTime instance, never null. Value obeys logic specified above.
   * @throws NoSuchValueException
   */
  DateTime nextClosestMatch(DateTime date) throws NoSuchValueException {
    List<Integer> year = yearsValueGenerator.generateCandidates(date.getYear(), date.getYear());
    TimeNode days = null;
    int lowestMonth = months.getValues().get(0);
    int lowestHour = hours.getValues().get(0);
    int lowestMinute = minutes.getValues().get(0);
    int lowestSecond = seconds.getValues().get(0);

    NearestValue nearestValue;
    DateTime newDate;
    if (year.isEmpty()) {
      int newYear = yearsValueGenerator.generateNextValue(date.getYear());
      days = generateDays(cronDefinition, new DateTime(newYear, lowestMonth, 1, 0, 0));
      return initDateTime(
          yearsValueGenerator.generateNextValue(date.getYear()),
          lowestMonth,
          days.getValues().get(0),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!months.getValues().contains(date.getMonthOfYear())) {
      nearestValue = months.getNextValue(date.getMonthOfYear(), 0);
      int nextMonths = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(date.getYear(), 1, 1, 0, 0, 0, date.getZone())
                .plusYears(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getMonthOfYear()) {
        date = date.plusYears(1);
      }
      days = generateDays(cronDefinition, new DateTime(date.getYear(), nextMonths, 1, 0, 0));
      return initDateTime(
          date.getYear(),
          nextMonths,
          days.getValues().get(0),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    days = generateDays(cronDefinition, date);
    if (!days.getValues().contains(date.getDayOfMonth())) {
      nearestValue = days.getNextValue(date.getDayOfMonth(), 0);
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, date.getZone())
                .plusMonths(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getDayOfMonth()) {
        date = date.plusMonths(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          nearestValue.getValue(),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!hours.getValues().contains(date.getHourOfDay())) {
      nearestValue = hours.getNextValue(date.getHourOfDay(), 0);
      int nextHours = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    0,
                    0,
                    0,
                    date.getZone())
                .plusDays(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getHourOfDay()) {
        date = date.plusDays(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          nextHours,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!minutes.getValues().contains(date.getMinuteOfHour())) {
      nearestValue = minutes.getNextValue(date.getMinuteOfHour(), 0);
      int nextMinutes = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    date.getHourOfDay(),
                    0,
                    0,
                    date.getZone())
                .plusHours(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getMinuteOfHour()) {
        date = date.plusHours(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          date.getHourOfDay(),
          nextMinutes,
          lowestSecond,
          date.getZone());
    }
    if (!seconds.getValues().contains(date.getSecondOfMinute())) {
      nearestValue = seconds.getNextValue(date.getSecondOfMinute(), 0);
      int nextSeconds = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    date.getHourOfDay(),
                    date.getMinuteOfHour(),
                    0,
                    date.getZone())
                .plusMinutes(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getSecondOfMinute()) {
        date = date.plusMinutes(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          date.getHourOfDay(),
          date.getMinuteOfHour(),
          nextSeconds,
          date.getZone());
    }
    return date;
  }