@Test
  public void shouldGetAllPeriodsForPeriodDateRange() throws Exception {
    DateTime currentDate = DateTime.parse("2013-01-01");
    ProcessingPeriod period1 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(1).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month1")));
    ProcessingPeriod period2 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusMonths(1).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(2).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month2")));
    ProcessingPeriod period3 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusMonths(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(3).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month3")));
    ProcessingPeriod period4 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusDays(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(1).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month4")));
    ProcessingPeriod period5 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.minusDays(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(3).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month5")));

    mapper.insert(period1);
    mapper.insert(period2);
    mapper.insert(period3);
    mapper.insert(period4);
    mapper.insert(period5);
    DateTime searchStartDate = currentDate;
    DateTime searchEndDate = searchStartDate.plusDays(45);
    List<ProcessingPeriod> searchResults =
        mapper.getAllPeriodsForDateRange(
            schedule.getId(), searchStartDate.toDate(), searchEndDate.toDate());
    for (ProcessingPeriod period : searchResults) {
      period.setModifiedDate(null);
    }
    assertThat(searchResults, is(hasItems(period1, period2, period4, period5)));
    assertThat(searchResults, is(not(hasItems(period3))));
  }
  /** Test the get methods in {@link TimeAxisImpl}. */
  @Test
  public void testGetMethods() {
    assertEquals(chronology, tAxis.getChronology());
    Extent<DateTime> dateExtent = tAxis.getCoordinateExtent();
    Extent<DateTime> expectedDateExtent = Extents.newExtent(start, start.plusDays(numberOfDate));
    assertEquals(expectedDateExtent, dateExtent);

    Array<Extent<DateTime>> dates = tAxis.getDomainObjects();
    int dateCounter = 0;
    for (Extent<DateTime> tExtent : dates) {
      Extent<DateTime> expectedExtent =
          Extents.newExtent(start.plusDays(dateCounter), start.plusDays(dateCounter));
      dateCounter++;
      assertEquals(expectedExtent, tExtent);
    }

    int expectedIndex = 4;
    // the first date is index 0
    DateTime fifthDate = tAxis.getCoordinateValue(expectedIndex);
    assertEquals(start.plusDays(expectedIndex), fifthDate);

    Extent<DateTime> expectedFifthDateBound = Extents.newExtent(fifthDate, fifthDate);
    assertEquals(expectedFifthDateBound, tAxis.getCoordinateBounds(expectedIndex));
    assertEquals(datetimes, tAxis.getCoordinateValues());
    assertEquals(tAxisName, tAxis.getName());
  }
Example #3
0
  @GET
  @Path("/participation/daily/{id}")
  public String participationForGraph(@PathParam("id") String id) {
    try {
      List<NQAnswerReceipt> res = Services.vote.particpationsForPoll(id);
      Collections.sort(res);
      Map<DateTime, Integer> result = new TreeMap<DateTime, Integer>();
      DateTime z = DateTime.now();
      UUID idid = UUID.fromString(id);
      NQQuestion p = Services.vote.pollById(idid);
      if (p == null) System.out.println("Particiaption Daily on null " + id);
      DateTime a = p.acceptedDate;
      result.put(a, 0);

      // go through votes and count until
      int count = 0;
      a = a.plusDays(1);
      for (NQAnswerReceipt h : res) {
        count++;
        if (h.timestamp.isAfter(a)) {
          while (h.timestamp.isAfter(a)) {
            a = a.plusDays(1);
          }
          result.put(a, count);
        }
      }
      result.put(z, res.size());
      return g.toJson(result);
    } catch (NoSuchPoll e) {
      return "NoSuchPoll";
    }
  }
  private DateTime scheduleMonthly(DateTime now) {
    DateTime nowMidnight = now.toDateMidnight().toDateTime();

    if (schedule.getByDayOfMonth()) {
      int nowDOM = nowMidnight.getDayOfMonth();
      if (nowDOM == schedule.getDayOfMonth()) {
        DateTime nextTimeToday = getNextTimeToday(now, nowMidnight);
        if (nextTimeToday != null) {
          return nextTimeToday;
        }
      }
      DateTime nextDay = getNextScheduleDay(nowMidnight.plusDays(1));
      return getFirstScheduledTimeOnDay(nextDay);
    } else {
      DateTime nextDay = getNextScheduleDay(nowMidnight);
      if (nextDay.equals(nowMidnight)) {
        DateTime nextTimeToday = getNextTimeToday(now, nextDay);
        if (nextTimeToday != null) {
          return nextTimeToday;
        }
        nextDay = getNextScheduleDay(nowMidnight.plusDays(1));
        return getFirstScheduledTimeOnDay(nextDay);
      } else {
        return getFirstScheduledTimeOnDay(nextDay);
      }
    }
  }
  /** Test the method of {@link TimeAxisImpl#contains}. */
  @Test
  public void testContains() {
    // pick up the fifth date in the range of t axis
    DateTime dt = start.plusDays(5);
    assertTrue(tAxis.contains(dt));

    assertFalse(tAxis.contains(null));

    // pick up a date out of the range of t axis
    dt = start.plusDays(25);
    assertFalse(tAxis.contains(dt));
    // pick up a date out of the range of t axis
    dt = start.minusDays(5);
    assertFalse(tAxis.contains(dt));
  }
  @Test
  public void testUpdateLMP() throws Exception {
    createLocationData();

    Long msisdn = subscriptionHelper.makeNumber();
    String motherId = "0123456789";
    DateTime originalLMP = DateTime.now().minusDays(100);
    DateTime updatedLMP = originalLMP.minusDays(200);

    subscriptionHelper.mksub(
        SubscriptionOrigin.MCTS_IMPORT, originalLMP, SubscriptionPackType.PREGNANCY, msisdn);
    Subscriber subscriber = subscriberDataService.findByCallingNumber(msisdn);
    subscriber.setLastMenstrualPeriod(originalLMP);
    MctsMother mother = new MctsMother(motherId);
    mother.setState(stateDataService.findByCode(21L));
    mother.setDistrict(districtService.findByStateAndCode(mother.getState(), 3L));
    subscriber.setMother(mother);
    subscriberDataService.update(subscriber);

    Reader reader =
        createUpdateReaderWithHeaders(
            "1," + motherId + ",,," + getDateString(updatedLMP) + ",,,,,,,,,,");
    mctsBeneficiaryUpdateService.updateBeneficiaryData(reader);

    Subscriber updatedSubscriber = subscriberDataService.findByCallingNumber(msisdn);
    assertEquals(
        getDateString(updatedLMP), getDateString(updatedSubscriber.getLastMenstrualPeriod()));
    Subscription updatedSubscription =
        updatedSubscriber.getActiveAndPendingSubscriptions().iterator().next();
    assertEquals(
        getDateString(updatedLMP.plusDays(90)), getDateString(updatedSubscription.getStartDate()));
    assertEquals(SubscriptionStatus.ACTIVE, updatedSubscription.getStatus());
  }
Example #7
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);
  }
Example #8
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));
  }
  @Test(groups = "fast")
  public void testEventsAfterTransferForMigratedBundle4() throws Exception {
    // MIGRATE_ENTITLEMENT then MIGRATE_BILLING (both in the future)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateEntitlementEventEffectiveDate = transferDate.plusDays(10);
    final DateTime migrateBillingEventEffectiveDate =
        migrateEntitlementEventEffectiveDate.plusDays(20);
    final List<EntitlementEvent> events =
        transferBundle(
            migrateEntitlementEventEffectiveDate, migrateBillingEventEffectiveDate, transferDate);

    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), migrateEntitlementEventEffectiveDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getEventType(), ApiEventType.TRANSFER);
  }
  private boolean parseAuditLogForm(
      AuditLogForm auditLogForm,
      JEventCategory eventCategory,
      Model uiModel,
      Integer page,
      Integer size) {

    boolean hasParseErrors = false;
    String sDate = auditLogForm.getStartDateAsString();
    String eDate = auditLogForm.getEndDateAsString();
    try {

      if (!StringUtils.isEmpty(sDate)) {
        Date startDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(sDate));
        auditLogForm.setStartDate(startDate);
      }
      // Include endDate
      if (!StringUtils.isEmpty(eDate)) {
        Date endDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(eDate));
        if (endDate != null) {
          DateTime dateTime = new DateTime(endDate);
          dateTime = dateTime.plusDays(1);
          auditLogForm.setEndDate(dateTime.toDate());
        }
      }

    } catch (ParseException e) {
      logger.error(">>> Failed parsing date.", e);
      uiModel.addAttribute("error_msg", "Saisie invalide. Le format de date est incorrect.");
      populateAuditLog(new AuditLogForm(), eventCategory, uiModel, "auditconnections", page, size);
      hasParseErrors = true;
    }

    return hasParseErrors;
  }
Example #11
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;
 }
 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;
 }
  @Test(groups = "fast")
  public void testEventsForCancelledSubscriptionBeforeTransfer() throws Exception {
    final DateTime subscriptionStartTime = clock.getUTCNow();
    final DateTime subscriptionCancelTime = subscriptionStartTime.plusDays(1);
    final ImmutableList<ExistingEvent> existingEvents =
        ImmutableList.<ExistingEvent>of(
            createEvent(subscriptionStartTime, SubscriptionTransitionType.CREATE),
            createEvent(subscriptionCancelTime, SubscriptionTransitionType.CANCEL));
    final SubscriptionBuilder subscriptionBuilder = new SubscriptionBuilder();
    final SubscriptionData subscription = new SubscriptionData(subscriptionBuilder);

    final DateTime transferDate = subscriptionStartTime.plusDays(10);
    final List<EntitlementEvent> events =
        transferApi.toEvents(existingEvents, subscription, transferDate, callContext);

    Assert.assertEquals(events.size(), 0);
  }
Example #14
0
 private DateTime nextRepeatDaily(DateTime midnightTomorrow) {
   if (schedule.getRepeatRate() == 1) {
     return midnightTomorrow;
   }
   int distanceBetweenStartAndTomorrow =
       Days.daysBetween(new DateTime(schedule.getBeginDate()).toDateMidnight(), midnightTomorrow)
           .getDays();
   if (distanceBetweenStartAndTomorrow == 0
       || distanceBetweenStartAndTomorrow == schedule.getRepeatRate()) {
     return midnightTomorrow;
   } else if (distanceBetweenStartAndTomorrow > schedule.getRepeatRate()) {
     int remainder = distanceBetweenStartAndTomorrow % schedule.getRepeatRate();
     return midnightTomorrow.plusDays(schedule.getRepeatRate() - remainder);
   } else {
     return midnightTomorrow.plusDays(schedule.getRepeatRate() - distanceBetweenStartAndTomorrow);
   }
 }
Example #15
0
  @Test
  public void totalDosesWhenEndTimeIsGreaterThanDosageEndTime() {
    DateTime now = new DateTime(2011, 10, 3, 10, 0, 0, 0);
    final DateTime dosageStartTime = now;
    final DateTime dosageEndTime = now.plusDays(1);
    final DateTime endTime = dosageEndTime.plusDays(1);
    Dosage dosage =
        new Dosage(
            new DosageResponse(
                "dosage_id",
                new Time(dosageStartTime.getHourOfDay(), dosageStartTime.getMinuteOfHour()),
                dosageStartTime.toLocalDate(),
                dosageEndTime.toLocalDate(),
                null,
                null));

    assertEquals(2, dosage.getDosesBetween(dosageStartTime.toLocalDate(), endTime));
  }
  /** Initialising. */
  @Before
  public void setUp() {
    start = new DateTime(1999, 12, 1, 10, 0, chronology);

    datetimes = new ArrayList<DateTime>();
    for (int i = 0; i < numberOfDate + 1; i++) {
      datetimes.add(start.plusDays(i));
    }
    tAxis = new TimeAxisImpl(tAxisName, datetimes);
  }
Example #17
0
 @Test
 public void testGetStoryTasksWithEffortLeft_notInTimeframe() {
   executeClassSql();
   DateTime start = new DateTime(2008, 6, 10, 1, 0, 0, 0);
   User user = new User();
   user.setId(1);
   Interval interval = new Interval(start, start.plusDays(5));
   List<Task> actual = this.taskDAO.getStoryTasksWithEffortLeft(user, interval);
   assertEquals(0, actual.size());
 }
 /** Test the method of {@link TimeAxisImpl#findIndexOf}. */
 @Test
 public void testFindIndexOf() {
   // the first date is index 0
   int expectedIndex = 4;
   DateTime fifthDate = tAxis.getCoordinateValue(expectedIndex);
   assertEquals(expectedIndex, tAxis.findIndexOf(fifthDate));
   int notFoundIndex = -1;
   // a date is outside t axis.
   assertEquals(notFoundIndex, tAxis.findIndexOf(start.plusDays(25)));
 }
Example #19
0
  private List<CuriositySegment> parseSegments(Element element) {
    List<CuriositySegment> segments = Lists.newArrayList();
    DateTime flightDate = new DateTime();
    Elements segmentElements = element.select("tbody>tr");
    for (Element segmentElement : segmentElements) {
      if (!segmentElement.select("td.upsellCity").text().equalsIgnoreCase("")
          && segmentElement.select("td.upsellCity").text() != null) {
        CuriositySegment segment = new CuriositySegment();
        String airlineCode = segmentElement.select("td[id~=idUpsellIti]").text();
        String depCode = segmentElement.select("td.upsellCity").get(0).text();
        String arrCode = segmentElement.select("td.upsellCity").get(1).text();
        String depTime = segmentElement.select("td.upsellTime").get(0).text();
        String arrTime = segmentElement.select("td.upsellTime").get(1).text();
        segment.setDepartureName(depCode);
        segment.setArrivalName(arrCode);

        if (depTime.contains("+")) {
          flightDate =
              flightDate.plusDays(
                  Integer.parseInt(
                      depTime.substring(depTime.indexOf("+") + 1, depTime.indexOf("+") + 2)));
          depTime = depTime.substring(0, (depTime.indexOf("+") - 1));
        }
        segment.setDepartureTime(
            PARSER_DATE_TIME_FORMATTER, DATE_TIME_FORMATTER.print(flightDate) + depTime);
        if (arrTime.contains("+")) {
          flightDate =
              flightDate.plusDays(
                  Integer.parseInt(
                      arrTime.substring(arrTime.indexOf("+") + 1, arrTime.indexOf("+") + 2)));
          arrTime = arrTime.substring(0, (arrTime.indexOf("+") - 1));
        }

        segment.setArrivalTime(
            PARSER_DATE_TIME_FORMATTER, DATE_TIME_FORMATTER.print(flightDate) + arrTime);
        segment.setAirlineCode(airlineCode.substring(0, 2));
        segment.setFlightNumber(airlineCode.substring(2));
        segments.add(segment);
      }
    }
    return segments;
  }
Example #20
0
  @Test
  public void testGetAllIterationAndStoryTasks_user_hasNoAssigned() {
    executeClassSql();
    DateTime start = new DateTime(2009, 6, 10, 1, 0, 0, 0);
    Interval interval = new Interval(start, start.plusDays(5));
    User user = new User();
    user.setId(4);

    List<Task> actual = this.taskDAO.getAllIterationAndStoryTasks(user, interval);
    assertEquals(0, actual.size());
  }
Example #21
0
 @Test
 public void testGetUnassignedStoryTasksWithEffortLeftWithNullEffortSpent() {
   executeClassSql();
   DateTime start = new DateTime(2009, 6, 10, 1, 0, 0, 0);
   User user = new User();
   user.setId(3);
   Interval interval = new Interval(start, start.plusDays(5));
   List<UnassignedLoadTO> actual =
       this.taskDAO.getUnassignedStoryTasksWithEffortLeft(user, interval);
   assertTrue(actual.isEmpty());
 }
 /**
  * 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;
 }
Example #23
0
 private DateTime scheduleDaily(DateTime now) {
   DateTime nowMidnight = now.toDateMidnight().toDateTime();
   if (nextRepeatDaily(nowMidnight).equals(nowMidnight)) {
     DateTime nextTimeToday = getNextTimeToday(now, nowMidnight);
     if (nextTimeToday != null) {
       return nextTimeToday;
     }
   }
   DateTime nextDay = getNextScheduleDay(nowMidnight.plusDays(1));
   return getFirstScheduledTimeOnDay(nextDay);
 }
  /** Sets the correct start and end dates and date format. */
  protected void formatChartAxes(JFreeChart chart, DateTime start, DateTime end) {
    XYPlot plot = chart.getXYPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setMaximumDate(end.plusDays(1).toDateMidnight().toDate());
    axis.setMinimumDate(start.toDateMidnight().toDate());
    axis.setDateFormatOverride(new SimpleDateFormat("EEE d.M."));

    axis.setStandardTickUnits(tickUnits);

    plot.setDomainGridlinePaint(GRIDLINE_COLOR);
    plot.setRangeGridlinePaint(GRIDLINE_COLOR);
  }
  @Test
  public void whenADateFallsOnNonWorkingDayItShouldBeAdjustedToTheNearestWorkingDay() {

    DateTime firstOfNextMonth =
        new DateTime().plusMonths(1).withDayOfMonth(1).toDateMidnight().toDateTime();
    DateTime firstSaturdayOfNextMonth = firstOfNextMonth.withDayOfWeek(DayOfWeek.saturday());

    // exercise test
    DateTime adjustedDate = workingDayStrategy.adjust(firstSaturdayOfNextMonth);

    assertThat(adjustedDate, is(firstSaturdayOfNextMonth.plusDays(2)));
  }
Example #26
0
  @Transactional
  @Rollback(true)
  @Test
  public void testGetAuthorizedDevicesExceptSome() {
    String userId = "userId";
    String udid = "udid";
    String deviceId = "deviceId";

    String udid2 = "udid2";
    String deviceId2 = "deviceId2";

    DateTime expiry = new DateTime();
    expiry = expiry.plusDays(PoConstants.AUTHORIZED_DEVICE__TOKEN_LIFE_EXPECTANCY_DAYS);

    // first device for user
    AuthorizedDevice ad = new AuthorizedDevice();
    ad.setUserId(userId);
    ad.setUdid(udid);
    ad.setDeviceId(deviceId);
    ad.setExpires(expiry.toDate());

    // second device for user
    AuthorizedDevice ad2 = new AuthorizedDevice();
    ad2.setUserId(userId);
    ad2.setUdid(udid2);
    ad2.setDeviceId(deviceId2);
    ad2.setExpires(expiry.toDate());

    // save both to the database
    List<AuthorizedDevice> adList = new ArrayList<AuthorizedDevice>();
    adList.add(ad2);
    adList.add(ad);
    getAuthorizedDeviceDao().save(ad);
    getAuthorizedDeviceDao().save(adList);

    long deviceCount = getAuthorizedDeviceDao().count();
    Assert.assertTrue(deviceCount > 0);
    // the authorized device ids to exclude
    List<String> id = new ArrayList<String>();
    id.add(ad.getId());

    // log.error("adList=" + adList);
    // log.error("id=" + id);

    // get all but the first device for user
    assertNotNull("wtf userId is null", userId);
    assertNotNull("wtf id is null", id);
    assertTrue("id=" + id, !id.isEmpty());
    List<AuthorizedDevice> inDbList = getAuthorizedDeviceDao().findByUserIdAndIdNotIn(userId, id);

    assertTrue("inDbList=" + inDbList, inDbList.size() == 1);
    log.info("Should be same objects: inDbList=" + inDbList + " ad2=" + ad2);
  }
Example #27
0
  private void checkManifestValidityTimes(ValidationOptions options, ValidationResult result) {
    DateTime now = new DateTime();
    DateTime nextUpdateTime = getNextUpdateTime();

    if (now.isAfter(nextUpdateTime)) {
      if (nextUpdateTime.plusDays(options.getMaxStaleDays()).isAfter(now)) {
        result.warnIfTrue(true, ValidationString.MANIFEST_PAST_NEXT_UPDATE_TIME);
      } else {
        result.rejectIfTrue(true, ValidationString.MANIFEST_PAST_NEXT_UPDATE_TIME);
      }
    }
  }
Example #28
0
 private DateTime scheduleWeekday(DateTime now) {
   DateTime nowMidnight = now.toDateMidnight().toDateTime();
   if (nowMidnight.getDayOfWeek()
       < DateTimeConstants.SATURDAY) { // jodatime starts with Monday = 0
     DateTime nextTimeToday = getNextTimeToday(now, nowMidnight);
     if (nextTimeToday != null) {
       return nextTimeToday;
     }
   }
   DateTime nextDay = getNextScheduleDay(nowMidnight.plusDays(1));
   return getFirstScheduledTimeOnDay(nextDay);
 }
  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;
  }
Example #30
0
 /**
  * 日期加法
  *
  * @param txDate 日期格式"20150404"
  * @param proi DAYS|加上几天|MONTHS|加上几月|YEARS|加上几年
  * @param type 选择 DAYS||MONTHS||YEARS
  * @return
  */
 public static String plus(String txDate, int proi, String type) {
   if (txDate != null) {
     DateTime txDT = DateTime.parse(txDate, ISODateTimeFormat.basicDate());
     if (type.toUpperCase().endsWith("DAYS")) {
       return txDT.plusDays(proi).toString(ISODateTimeFormat.basicDate());
     } else if (type.toUpperCase().endsWith("MONTHS")) {
       return txDT.plusMonths(proi).toString(ISODateTimeFormat.basicDate());
     } else if (type.toUpperCase().endsWith("YEARS")) {
       return txDT.plusYears(proi).toString(ISODateTimeFormat.basicDate());
     }
   }
   return txDate;
 }