Java Code Examples for org.joda.time.DateTime#plusYears()

The following examples show how to use org.joda.time.DateTime#plusYears() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void storeState(ModerationActionRequest request) {
    MuteState state = new MuteState();
    state.setGlobal(request.isGlobal());
    state.setUserId(request.getViolator().getUser().getId());
    state.setGuildId(request.getViolator().getGuild().getIdLong());
    DateTime dateTime = DateTime.now();
    if (request.getDuration() != null) {
        dateTime = dateTime.plus(request.getDuration());
    } else {
        dateTime = dateTime.plusYears(100);
    }
    state.setExpire(dateTime.toDate());
    state.setReason(request.getReason());
    if (request.getChannel() != null) {
        state.setChannelId(request.getChannel().getId());
    }
    muteStateRepository.save(state);
}
 
Example 2
private String handlerDate() throws Exception {
	String dateStr = this.getFields().get("date");
	String frequency = this.getFields().get("frequency");
	String dateStatus = this.getFields().get("dateStatus");
	DateTime dateTime = new DateTime(dateStr);
	if ("-1".equals(dateStatus)) { // 上一個
		if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 上一個月
			dateTime = dateTime.plusMonths(-1);
		} else { // 上一個年
			dateTime = dateTime.plusYears(-1);
		}			
	}
	if ("1".equals(dateStatus)) { // 下一個
		if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 下一個月
			dateTime = dateTime.plusMonths(1);
		} else { // 下一個年
			dateTime = dateTime.plusYears(1);
		}			
	}		
	return dateTime.toString("yyyy-MM-dd");
}
 
Example 3
private DateInterval toYearIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
    DateTime from = dateTimeUnit.toJodaDateTime( chronology );

    if ( offset > 0 )
    {
        from = from.plusYears( offset );
    }
    else if ( offset < 0 )
    {
        from = from.minusYears( -offset );
    }

    DateTime to = new DateTime( from ).plusYears( length ).minusDays( 1 );

    DateTimeUnit fromDateTimeUnit = DateTimeUnit.fromJodaDateTime( from );
    DateTimeUnit toDateTimeUnit = DateTimeUnit.fromJodaDateTime( to );

    fromDateTimeUnit.setDayOfWeek( isoWeekday( fromDateTimeUnit ) );
    toDateTimeUnit.setDayOfWeek( isoWeekday( toDateTimeUnit ) );

    return new DateInterval( toIso( fromDateTimeUnit ), toIso( toDateTimeUnit ), DateIntervalType.ISO8601_YEAR );
}
 
Example 4
/**
 * Converts this period to a list of year periods.  Partial years will not be
 * included.  For example, a period of "2009-2010" will return a list
 * of 2 years - one for 2009 and one for 2010.  On the other hand, a period
 * of "January 2009" would return an empty list since partial
 * years are not included.
 * @return A list of year periods contained within this period
 */
public List<DateTimePeriod> toYears() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();

    // default "current" year to start datetime
    DateTime currentStart = getStart();
    // calculate "next" year
    DateTime nextStart = currentStart.plusYears(1);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeYear(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusYears(1);
    }

    return list;
}
 
Example 5
Source Project: liteflow   File: TimeExpressionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 按某个时间单位添加时间
     * @param dateTime
     * @param n
     * @param timeUnit
     * @return
     */
    public static DateTime calculateTime(DateTime dateTime, int n, TimeUnit timeUnit) {

        DateTime addedDateTime = null;
        switch (timeUnit){
//            case SECOND:
//                addedDateTime = dateTime.plusSeconds(n);
//                break;
            case MINUTE:
                addedDateTime = dateTime.plusMinutes(n);
                break;
            case HOUR:
                addedDateTime = dateTime.plusHours(n);
                break;
            case DAY:
                addedDateTime = dateTime.plusDays(n);
                break;
            case WEEK:
                addedDateTime = dateTime.plusWeeks(n);
                break;
            case MONTH:
                addedDateTime = dateTime.plusMonths(n);
                break;
            case YEAR:
                addedDateTime = dateTime.plusYears(n);
                break;
        }

        return addedDateTime;
    }
 
Example 6
public static DateTime addTime(int tempRes, int increment, DateTime start) {
    
    DateTime d = null;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return d;
    
}
 
Example 7
Source Project: timecat   File: InfoOperationActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void refreshViewByAttach(DBSubPlan dbSubPlan) {
    dialog_add_task_type_task.postDelayed(new Runnable() {
        @Override
        public void run() {
            dialog_add_task_type_task.callOnClick();
        }
    }, 500);
    DateTime date = new DateTime();
    date = date.plusYears(50);
    startDateTime = startDateTime.withYear(date.getYear());
    endDateTime = endDateTime.withYear(date.getYear());
}
 
Example 8
Source Project: nomulus   File: TimeOfYear.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link TimeOfYear} from a {@link DateTime}.
 *
 * <p>This handles leap years in an intentionally peculiar way by always treating February 29 as
 * February 28. It is impossible to construct a {@link TimeOfYear} for February 29th.
 */
public static TimeOfYear fromDateTime(DateTime dateTime) {
  DateTime nextYear = dateTime.plusYears(1);  // This turns February 29 into February 28.
  TimeOfYear instance = new TimeOfYear();
  instance.timeString = String.format(
      "%02d %02d %08d",
      nextYear.getMonthOfYear(),
      nextYear.getDayOfMonth(),
      nextYear.getMillisOfDay());
  return instance;
}
 
Example 9
Source Project: nomulus   File: DomainBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClone_extendsExpirationForNonExpiredTransferredDomain() {
  // If the transfer implicitly succeeded, the expiration time should be extended even if it
  // hadn't already expired
  DateTime now = DateTime.now(UTC);
  DateTime transferExpirationTime = now.minusDays(1);
  DateTime previousExpiration = now.plusWeeks(2);

  DomainTransferData transferData =
      new DomainTransferData.Builder()
          .setPendingTransferExpirationTime(transferExpirationTime)
          .setTransferStatus(TransferStatus.PENDING)
          .setGainingClientId("TheRegistrar")
          .build();
  Period extensionPeriod = transferData.getTransferPeriod();
  DateTime newExpiration = previousExpiration.plusYears(extensionPeriod.getValue());
  domain =
      persistResource(
          domain
              .asBuilder()
              .setRegistrationExpirationTime(previousExpiration)
              .setTransferData(transferData)
              .build());

  assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime())
      .isEqualTo(newExpiration);
}
 
Example 10
@Test
public void testSuccess_autorenewGraceActive_onlyAtTransferRequestTime() throws Exception {
  setupDomain("example", "tld");
  // Set the domain to have auto-renewed long enough ago that it is still in the autorenew grace
  // period at the transfer request time, but will have exited it by the automatic transfer time.
  DateTime autorenewTime =
      clock.nowUtc().minus(Registry.get("tld").getAutoRenewGracePeriodLength()).plusDays(1);
  DateTime expirationTime = autorenewTime.plusYears(1);
  domain =
      persistResource(
          domain
              .asBuilder()
              .setRegistrationExpirationTime(expirationTime)
              .addGracePeriod(
                  GracePeriod.createForRecurring(
                      GracePeriodStatus.AUTO_RENEW,
                      autorenewTime.plus(Registry.get("tld").getAutoRenewGracePeriodLength()),
                      "TheRegistrar",
                      domain.getAutorenewBillingEvent()))
              .build());
  clock.advanceOneMilli();
  // The response from DomainTransferRequestFlow returns exDate based on if the transfer were to
  // occur now.
  doSuccessfulTest(
      "domain_transfer_request.xml",
      "domain_transfer_request_response_autorenew_grace_at_request_only.xml",
      expirationTime.plusYears(1));
}
 
Example 11
@Test
public void testSuccess_superuserExtension_transferPeriodZero_autorenewGraceActive()
    throws Exception {
  DomainBase domain = reloadResourceByForeignKey();
  Key<Recurring> existingAutorenewEvent = domain.getAutorenewBillingEvent();
  // Set domain to have auto-renewed just before the transfer request, so that it will have an
  // active autorenew grace period spanning the entire transfer window.
  DateTime autorenewTime = clock.nowUtc().minusDays(1);
  DateTime expirationTime = autorenewTime.plusYears(1);
  DomainTransferData.Builder transferDataBuilder = domain.getTransferData().asBuilder();
  domain =
      persistResource(
          domain
              .asBuilder()
              .setTransferData(
                  transferDataBuilder.setTransferPeriod(Period.create(0, Unit.YEARS)).build())
              .setRegistrationExpirationTime(expirationTime)
              .addGracePeriod(
                  GracePeriod.createForRecurring(
                      GracePeriodStatus.AUTO_RENEW,
                      autorenewTime.plus(Registry.get("tld").getAutoRenewGracePeriodLength()),
                      "TheRegistrar",
                      existingAutorenewEvent))
              .build());
  clock.advanceOneMilli();
  runSuccessfulFlowWithAssertions(
      "tld",
      "domain_transfer_approve.xml",
      "domain_transfer_approve_response_zero_period_autorenew_grace.xml",
      domain.getRegistrationExpirationTime());
  assertHistoryEntriesDoNotContainTransferBillingEventsOrGracePeriods();
}
 
Example 12
public static int addTimeSteps(int tempRes, int increment, DateTime start) {
    
    DateTime d;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return (int) (d.getMillis()/1000);
    
}
 
Example 13
Source Project: timecat   File: DefaultDataGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public static void fillDBWithDummyData(Context ctx) {
    Resources r = ctx.getResources();
    if (DB.plans().findAll().size() == 0 && DB.schedules().findAll().size() == 0) {
        try {
            Log.i("DefaultDataGenerator", "Creating dummy data...");
            DBUser u = DB.users().getActive();
            DBPlan dbPlan = new DBPlan();
            dbPlan.setIs_star(1);
            dbPlan.setTitle("抗焦虑锦囊");
            dbPlan.setContent("在夜晚失眠时把担心的事放到锦囊里,在失去动力成为咸鱼时打开锦囊,不忘初心,做真正的自己");
            dbPlan.setCoverImageUrl("http://img.hb.aicdn.com/3f04db36f22e2bf56d252a3bc1eacdd2a0416d75221a7c-rpihP1_fw658");
            dbPlan.setCreated_datetime(TimeUtil.formatGMTDate(new Date()));
            dbPlan.setUpdate_datetime(dbPlan.getCreated_datetime());
            dbPlan.setOwner(Converter.getOwnerUrl(u));
            dbPlan.setActiveUser();
            DB.plans().safeSaveDBPlan(dbPlan);
            for (int i = 0; i < 3; i++) {
                DBSubPlan subPlan = new DBSubPlan();
                subPlan.setTitle("子计划" + i);
                subPlan.setContent("子计划的描述");
                subPlan.setCreated_datetime(TimeUtil.formatGMTDate(new Date()));
                subPlan.setUpdate_datetime(subPlan.getCreated_datetime());
                subPlan.setColor(Color.BLUE);
                subPlan.setOwner(dbPlan.getOwner());
                subPlan.setPlan(dbPlan);
                subPlan.setActiveUser();
                DB.subPlans().safeSaveDBSubPlan(subPlan);
                for (int j=0; j<4; j++) {
                    DBTask dbTask = new DBTask();
                    dbTask.setTitle("计划"+i+"的task");
                    dbTask.setContent("计划"+i+"的task的content");
                    dbTask.setCreated_datetime(TimeUtil.formatGMTDate(new Date()));

                    dbTask.setIs_all_day(false);
                    DateTime date = new DateTime();
                    date = date.plusYears(50);
                    Date d = new Date();
                    d.setYear(d.getYear() + 50);
                    d.setMonth(date.getMonthOfYear());
                    d.setDate(date.getDayOfMonth());
                    dbTask.setBegin_datetime(TimeUtil.formatGMTDate(d));
                    dbTask.setEnd_datetime(TimeUtil.formatGMTDate(d));

                    dbTask.setLabel(0);
                    dbTask.setUser(u);
                    dbTask.setOwner(Converter.getOwnerUrl(u));
                    dbTask.setSubplan(subPlan);
                    dbTask.setActiveUser();
                    DB.schedules().safeSaveDBTask(dbTask);
                }
            }
            LogUtil.i("DefaultDataGenerator", "Dummy data saved successfully!");
        } catch (Exception e) {
            LogUtil.e("DefaultDataGenerator", "Error filling db with dummy data!" + e);
        }
    }
}
 
Example 14
static public DateTimePeriod createYear(DateTime start) {
    DateTime end = start.plusYears(1);
    return new DateTimeYear(start, end);
}
 
Example 15
Source Project: nomulus   File: DomainBaseTest.java    License: Apache License 2.0 4 votes vote down vote up
private void doExpiredTransferTest(DateTime oldExpirationTime) {
  HistoryEntry historyEntry = new HistoryEntry.Builder().setParent(domain).build();
  BillingEvent.OneTime transferBillingEvent =
      persistResource(
          new BillingEvent.OneTime.Builder()
              .setReason(Reason.TRANSFER)
              .setClientId("winner")
              .setTargetId("example.com")
              .setEventTime(fakeClock.nowUtc())
              .setBillingTime(
                  fakeClock
                      .nowUtc()
                      .plusDays(1)
                      .plus(Registry.get("com").getTransferGracePeriodLength()))
              .setCost(Money.of(USD, 11))
              .setPeriodYears(1)
              .setParent(historyEntry)
              .build());
  domain =
      domain
          .asBuilder()
          .setRegistrationExpirationTime(oldExpirationTime)
          .setTransferData(
              domain
                  .getTransferData()
                  .asBuilder()
                  .setTransferStatus(TransferStatus.PENDING)
                  .setTransferRequestTime(fakeClock.nowUtc().minusDays(4))
                  .setPendingTransferExpirationTime(fakeClock.nowUtc().plusDays(1))
                  .setGainingClientId("winner")
                  .setServerApproveBillingEvent(transferBillingEvent.createVKey())
                  .setServerApproveEntities(ImmutableSet.of(transferBillingEvent.createVKey()))
                  .build())
          .addGracePeriod(
              // Okay for billing event to be null since the point of this grace period is just
              // to check that the transfer will clear all existing grace periods.
              GracePeriod.create(
                  GracePeriodStatus.ADD, fakeClock.nowUtc().plusDays(100), "foo", null))
          .build();
  DomainBase afterTransfer = domain.cloneProjectedAtTime(fakeClock.nowUtc().plusDays(1));
  DateTime newExpirationTime = oldExpirationTime.plusYears(1);
  Key<BillingEvent.Recurring> serverApproveAutorenewEvent =
      domain.getTransferData().getServerApproveAutorenewEvent().getOfyKey();
  assertTransferred(afterTransfer, newExpirationTime, serverApproveAutorenewEvent);
  assertThat(afterTransfer.getGracePeriods())
      .containsExactly(
          GracePeriod.create(
              GracePeriodStatus.TRANSFER,
              fakeClock
                  .nowUtc()
                  .plusDays(1)
                  .plus(Registry.get("com").getTransferGracePeriodLength()),
              "winner",
              Key.create(transferBillingEvent)));
  // If we project after the grace period expires all should be the same except the grace period.
  DomainBase afterGracePeriod =
      domain.cloneProjectedAtTime(
          fakeClock
              .nowUtc()
              .plusDays(2)
              .plus(Registry.get("com").getTransferGracePeriodLength()));
  assertTransferred(afterGracePeriod, newExpirationTime, serverApproveAutorenewEvent);
  assertThat(afterGracePeriod.getGracePeriods()).isEmpty();
}
 
Example 16
Source Project: onetwo   File: JodatimeUtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testDate(){
	/*LocalDateTime fromDate = new LocalDateTime(new Date());
	String str = fromDate.toString("yyyy-MM-dd HH:mm:ss.SSS");
	System.out.println("str:"+str);
	LocalTime localTime = fromDate.toLocalTime();
	System.out.println("localTime:"+localTime.toString());
	System.out.println("localTime:"+localTime.toString("yyyy-MM-dd HH:mm:ss"));
	System.out.println("toDateTimeToday:"+localTime.toDateTimeToday().toDate().toLocaleString());
	
	fromDate = new LocalDateTime(new Date());
	fromDate = fromDate.year().setCopy(1970).monthOfYear().setCopy(1).dayOfMonth().setCopy(1);
	System.out.println("fromDate:"+fromDate.toString("yyyy-MM-dd HH:mm:ss"));
	
	Calendar cal = Calendar.getInstance();
	cal.setTime(new Date());
	cal.set(1970, 0, 1);
	System.out.println("cal:"+cal.getTime().toLocaleString());*/
	
	DateTime dt = DateTime.now().millisOfDay().withMinimumValue();
	System.out.println(JodatimeUtils.formatDateTime(dt.toDate()));
	dt = dt.millisOfDay().withMaximumValue();
	System.out.println(JodatimeUtils.formatDateTime(dt.toDate()));
	System.out.println(JodatimeUtils.formatDateTime(JodatimeUtils.atEndOfDate(dt.toDate()).toDate()));
	
	DateTime date = JodatimeUtils.parse("2015-03-18");
	System.out.println("date: " + date.getDayOfMonth());
	Assert.assertEquals(18, date.getDayOfMonth());
	
	date = JodatimeUtils.parse("2016-04-13");
	System.out.println("week: " + date.getWeekOfWeekyear());
	Assert.assertEquals(15, date.getWeekOfWeekyear());
	
	DateTime dateTime = DateTime.parse("2016-04-13");
	System.out.println("dateTime:"+dateTime);
	DateTime start = dateTime.dayOfWeek().withMinimumValue();
	DateTime end = start.plusWeeks(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-04-11", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2016-04-18", end.toString("yyyy-MM-dd"));


	start = dateTime.dayOfMonth().withMinimumValue();
	end = start.plusMonths(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-04-01", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2016-05-01", end.toString("yyyy-MM-dd"));

	start = dateTime.dayOfYear().withMinimumValue();
	end = start.plusYears(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-01-01", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2017-01-01", end.toString("yyyy-MM-dd"));
}
 
Example 17
Source Project: nomulus   File: DomainRenewFlowTest.java    License: Apache License 2.0 4 votes vote down vote up
private void doSuccessfulTest(
    String responseFilename,
    int renewalYears,
    String renewalClientId,
    UserPrivileges userPrivileges,
    Map<String, String> substitutions,
    Money totalRenewCost)
    throws Exception {
  assertTransactionalFlow(true);
  DateTime currentExpiration = reloadResourceByForeignKey().getRegistrationExpirationTime();
  DateTime newExpiration = currentExpiration.plusYears(renewalYears);
  runFlowAssertResponse(
      CommitMode.LIVE, userPrivileges, loadFile(responseFilename, substitutions));
  DomainBase domain = reloadResourceByForeignKey();
  HistoryEntry historyEntryDomainRenew =
      getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_RENEW);
  assertThat(ofy().load().key(domain.getAutorenewBillingEvent()).now().getEventTime())
      .isEqualTo(newExpiration);
  assertAboutDomains()
      .that(domain)
      .isActiveAt(clock.nowUtc())
      .and()
      .hasRegistrationExpirationTime(newExpiration)
      .and()
      .hasOneHistoryEntryEachOfTypes(
          HistoryEntry.Type.DOMAIN_CREATE, HistoryEntry.Type.DOMAIN_RENEW)
      .and()
      .hasLastEppUpdateTime(clock.nowUtc())
      .and()
      .hasLastEppUpdateClientId(renewalClientId);
  assertAboutHistoryEntries().that(historyEntryDomainRenew).hasPeriodYears(renewalYears);
  BillingEvent.OneTime renewBillingEvent =
      new BillingEvent.OneTime.Builder()
          .setReason(Reason.RENEW)
          .setTargetId(getUniqueIdFromCommand())
          .setClientId(renewalClientId)
          .setCost(totalRenewCost)
          .setPeriodYears(renewalYears)
          .setEventTime(clock.nowUtc())
          .setBillingTime(clock.nowUtc().plus(Registry.get("tld").getRenewGracePeriodLength()))
          .setParent(historyEntryDomainRenew)
          .build();
  assertBillingEvents(
      renewBillingEvent,
      new BillingEvent.Recurring.Builder()
          .setReason(Reason.RENEW)
          .setFlags(ImmutableSet.of(Flag.AUTO_RENEW))
          .setTargetId(getUniqueIdFromCommand())
          .setClientId("TheRegistrar")
          .setEventTime(expirationTime)
          .setRecurrenceEndTime(clock.nowUtc())
          .setParent(getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_CREATE))
          .build(),
      new BillingEvent.Recurring.Builder()
          .setReason(Reason.RENEW)
          .setFlags(ImmutableSet.of(Flag.AUTO_RENEW))
          .setTargetId(getUniqueIdFromCommand())
          .setClientId("TheRegistrar")
          .setEventTime(domain.getRegistrationExpirationTime())
          .setRecurrenceEndTime(END_OF_TIME)
          .setParent(historyEntryDomainRenew)
          .build());
  // There should only be the new autorenew poll message, as the old one will have been deleted
  // since it had no messages left to deliver.
  assertPollMessages(
      new PollMessage.Autorenew.Builder()
          .setTargetId(getUniqueIdFromCommand())
          .setClientId("TheRegistrar")
          .setEventTime(domain.getRegistrationExpirationTime())
          .setAutorenewEndTime(END_OF_TIME)
          .setMsg("Domain was auto-renewed.")
          .setParent(historyEntryDomainRenew)
          .build());
  assertGracePeriods(
      domain.getGracePeriods(),
      ImmutableMap.of(
          GracePeriod.create(
              GracePeriodStatus.RENEW,
              clock.nowUtc().plus(Registry.get("tld").getRenewGracePeriodLength()),
              renewalClientId,
              null),
          renewBillingEvent));
}
 
Example 18
@Test
public void testSuccess_expiryInPast_extendedByOneYear() throws Exception {
  setEppInput("domain_update_restore_request.xml", ImmutableMap.of("DOMAIN", "example.tld"));
  DateTime expirationTime = clock.nowUtc().minusDays(20);
  DateTime newExpirationTime = expirationTime.plusYears(1);
  persistPendingDeleteDomain(expirationTime);
  assertTransactionalFlow(true);
  // Double check that we see a poll message in the future for when the delete happens.
  assertThat(getPollMessages("TheRegistrar", clock.nowUtc().plusMonths(1))).hasSize(1);
  runFlowAssertResponse(loadFile("generic_success_response.xml"));
  DomainBase domain = reloadResourceByForeignKey();
  HistoryEntry historyEntryDomainRestore =
      getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_RESTORE);
  assertThat(ofy().load().key(domain.getAutorenewBillingEvent()).now().getEventTime())
      .isEqualTo(newExpirationTime);
  assertAboutDomains()
      .that(domain)
      // New expiration time should be exactly a year from now.
      .hasRegistrationExpirationTime(newExpirationTime)
      .and()
      .doesNotHaveStatusValue(StatusValue.PENDING_DELETE)
      .and()
      .hasDeletionTime(END_OF_TIME)
      .and()
      .hasOneHistoryEntryEachOfTypes(
          HistoryEntry.Type.DOMAIN_DELETE, HistoryEntry.Type.DOMAIN_RESTORE)
      .and()
      .hasLastEppUpdateTime(clock.nowUtc())
      .and()
      .hasLastEppUpdateClientId("TheRegistrar");
  assertThat(domain.getGracePeriods()).isEmpty();
  assertDnsTasksEnqueued("example.tld");
  // The poll message for the delete should now be gone. The only poll message should be the new
  // autorenew poll message.
  assertPollMessages(
      "TheRegistrar",
      new PollMessage.Autorenew.Builder()
          .setTargetId("example.tld")
          .setClientId("TheRegistrar")
          .setEventTime(domain.getRegistrationExpirationTime())
          .setAutorenewEndTime(END_OF_TIME)
          .setMsg("Domain was auto-renewed.")
          .setParent(historyEntryDomainRestore)
          .build());
  // There should be a bill for the restore and an explicit renew, along with a new recurring
  // autorenew event.
  assertBillingEvents(
      new BillingEvent.Recurring.Builder()
          .setReason(Reason.RENEW)
          .setFlags(ImmutableSet.of(Flag.AUTO_RENEW))
          .setTargetId("example.tld")
          .setClientId("TheRegistrar")
          .setEventTime(newExpirationTime)
          .setRecurrenceEndTime(END_OF_TIME)
          .setParent(historyEntryDomainRestore)
          .build(),
      new BillingEvent.OneTime.Builder()
          .setReason(Reason.RESTORE)
          .setTargetId("example.tld")
          .setClientId("TheRegistrar")
          .setCost(Money.of(USD, 17))
          .setPeriodYears(1)
          .setEventTime(clock.nowUtc())
          .setBillingTime(clock.nowUtc())
          .setParent(historyEntryDomainRestore)
          .build(),
      new BillingEvent.OneTime.Builder()
          .setReason(Reason.RENEW)
          .setTargetId("example.tld")
          .setClientId("TheRegistrar")
          .setCost(Money.of(USD, 11))
          .setPeriodYears(1)
          .setEventTime(clock.nowUtc())
          .setBillingTime(clock.nowUtc())
          .setParent(historyEntryDomainRestore)
          .build());
}
 
Example 19
Source Project: beam   File: CalendarWindows.java    License: Apache License 2.0 3 votes vote down vote up
@Override
public IntervalWindow assignWindow(Instant timestamp) {
  DateTime datetime = new DateTime(timestamp, timeZone);

  DateTime offsetStart = startDate.withMonthOfYear(monthOfYear).withDayOfMonth(dayOfMonth);

  int yearOffset = Years.yearsBetween(offsetStart, datetime).getYears() / number * number;

  DateTime begin = offsetStart.plusYears(yearOffset);
  DateTime end = begin.plusYears(number);

  return new IntervalWindow(begin.toInstant(), end.toInstant());
}
 
Example 20
@Test
public void add_years_to_date_in_java_joda () {

	DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
	DateTime fortyNinersSuck = superBowlXLV.plusYears(2);

	DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
	
	logger.info(superBowlXLV.toString(fmt));
	logger.info(fortyNinersSuck.toString(fmt));

	assertTrue(fortyNinersSuck.isAfter(superBowlXLV));
}