private RunTimeElements getNextSingleStarts(DateTime baseDate) {
   DateTimeFormatter fmtDate = DateTimeFormat.forPattern("yyyy-MM-dd");
   DateTimeFormatter fmtDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
   RunTimeElements result = new RunTimeElements(baseDate);
   logger.debug(getDay().size() + " day elements detected.");
   Iterator<String> it = getDay().iterator();
   while (it.hasNext()) {
     String dayString = it.next();
     logger.debug("parsing day string " + dayString);
     List<Integer> days = JodaTools.getJodaWeekdays(dayString);
     for (int i = 0; i < days.size(); i++) {
       DateTime nextWeekDay = JodaTools.getNextWeekday(baseDate, days.get(i));
       logger.debug("calculated date " + fmtDate.print(nextWeekDay));
       List<Period> periods = getPeriod();
       Iterator<Period> itP = periods.iterator();
       logger.debug(periods.size() + " periods found.");
       while (itP.hasNext()) {
         Period p = itP.next();
         JSObjPeriod period = new JSObjPeriod(objFactory);
         period.setObjectFieldsFrom(p);
         DateTime start = period.getDtSingleStartOrNull(nextWeekDay);
         if (start != null) {
           logger.debug("start from period " + fmtDateTime.print(start));
           if (start.isBefore(baseDate)) {
             start = start.plusWeeks(1);
             logger.debug("start is corrected to " + fmtDateTime.print(start));
           }
           result.add(new RunTimeElement(start, period.getWhenHoliday()));
         }
       }
     }
     //				Collections.sort(result, DateTimeComparator.getInstance());
   }
   return result;
 }
Esempio n. 2
0
  @Test
  public void test_aggregationByDay() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 3, 3, 0, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

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

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

    DataPointGroup dayCount = aggregator.aggregate(group);

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

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

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

    assertThat(dayCount.hasNext(), is(false));
  }
Esempio n. 3
0
  @Test
  public void test_aggregationBySecond() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 1, 0, 0, 2, 200, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime milliSecond = startDate;
        milliSecond.isBefore(endDate);
        milliSecond = milliSecond.plus(100)) {
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
    }

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

    DataPointGroup dayCount = aggregator.aggregate(group);

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

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

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(2L));
    assertThat(dayCount.hasNext(), is(false));
  }
Esempio n. 4
0
  @Test
  public void test_yearAggregationWithoutLeapYears() {
    DateTimeZone utc = DateTimeZone.UTC;
    ListDataPointGroup dpGroup = new ListDataPointGroup("range_test");

    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, utc);
    for (DateTime date = startDate;
        date.isBefore(new DateTime(2015, 6, 2, 0, 0, utc));
        date = date.plusMonths(1)) {
      dpGroup.addDataPoint(new LongDataPoint(date.getMillis(), 1));
    }

    SumAggregator agg = new SumAggregator(new DoubleDataPointFactoryImpl());
    agg.setSampling(new Sampling(1, TimeUnit.YEARS));
    agg.setAlignSampling(false);
    agg.setStartTime(startDate.getMillis());

    DataPointGroup aggregated = agg.aggregate(dpGroup);

    assertThat(aggregated.hasNext(), is(true));
    assertThat(aggregated.next().getLongValue(), is(12L));

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

    assertThat(aggregated.hasNext(), is(false));
  }
Esempio n. 5
0
  @Test
  public void test_aggregationByYearOverLeapYears() {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2010, 1, 1, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 1, 0, 0, utc);

    ListDataPointGroup dpGroup = new ListDataPointGroup("range_test");
    for (DateTime iterationDT = startDate;
        iterationDT.isBefore(endDate);
        iterationDT = iterationDT.plusDays(1)) {
      dpGroup.addDataPoint(new LongDataPoint(iterationDT.getMillis(), 1));
    }

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

    DataPointGroup dayCount = aggregator.aggregate(dpGroup);

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(365L)); // 2010

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(365L)); // 2011

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(366L)); // 2012

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(365L)); // 2013

    assertThat(dayCount.hasNext(), is(false));
  }
  public long getEffectiveDateToDifference(final Entity parameter, final Entity order) {
    if (!neededWhenChangingEffectiveDateTo(parameter)) {
      return 0L;
    }
    final long dateToTimestamp = getTimestampFromOrder(order, DATE_TO, CORRECTED_DATE_TO);
    if (dateToTimestamp == 0L) {
      return 0L;
    }
    final DateTime dateTo = new DateTime(dateToTimestamp);

    if (getEffectiveDate(order, EFFECTIVE_DATE_TO) == null) {
      return 0L;
    }
    final DateTime effectiveDateTo = new DateTime(getEffectiveDate(order, EFFECTIVE_DATE_TO));
    final DateTime maxTime =
        new DateTime(
            dateToTimestamp
                + getAllowedDelayFromParametersAsMiliseconds(DELAYED_EFFECTIVE_DATE_TO_TIME));
    final DateTime minTime =
        new DateTime(
            dateToTimestamp
                - getAllowedDelayFromParametersAsMiliseconds(EARLIER_EFFECTIVE_DATE_TO_TIME));

    long difference = 0L;
    if ((effectiveDateTo.isAfter(maxTime) && needForDelayedDateTo(parameter))
        || (effectiveDateTo.isBefore(minTime) && needForEarlierDateTo(parameter))) {
      difference = Seconds.secondsBetween(dateTo, effectiveDateTo).getSeconds();
    }
    return difference;
  }
  // IMPLEMENTATION
  @Override
  public void validate(final ValidationContext ctx) {
    final Date value = ValidationUtils.getDate(getValue(ctx));

    if (value != null) {
      final DateTime date = new DateTime(value);

      addParam(MessageSubstitutor.VALUE, date.toString());
      addParam("type", type);

      // lower
      if (lowerBoundary != null) {
        final DateTime lower = getDateLimit(false);
        if (date.isBefore(lower)) {
          ctx.getStatus().error(this);
        }
      }

      // upper
      if (upperBoundary != null) {
        final DateTime upper = getDateLimit(true);
        if (date.isAfter(upper)) {
          ctx.getStatus().error(this);
        }
      }
    }
  }
Esempio n. 8
0
  /** Remove completed queries after a waiting period */
  public void removeExpiredQueries() {
    List<QueryExecution> sortedQueries =
        IterableTransformer.on(queries.values())
            .select(compose(not(isNull()), endTimeGetter()))
            .orderBy(Ordering.natural().onResultOf(endTimeGetter()))
            .list();

    int toRemove = Math.max(sortedQueries.size() - maxQueryHistory, 0);
    DateTime oldestAllowedQuery = DateTime.now().minus(maxQueryAge.toMillis());

    for (QueryExecution queryExecution : sortedQueries) {
      try {
        DateTime endTime = queryExecution.getQueryInfo().getQueryStats().getEndTime();
        if ((endTime.isBefore(oldestAllowedQuery) || toRemove > 0) && isAbandoned(queryExecution)) {
          removeQuery(queryExecution.getQueryInfo().getQueryId());
          --toRemove;
        }
      } catch (RuntimeException e) {
        log.warn(
            e,
            "Error while inspecting age of query %s",
            queryExecution.getQueryInfo().getQueryId());
      }
    }
  }
Esempio n. 9
0
  public Iterable<Result<TimeBoundaryResultValue>> mergeResults(
      List<Result<TimeBoundaryResultValue>> results) {
    if (results == null || results.isEmpty()) {
      return Lists.newArrayList();
    }

    DateTime min = new DateTime(Long.MAX_VALUE);
    DateTime max = new DateTime(Long.MIN_VALUE);
    for (Result<TimeBoundaryResultValue> result : results) {
      TimeBoundaryResultValue val = result.getValue();

      DateTime currMinTime = val.getMinTime();
      if (currMinTime.isBefore(min)) {
        min = currMinTime;
      }
      DateTime currMaxTime = val.getMaxTime();
      if (currMaxTime.isAfter(max)) {
        max = currMaxTime;
      }
    }

    return Arrays.asList(
        new Result<TimeBoundaryResultValue>(
            min,
            new TimeBoundaryResultValue(
                ImmutableMap.<String, Object>of(
                    TimeBoundaryQuery.MIN_TIME, min,
                    TimeBoundaryQuery.MAX_TIME, max))));
  }
Esempio n. 10
0
 private static BinaryOperator<List<Prediction>> linearInterpolation() {
   return (interpolated, input) -> {
     if (input.size() != 1) {
       throw new IllegalArgumentException("expected one element, but got " + input);
     }
     if (interpolated.isEmpty()) {
       interpolated.addAll(input);
       return interpolated;
     }
     Prediction previous = interpolated.get(interpolated.size() - 1);
     Prediction next = input.get(0);
     for (DateTime timestamp = previous.timestamp.plus(PREDICTION_RESOLUTION);
         timestamp.isBefore(next.timestamp);
         timestamp = timestamp.plus(PREDICTION_RESOLUTION)) {
       double totalDuration = new Duration(previous.timestamp, next.timestamp).getMillis();
       double currentDuration = new Duration(previous.timestamp, timestamp).getMillis();
       double proportion = currentDuration / totalDuration;
       int totalChange = next.spacesAvailable - previous.spacesAvailable;
       int currentChange = (int) Math.round(totalChange * proportion);
       int spacesAvailable = previous.spacesAvailable + currentChange;
       interpolated.add(new Prediction(timestamp, spacesAvailable));
     }
     interpolated.add(next);
     return interpolated;
   };
 }
Esempio n. 11
0
 /**
  * Is this TimePeriod contained by another TimePeriod? Equal start/end times are considered to be
  * containing, as are equal indeterminate times.
  *
  * @param otherTimePeriod Potentially containing TimePeriod
  * @return Whether the argument TimePeriod contains this one
  */
 public boolean isWithin(TimePeriod otherTimePeriod) {
   if (otherTimePeriod == null) {
     throw new NullPointerException("otherTimePeriod cannot be null");
   }
   boolean startWithin = false;
   boolean endWithin = false;
   if (start != null && otherTimePeriod.getStart() != null) {
     startWithin =
         start.isEqual(otherTimePeriod.getStart()) || start.isAfter(otherTimePeriod.getStart());
   } else if (start == null
       && otherTimePeriod.getStart() == null
       && startIndet != null
       && otherTimePeriod.getStartIndet() != null
       && startIndet.equals(otherTimePeriod.getStartIndet())) {
     startWithin = true;
   }
   if (end != null && otherTimePeriod.getEnd() != null) {
     endWithin = end.isEqual(otherTimePeriod.getEnd()) || end.isBefore(otherTimePeriod.getEnd());
   } else if (end == null
       && otherTimePeriod.getEnd() == null
       && endIndet != null
       && otherTimePeriod.getEndIndet() != null
       && endIndet.equals(otherTimePeriod.getEndIndet())) {
     endWithin = true;
   }
   return startWithin && endWithin;
 }
Esempio n. 12
0
  @Override
  public ConnectorSplitSource getSplits(
      ConnectorTransactionHandle transactionHandle,
      ConnectorSession session,
      ConnectorTableLayoutHandle layoutHandle) {
    AtopTableLayoutHandle handle =
        checkType(layoutHandle, AtopTableLayoutHandle.class, "layoutHandle");

    AtopTableHandle table = handle.getTableHandle();

    List<ConnectorSplit> splits = new ArrayList<>();
    DateTime end = DateTime.now().withZone(timeZone);
    for (Node node : nodeManager.getActiveDatasourceNodes(connectorId.getId())) {
      DateTime start = end.minusDays(maxHistoryDays - 1).withTimeAtStartOfDay();
      while (start.isBefore(end)) {
        DateTime splitEnd = start.withTime(23, 59, 59, 999);
        Domain splitDomain =
            Domain.create(
                ValueSet.ofRanges(
                    Range.range(TIMESTAMP, start.getMillis(), true, splitEnd.getMillis(), true)),
                false);
        if (handle.getStartTimeConstraint().overlaps(splitDomain)
            && handle.getEndTimeConstraint().overlaps(splitDomain)) {
          splits.add(new AtopSplit(table.getTable(), node.getHostAndPort(), start));
        }
        start = start.plusDays(1).withTimeAtStartOfDay();
      }
    }

    return new FixedSplitSource(connectorId.getId(), splits);
  }
 public static Map<String, Double> constructDatePlaceHolderForDouble(
     final DateTime startDate, final DateTime endDate, final String pattern) {
   final Map<String, Double> currentYearTillDays = new LinkedHashMap<String, Double>();
   for (DateTime date = startDate; date.isBefore(endDate); date = date.plusDays(1))
     currentYearTillDays.put(date.toString(pattern), Double.valueOf(0));
   currentYearTillDays.put(endDate.toString(pattern), Double.valueOf(0));
   return currentYearTillDays;
 }
Esempio n. 14
0
 private DateTime earliestDateTimeOf(DateTime date1, DateTime date2) {
   if (date1 == null) {
     return date2;
   }
   if (date2 == null) {
     return date1;
   }
   return date1.isBefore(date2) ? date1 : date2;
 }
Esempio n. 15
0
 /**
  * Extend TimePeriod to contain DateTime. Used by other extendToContain methods.
  *
  * @param time
  */
 public void extendToContain(DateTime time) {
   if (time != null) {
     if (!isSetStart() || time.isBefore(getStart())) {
       setStart(time);
     }
     if (!isSetEnd() || time.isAfter(getEnd())) {
       setEnd(time);
     }
   }
 }
Esempio n. 16
0
  /**
   * Builds and returns text for the "exact" time an alarm occurs as opposed to the period left for
   * it to occur.<br>
   * In English, 12:00 today would become "Today 12:00", tomorrow would be come "Tomorrow 12:00",
   * and on Monday it would become
   *
   * @param formats the formats to use, e.g: [Today %1$s, Tomorrow %1$s, %2$s %1$s].
   * @param noActive if no alarm was active, this is used.
   * @param now current time in Unix epoch timestamp.
   * @param ats an AlarmTimestamp: the information about the alarm & its timestamp.
   * @param locale the locale to use for weekdays.
   * @return the built time-to string.
   */
  public static final String getTime(
      String[] formats, String noActive, long now, AlarmTimestamp ats, Locale locale) {

    if (ats == AlarmTimestamp.INVALID) {
      return noActive;
    } else {
      if (ats.getMillis() < now) {
        throw new RuntimeException("Time given is before now.");
      }

      // Prepare replacements.
      Alarm alarm = ats.getAlarm();
      String timeReplacement = StringUtils.joinTime(alarm.getHour(), alarm.getMinute());

      // Calculate start of tomorrow.
      DateTime nowTime = new DateTime(now);
      DateTime time = new DateTime(ats.getMillis());
      LocalDate tomorrow = new LocalDate(nowTime).plusDays(1);
      DateTime startOfTomorrow = tomorrow.toDateTimeAtStartOfDay(nowTime.getZone());

      if (time.isBefore(startOfTomorrow)) {
        // Alarm is today.
        Log.d(TAG, "today");
        return String.format(formats[0], timeReplacement);
      }

      // Calculate start of the day after tomorrow.
      LocalDate afterTomorrow = tomorrow.plusDays(1);
      DateTime startOfAfterTomorrow = afterTomorrow.toDateTimeAtStartOfDay(nowTime.getZone());

      if (time.isBefore(startOfAfterTomorrow)) {
        Log.d(TAG, "tomorrow");
        // Alarm is tomorrow.
        return String.format(formats[1], timeReplacement);
      }

      // Alarm is after tomorrow.
      Log.d(TAG, "after tomorrow");
      String weekday = new DateTime(ats.getMillis()).dayOfWeek().getAsText(locale);
      return String.format(formats[2], timeReplacement, weekday);
    }
  }
Esempio n. 17
0
 /**
  * We need the number of days rather than the number of elapsed milliseconds divided by the number
  * in a day - timezone changes ete... To avoid confusion about what constitutes a full day we
  * count the number of lunchtimes (noon).
  *
  * @param start
  * @param end
  * @return
  */
 private int countDays(DateTime start, DateTime end) {
   int count = 0;
   Assert.assertEquals(start.getHourOfDay(), 0);
   Assert.assertEquals(start.getMinuteOfHour(), 0);
   start = start.plusHours(12);
   while (start.isBefore(end)) {
     count++;
     start = start.plusDays(1);
   }
   return count;
 }
Esempio n. 18
0
 public static Set<String> getMondaySet() {
   DateTime startDate = new DateTime(2015, 9, 28, 0, 0);
   Date date = new Date();
   DateTime endDate = new DateTime(date);
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   HashSet<String> mondaySet = new HashSet<String>();
   while (startDate.isBefore(endDate)) {
     mondaySet.add(dateFormatter.print(startDate));
     startDate = startDate.plusWeeks(1);
   }
   return mondaySet;
 }
 public double getStartAsFractionOfPeriod(DateTime beginOfPeriod, DateTime endOfPeriod) {
   if (isCovered(beginOfPeriod, endOfPeriod)) {
     if (start.isBefore(beginOfPeriod)) { // { ? beginOfPeriod : start;
       return 0;
     } else {
       return Days.daysBetween(beginOfPeriod, start).getDays()
           / coveredPeriodLength(beginOfPeriod, endOfPeriod);
     }
   } else {
     return -1;
   }
 }
Esempio n. 20
0
  /**
   * Computes the earliest of the two end dates. Either of them can be null, but not both. In this
   * case, the non-null date is considered the earliest end.
   *
   * @throws IllegalArgumentException if both dates are null
   */
  public static DateTime earliestEnd(DateTime one, DateTime two) {
    checkMaxOneDateNull(one, two);

    DateTime first;
    if (one == null) {
      first = two;
    } else if (two == null) {
      first = one;
    } else {
      first = (one.isBefore(two)) ? one : two;
    }
    return first;
  }
Esempio n. 21
0
 private int calcWorkingDayNum() {
   DateTime start = sprint.getStartDate();
   DateTime end = sprint.getEndDate();
   start = start.minusMillis(start.millisOfDay().get());
   end = end.minusMillis(end.millisOfDay().get());
   int i = 0;
   for (; start.isBefore(end); start = start.plusDays(1)) {
     if (start.getDayOfWeek() < DateTimeConstants.SATURDAY) {
       i++;
     }
   }
   return i;
 }
Esempio n. 22
0
      @Override
      public int compare(ScheduledJob arg0, ScheduledJob arg1) {
        DateTime first = arg1.getScheduledExecution();
        DateTime second = arg0.getScheduledExecution();

        if (first.isEqual(second)) {
          return 0;
        } else if (first.isBefore(second)) {
          return 1;
        }

        return -1;
      }
Esempio n. 23
0
 @Test
 public void testIndeterminateNowEnd() {
   DateTime beforeResolve = new DateTime();
   DateTime resolvedValue =
       new TimePeriod(new DateTime(), null, null, TimeIndeterminateValue.now).resolveEnd();
   DateTime afterResolve = new DateTime();
   assertNotNull("TimePeriod end now value is null", resolvedValue);
   assertTrue(
       "TimePeriod end now value is too early",
       resolvedValue.isAfter(beforeResolve) || resolvedValue.isEqual(beforeResolve));
   assertTrue(
       "TimePeriod end now value is too late",
       resolvedValue.isBefore(afterResolve) || resolvedValue.isEqual(afterResolve));
 }
 @Override
 public DateTime getNextBillingDate(final UUID accountId, final InternalTenantContext context) {
   final List<SubscriptionBaseBundle> bundles = getBundlesForAccount(accountId, context);
   DateTime result = null;
   for (final SubscriptionBaseBundle bundle : bundles) {
     final List<SubscriptionBase> subscriptions =
         getSubscriptionsForBundle(bundle.getId(), context);
     for (final SubscriptionBase subscription : subscriptions) {
       final DateTime chargedThruDate = subscription.getChargedThroughDate();
       if (result == null || (chargedThruDate != null && chargedThruDate.isBefore(result))) {
         result = subscription.getChargedThroughDate();
       }
     }
   }
   return result;
 }
  @Override
  public AggregateCount getCounts(String name, Interval interval, DateTimeField resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();
    DurationField resolutionDuration = resolution.getDurationField();

    long[] counts;

    if (resolutionDuration.getUnitMillis() == DateTimeConstants.MILLIS_PER_MINUTE) {
      // Iterate through each hour in the interval and load the minutes for it
      MutableDateTime dt = new MutableDateTime(interval.getStart());
      dt.setRounding(c.hourOfDay());
      Duration step = Duration.standardHours(1);
      List<long[]> hours = new ArrayList<long[]>();
      while (dt.isBefore(end)) {
        hours.add(getMinCountsForHour(name, dt));
        dt.add(step);
      }
      counts =
          MetricUtils.concatArrays(
              hours,
              interval.getStart().getMinuteOfHour(),
              interval.toPeriod().toStandardMinutes().getMinutes() + 1,
              60);

    } else if (resolutionDuration.getUnitMillis() == DateTimeConstants.MILLIS_PER_HOUR) {
      DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
      List<long[]> days = new ArrayList<long[]>();
      Duration step = Duration.standardHours(24);
      while (cursor.isBefore(end)) {
        days.add(getHourCountsForDay(name, cursor));
        cursor = cursor.plus(step);
      }

      counts =
          MetricUtils.concatArrays(
              days,
              interval.getStart().getHourOfDay(),
              interval.toPeriod().toStandardHours().getHours() + 1,
              24);

    } else {
      throw new IllegalArgumentException("Only minute or hour resolution is currently supported");
    }
    return new AggregateCount(name, interval, counts, resolution);
  }
  @Test
  public void
      shouldScheduleDailyAdherenceQualityJobsForAPatientOnDailyReminderStartingFromTodayIfTreatmentAdviceStartDateIsInPast() {
    final String patientId = "123456";
    Patient patient =
        PatientBuilder.startRecording()
            .withDefaults()
            .withId(patientId)
            .withCallPreference(CallPreference.DailyPillReminder)
            .build();

    final LocalDate startDate = DateUtil.today().minusDays(2);
    final LocalDate endDate = DateUtil.today().plusDays(2);
    final DateTime timeFewMillisBack = DateUtil.now().minusMillis(1000);

    TreatmentAdvice advice = getTreatmentAdvice(startDate, endDate);

    schedulerService.scheduleJobForDeterminingAdherenceQualityInDailyPillReminder(patient, advice);

    final ArgumentCaptor<CronSchedulableJob> cronArgCaptor =
        ArgumentCaptor.forClass(CronSchedulableJob.class);
    verify(motechSchedulerService).safeScheduleJob(cronArgCaptor.capture());

    CronSchedulableJob jobScheduledWithParams = cronArgCaptor.getValue();
    final MotechEvent motechEventInScheduledJob = jobScheduledWithParams.getMotechEvent();
    Map<String, Object> paramsInScheduledJob = motechEventInScheduledJob.getParameters();

    assertEquals(
        "Should setup the cron expression to run at every midnight.",
        jobScheduledWithParams.getCronExpression(),
        "0 0 0 * * ?");

    DateTime actualTimeWhenTriggerWasActivated =
        DateUtil.newDateTime(jobScheduledWithParams.getStartTime());
    assertTrue(
        "Since the advice has already started in past, we should schedule it starting now, which is after a time few milli seconds back.",
        timeFewMillisBack.isBefore(actualTimeWhenTriggerWasActivated));
    DateTime rightNow = DateUtil.now();
    assertTrue(rightNow.isEqual(actualTimeWhenTriggerWasActivated));

    assertEquals(jobScheduledWithParams.getEndTime(), endDate.plusDays(1).toDate());

    assertEquals(paramsInScheduledJob.get(EventKeys.EXTERNAL_ID_KEY), patientId);
    assertEquals(
        motechEventInScheduledJob.getSubject(), TAMAConstants.DAILY_ADHERENCE_IN_RED_ALERT_SUBJECT);
  }
Esempio n. 27
0
  private void bulkloadDummyStreamData(String streamOwner, DateTime day)
      throws ClassNotFoundException, SQLException, IOException, NamingException,
          NoSuchAlgorithmException {
    DateTime curTime = new DateTime(day);
    DateTime endTime = new DateTime(day.plusDays(1).minusMillis(1));

    // delete for the day
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.deleteStream(streamOwner, DUMMY_STREAM_NAME, fmt.print(curTime), fmt.print(endTime));
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    // generate a bulkload data
    StringBuilder sb = new StringBuilder();
    while (curTime.isBefore(endTime)) {
      sb.append(fmt.print(curTime));
      sb.append(",1\n");
      curTime = curTime.plusSeconds(DUMMY_STREAM_INTERVAL);
    }

    // perform bulkload
    String bulkloadData = sb.toString();
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.bulkLoad(streamOwner, DUMMY_STREAM_NAME, bulkloadData);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
  @Override
  public Optional<Reservation> lookup(final NodeUrn nodeUrn, final DateTime timestamp) {

    log.trace("ReservationCacheImpl.lookup({}, {})", nodeUrn, timestamp);
    checkRunning();

    synchronized (reservationsByNodeUrn) {
      final List<CacheItem<Reservation>> entry = reservationsByNodeUrn.get(nodeUrn);

      if (entry == null) {
        log.trace("ReservationManagerImpl.lookup() CACHE MISS");
        return Optional.absent();
      }

      for (CacheItem<Reservation> item : entry) {

        final Interval effectiveInterval;
        final Reservation reservation = item.get();
        final DateTime reservationStart = reservation.getInterval().getStart();
        final DateTime reservationCancellation = reservation.getCancelled();

        if (reservationCancellation != null) {
          if (reservationCancellation.isBefore(reservationStart)) {
            continue;
          } else {
            effectiveInterval = new Interval(reservationStart, reservationCancellation);
          }
        } else {
          effectiveInterval = reservation.getInterval();
        }

        if (effectiveInterval.contains(timestamp)) {
          if (!item.isOutdated()) {
            item.touch();
            log.trace("ReservationManagerImpl.lookup() CACHE HIT");
            return Optional.of(reservation);
          }
        }
      }
    }
    return Optional.absent();
  }
 public static List<Map<String, Object>> constructDayPlaceHolder(
     final DateTime startDate,
     final DateTime endDate,
     final String pattern,
     final String toolTipPattern) {
   final Map<String, Object> currentYearEndDays = new LinkedHashMap<String, Object>();
   final List<Map<String, Object>> dataHolder = new LinkedList<Map<String, Object>>();
   for (DateTime date = startDate; date.isBefore(endDate); date = date.plusDays(1)) {
     final Map<String, Object> currentYearTillDays = new LinkedHashMap<String, Object>();
     currentYearTillDays.put("name", date.toString(pattern));
     currentYearTillDays.put("y", Double.valueOf(0));
     currentYearTillDays.put("tooltipFormat", date.toString(toolTipPattern));
     dataHolder.add(currentYearTillDays);
   }
   currentYearEndDays.put("name", endDate.toString(pattern));
   currentYearEndDays.put("y", Double.valueOf(0));
   currentYearEndDays.put("tooltipFormat", endDate.toString(toolTipPattern));
   dataHolder.add(currentYearEndDays);
   return dataHolder;
 }
Esempio n. 30
0
  public Iterable<Result<TimeBoundaryResultValue>> mergeResults(
      List<Result<TimeBoundaryResultValue>> results) {
    if (results == null || results.isEmpty()) {
      return Lists.newArrayList();
    }

    DateTime min = new DateTime(JodaUtils.MAX_INSTANT);
    DateTime max = new DateTime(JodaUtils.MIN_INSTANT);
    for (Result<TimeBoundaryResultValue> result : results) {
      TimeBoundaryResultValue val = result.getValue();

      DateTime currMinTime = val.getMinTime();
      if (currMinTime != null && currMinTime.isBefore(min)) {
        min = currMinTime;
      }
      DateTime currMaxTime = val.getMaxTime();
      if (currMaxTime != null && currMaxTime.isAfter(max)) {
        max = currMaxTime;
      }
    }

    final DateTime ts;
    final DateTime minTime;
    final DateTime maxTime;

    if (isMinTime()) {
      ts = min;
      minTime = min;
      maxTime = null;
    } else if (isMaxTime()) {
      ts = max;
      minTime = null;
      maxTime = max;
    } else {
      ts = min;
      minTime = min;
      maxTime = max;
    }

    return buildResult(ts, minTime, maxTime);
  }