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:fi.okm.mpass.idp.authn.impl.ValidateOIDCIDTokenAuthenticationTime.java

License:Open Source License

/** {@inheritDoc} */
@Override//  w  ww  . j  av a2s . com
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {
    log.trace("Entering");

    if (!authenticationContext.isForceAuthn()) {
        log.trace("Leaving");
        return;
    }
    // If we have forced authentication, we will check for authentication age
    final SocialUserOpenIdConnectContext suCtx = authenticationContext
            .getSubcontext(SocialUserOpenIdConnectContext.class);
    if (suCtx == null) {
        log.error("{} Not able to find su oidc context", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        log.trace("Leaving");
        return;
    }
    final Date authTimeDate;
    try {
        authTimeDate = suCtx.getIDToken().getJWTClaimsSet().getDateClaim("auth_time");
    } catch (ParseException e) {
        log.error("{} Error parsing id token", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        log.trace("Leaving");
        return;
    }
    if (authTimeDate == null) {
        log.error("{} max age set but no auth_time received", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        log.trace("Leaving");
        return;
    }
    final DateTime authTime = new DateTime(authTimeDate);
    final DateTime now = new DateTime();
    final DateTime latestValid = now.plus(getClockSkew());
    final DateTime expiration = authTime.plus(getClockSkew() + getAuthnLifetime());

    // Check authentication wasn't performed in the future
    // Based on org.opensaml.saml.common.binding.security.impl.MessageLifetimeSecurityHandler
    if (authTime.isAfter(latestValid)) {
        log.warn("{} Authentication time was not yet valid: time was {}, latest valid is: {}", getLogPrefix(),
                authTime, latestValid);
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        log.trace("Leaving");
        return;
    }

    // Check authentication time has not expired
    if (expiration.isBefore(now)) {
        log.warn("{} Authentication time was expired: time was '{}', expired at: '{}', current time: '{}'",
                getLogPrefix(), authTime, expiration, now);
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        log.trace("Leaving");
        return;
    }
    log.trace("Leaving");
}

From source file:fi.vm.sade.osoitepalvelu.kooste.service.koodisto.DefaultKoodistoService.java

License:EUPL

private boolean isCacheUsable(DateTime updatedAt) {
    return updatedAt.plus(cacheTimeoutSeconds * MILLIS_IN_SECOND).compareTo(new DateTime()) > 0;
}

From source file:fi.vm.sade.osoitepalvelu.kooste.service.organisaatio.DefaultOrganisaatioService.java

License:EUPL

private boolean isCacheUsable(DateTime updatedAt, DateTime now) {
    return updatedAt.plus(cacheTimeoutSeconds * MILLIS_IN_SECOND).compareTo(now) > 0
            && updatedAt.isAfter(OrganisaatioDetails.MODEL_CHANGED_AT);
}

From source file:fi.vm.sade.osoitepalvelu.kooste.webapp.OrganisaatioCacheHealthCheck.java

License:EUPL

private boolean isCacheUsable(DateTime updatedAt) {
    return updatedAt.plus((cacheTimeoutSeconds) * MILLIS_IN_SECOND).plusHours(2).compareTo(new DateTime()) > 0;
}

From source file:fr.mby.saml2.sp.opensaml.core.OpenSaml20IdpConnector.java

License:Apache License

/**
 * Build the NotOnOrAfter time considering the time validity window parameter.
 * //from   w  w w  . j  av a  2  s  . c om
 * @param issueInstant
 *            the request issue instant
 * @return the NotOnOrAfter time
 */
protected DateTime buildNotOnOrAfterTime(final DateTime issueInstant) {
    return issueInstant.plus(this.idpConfig.getTimeValidityWindow());
}

From source file:fr.norad.visuwall.providers.bamboo.Bamboo.java

License:Apache License

public Date getEstimatedFinishTime(String planKey)
        throws BambooPlanNotFoundException, BambooEstimatedFinishTimeNotFoundException {
    checkPlanKey(planKey);/*  w  w w .  j  a  v a 2  s .c o m*/
    try {
        Result result = getLastResult(planKey);
        Date startTime = result.getBuildStartedTime();
        long duration = getAverageBuildDurationTime(planKey);
        DateTime startDate = new DateTime(startTime.getTime());
        DateTime estimatedFinishTime = startDate.plus(duration * 1000);
        return estimatedFinishTime.toDate();
    } catch (BambooResultNotFoundException e) {
        throw new BambooEstimatedFinishTimeNotFoundException(
                "Can't find estimated finish time of plan:" + planKey, e);
    }
}

From source file:fr.norad.visuwall.providers.hudson.Hudson.java

License:Apache License

/**
 * @param jobName//from   w ww.ja v  a  2s. c om
 * @return Date which we think the project will finish to build
 * @throws HudsonJobNotFoundException
 */
public Date getEstimatedFinishTime(String jobName) throws HudsonJobNotFoundException {
    checkJobName(jobName);
    try {
        HudsonJob hudsonJob = hudsonFinder.findJob(jobName);
        HudsonBuild currentBuild = hudsonFinder.getCurrentBuild(jobName);
        if (currentBuild == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(jobName + " has no current build");
            }
            return new Date();
        }
        long averageBuildDurationTime = computeBuildDurationTime(hudsonJob);
        Date startTime = currentBuild.getStartTime();
        if (startTime == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(currentBuild + " has no start time");
            }
            return new Date();
        }
        long time = startTime.getTime();
        DateTime dateTime = new DateTime(time);
        DateTime estimatedFinishTime = dateTime.plus(averageBuildDurationTime);
        return estimatedFinishTime.toDate();
    } catch (HudsonBuildNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Can't find estimated finish time of job: " + jobName, e);
        }
    }
    return new Date();
}

From source file:gobblin.data.management.retention.policy.TimeBasedRetentionPolicy.java

License:Apache License

/**
 * Since months and years can have arbitrary days, joda time does not allow conversion of a period string containing
 * months or years to a duration. Hence we calculate the duration using 1970 01:01:00:00:00 UTC as a reference time.
 *
 * <p>/*w  w  w  . j  a v a2s. c  om*/
 * <code>
 * (1970 01:01:00:00:00 + P2Y) - 1970 01:01:00:00:00 = Duration for 2 years
 * </code>
 * </p>
 *
 * @param periodString
 * @return duration for this period.
 */
private static Duration parseDuration(String periodString) {
    DateTime zeroEpoc = new DateTime(0);
    return new Duration(zeroEpoc, zeroEpoc.plus(ISOPeriodFormat.standard().parsePeriod(periodString)));
}

From source file:google.registry.flows.contact.ContactTransferRequestFlow.java

License:Open Source License

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(MetadataExtension.class);
    extensionManager.validate();/*from  w w w . j  a v a2s.c om*/
    validateClientIsLoggedIn(gainingClientId);
    DateTime now = ofy().getTransactionTime();
    ContactResource existingContact = loadAndVerifyExistence(ContactResource.class, targetId, now);
    verifyAuthInfoPresentForResourceTransfer(authInfo);
    verifyAuthInfo(authInfo.get(), existingContact);
    // Verify that the resource does not already have a pending transfer.
    if (TransferStatus.PENDING.equals(existingContact.getTransferData().getTransferStatus())) {
        throw new AlreadyPendingTransferException(targetId);
    }
    String losingClientId = existingContact.getCurrentSponsorClientId();
    // Verify that this client doesn't already sponsor this resource.
    if (gainingClientId.equals(losingClientId)) {
        throw new ObjectAlreadySponsoredException();
    }
    verifyNoDisallowedStatuses(existingContact, DISALLOWED_STATUSES);
    HistoryEntry historyEntry = historyBuilder.setType(HistoryEntry.Type.CONTACT_TRANSFER_REQUEST)
            .setModificationTime(now).setParent(Key.create(existingContact)).build();
    DateTime transferExpirationTime = now.plus(automaticTransferLength);
    TransferData serverApproveTransferData = new TransferData.Builder().setTransferRequestTime(now)
            .setTransferRequestTrid(trid).setGainingClientId(gainingClientId).setLosingClientId(losingClientId)
            .setPendingTransferExpirationTime(transferExpirationTime)
            .setTransferStatus(TransferStatus.SERVER_APPROVED).build();
    // If the transfer is server approved, this message will be sent to the losing registrar. */
    PollMessage serverApproveLosingPollMessage = createLosingTransferPollMessage(targetId,
            serverApproveTransferData, historyEntry);
    // If the transfer is server approved, this message will be sent to the gaining registrar. */
    PollMessage serverApproveGainingPollMessage = createGainingTransferPollMessage(targetId,
            serverApproveTransferData, historyEntry);
    TransferData pendingTransferData = serverApproveTransferData.asBuilder()
            .setTransferStatus(TransferStatus.PENDING)
            .setServerApproveEntities(ImmutableSet.<Key<? extends TransferData.TransferServerApproveEntity>>of(
                    Key.create(serverApproveGainingPollMessage), Key.create(serverApproveLosingPollMessage)))
            .build();
    // When a transfer is requested, a poll message is created to notify the losing registrar.
    PollMessage requestPollMessage = createLosingTransferPollMessage(targetId, pendingTransferData,
            historyEntry).asBuilder().setEventTime(now) // Unlike the serverApprove messages, this applies immediately.
                    .build();
    ContactResource newContact = existingContact.asBuilder().setTransferData(pendingTransferData)
            .addStatusValue(StatusValue.PENDING_TRANSFER).build();
    ofy().save().<Object>entities(newContact, historyEntry, requestPollMessage, serverApproveGainingPollMessage,
            serverApproveLosingPollMessage);
    return responseBuilder.setResultFromCode(SUCCESS_WITH_ACTION_PENDING)
            .setResData(createTransferResponse(targetId, newContact.getTransferData())).build();
}

From source file:google.registry.flows.domain.DomainAllocateFlow.java

License:Open Source License

private BillingEvent.OneTime createOneTimeBillingEvent(DomainApplication application, HistoryEntry historyEntry,
        boolean isSunrushAddGracePeriod, Registry registry, DateTime now, int years) {
    return new BillingEvent.OneTime.Builder().setReason(Reason.CREATE)
            .setFlags(ImmutableSet.of(Flag.ALLOCATION,
                    application.getEncodedSignedMarks().isEmpty() ? Flag.LANDRUSH : Flag.SUNRISE))
            .setTargetId(targetId).setClientId(clientId)
            // Note that the cost is calculated as of now, i.e. the event time, not the billing time,
            // which may be some additional days into the future.
            .setCost(getDomainCreateCost(targetId, now, years)).setPeriodYears(years).setEventTime(now)
            // If there are no nameservers on the domain, then they get the benefit of the sunrush
            // add grace period, which is longer than the standard add grace period.
            .setBillingTime(now.plus(isSunrushAddGracePeriod ? registry.getSunrushAddGracePeriodLength()
                    : registry.getAddGracePeriodLength()))
            .setParent(historyEntry).build();
}