@Test
  public void testGetVolumeWeightStockPrice() {
    Transaction localTransactionMockOne = mock(Transaction.class);
    Transaction localTransactionMockTwo = mock(Transaction.class);
    Transaction localTransactionMockThree = mock(Transaction.class);
    DateTime current = DateTime.now();
    BigDecimal expectedResult =
        new BigDecimal(41.96861852).setScale(BIG_DECIMAL_SCALE, ROUNDING_MODE);

    when(TRANSACTION_MOCK.getTimeStamp()).thenReturn(current.minusMinutes(16));
    when(TRANSACTION_MOCK.getQuantity()).thenReturn(BigInteger.valueOf(100));
    when(TRANSACTION_MOCK.getPrice()).thenReturn(new BigDecimal(3.123));
    when(localTransactionMockOne.getTimeStamp()).thenReturn(current.minusMinutes(1));
    when(localTransactionMockOne.getQuantity()).thenReturn(BigInteger.valueOf(50));
    when(localTransactionMockOne.getPrice()).thenReturn(new BigDecimal(100.3286));
    when(localTransactionMockTwo.getTimeStamp()).thenReturn(current.minusMinutes(5));
    when(localTransactionMockTwo.getQuantity()).thenReturn(BigInteger.valueOf(350));
    when(localTransactionMockTwo.getPrice()).thenReturn(new BigDecimal(34.231));
    when(localTransactionMockThree.getTimeStamp()).thenReturn(current.minusMinutes(10));
    when(localTransactionMockThree.getQuantity()).thenReturn(BigInteger.valueOf(5));
    when(localTransactionMockThree.getPrice()).thenReturn(new BigDecimal(0.0021));

    assertFalse(stockImpl.getVolumeWeightedStockPrice(15).isPresent());

    stockImpl.addTransaction(TRANSACTION_MOCK);
    stockImpl.addTransaction(localTransactionMockOne);
    stockImpl.addTransaction(localTransactionMockTwo);
    stockImpl.addTransaction(localTransactionMockThree);

    assertTrue(stockImpl.getVolumeWeightedStockPrice(15).isPresent());
    assertEquals(expectedResult, stockImpl.getVolumeWeightedStockPrice(15).get());
  }
 /**
  * Constructs the <code>TimeSeries</code> for the reference velocity.
  *
  * <p>Start point is at (startDate, originalEstimateSum). End point is at (endDate + 1, 0.0)
  *
  * @param timeDifferenceHours
  */
 protected TimeSeries getReferenceVelocityTimeSeries(
     DateTime startDate, DateTime endDate, ExactEstimate originalEstimateSum) {
   if (settingBusiness.isWeekendsInBurndown()) {
     return this.getReferenceVelocityWithWeekends(
         REFERENCE_SERIES_NAME, startDate, endDate, originalEstimateSum);
   } else {
     return this.getSeriesByStartAndEndPoints(
         REFERENCE_SERIES_NAME,
         startDate.minusMinutes(timeDifferenceMinutes),
         originalEstimateSum,
         endDate.minusMinutes(timeDifferenceMinutes).plusDays(1),
         new ExactEstimate(0));
   }
 }
Exemplo n.º 3
0
  @Test
  public void niceTimeDeltaCanBeOutputInAlterativeLangauges() throws Exception {
    final DateTime now = DateTime.now().minusSeconds(1);

    DateTime lessThanOneMinuteAgo = now.minusSeconds(30);
    assertEquals("En este momento", spanishDateFormatter.timeSince(lessThanOneMinuteAgo.toDate()));

    DateTime oneMinuteAgo = now.minusSeconds(70);
    assertEquals("Hace 1 minuto", spanishDateFormatter.timeSince(oneMinuteAgo.toDate()));

    DateTime fiveMinutesBefore = now.minusMinutes(5);
    assertEquals("Hace 5 minutos", spanishDateFormatter.timeSince(fiveMinutesBefore.toDate()));

    DateTime anHourAgo = now.minusHours(1);
    assertEquals("Hace 1 hora", spanishDateFormatter.timeSince(anHourAgo.toDate()));

    DateTime twoHoursAgo = now.minusHours(2);
    assertEquals("Hace 2 horas", spanishDateFormatter.timeSince(twoHoursAgo.toDate()));

    DateTime oneDayAgo = now.minusDays(1);
    assertEquals("Hace 1 día", spanishDateFormatter.timeSince(oneDayAgo.toDate()));

    DateTime oneWeekAgo = now.minusWeeks(1).minusHours(1);
    assertEquals("Hace 1 semana", spanishDateFormatter.timeSince(oneWeekAgo.toDate()));

    DateTime nineMonthsAgo = now.minusMonths(9).minusWeeks(1);
    assertEquals("Hace 9 meses", spanishDateFormatter.timeSince(nineMonthsAgo.toDate()));
  }
Exemplo n.º 4
0
  @Test
  public void shouldBeAbleToOutputNiceTimeDeltas() throws Exception {
    final DateTime now = DateTime.now().minusSeconds(1);

    DateTime lessThanOneMinuteAgo = now.minusSeconds(30);
    assertEquals("just now", dateFormatter.timeSince(lessThanOneMinuteAgo.toDate()));

    DateTime fiveMinutesBefore = now.minusMinutes(5);
    assertEquals("5 minutes ago", dateFormatter.timeSince(fiveMinutesBefore.toDate()));

    DateTime anHourAgo = now.minusHours(1);
    assertEquals("1 hour ago", dateFormatter.timeSince(anHourAgo.toDate()));

    DateTime twoHoursAgo = now.minusHours(2);
    assertEquals("2 hours ago", dateFormatter.timeSince(twoHoursAgo.toDate()));

    DateTime oneDayAgo = now.minusDays(1);
    assertEquals("1 day ago", dateFormatter.timeSince(oneDayAgo.toDate()));

    DateTime oneWeekAgo = now.minusWeeks(1).minusHours(1);
    assertEquals("1 week ago", dateFormatter.timeSince(oneWeekAgo.toDate()));

    DateTime nineMonthsAgo = now.minusMonths(9).minusWeeks(1);
    assertEquals("9 months ago", dateFormatter.timeSince(nineMonthsAgo.toDate()));
  }
Exemplo n.º 5
0
  private void runDataCheck(String mode, TableMonitor tableMon, DateTime now, long time) {
    int periodInMinutes = (int) tableMon.getUpdatePeriod();

    // find begin period and add 30 seconds as well in case last data point
    // was a little early.
    DateTime beginPeriod = now.minusMinutes(periodInMinutes).minusSeconds(30);

    DateTime lastDataPoint = new DateTime(time);
    String msg =
        "lastpoint=("
            + time
            + ")"
            + lastDataPoint
            + " beginPeriod="
            + beginPeriod
            + " now="
            + now
            + " m="
            + tableMon.getId();
    if (lastDataPoint.isAfter(beginPeriod)) {
      if (log.isInfoEnabled()) log.info("Stream is good.  " + msg);
      return; // nothing to do
    }

    if (log.isInfoEnabled()) log.info("Stream is down.  " + msg);
    fireEmailStreamIsDown(mode, lastDataPoint, now, tableMon);
  }
Exemplo n.º 6
0
  private void initTime() {

    DateTime current = new DateTime();
    inTime = current.minusMinutes(1);
    // 有效期30分钟
    expireTime = current.plusMinutes(30);
  }
Exemplo n.º 7
0
  @Test
  public void shouldNotMakeACallWhenCurrentTimeIsConfiguredMinutesLessThanScheduledTime() {
    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.minusMinutes(16).toDate(),
        TIMES_SENT,
        TOTAL_TIMES_TO_SEND,
        RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService, never()).initiateCall(callRequestArgumentCaptor.capture());
  }
  @Test
  // org.quartz.jobStore.misfireThreshold=1000 (in quartz.properties) makes the test reliable.
  // See http://quartz-scheduler.org/documentation/quartz-2.x/configuration/ConfigJobStoreTX
  public void shouldNotIgnoreFiresInPastWhenSchedulingCronJob()
      throws InterruptedException, SchedulerException {
    final String eventSubject = id("eve");
    try {
      TestEventListener listener = new TestEventListener();
      eventRegistry.registerListener(listener, eventSubject);

      DateTime now = findSuitableTimeToScheduleWithSafeBufferFromTriggerTime();
      Map<String, Object> params = new HashMap<>();
      params.put(MotechSchedulerService.JOB_ID_KEY, "job_id");
      DateTime jobStartTimeInPast = now.minusMinutes(3);
      schedulerService.scheduleJob(
          new CronSchedulableJob(
              new MotechEvent(eventSubject, params),
              "0 0/1 * 1/1 * ? *",
              jobStartTimeInPast,
              null,
              false));

      synchronized (listener.getReceivedEvents()) {
        listener.getReceivedEvents().wait(5000);
      }
      assertTrue(
          "Listener didn't receive misfired events.", listener.getReceivedEvents().size() > 0);
    } finally {
      eventRegistry.clearListenersForBean(eventSubject);
      schedulerService.unscheduleAllJobs(eventSubject + "-job_id");
    }
  }
  @Test
  public void shouldIgnoreFiresInPastWhenSchedulingCronJob()
      throws InterruptedException, SchedulerException {
    String subject = "cron_ignore_misfire";
    try {
      TestEventListener listener = new TestEventListener();
      eventRegistry.registerListener(listener, subject);

      DateTime now;
      for (now = now();
          now.getSecondOfMinute() > 55 || now.getSecondOfMinute() < 5;
          now = now()) { // we don't want triggers now, only misfires
        Thread.sleep(1000);
      }
      DateTime jobStartTime = now.minusMinutes(3);
      Map<String, Object> params = new HashMap<>();
      params.put(MotechSchedulerService.JOB_ID_KEY, "job_id");
      schedulerService.scheduleJob(
          new CronSchedulableJob(
              new MotechEvent(subject, params), "0 0/1 * 1/1 * ? *", jobStartTime, null, true));

      synchronized (listener.getReceivedEvents()) {
        listener.getReceivedEvents().wait(2000);
      }
      assertTrue(listener.getReceivedEvents().size() == 0);
    } finally {
      eventRegistry.clearListenersForBean("test");
      schedulerService.unscheduleAllJobs(subject);
    }
  }
  @Test
  public void returnsJobsWithOldestFirstWhenPriorityIsTheSame() {
    final DateTime now = DateTime.now();

    ArrayList<Job> jobs =
        Lists.newArrayList(
            makeJob(1, 1, now),
            makeJob(2, 1, now.minusMinutes(1)),
            makeJob(3, 1, now.minusMinutes(2)));
    Collections.sort(jobs, comparator);
    assertEquals(Lists.newArrayList(3l, 2l, 1l), extractJobIds(jobs));
  }
  protected TimeSeries getReferenceVelocityWithWeekends(
      String seriesKey, DateTime startDate, DateTime endDate, ExactEstimate oeSum) {
    TimeSeries ts = new TimeSeries(seriesKey);
    MutableDateTime date;
    startDate = startDate.minusMinutes(timeDifferenceMinutes).toDateMidnight().toDateTime();
    endDate = endDate.minusMinutes(timeDifferenceMinutes).toDateMidnight().toDateTime();

    double originalEstimate = ExactEstimateUtils.extractMajorUnits(oeSum);

    ts.add(new TimeSeriesDataItem(new Second(startDate.toDate()), originalEstimate));

    // Get the amount of work days
    int amountOfWorkDays = 0;
    for (date = new MutableDateTime(startDate);
        date.isBefore(endDate.plusDays(1));
        date.addDays(1)) {
      if (date.dayOfWeek().get() != DateTimeConstants.SATURDAY
          && date.dayOfWeek().get() != DateTimeConstants.SUNDAY) {
        amountOfWorkDays++;
      }
    }

    double decrement = originalEstimate / ((double) amountOfWorkDays);

    double currentval = ExactEstimateUtils.extractMajorUnits(oeSum);
    for (date = new MutableDateTime(startDate); date.isBefore(endDate); date.addDays(1)) {
      if (date.dayOfWeek().get() != DateTimeConstants.SATURDAY
          && date.dayOfWeek().get() != DateTimeConstants.SUNDAY) {
        currentval -= decrement;
      }

      ts.add(
          new TimeSeriesDataItem(new Second(date.toDateTime().plusDays(1).toDate()), currentval));
    }

    ts.add(new TimeSeriesDataItem(new Second(endDate.plusDays(1).toDate()), 0.0));

    return ts;
  }
Exemplo n.º 12
0
  /**
   * Filters out and removes intervals which are older than 10 hours from Database. Filters
   * intervals for selected time span.
   */
  private void filterIntervals() {
    ArrayList<IntervalBase> filteredIntervals = new ArrayList<IntervalBase>();
    ArrayList<IntervalBase> intervalsToRemove = new ArrayList<IntervalBase>();

    if (intervals.size() == 0) {
      return;
    }

    mostRecentDate = intervals.get(intervals.size() - 1).getEnd();
    DateTime thresholdDateDatabase = new DateTime(mostRecentDate);
    thresholdDateDatabase = thresholdDateDatabase.minusMinutes(FILTERED_INTERVALS_IN_MINUTES);

    DateTime thresholdDateView = new DateTime(mostRecentDate);
    thresholdDateView = thresholdDateView.minusMinutes(selectedInterval.minutes);

    for (IntervalBase interval : intervals) {
      if (intervalIsOlderThanThreshold(thresholdDateDatabase, interval)) {
        intervalsToRemove.add(interval);
        continue;
      }

      if (!intervalIsOlderThanThreshold(thresholdDateView, interval)) {
        IntervalBase clonedInterval = null;
        try {
          clonedInterval = (IntervalBase) interval.clone();
          adjustIntervalStartAndEndDate(thresholdDateView, interval, clonedInterval);
          filteredIntervals.add(clonedInterval);
        } catch (CloneNotSupportedException e) {
          // intentionally empty
        }
      }
    }

    oldestDate = filteredIntervals.get(0).getStart();
    intervalPersister.removeIntervals(intervalsToRemove);
    intervals = filteredIntervals;
  }
Exemplo n.º 13
0
  public UserProfileDto getUserProfile(Long userId) {
    UserDetails userDetails = getUserDetails(userId);

    UserProfileDto userProfileDto = new UserProfileDto();
    if (userDetails.getLastLocationTime() != null) {
      userProfileDto.setLastPlace(
          CityUtils.getLocationName(
              userDetails.getCurrentCity(), MAX_LOCATION_NAME_PROFILE_DETAILS));
      userProfileDto.setLastLat(userDetails.getLocation().getLatitude());
      userProfileDto.setLastLng(userDetails.getLocation().getLongitude());
      userProfileDto.setLastLocationTime(userDetails.getLastInteractionTime().toDate());
    }

    User user = userDetails.getUser();
    userProfileDto.setEmailRegistration(user.getEmailRegistration());
    userProfileDto.setNick(user.getNickname());

    Long userRank = rankingService.getRank(userId);
    if (userRank == null) {
      userProfileDto.setRank("No rank");
    } else {
      userProfileDto.setRank(userRank.toString());
      Long score = rankingService.getScore(userId);
      userProfileDto.setRankScore(score < 0 ? "< 0" : String.valueOf(score));
    }

    UserStatisticsDto userStatistics = statisticsService.getUserStatistics(userId);
    userProfileDto.setTotalDislikes(userStatistics.getTotalDislikeCount());
    userProfileDto.setTotalLikes(userStatistics.getTotalLikeCount());
    userProfileDto.setCitiesCount(userStatistics.getTotalCityCount());
    userProfileDto.setUnseenPhotoCount(userStatistics.getUnseenPhotoCount());
    userProfileDto.setDailySendLimitLeft(getSentLimitLeft(userDetails, userStatistics));
    userProfileDto.setNewActivities(userStatistics.getHasNewActivities());
    userProfileDto.setNewPhotoReplyActivities(userStatistics.getHasNewPhotoReplyActivities());
    userProfileDto.setUnreadInboxItemCount(userStatistics.getUnreadInboxItemCount());
    userProfileDto.setId(userId);

    DateTime now = DateTime.now();
    if (userDetails.getLastInteractionTime() != null
        && userDetails.getLastInteractionTime().isBefore(now.minusMinutes(10))) {
      userDetails.setLastInteractionTime(now);
      userDetails.setComeBackReminderTime(null);
      userDetailsRepository.save(userDetails);
    }

    return userProfileDto;
  }
  private Map<String, String> createValueMap(
      Azure azure, String namespaceName, String resourceType, Set<String> queueStats) {
    Map<String, String> valueMap = new HashMap<String, String>();
    valueMap.put("SubscriptionId", azure.getSubscriptionId());
    valueMap.put("NameSpace", namespaceName);
    valueMap.put("ResourceType", resourceType);

    String stats = Joiner.on(",").skipNulls().join(queueStats);
    valueMap.put("Stats", stats);

    DateTime dateTime = new DateTime(DateTimeZone.UTC).minusMinutes(25);
    String endTime = dateTime.toString(DateTimeFormat.forPattern(DATE_FORMAT));
    String startTime = dateTime.minusMinutes(1).toString(DateTimeFormat.forPattern(DATE_FORMAT));
    valueMap.put("StartTime", startTime);
    valueMap.put("EndTime", endTime);
    return valueMap;
  }
  @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)));
    }
  }
Exemplo n.º 16
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));
  }
Exemplo n.º 17
0
  /**
   * 计算指定时间之前的日期
   *
   * @param date 待计算时间
   * @param random 待计算数
   * @param timeType 时间类型枚举
   * @see org.codingsills.modules.utils.DateKit.TimeType
   * @return Date
   */
  public static Date preDate(Date date, int random, TimeType timeType) {
    Date preDate = null;
    if (date == null) {
      return preDate;
    }
    DateTime dateTime = fromDate(date);
    random = Math.abs(random);
    switch (timeType.getCode()) {
      case "Y":
        preDate = dateTime.minusYears(random).toDate();
        break;
      case "M":
        preDate = dateTime.minusMonths(random).toDate();
        break;
      case "W":
        preDate = dateTime.minusWeeks(random).toDate();
        break;
      case "D":
        preDate = dateTime.minusDays(random).toDate();
        break;
      case "H":
        preDate = dateTime.minusHours(random).toDate();
        break;
      case "MIN":
        preDate = dateTime.minusMinutes(random).toDate();
        break;
      case "S":
        preDate = dateTime.minusSeconds(random).toDate();
        break;
      case "MS":
        preDate = dateTime.minusMillis(random).toDate();
        break;
      default:
        break;
    }

    return preDate;
  }
Exemplo n.º 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));
  }
Exemplo n.º 19
0
  private void showAlarms(Long minDuration, int minutes) {
    final DateTime now = new DateTime();
    final DateTime start = now.minusMinutes(minutes);
    final List<PollResult> alarms =
        pollService.listAlarms(start.toDate(), now.toDate(), minDuration);
    final List<PollResult> problems = pollService.listProblems(start.toDate(), now.toDate());

    System.out.println("\nListing events over last " + minutes + " minutes");
    System.out.println(" ALARMS (duration > " + minDuration + ")");
    TextTable table =
        new TextTable(
            "  ",
            TextTable.ALIGN.LEFT,
            TextTable.ALIGN.LEFT,
            TextTable.ALIGN.LEFT,
            TextTable.ALIGN.RIGHT,
            TextTable.ALIGN.CENTER);
    if (!alarms.isEmpty()) {
      for (PollResult pollResult : alarms) {
        table.add(format2(pollResult));
      }
      System.out.println(table.toString());
    } else {
      System.out.println("  No alarms");
    }
    table.clear();
    System.out.println(" PROBLEMS (non-successful events)");
    if (!problems.isEmpty()) {
      for (PollResult pollResult : problems) {
        table.add(format2(pollResult));
      }
      System.out.println(table.toString());
    } else {
      System.out.println("  No problems");
    }
  }
Exemplo n.º 20
0
 public static Date minusMinutes(Date date, int numberOfMinutes) {
   if (date == null) date = new Date();
   DateTime dt = new DateTime(date);
   return dt.minusMinutes(numberOfMinutes).toDate();
 }
Exemplo n.º 21
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());
 }
Exemplo n.º 22
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);
  }
Exemplo n.º 23
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);
  }