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:org.forgerock.openidm.scheduler.impl.TaskScannerJob.java

License:CDDL license

private void performTaskOverSet(JsonValue results) throws ExecutionException {
    for (JsonValue input : results) {
        if (taskScannerContext.isCanceled()) {
            logger.info("Task '" + taskScannerContext.getTaskScanID() + "' cancelled. Terminating execution.");
            break; // Jump out quick since we've cancelled the job
        }/*from w w w .j a v a  2s .c  o m*/
        // Check if this object has a STARTED time already
        JsonValue startTime = input.get(taskScannerContext.getStartField());
        String startTimeString = null;
        if (startTime != null && !startTime.isNull()) {
            startTimeString = startTime.asString();
            DateTime startedTime = DATE_UTIL.parseTimestamp(startTimeString);

            // Skip if the startTime + interval has not been passed
            ReadablePeriod period = taskScannerContext.getRecoveryTimeout();
            DateTime expirationDate = startedTime.plus(period);
            if (expirationDate.isAfterNow()) {
                logger.debug(
                        "Object already started and has not expired. Started at: {}. Timeout: {}. Expires at: {}",
                        new Object[] { DATE_UTIL.formatDateTime(startedTime), period,
                                DATE_UTIL.formatDateTime(expirationDate) });
                continue;
            }
        }

        try {
            claimAndExecScript(input, startTimeString);
        } catch (ResourceException e) {
            throw new ExecutionException("Error during claim and execution phase", e);
        }
    }
}

From source file:org.forgerock.openidm.util.ConfigMacroUtil.java

License:Open Source License

/**
 * Handles the Time.now macro/* ww  w  .jav a  2 s  . c o m*/
 *
 * @param tokens
 *            list of tokens
 * @param iter
 *            iterator used to iterate over the list of tokens
 * @return string containing the interpolated time token
 */
private static String handleTime(List<String> tokens, Iterator<String> iter) {
    DateTime dt = new DateTime();

    // Add some amount
    if (iter.hasNext()) {
        String operationToken = iter.next();
        if (operationToken.equals("+") || operationToken.equals("-")) {
            if (iter.hasNext()) {
                String quantityToken = iter.next(); // Get the magnitude to
                                                    // add or subtract

                ReadablePeriod period = getTimePeriod(quantityToken);

                if (operationToken.equals("-")) {
                    dt = dt.minus(period);
                } else {
                    dt = dt.plus(period);
                }
            } else {
                logger.warn("Token '{}' not followed by a quantity", operationToken);
            }
        } else {
            logger.warn("Invalid token '{}', must be operator '+' or '-'", operationToken);
        }
    }

    return DATE_UTIL.formatDateTime(dt);
}

From source file:org.geant.idpextension.oidc.profile.impl.GenerateClientSecret.java

License:BSD License

/** {@inheritDoc} */
@Override/*from   w ww.  java2  s.  com*/
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
    final Long lifetime = secretExpirationPeriodStrategy != null
            ? secretExpirationPeriodStrategy.apply(profileRequestContext)
            : null;
    if (lifetime == null) {
        log.debug("{} No secret expiration period supplied, using default", getLogPrefix());
    }
    final DateTime now = DateTime.now();
    final DateTime expiration = now.plus(lifetime != null ? lifetime : defaultSecretExpirationPeriod);

    final String clientSecret = idGenerator.generateIdentifier();
    oidcResponseCtx.setClientSecret(clientSecret);
    if (expiration.isAfter(now)) {
        oidcResponseCtx.setClientSecretExpiresAt(expiration);
        log.debug("{} Created a new client secret, expiring at {}", getLogPrefix(), expiration);
    } else {
        log.debug("{} Created a new client secret, non-expiring", getLogPrefix());
    }
}

From source file:org.graylog.plugins.pipelineprocessor.ast.expressions.AdditionExpression.java

License:Open Source License

@Nullable
@Override//w  w  w  .  jav a 2 s .  c om
public Object evaluateUnsafe(EvaluationContext context) {
    final Object leftValue = left.evaluateUnsafe(context);
    final Object rightValue = right.evaluateUnsafe(context);

    // special case for date arithmetic
    final boolean leftDate = DateTime.class.equals(leftValue.getClass());
    final boolean leftPeriod = Period.class.equals(leftValue.getClass());
    final boolean rightDate = DateTime.class.equals(rightValue.getClass());
    final boolean rightPeriod = Period.class.equals(rightValue.getClass());

    if (leftDate && rightPeriod) {
        final DateTime date = (DateTime) leftValue;
        final Period period = (Period) rightValue;

        return isPlus() ? date.plus(period) : date.minus(period);
    } else if (leftPeriod && rightDate) {
        final DateTime date = (DateTime) rightValue;
        final Period period = (Period) leftValue;

        return isPlus() ? date.plus(period) : date.minus(period);
    } else if (leftPeriod && rightPeriod) {
        final Period period1 = (Period) leftValue;
        final Period period2 = (Period) rightValue;

        return isPlus() ? period1.plus(period2) : period1.minus(period2);
    } else if (leftDate && rightDate) {
        // the most uncommon, this is only defined for - really and means "interval between them"
        // because adding two dates makes no sense
        if (isPlus()) {
            // makes no sense to compute and should be handles in the parser already
            return null;
        }
        final DateTime left = (DateTime) leftValue;
        final DateTime right = (DateTime) rightValue;

        if (left.isBefore(right)) {
            return new Duration(left, right);
        } else {
            return new Duration(right, left);
        }
    }
    if (isIntegral()) {
        final long l = (long) leftValue;
        final long r = (long) rightValue;
        if (isPlus) {
            return l + r;
        } else {
            return l - r;
        }
    } else {
        final double l = (double) leftValue;
        final double r = (double) rightValue;
        if (isPlus) {
            return l + r;
        } else {
            return l - r;
        }
    }
}

From source file:org.hawkular.metrics.core.jobs.CompressData.java

License:Apache License

@Override
public Completable call(JobDetails jobDetails) {
    Duration runtimeBlockSize = blockSize;
    DateTime timeSliceInclusive;/*from  w w w.  j a  va 2 s  .c o  m*/

    Trigger trigger = jobDetails.getTrigger();
    if (trigger instanceof RepeatingTrigger) {
        if (!enabled) {
            return Completable.complete();
        }
        timeSliceInclusive = new DateTime(trigger.getTriggerTime(), DateTimeZone.UTC).minus(runtimeBlockSize);
    } else {
        if (jobDetails.getParameters().containsKey(TARGET_TIME)) {
            // DateTime parsing fails without casting to Long first
            Long parsedMillis = Long.valueOf(jobDetails.getParameters().get(TARGET_TIME));
            timeSliceInclusive = new DateTime(parsedMillis, DateTimeZone.UTC);
        } else {
            logger.error("Missing " + TARGET_TIME + " parameter from manual execution of " + JOB_NAME + " job");
            return Completable.complete();
        }

        if (jobDetails.getParameters().containsKey(BLOCK_SIZE)) {
            java.time.Duration parsedDuration = java.time.Duration
                    .parse(jobDetails.getParameters().get(BLOCK_SIZE));
            runtimeBlockSize = Duration.millis(parsedDuration.toMillis());
        }
    }

    // Rewind to previous timeslice
    DateTime timeSliceStart = DateTimeService.getTimeSlice(timeSliceInclusive, runtimeBlockSize);
    long startOfSlice = timeSliceStart.getMillis();
    long endOfSlice = timeSliceStart.plus(runtimeBlockSize).getMillis() - 1;

    Stopwatch stopwatch = Stopwatch.createStarted();
    logger.info("Starting compression of timestamps (UTC) between " + startOfSlice + " - " + endOfSlice);

    Observable<? extends MetricId<?>> metricIds = metricsService.findAllMetrics().map(Metric::getMetricId)
            .filter(m -> (m.getType() == GAUGE || m.getType() == COUNTER || m.getType() == AVAILABILITY));

    PublishSubject<Metric<?>> subject = PublishSubject.create();
    subject.subscribe(metric -> {
        try {
            this.metricsService.updateMetricExpiration(metric.getMetricId());
        } catch (Exception e) {
            logger.error("Could not update the metric expiration index for metric " + metric.getId()
                    + " of tenant " + metric.getTenantId());
        }
    });

    // Fetch all partition keys and compress the previous timeSlice
    // TODO Optimization - new worker per token - use parallelism in Cassandra (with configured parallelism)
    return metricsService.compressBlock(metricIds, startOfSlice, endOfSlice, pageSize, subject).doOnError(t -> {
        subject.onCompleted();
        logger.warn("Failed to compress data", t);
    }).doOnCompleted(() -> {
        subject.onCompleted();
        stopwatch.stop();
        logger.info("Finished compressing data in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    });
}

From source file:org.hawkular.metrics.tasks.impl.TaskServiceImpl.java

License:Apache License

@Override
public Observable<Task> scheduleTask(DateTime time, Task task) {
    TaskType taskType = findTaskType(task.getTaskType().getName());

    DateTime currentTimeSlice = dateTimeService.getTimeSlice(time, task.getInterval());
    DateTime timeSlice = currentTimeSlice.plus(task.getInterval());

    return scheduleTaskAt(timeSlice, task).map(scheduledTime -> new TaskImpl(task.getTaskType(), scheduledTime,
            task.getTarget(), task.getSources(), task.getInterval(), task.getWindow()));
}

From source file:org.integratedmodelling.time.literals.DurationValue.java

License:Open Source License

/**
 * Localize a duration to an extent starting at the current moment
 * using the same resolution that was implied in the generating 
 * text. For example, if the duration was one year, localize to the 
 * current year (jan 1st to dec 31st). Return the start and end points
 * of the extent./*from  w ww.  j a va  2 s  .  c  o  m*/
 * 
 * @return
 */
public Pair<TimeValue, TimeValue> localize() {

    DateTime date = new DateTime();
    TimeValue start = null, end = null;
    long val = value;

    switch (precision) {

    case TemporalPrecision.MILLISECOND:
        start = new TimeValue(date);
        end = new TimeValue(date.plus(val));
        break;
    case TemporalPrecision.SECOND:
        val = value / DateTimeConstants.MILLIS_PER_SECOND;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), date.getMinuteOfHour(), date.getSecondOfMinute(), 0));
        end = new TimeValue(start.getTimeData().plusSeconds((int) val));
        break;
    case TemporalPrecision.MINUTE:
        val = value / DateTimeConstants.MILLIS_PER_MINUTE;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), date.getMinuteOfHour(), 0, 0));
        end = new TimeValue(start.getTimeData().plusMinutes((int) val));
        break;
    case TemporalPrecision.HOUR:
        val = value / DateTimeConstants.MILLIS_PER_HOUR;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusHours((int) val));
        break;
    case TemporalPrecision.DAY:
        val = value / DateTimeConstants.MILLIS_PER_DAY;
        start = new TimeValue(
                new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusDays((int) val));
        break;
    case TemporalPrecision.MONTH:
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusMonths(origQuantity));
        break;
    case TemporalPrecision.YEAR:
        start = new TimeValue(new DateTime(date.getYear(), 1, 1, 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusYears(origQuantity));
        break;
    }

    return new Pair<TimeValue, TimeValue>(start, end);
}

From source file:org.isisaddons.module.fakedata.dom.JodaDateTimes.java

License:Apache License

@Programmatic
public DateTime after(final Period period) {
    final DateTime now = fake.clockService.nowAsDateTime();
    return now.plus(period);
}

From source file:org.jasig.cas.client.validation.Saml11TicketValidator.java

License:Apache License

private boolean isValidAssertion(final org.opensaml.saml1.core.Assertion assertion) {
    final DateTime notBefore = assertion.getConditions().getNotBefore();
    final DateTime notOnOrAfter = assertion.getConditions().getNotOnOrAfter();

    if (notBefore == null || notOnOrAfter == null) {
        logger.debug("Assertion has no bounding dates. Will not process.");
        return false;
    }//from w w  w.  j  a  va  2 s.co  m

    final DateTime currentTime = new DateTime(DateTimeZone.UTC);
    final Interval validityRange = new Interval(notBefore.minus(this.tolerance),
            notOnOrAfter.plus(this.tolerance));

    if (validityRange.contains(currentTime)) {
        logger.debug("Current time is within the interval validity.");
        return true;
    }

    if (currentTime.isBefore(validityRange.getStart())) {
        logger.debug("skipping assertion that's not yet valid...");
        return false;
    }

    logger.debug("skipping expired assertion...");
    return false;
}

From source file:org.jasig.cas.support.saml.util.Saml10ObjectBuilder.java

License:Apache License

/**
 * New conditions element./*from w  w w. ja  v a  2s. c o  m*/
 *
 * @param issuedAt the issued at
 * @param audienceUri the service id
 * @param issueLength the issue length
 * @return the conditions
 */
public Conditions newConditions(final DateTime issuedAt, final String audienceUri, final long issueLength) {
    final Conditions conditions = newSamlObject(Conditions.class);
    conditions.setNotBefore(issuedAt);
    conditions.setNotOnOrAfter(issuedAt.plus(issueLength));
    final AudienceRestrictionCondition audienceRestriction = newSamlObject(AudienceRestrictionCondition.class);
    final Audience audience = newSamlObject(Audience.class);
    audience.setUri(audienceUri);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictionConditions().add(audienceRestriction);
    return conditions;
}