コード例 #1
0
ファイル: RuleTest.java プロジェクト: hornd/bateman
  public void quitsIfInsufficientFunds() throws Exception {
    account = new Account(new BigDecimal(1), today.minusDays(6));
    Rule buyAndHold = new BuyAndHoldRule(account, asset, conditions);

    assertEquals(
        0, buyAndHold.generateSignals(today.minusDays(5), today.minusDays(4)).getTrades().size());
  }
コード例 #2
0
ファイル: RuleTest.java プロジェクト: hornd/bateman
  public void testSignalGenerationSize() throws Exception {
    Rule buySell = new BuySellNextDayRule(account, asset, conditions);
    Session session = buySell.generateSignals(today.minusDays(5), today.minusDays(2));
    assertEquals(2, session.getTrades().size());

    account = new Account(new BigDecimal(1000), today.minusDays(6));

    buySell = new BuySellNextDayRule(account, asset, conditions);

    assertEquals(
        2, buySell.generateSignals(today.minusDays(5), today.minusDays(1)).getTrades().size());
  }
コード例 #3
0
  @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))));
  }
コード例 #4
0
  private void execute() {
    search();
    // from home - find more candidates
    String findDue = (String) data.get("findDue");
    if (FieldUtil.isNotEmpty(findDue)) {

      LOGGER.debug(findDue);
      // 設條件
      DateField dfFrom = (DateField) gridFilter.getField("dueOn" + "_From");
      DateField dfTo = (DateField) gridFilter.getField("dueOn" + "_To");

      if (findDue.equals(CardDonut.MODE_DUE.DUE_TODAY.getValue())) {
        dfFrom.setValue(DateUtil.getOnlyDate(new Date(), timeZone));
        dfTo.setValue(DateUtil.getOnlyDate(new Date(), timeZone));
      } else if (findDue.equals(CardDonut.MODE_DUE.OVERDUE.getValue())) {
        DateTime dt = new DateTime();
        dfTo.setValue(DateUtil.getOnlyDate(dt.minusDays(1).toDate(), timeZone));
      } else if (findDue.equals(CardDonut.MODE_DUE.TOTAL.getValue())) {

      }
      // 清除
      data.put("findDue", null);
      UI.getCurrent().setData(data);

      gridFilter.search();
    }
  }
コード例 #5
0
  private void processType(SelectQuery selectQuery, TransactionQueryForm form) {
    switch (form.getPeriodType()) {
      case TODAY:
        selectQuery.addConditions(
            date(TRANSACTION.START_TIMESTAMP).eq(date(CustomDSL.utcTimestamp())));
        break;

      case LAST_10:
      case LAST_30:
      case LAST_90:
        DateTime now = DateTime.now();
        selectQuery.addConditions(
            date(TRANSACTION.START_TIMESTAMP)
                .between(date(now.minusDays(form.getPeriodType().getInterval())), date(now)));
        break;

      case ALL:
        break;

      case FROM_TO:
        selectQuery.addConditions(
            TRANSACTION.START_TIMESTAMP.between(
                form.getFrom().toDateTime(), form.getTo().toDateTime()));
        break;

      default:
        throw new SteveException("Unknown enum type");
    }
  }
コード例 #6
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()));
  }
コード例 #7
0
 public List<Map<String, Object>> revenueTrendForTheWeek() {
   final Query qry = getQuery("revenue.ptis.collectiontrend");
   final DateTime currentDate = new DateTime();
   qry.setParameter("fromDate", startOfGivenDate(currentDate.minusDays(6)).toDate());
   qry.setParameter("toDate", endOfGivenDate(currentDate).toDate());
   final List<Object[]> revenueData = qry.list();
   final List<Map<String, Object>> currentYearTillDays =
       constructDayPlaceHolder(currentDate.minusDays(6), currentDate, "E-dd", "EEEE, dd MMM yyyy");
   for (final Object[] revnueObj : revenueData)
     for (final Map<String, Object> mapdata : currentYearTillDays)
       if (mapdata.containsValue(
           org.apache.commons.lang.StringUtils.capitalize(
               String.valueOf(revnueObj[0]).toLowerCase())))
         mapdata.put("y", Double.valueOf(String.valueOf(revnueObj[1])));
   return currentYearTillDays;
 }
コード例 #8
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()));
  }
コード例 #9
0
  @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());
  }
コード例 #10
0
ファイル: AtopSplitManager.java プロジェクト: cdma/presto
  @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);
  }
コード例 #11
0
ファイル: DateUtils.java プロジェクト: ezabus/fantasy-hockey
 public static String getWeekRange(String dateCode) {
   DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   DateTimeFormatter outformatter = DateTimeFormat.forPattern("dd.MM");
   DateTime endWeek = formatter.parseDateTime(dateCode);
   DateTime startWeek = endWeek.minusDays(6);
   return outformatter.print(startWeek) + "-" + outformatter.print(endWeek);
 }
コード例 #12
0
  @Test
  public void testUpdateDOBAndCompleteActiveSubscription() throws Exception {
    createLocationData();

    Long msisdn = subscriptionHelper.makeNumber();
    String childId = "0123456789";
    DateTime originalDOB = DateTime.now().minusDays(100);
    DateTime updatedDOB = originalDOB.minusDays(400);

    MctsChild child = new MctsChild(childId);
    child.setState(stateDataService.findByCode(21L));
    child.setDistrict(districtService.findByStateAndCode(child.getState(), 3L));
    makeMctsSubscription(child, originalDOB, SubscriptionPackType.CHILD, msisdn);

    // verify that the subscription is active
    Subscriber subscriber = subscriberDataService.findByCallingNumber(msisdn);
    Subscription subscription = subscriber.getAllSubscriptions().iterator().next();
    assertEquals(SubscriptionStatus.ACTIVE, subscription.getStatus());

    // now, via CSV update, change the DOB to a past subscription date; subscription should be
    // marked completed
    Reader reader =
        createUpdateReaderWithHeaders(
            "1," + childId + ",," + getDateString(updatedDOB) + ",,,,,,,,,,,");
    mctsBeneficiaryUpdateService.updateBeneficiaryData(reader);

    Subscriber updatedSubscriber = subscriberDataService.findByCallingNumber(msisdn);
    assertEquals(getDateString(updatedDOB), getDateString(updatedSubscriber.getDateOfBirth()));
    Subscription updatedSubscription = updatedSubscriber.getAllSubscriptions().iterator().next();
    assertEquals(getDateString(updatedDOB), getDateString(updatedSubscription.getStartDate()));
    assertEquals(SubscriptionStatus.COMPLETED, updatedSubscription.getStatus());
  }
コード例 #13
0
  @Test
  public void testUpdateDOB() throws Exception {
    createLocationData();

    Long msisdn = subscriptionHelper.makeNumber();
    String childId = "0123456789";
    DateTime originalDOB = DateTime.now();
    DateTime updatedDOB = originalDOB.minusDays(100);

    subscriptionHelper.mksub(
        SubscriptionOrigin.MCTS_IMPORT, originalDOB, SubscriptionPackType.CHILD, msisdn);
    Subscriber subscriber = subscriberDataService.findByCallingNumber(msisdn);
    subscriber.setDateOfBirth(originalDOB);
    MctsChild child = new MctsChild(childId);
    child.setState(stateDataService.findByCode(21L));
    child.setDistrict(districtService.findByStateAndCode(child.getState(), 3L));
    subscriber.setChild(child);
    subscriberDataService.update(subscriber);

    // this updates the db with the new data (DOB)
    Reader reader =
        createUpdateReaderWithHeaders(
            "1," + childId + ",," + getDateString(updatedDOB) + ",,,,,,,,,,,");
    mctsBeneficiaryUpdateService.updateBeneficiaryData(reader);

    // This query should return the updated subscriber information (but it doesn't...causing the
    // assert to fail)
    Subscriber updatedSubscriber = subscriberDataService.findByCallingNumber(msisdn);
    assertEquals(getDateString(updatedDOB), getDateString(updatedSubscriber.getDateOfBirth()));
    Subscription updatedSubscription =
        updatedSubscriber.getActiveAndPendingSubscriptions().iterator().next();
    assertEquals(getDateString(updatedDOB), getDateString(updatedSubscription.getStartDate()));
    assertEquals(SubscriptionStatus.ACTIVE, updatedSubscription.getStatus());
  }
  public void testAutoCreateIndexWithDateMathExpression() throws Exception {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));

    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
    client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
    client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
    refresh();

    SearchResponse searchResponse =
        client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertHitCount(searchResponse, 3);
    assertSearchHits(searchResponse, "1", "2", "3");

    IndicesStatsResponse indicesStatsResponse =
        client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
  }
コード例 #15
0
ファイル: UserServiceTest.java プロジェクト: bipolar/MilkyWay
 @Test
 public void testFindNotActivatedUsersByCreationDateBefore() {
   userService.removeNotActivatedUsers();
   DateTime now = new DateTime();
   List<User> users =
       userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
   assertThat(users).isEmpty();
 }
コード例 #16
0
ファイル: DateUtils.java プロジェクト: ezabus/fantasy-hockey
 public static String getYesterdayDate() {
   Date date = new Date();
   DateTime dt = new DateTime(date);
   dt = dt.minusDays(1);
   // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   return dateFormatter.print(dt);
 }
コード例 #17
0
 @Test
 public void calculate_datetime_different() {
   DateTime now = DateTime.now();
   LogicalExpression left = new Literal<DateTime>(ValueType.DATETIME, now);
   LogicalExpression right = new Literal<DateTime>(ValueType.DATETIME, now.minusDays(1));
   NotEqual op = new NotEqual(left, right);
   Boolean result = (Boolean) op.execute();
   assertTrue(result);
 }
コード例 #18
0
ファイル: UserService.java プロジェクト: Raithfall/fuego
 /**
  * Not activated users should be automatically deleted after 3 days.
  *
  * <p>
  *
  * <p>This is scheduled to get fired everyday, at 01:00 (am).
  */
 @Scheduled(cron = "0 0 1 * * ?")
 public void removeNotActivatedUsers() {
   DateTime now = new DateTime();
   List<User> users = userRepository.findNotActivatedUsersByCreationDateBefore(now.minusDays(3));
   for (User user : users) {
     log.debug("Deleting not activated user {}", user.getLogin());
     userRepository.delete(user);
   }
 }
コード例 #19
0
ファイル: DosageTest.java プロジェクト: motech/TAMA-Web
  @Test
  public void totalDosesWhenStartTimeIsBeforeDosageStartTime() {
    DateTime now = new DateTime(2011, 10, 3, 10, 0, 0, 0);
    final DateTime dosageStartTime = now.minusDays(1);
    final DateTime startTime = dosageStartTime.minusDays(1);
    final DateTime dosageEndTime = now.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(startTime.toLocalDate(), now));
  }
コード例 #20
0
  /** Test the method of {@link TimeAxisImpl#isAscending}. */
  @Test
  public void testIsAscending() {
    assertTrue(tAxis.isAscending());

    ArrayList<DateTime> dts = new ArrayList<>();
    for (int i = 0; i < numberOfDate + 1; i++) {
      dts.add(start.minusDays(i));
    }
    TimeAxis ta = new TimeAxisImpl(tAxisName, dts);
    assertFalse(ta.isAscending());
  }
コード例 #21
0
ファイル: RuleTest.java プロジェクト: hornd/bateman
  @Override
  public void setUp() throws Exception {
    super.setUp();

    today = DateTime.now();

    toyPrices = new TreeMap<DateTime, BigDecimal>();
    toyPrices.put(today.minusDays(5), new BigDecimal(10));
    toyPrices.put(today.minusDays(4), new BigDecimal(15));
    toyPrices.put(today.minusDays(3), new BigDecimal(20));
    toyPrices.put(today.minusDays(2), new BigDecimal(10));
    toyPrices.put(today.minusDays(1), new BigDecimal(5));
    toyPrices.put(today, new BigDecimal(10));

    series = new TimeSeries(toyPrices);
    asset = new Asset("FOO", series);

    account = new Account(new BigDecimal(1000), today.minusDays(6));

    conditions = new Conditions(BigDecimal.ZERO, BigDecimal.ZERO);
    moneyManager = new FixedPercentageAllocationStrategy(0.2, asset);
  }
コード例 #22
0
 private void makeMctsSubscription(
     MctsBeneficiary beneficiary, DateTime startDate, SubscriptionPackType packType, Long number) {
   subscriptionHelper.mksub(SubscriptionOrigin.MCTS_IMPORT, startDate, packType, number);
   Subscriber subscriber = subscriberDataService.findByCallingNumber(number);
   if (packType == SubscriptionPackType.CHILD) {
     subscriber.setChild((MctsChild) beneficiary);
     subscriber.setDateOfBirth(startDate);
   } else {
     subscriber.setMother((MctsMother) beneficiary);
     subscriber.setLastMenstrualPeriod(startDate.minusDays(90));
   }
   subscriberDataService.update(subscriber);
 }
  public void testIndexNameDateMathExpressions() {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
    createIndex(index1, index2, index3);

    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
    client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
    client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
    refresh();

    SearchResponse searchResponse =
        client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertHitCount(searchResponse, 3);
    assertSearchHits(searchResponse, "1", "2", "3");

    GetResponse getResponse = client().prepareGet(dateMathExp1, "type", "1").get();
    assertThat(getResponse.isExists(), is(true));
    assertThat(getResponse.getId(), equalTo("1"));

    getResponse = client().prepareGet(dateMathExp2, "type", "2").get();
    assertThat(getResponse.isExists(), is(true));
    assertThat(getResponse.getId(), equalTo("2"));

    getResponse = client().prepareGet(dateMathExp3, "type", "3").get();
    assertThat(getResponse.isExists(), is(true));
    assertThat(getResponse.getId(), equalTo("3"));

    IndicesStatsResponse indicesStatsResponse =
        client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index3), notNullValue());

    DeleteResponse deleteResponse = client().prepareDelete(dateMathExp1, "type", "1").get();
    assertEquals(DocWriteResponse.Result.DELETED, deleteResponse.getResult());
    assertThat(deleteResponse.getId(), equalTo("1"));

    deleteResponse = client().prepareDelete(dateMathExp2, "type", "2").get();
    assertEquals(DocWriteResponse.Result.DELETED, deleteResponse.getResult());
    assertThat(deleteResponse.getId(), equalTo("2"));

    deleteResponse = client().prepareDelete(dateMathExp3, "type", "3").get();
    assertEquals(DocWriteResponse.Result.DELETED, deleteResponse.getResult());
    assertThat(deleteResponse.getId(), equalTo("3"));
  }
コード例 #24
0
  /*
              <![CDATA[
                             var endDate = thisComponent.getBundleProxy().getValueFromInfo("endDate");
                             if (endDate == null) {
                                 result = false;
                             }
                             if ("yes".equalsIgnoreCase(thisComponent.get("autoRenewal").toString())) {
                                 var objDate = thisComponent.get("/endDate");
                                 var jendDate = new Packages.org.joda.time.DateTime(objDate.getTime().getTime()).withTimeAtStartOfDay();//end date with start of the day time
                                 var noticePeriod = 0;
                                 noticePeriod = thisComponent.get("renNoticePer");

                                 var reminder = thisComponent.addNode("ReqReminder/");
                                 var recipient = reminder.addNode("/ReqReminderRecipientAccountUser/");
                                 reminder.setValue("/status", "active", false);
                                 reminder.setValue("/eventType", endDate.getDefinition().getAbsoluteJXPath(), false);
                                 reminder.setValue("/resolvedEventDate", endDate.getValue(), false);
                                 var dateTime = jendDate.minusDays(noticePeriod).withTimeAtStartOfDay();
                                 var clnd = Packages.java.util.Calendar.getInstance();
                                 clnd.setTime(new Packages.java.util.Date(dateTime.getMillis()));
                                 reminder.setDateValue("/notificationDate", clnd, false);
                                 reminder.setValue("/notificationDelta", ""+ noticePeriod, false);
                                 reminder.setValue("/notificationFreq", "once", false);
                                 reminder.setValue("/subject", "Renewal notification letter", false);
                                 var sb = "Your contract "+thisComponent.get("name").toString()+" will be automatically renewed at "+endDate.getDisplayValue();
                                 reminder.setValue("/comments", sb.toString(), false);
                                 recipient.setValue("/accountUserRecipient", thisComponent.getBundleProxy().getOwner().getID(), false);
                                 reminder.save();
                                 recipient.save();
                         	   scheduler.scheduleReminder(node, reminder);
                             }
                             result = true;

  ]]>
   */
  @Override
  public Boolean process() throws Exception {
    boolean result = false;

    CFR1Details info = getHelper().getInfoComponentStub();
    Date endDate = info.getEndDate();
    if (endDate != null) {
      if ("yes".equals(info.getAutoRenewal())) {

        DateTime jEndDate = new DateTime(endDate.getTime()).withTimeAtStartOfDay();
        Integer noticePeriod = info.getRenNoticePer();
        if (noticePeriod == null) {
          noticePeriod = 0;
        }

        Reminder reminder = getHelper().addNewComponent("ReqReminder");
        reminder.setStatus("active");
        reminder.setEventType(
            getHelper().getParameterDefinitionHelper(info, "endDate").getAbsoluteJXPath());
        reminder.setResolvedEventDate(endDate);

        DateTime dateTime = jEndDate.minusDays(noticePeriod).withTimeAtStartOfDay();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateTime.getMillis());
        reminder.setNotificationDate(calendar.getTime());
        reminder.setNotificationDelta(noticePeriod);
        reminder.setNotificationFreq("once");
        reminder.setSubject("Renewal notification letter");
        reminder.setComments(
            "Your contract "
                + info.getContractName()
                + " will be automatically renewed at "
                + endDate.getDate());

        reminder.setRecipientAccountUser(getHelper().getCurrentBundleWrapper().getOwnerEmail());
        getHelper().saveComponent(reminder);

        /**
         * ReminderRecipientAccountUser recipient =
         * getHelper().addNewSubComponent("ReqReminderRecipientAccountUser", reminder);
         * RCFBundleWrapper bundleWrapper = getHelper().getCurrentBundleWrapper();
         * recipient.setAccountUserRecipient(bundleWrapper.getOwnerID());
         * getHelper().saveComponent(recipient);
         */
        RCFSchedulerAPI.scheduleReminder(reminder);
        result = true;
      }
    }
    return result;
  }
コード例 #25
0
  // TOOLS
  private DateTime getDateLimit(final boolean upper) {
    final Date date = DateUtils.truncate(new Date(), Calendar.DATE);
    final DateTime now = new DateTime(date);

    switch (type) {
      case YEAR:
        return upper ? now.plusYears(upperBoundary) : now.minusYears(lowerBoundary);
      case MONTH:
        return upper ? now.plusMonths(upperBoundary) : now.minusMonths(lowerBoundary);
      case DAY:
        return upper ? now.plusDays(upperBoundary) : now.minusDays(lowerBoundary);
      default:
        throw new IllegalArgumentException("Unsupported type of time unit: " + type);
    }
  }
コード例 #26
0
  @Test(groups = "fast")
  public void testEventsAfterTransferForMigratedBundle2() throws Exception {
    // MIGRATE_ENTITLEMENT and MIGRATE_BILLING at the same time (both in the past)
    final DateTime transferDate = clock.getUTCNow();
    final DateTime migrateEntitlementEventEffectiveDate = transferDate.minusDays(10);
    final DateTime migrateBillingEventEffectiveDate = migrateEntitlementEventEffectiveDate;
    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(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getEventType(), ApiEventType.TRANSFER);
  }
コード例 #27
0
  /** 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));
  }
  public void testCreateIndexWithDateMathExpression() throws Exception {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));

    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    createIndex(dateMathExp1, dateMathExp2, dateMathExp3);

    ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
    assertThat(clusterState.metaData().index(index1), notNullValue());
    assertThat(clusterState.metaData().index(index2), notNullValue());
    assertThat(clusterState.metaData().index(index3), notNullValue());
  }
コード例 #29
0
ファイル: DateTimeUtils.java プロジェクト: yufeng1982/EMP
 public static Date getDateFromDateDesc(String leadTime) {
   DateTime dateTime = new DateTime(0, 12, 31, 0, 0, 0, 0);
   if (!Strings.isEmpty(leadTime)) {
     String time = "0";
     if (leadTime.indexOf(".") > 0) {
       time = leadTime.substring(0, leadTime.indexOf("."));
     } else {
       time = leadTime.substring(0, leadTime.length() - 1);
     }
     int timeVal = Integer.parseInt(time);
     if (leadTime.indexOf(DAY) >= 0) {
       if (timeVal > 0) {
         dateTime = dateTime.plusDays(timeVal);
       } else {
         dateTime = dateTime.minusDays(Math.abs(timeVal));
       }
     } else if (leadTime.indexOf(WEEK) >= 0) {
       if (timeVal > 0) {
         dateTime = dateTime.plusWeeks(timeVal);
       } else {
         dateTime = dateTime.minusWeeks(Math.abs(timeVal));
       }
     } else if (leadTime.indexOf(MONTH) >= 0) {
       if (timeVal > 0) {
         dateTime = dateTime.plusMonths(timeVal);
       } else {
         dateTime = dateTime.minusMonths(Math.abs(timeVal));
       }
     } else if (leadTime.indexOf(QUARTER) >= 0) {
       if (timeVal > 0) {
         dateTime = dateTime.plusMonths(timeVal * 3);
       } else {
         dateTime = dateTime.minusMonths(Math.abs(timeVal * 3));
       }
     } else if (leadTime.indexOf(YEAR) >= 0) {
       if (timeVal > 0) {
         dateTime = dateTime.plusYears(timeVal);
       } else {
         dateTime = dateTime.minusYears(Math.abs(timeVal));
       }
     }
     return dateTime.toDate();
   }
   return dateTime.toDate();
 }
コード例 #30
0
  /**
   * FileUtils.touch Implements the same behaviour as the "touch" utility on Unix. It creates a new
   * file with size 0 or, if the file exists already, it is opened and closed without modifying it,
   * but updating the file date and time.
   *
   * @throws IOException
   */
  @Test
  public void touch_file_apache() throws IOException {

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    DateTime today = new DateTime();

    File file = new File(OUTPUT_FILE_NAME);

    // set last modified to 5 days ago
    file.setLastModified(today.minusDays(5).getMillis());

    // display latest lastmodified
    logger.info(dateFormatter.format(file.lastModified()));

    FileUtils.touch(file);

    // display latest lastmodified
    logger.info(dateFormatter.format(file.lastModified()));
  }