Example usage for org.joda.time DateTime plus

List of usage examples for org.joda.time DateTime plus

Introduction

In this page you can find the example usage for org.joda.time DateTime plus.

Prototype

public DateTime plus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period added.

Usage

From source file:google.registry.rde.EscrowTaskRunner.java

License:Open Source License

/**
 * Acquires lock, checks cursor, invokes {@code task}, and advances cursor.
 *
 * @param task the task to run//from   ww  w  . j  a  v a2  s .  c  o m
 * @param registry the {@link Registry} that we are performing escrow for
 * @param timeout time when we assume failure, kill the task (and instance) and release the lock
 * @param cursorType the cursor to advance on success, indicating the next required runtime
 * @param interval how far to advance the cursor (e.g. a day for RDE, a week for BRDA)
 */
void lockRunAndRollForward(final EscrowTask task, final Registry registry, Duration timeout,
        final CursorType cursorType, final Duration interval) {
    Callable<Void> lockRunner = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            logger.info("tld=" + registry.getTld());
            DateTime startOfToday = clock.nowUtc().withTimeAtStartOfDay();
            Cursor cursor = ofy().load().key(Cursor.createKey(cursorType, registry)).now();
            final DateTime nextRequiredRun = (cursor == null ? startOfToday : cursor.getCursorTime());
            if (nextRequiredRun.isAfter(startOfToday)) {
                throw new NoContentException("Already completed");
            }
            logger.info("cursor=" + nextRequiredRun);
            task.runWithLock(nextRequiredRun);
            ofy().transact(new VoidWork() {
                @Override
                public void vrun() {
                    ofy().save().entity(Cursor.create(cursorType, nextRequiredRun.plus(interval), registry));
                }
            });
            return null;
        }
    };
    String lockName = String.format("%s %s", task.getClass().getSimpleName(), registry.getTld());
    if (!Lock.executeWithLocks(lockRunner, null, tld, timeout, lockName)) {
        // This will happen if either: a) the task is double-executed; b) the task takes a long time
        // to run and the retry task got executed while the first one is still running. In both
        // situations the safest thing to do is to just return 503 so the task gets retried later.
        throw new ServiceUnavailableException("Lock in use: " + lockName);
    }
}

From source file:google.registry.rde.RdeUploadAction.java

License:Open Source License

@Override
public void runWithLock(final DateTime watermark) throws Exception {
    DateTime stagingCursorTime = getCursorTimeOrStartOfTime(
            ofy().load().key(Cursor.createKey(CursorType.RDE_STAGING, Registry.get(tld))).now());
    if (!stagingCursorTime.isAfter(watermark)) {
        logger.infofmt("tld=%s uploadCursor=%s stagingCursor=%s", tld, watermark, stagingCursorTime);
        throw new ServiceUnavailableException("Waiting for RdeStagingAction to complete");
    }/*from   w  ww.  j  av  a  2  s  .c  om*/
    DateTime sftpCursorTime = getCursorTimeOrStartOfTime(
            ofy().load().key(Cursor.createKey(CursorType.RDE_UPLOAD_SFTP, Registry.get(tld))).now());
    if (sftpCursorTime.plus(sftpCooldown).isAfter(clock.nowUtc())) {
        // Fail the task good and hard so it retries until the cooldown passes.
        logger.infofmt("tld=%s cursor=%s sftpCursor=%s", tld, watermark, sftpCursorTime);
        throw new ServiceUnavailableException("SFTP cooldown has not yet passed");
    }
    int revision = RdeRevision.getNextRevision(tld, watermark, FULL) - 1;
    verify(revision >= 0, "RdeRevision was not set on generated deposit");
    final String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision);
    final GcsFilename xmlFilename = new GcsFilename(bucket, name + ".xml.ghostryde");
    final GcsFilename xmlLengthFilename = new GcsFilename(bucket, name + ".xml.length");
    GcsFilename reportFilename = new GcsFilename(bucket, name + "-report.xml.ghostryde");
    verifyFileExists(xmlFilename);
    verifyFileExists(xmlLengthFilename);
    verifyFileExists(reportFilename);
    final long xmlLength = readXmlLength(xmlLengthFilename);
    retrier.callWithRetry(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            upload(xmlFilename, xmlLength, watermark, name);
            return null;
        }
    }, JSchException.class);
    ofy().transact(new VoidWork() {
        @Override
        public void vrun() {
            Cursor cursor = Cursor.create(CursorType.RDE_UPLOAD_SFTP, ofy().getTransactionTime(),
                    Registry.get(tld));
            ofy().save().entity(cursor).now();
        }
    });
    response.setContentType(PLAIN_TEXT_UTF_8);
    response.setPayload(String.format("OK %s %s\n", tld, watermark));
}

From source file:google.registry.testing.DatastoreHelper.java

License:Open Source License

public static BillingEvent.OneTime createBillingEventForTransfer(DomainResource domain,
        HistoryEntry historyEntry, DateTime costLookupTime, DateTime eventTime,
        Integer extendedRegistrationYears) {
    return new BillingEvent.OneTime.Builder().setReason(Reason.TRANSFER)
            .setTargetId(domain.getFullyQualifiedDomainName()).setEventTime(eventTime)
            .setBillingTime(eventTime.plus(Registry.get(domain.getTld()).getTransferGracePeriodLength()))
            .setClientId("NewRegistrar").setPeriodYears(extendedRegistrationYears)
            .setCost(getDomainRenewCost(domain.getFullyQualifiedDomainName(), costLookupTime,
                    extendedRegistrationYears))
            .setParent(historyEntry).build();
}

From source file:google.registry.testing.DatastoreHelper.java

License:Open Source License

public static ContactResource persistContactWithPendingTransfer(ContactResource contact, DateTime requestTime,
        DateTime expirationTime, DateTime now) {
    HistoryEntry historyEntryContactTransfer = persistResource(new HistoryEntry.Builder()
            .setType(HistoryEntry.Type.CONTACT_TRANSFER_REQUEST).setParent(contact).build());
    return persistResource(contact.asBuilder().setCurrentSponsorClientId("TheRegistrar")
            .addStatusValue(StatusValue.PENDING_TRANSFER)
            .setTransferData(createTransferDataBuilder(requestTime, expirationTime)
                    .setPendingTransferExpirationTime(now.plus(CONTACT_AUTOMATIC_TRANSFER_LENGTH))
                    .setServerApproveEntities(ImmutableSet.<Key<? extends TransferServerApproveEntity>>of(
                            // Pretend it's 3 days since the request
                            Key.create(persistResource(
                                    createPollMessageForImplicitTransfer(contact, historyEntryContactTransfer,
                                            "NewRegistrar", requestTime, expirationTime, now))),
                            Key.create(persistResource(
                                    createPollMessageForImplicitTransfer(contact, historyEntryContactTransfer,
                                            "TheRegistrar", requestTime, expirationTime, now)))))
                    .setTransferRequestTrid(Trid.create("transferClient-trid", "transferServer-trid")).build())
            .build());/*from w  w w . ja  v a 2s. c o m*/
}

From source file:io.cassandrareaper.service.ClusterRepairScheduler.java

License:Apache License

private DateTime nextActivationStartDate(int scheduleIndex) {
    DateTime timeBeforeFirstSchedule = DateTime.now()
            .plus(context.config.getAutoScheduling().getTimeBeforeFirstSchedule().toMillis());

    if (context.config.getAutoScheduling().hasScheduleSpreadPeriod()) {
        return timeBeforeFirstSchedule
                .plus(scheduleIndex * context.config.getAutoScheduling().getScheduleSpreadPeriod().toMillis());
    }/*from www. j a  va2  s .  co m*/
    return timeBeforeFirstSchedule;
}

From source file:io.coala.time.AbstractInstant.java

License:Apache License

/** @seeInstant#toDateTime(DateTime) */
@Override//from   w ww.  jav a 2 s  .  com
public DateTime toDateTime(final DateTime offset) {
    return offset.plus(getMillis());
}

From source file:io.coala.xml.XmlUtil.java

License:Apache License

/**
 * @param duration a JAXP {@link Duration}
 * @param startInstant//from  w w  w  .  j  av a  2  s.co  m
 * @return the {@link Interval}
 */
public static Interval toInterval(final Duration duration, final DateTime offset) {
    return new Interval(offset, offset.plus(duration.getTimeInMillis(offset.toDate())));
}

From source file:io.druid.indexing.jdbc.supervisor.JDBCSupervisor.java

License:Apache License

private void checkTaskDuration() throws InterruptedException, ExecutionException, TimeoutException {
    final List<ListenableFuture<Map<Integer, Long>>> futures = Lists.newArrayList();
    final List<Integer> futureGroupIds = Lists.newArrayList();

    for (Map.Entry<Integer, TaskGroup> entry : taskGroups.entrySet()) {
        Integer groupId = entry.getKey();
        TaskGroup group = entry.getValue();

        // find the longest running task from this group
        DateTime earliestTaskStart = DateTime.now();
        for (TaskData taskData : group.tasks.values()) {
            if (earliestTaskStart.isAfter(taskData.startTime)) {
                earliestTaskStart = taskData.startTime;
            }//from   ww w . j ava 2s  .c om
        }

        // if this task has run longer than the configured duration, signal all tasks in the group to persist
        if (earliestTaskStart.plus(ioConfig.getTaskDuration()).isBeforeNow()) {
            log.info("Task group [%d] has run for [%s]", groupId, ioConfig.getTaskDuration());
            futureGroupIds.add(groupId);
            futures.add(signalTasksToFinish(groupId));
        }
    }

    List<Map<Integer, Long>> results = Futures.successfulAsList(futures).get(futureTimeoutInSeconds,
            TimeUnit.SECONDS);
    log.info("checkTaskDuration results size is [%s]", results.size());
    log.info("checkTaskDuration results info is [%s]", results.toString());

    for (int j = 0; j < results.size(); j++) {
        Integer groupId = futureGroupIds.get(j);
        TaskGroup group = taskGroups.get(groupId);
        Map<Integer, Long> endOffsets = results.get(j);
        log.info("checkTaskDuration endOffsets is [%s]", endOffsets);

        if (endOffsets != null) {
            // set a timeout and put this group in pendingCompletionTaskGroups so that it can be monitored for completion
            group.completionTimeout = DateTime.now().plus(ioConfig.getCompletionTimeout());
            pendingCompletionTaskGroups.putIfAbsent(groupId, Lists.<TaskGroup>newCopyOnWriteArrayList());
            pendingCompletionTaskGroups.get(groupId).add(group);

            // set endOffsets as the next startOffsets
            for (Map.Entry<Integer, Long> entry : endOffsets.entrySet()) {
                groups.get(groupId).put(entry.getKey(), entry.getValue());
                log.info("checkTaskDuration groups info [%d], [%d]", entry.getKey(), entry.getValue());
            }
        } else {
            log.warn("All tasks in group [%s] failed to transition to publishing state, killing tasks [%s]",
                    groupId, group.taskIds());
            for (String id : group.taskIds()) {
                killTask(id);
            }
        }

        // remove this task group from the list of current task groups now that it has been handled
        log.info("TaskGroups removed by [%s]", groupId);
        taskGroups.remove(groupId);
    }
}

From source file:io.druid.indexing.kafka.supervisor.KafkaSupervisor.java

License:Apache License

private void checkTaskDuration() throws InterruptedException, ExecutionException, TimeoutException {
    final List<ListenableFuture<Map<Integer, Long>>> futures = Lists.newArrayList();
    final List<Integer> futureGroupIds = Lists.newArrayList();

    for (Map.Entry<Integer, TaskGroup> entry : taskGroups.entrySet()) {
        Integer groupId = entry.getKey();
        TaskGroup group = entry.getValue();

        // find the longest running task from this group
        DateTime earliestTaskStart = DateTime.now();
        for (TaskData taskData : group.tasks.values()) {
            if (earliestTaskStart.isAfter(taskData.startTime)) {
                earliestTaskStart = taskData.startTime;
            }/* ww w  .  jav  a 2s. c o  m*/
        }

        // if this task has run longer than the configured duration, signal all tasks in the group to persist
        if (earliestTaskStart.plus(ioConfig.getTaskDuration()).isBeforeNow()) {
            log.info("Task group [%d] has run for [%s]", groupId, ioConfig.getTaskDuration());
            futureGroupIds.add(groupId);
            futures.add(signalTasksToFinish(groupId));
        }
    }

    List<Map<Integer, Long>> results = Futures.successfulAsList(futures).get(futureTimeoutInSeconds,
            TimeUnit.SECONDS);
    for (int j = 0; j < results.size(); j++) {
        Integer groupId = futureGroupIds.get(j);
        TaskGroup group = taskGroups.get(groupId);
        Map<Integer, Long> endOffsets = results.get(j);

        if (endOffsets != null) {
            // set a timeout and put this group in pendingCompletionTaskGroups so that it can be monitored for completion
            group.completionTimeout = DateTime.now().plus(ioConfig.getCompletionTimeout());
            pendingCompletionTaskGroups.putIfAbsent(groupId, Lists.<TaskGroup>newCopyOnWriteArrayList());
            pendingCompletionTaskGroups.get(groupId).add(group);

            // set endOffsets as the next startOffsets
            for (Map.Entry<Integer, Long> entry : endOffsets.entrySet()) {
                partitionGroups.get(groupId).put(entry.getKey(), entry.getValue());
            }
        } else {
            log.warn("All tasks in group [%s] failed to transition to publishing state, killing tasks [%s]",
                    groupId, group.taskIds());
            for (String id : group.taskIds()) {
                killTask(id);
            }
        }

        // remove this task group from the list of current task groups now that it has been handled
        taskGroups.remove(groupId);
    }
}

From source file:jp.furplag.util.time.JodaPrettifier.java

License:Apache License

/**
 * Return the prettified String if the period includes specified moment.
 *
 * <pre>//  w w  w  .  j  a  v a2  s  .  co m
 * prettify(DateTime.now().minusHours(1), null, null, null, null) = "one hour ago." prettify(DateTime.now(), DateTime.now().plusYears(1), null, null, null) = "one year ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withDays(1)) = "one hour ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withMinites(10)) =
 * DateTime.now().withZone(DateTimeZone.UTC).minusHours(1).toString(DateTimeFormat.forStyle("-M"))
 *
 * <pre>
 *
 * @param then the datetime object, null means current date-time.
 * @param reference the moment of a starting point ( {@link org.joda.time.ReadableInstant} and {@link Long} specifiable ). Use {@code DateTime.now()} as a start point if {@code reference} is null.
 * @param locale the language for Localization ( {@code String} and {@code Locale} specifiable ). Use ROOT if {@code locale} is null.
 * @param limit if the moment is in the specified period, return prettified String ( {@code Period} and {@code Interval} specifiable ). Prettify all, if null.
 * @return the prettified String if the period includes specified moment. In other situation, return stringified date-time.
 */
public static String prettify(final Object then, final Object reference, final Locale locale,
        final DateTimeZone zone, final Object limit) {
    DateTime temporary = DateTimeUtils.toDT(then, zone, true);
    if (temporary == null)
        return StringUtils.EMPTY;
    DateTime ref = DateTimeUtils.toDT(reference, temporary.getZone(), true);
    if (ref == null)
        return doPrettify(temporary, null, locale);
    if (ref.isEqual(temporary))
        ref = ref.plusMillis(1);
    if (limit == null)
        return doPrettify(temporary, ref, locale);
    Interval limitter = null;
    if (Interval.class.equals(limit))
        limitter = (Interval) limit;
    if (limit instanceof Period) {
        limitter = new Interval(ref.minus((Period) limit), ref.plusMillis(1).plus((Period) limit));
    }
    if (limit instanceof BaseSingleFieldPeriod) {
        limitter = new Interval(ref.minus(new Period(limit)), ref.plusMillis(1).plus(new Period(limit)));
    }
    if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(limit.getClass()), Double.class, Float.class)) {
        limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref),
                toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref));
    } else if (BigDecimal.class.equals(limit.getClass())) {
        if (NumberUtils.compareTo((BigDecimal) limit, NumberUtils.down(limit)) == 0) {
            limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)),
                    ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1));
        } else {
            limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref),
                    toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref));
        }
    } else if (Number.class.isAssignableFrom(ClassUtils.primitiveToWrapper(limit.getClass()))) {
        limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)),
                ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1));
    }
    if (DateTime.class.equals(limit.getClass())) {
        limitter = new Interval(ref.minus(((DateTime) limit).getMillis()),
                ref.plus(((DateTime) limit).getMillis() + 1L));
    }
    if (Boolean.class.equals(limit.getClass())) {
        limitter = new Interval(temporary.minusMillis(1),
                ((Boolean) limit) ? temporary.plusMillis(1) : temporary.minusMillis(1));
    }
    if (limitter == null)
        return doPrettify(temporary, ref, locale);
    if (limitter.contains(temporary))
        return doPrettify(temporary, ref, locale);

    return toDT(temporary, GJChronology.getInstance(temporary.getZone()))
            .toString(DateTimeFormat.forStyle(isToday(temporary, temporary.getZone()) ? "-M" : "MS")
                    .withLocale(locale == null ? Locale.ROOT : locale));
}