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.opensaml.saml.metadata.resolver.impl.AbstractDynamicMetadataResolver.java

License:Open Source License

/**
 * Compute the refresh trigger time./*from   w ww  .j  a  v  a  2 s  .co  m*/
 * 
 * @param expirationTime the time at which the metadata effectively expires
 * @param nowDateTime the current date time instant
 * 
 * @return the time after which refresh attempt(s) should be made
 */
@Nonnull
protected DateTime computeRefreshTriggerTime(@Nullable final DateTime expirationTime,
        @Nonnull final DateTime nowDateTime) {

    DateTime nowDateTimeUTC = nowDateTime.toDateTime(ISOChronology.getInstanceUTC());
    long now = nowDateTimeUTC.getMillis();

    long expireInstant = 0;
    if (expirationTime != null) {
        expireInstant = expirationTime.toDateTime(ISOChronology.getInstanceUTC()).getMillis();
    }
    long refreshDelay = (long) ((expireInstant - now) * getRefreshDelayFactor());

    // if the expiration time was null or the calculated refresh delay was less than the floor
    // use the floor
    if (refreshDelay < getMinCacheDuration()) {
        refreshDelay = getMinCacheDuration();
    }

    return nowDateTimeUTC.plus(refreshDelay);
}

From source file:org.opensaml.saml.metadata.resolver.impl.AbstractReloadingMetadataResolver.java

License:Open Source License

/**
 * Processes a cached metadata document in order to determine, and schedule, the next time it should be refreshed.
 * //from w w  w . java  2 s .  c  om
 * @param metadataIdentifier identifier of the metadata source
 * @param refreshStart when the current refresh cycle started
 * 
 * @throws ResolverException throw is there is a problem process the cached metadata
 */
protected void processCachedMetadata(String metadataIdentifier, DateTime refreshStart)
        throws ResolverException {
    log.debug("Computing new expiration time for cached metadata from '{}", metadataIdentifier);
    DateTime metadataExpirationTime = SAML2Support.getEarliestExpiration(
            getBackingStore().getCachedOriginalMetadata(), refreshStart.plus(getMaxRefreshDelay()),
            refreshStart);

    expirationTime = metadataExpirationTime;
    long nextRefreshDelay = computeNextRefreshDelay(expirationTime);
    nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay);
}

From source file:org.opensaml.saml.metadata.resolver.impl.AbstractReloadingMetadataResolver.java

License:Open Source License

/**
 * Processes metadata that has been determined to be valid at the time it was fetched. A metadata document is
 * considered to be valid if its root element returns true when passed to the {@link #isValid(XMLObject)} method.
 * /*  www  .j  a v a 2 s  .  c om*/
 * @param metadataIdentifier identifier of the metadata source
 * @param refreshStart when the current refresh cycle started
 * @param metadataBytes raw bytes of the new metadata document
 * @param metadata new metadata document unmarshalled
 * 
 * @throws ResolverException thrown if there s a problem processing the metadata
 */
protected void processNonExpiredMetadata(String metadataIdentifier, DateTime refreshStart, byte[] metadataBytes,
        XMLObject metadata) throws ResolverException {
    Document metadataDom = metadata.getDOM().getOwnerDocument();

    log.debug("Preprocessing metadata from '{}'", metadataIdentifier);
    BatchEntityBackingStore newBackingStore = null;
    try {
        newBackingStore = preProcessNewMetadata(metadata);
    } catch (FilterException e) {
        String errMsg = "Error filtering metadata from " + metadataIdentifier;
        log.error(errMsg, e);
        throw new ResolverException(errMsg, e);
    }

    log.debug("Releasing cached DOM for metadata from '{}'", metadataIdentifier);
    releaseMetadataDOM(newBackingStore.getCachedOriginalMetadata());
    releaseMetadataDOM(newBackingStore.getCachedFilteredMetadata());

    log.debug("Post-processing metadata from '{}'", metadataIdentifier);
    postProcessMetadata(metadataBytes, metadataDom, newBackingStore.getCachedOriginalMetadata(),
            newBackingStore.getCachedFilteredMetadata());

    log.debug("Computing expiration time for metadata from '{}'", metadataIdentifier);
    // Note: As noted in its Javadocs, technically this method can sometimes return null, but won't in this case
    // since the candidate time (2nd arg) is not null.
    DateTime metadataExpirationTime = SAML2Support.getEarliestExpiration(
            newBackingStore.getCachedOriginalMetadata(), refreshStart.plus(getMaxRefreshDelay()), refreshStart);
    log.debug("Expiration of metadata from '{}' will occur at {}", metadataIdentifier,
            metadataExpirationTime.toString());

    // This is where the new processed data becomes effective. Exceptions thrown prior to this point
    // therefore result in the old data being kept effective.
    setBackingStore(newBackingStore);

    lastUpdate = refreshStart;

    long nextRefreshDelay;
    if (metadataExpirationTime.isBeforeNow()) {
        expirationTime = new DateTime(ISOChronology.getInstanceUTC()).plus(getMinRefreshDelay());
        nextRefreshDelay = getMaxRefreshDelay();
    } else {
        expirationTime = metadataExpirationTime;
        nextRefreshDelay = computeNextRefreshDelay(expirationTime);
    }
    nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay);

    log.info("New metadata successfully loaded for '{}'", getMetadataIdentifier());
}

From source file:org.opensaml.saml.saml2.assertion.SAML20AssertionValidator.java

License:Open Source License

/**
 * Validates the NotBefore and NotOnOrAfter Conditions constraints on the assertion.
 * //  w  w  w.  j  a v  a  2 s .c o m
 * @param assertion the assertion whose conditions will be validated
 * @param context current validation context
 * 
 * @return the result of the validation evaluation
 * 
 * @throws AssertionValidationException thrown if there is a problem determining the validity of the conditions
 */
@Nonnull
protected ValidationResult validateConditionsTimeBounds(@Nonnull final Assertion assertion,
        @Nonnull final ValidationContext context) throws AssertionValidationException {

    Conditions conditions = assertion.getConditions();
    if (conditions == null) {
        return ValidationResult.VALID;
    }

    DateTime now = new DateTime(ISOChronology.getInstanceUTC());
    long clockSkew = getClockSkew(context);

    DateTime notBefore = conditions.getNotBefore();
    log.debug("Evaluating Conditions NotBefore '{}' against 'skewed now' time '{}'", notBefore,
            now.plus(clockSkew));
    if (notBefore != null && notBefore.isAfter(now.plus(clockSkew))) {
        context.setValidationFailureMessage(
                String.format("Assertion '%s' with NotBefore condition of '%s' is not yet valid",
                        assertion.getID(), notBefore));
        return ValidationResult.INVALID;
    }

    DateTime notOnOrAfter = conditions.getNotOnOrAfter();
    log.debug("Evaluating Conditions NotOnOrAfter '{}' against 'skewed now' time '{}'", notOnOrAfter,
            now.minus(clockSkew));
    if (notOnOrAfter != null && notOnOrAfter.isBefore(now.minus(clockSkew))) {
        context.setValidationFailureMessage(
                String.format("Assertion '%s' with NotOnOrAfter condition of '%s' is no longer valid",
                        assertion.getID(), notOnOrAfter));
        return ValidationResult.INVALID;
    }

    return ValidationResult.VALID;
}

From source file:org.opensaml.saml.saml2.common.SAML2Support.java

License:Open Source License

/**
 * Gets the earliest effective expiration instant of the specified cacheable SAML object and the specified 
 * candidate time./*from   www  .  jav  a  2s .c om*/
 * 
 * @param cacheableObject the target XMLObject to evaluate
 * @param candidateTime the candidate earliest expiration instant
 * @param now when this method was called
 * 
 * @return the earliest effective expiration instant of the 2 targets. May be null if the input candiateTime 
 *          was null, otherwise will always be non-null.
 */
@Nullable
public static DateTime getEarliestExpirationFromCacheable(@Nonnull CacheableSAMLObject cacheableObject,
        @Nullable DateTime candidateTime, @Nonnull DateTime now) {

    DateTime earliestExpiration = candidateTime;

    if (cacheableObject.getCacheDuration() != null && cacheableObject.getCacheDuration().longValue() > 0) {
        DateTime elementExpirationTime = now.plus(cacheableObject.getCacheDuration().longValue());
        if (earliestExpiration == null) {
            earliestExpiration = elementExpirationTime;
        } else {
            if (elementExpirationTime != null && elementExpirationTime.isBefore(earliestExpiration)) {
                earliestExpiration = elementExpirationTime;
            }
        }
    }

    return earliestExpiration;
}

From source file:org.opensaml.saml2.common.SAML2Helper.java

License:Open Source License

/**
 * Gets the earliest expiration instant within a metadata tree.
 * //  ww  w. j  av  a  2  s  .  c o m
 * @param xmlObject the metadata
 * @param earliestExpiration the earliest expiration instant
 * @param now when this method was called
 * 
 * @return the earliest expiration instant within a metadata tree
 */
public static DateTime getEarliestExpiration(XMLObject xmlObject, DateTime earliestExpiration, DateTime now) {

    // expiration time for a specific element
    DateTime elementExpirationTime;

    // Test duration based times
    if (xmlObject instanceof CacheableSAMLObject) {
        CacheableSAMLObject cacheInfo = (CacheableSAMLObject) xmlObject;

        if (cacheInfo.getCacheDuration() != null && cacheInfo.getCacheDuration().longValue() > 0) {
            elementExpirationTime = now.plus(cacheInfo.getCacheDuration().longValue());
            if (earliestExpiration == null) {
                earliestExpiration = elementExpirationTime;
            } else {
                if (elementExpirationTime != null && elementExpirationTime.isBefore(earliestExpiration)) {
                    earliestExpiration = elementExpirationTime;
                }
            }
        }
    }

    // Test instant based times
    if (xmlObject instanceof TimeBoundSAMLObject) {
        TimeBoundSAMLObject timeBoundObject = (TimeBoundSAMLObject) xmlObject;
        elementExpirationTime = timeBoundObject.getValidUntil();
        if (earliestExpiration == null) {
            earliestExpiration = elementExpirationTime;
        } else {
            if (elementExpirationTime != null && elementExpirationTime.isBefore(earliestExpiration)) {
                earliestExpiration = elementExpirationTime;
            }
        }
    }

    // Inspect children
    List<XMLObject> children = xmlObject.getOrderedChildren();
    if (children != null) {
        for (XMLObject child : xmlObject.getOrderedChildren()) {
            if (child != null) {
                earliestExpiration = getEarliestExpiration(child, earliestExpiration, now);
            }
        }
    }

    return earliestExpiration;
}

From source file:org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.java

License:Open Source License

/**
 * Processes a cached metadata document in order to determine, and schedule, the next time it should be refreshed.
 * /*from  ww w.  j  av  a 2 s  . c  o  m*/
 * @param metadataIdentifier identifier of the metadata source
 * @param refreshStart when the current refresh cycle started
 * 
 * @throws MetadataProviderException throw is there is a problem process the cached metadata
 */
protected void processCachedMetadata(String metadataIdentifier, DateTime refreshStart)
        throws MetadataProviderException {
    log.debug("Computing new expiration time for cached metadata from '{}", metadataIdentifier);
    DateTime metadataExpirationTime = SAML2Helper.getEarliestExpiration(cachedMetadata,
            refreshStart.plus(getMaxRefreshDelay()), refreshStart);

    expirationTime = metadataExpirationTime;
    long nextRefreshDelay = computeNextRefreshDelay(expirationTime);
    nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay);
}

From source file:org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.java

License:Open Source License

/**
 * Processes metadata that has been determined to be valid at the time it was fetched. A metadata document is
 * considered be valid if its root element returns true when passed to the {@link #isValid(XMLObject)} method.
 * /* ww w  .  j  a v  a2s.com*/
 * @param metadataIdentifier identifier of the metadata source
 * @param refreshStart when the current refresh cycle started
 * @param metadataBytes raw bytes of the new metadata document
 * @param metadata new metadata document unmarshalled
 * 
 * @throws MetadataProviderException thrown if there s a problem processing the metadata
 */
protected void processNonExpiredMetadata(String metadataIdentifier, DateTime refreshStart, byte[] metadataBytes,
        XMLObject metadata) throws MetadataProviderException {
    Document metadataDom = metadata.getDOM().getOwnerDocument();

    log.debug("Filtering metadata from '{}'", metadataIdentifier);
    try {
        filterMetadata(metadata);
    } catch (FilterException e) {
        String errMsg = "Error filtering metadata from " + metadataIdentifier;
        log.error(errMsg, e);
        throw new MetadataProviderException(errMsg, e);
    }

    log.debug("Releasing cached DOM for metadata from '{}'", metadataIdentifier);
    releaseMetadataDOM(metadata);

    log.debug("Post-processing metadata from '{}'", metadataIdentifier);
    postProcessMetadata(metadataBytes, metadataDom, metadata);

    log.debug("Computing expiration time for metadata from '{}'", metadataIdentifier);
    DateTime metadataExpirationTime = SAML2Helper.getEarliestExpiration(metadata,
            refreshStart.plus(getMaxRefreshDelay()), refreshStart);
    log.debug("Expiration of metadata from '{}' will occur at {}", metadataIdentifier,
            metadataExpirationTime.toString());

    cachedMetadata = metadata;
    lastUpdate = refreshStart;

    long nextRefreshDelay;
    if (metadataExpirationTime.isBeforeNow()) {
        expirationTime = new DateTime(ISOChronology.getInstanceUTC()).plus(getMinRefreshDelay());
        nextRefreshDelay = getMaxRefreshDelay();
    } else {
        expirationTime = metadataExpirationTime;
        nextRefreshDelay = computeNextRefreshDelay(expirationTime);
    }
    nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay);

    emitChangeEvent();
    log.info("New metadata succesfully loaded for '{}'", getMetadataIdentifier());
}

From source file:org.opensaml.saml2.metadata.provider.HTTPMetadataProvider.java

License:Apache License

/**
 * Refreshes the metadata cache. Metadata is fetched from the URL through an HTTP get, unmarshalled, and then
 * filtered. This method also clears out the entity ID to entity descriptor cache.
 * /*  ww w .  j  av  a  2  s .  co m*/
 * @throws MetadataProviderException thrown if the metadata can not be read, unmarshalled, and filtered
 */
protected synchronized void refreshMetadata() throws MetadataProviderException {
    if (mdExpirationTime != null && !mdExpirationTime.isBeforeNow()) {
        // In case other requests stacked up behind the synchronize lock
        return;
    }

    log.debug("Refreshing cache of metadata from URL {}, max cache duration set to {} seconds", metadataURI,
            maxCacheDuration);
    try {
        XMLObject metadata = fetchMetadata();

        log.debug("Calculating expiration time");
        DateTime now = new DateTime();
        mdExpirationTime = SAML2Helper.getEarliestExpiration(metadata, now.plus(maxCacheDuration * 1000), now);
        log.debug("Metadata cache expires on " + mdExpirationTime);

        if (mdExpirationTime != null && !maintainExpiredMetadata() && mdExpirationTime.isBeforeNow()) {
            cachedMetadata = null;
        } else {
            filterMetadata(metadata);
            releaseMetadataDOM(metadata);
            cachedMetadata = metadata;
        }

        emitChangeEvent();
    } catch (IOException e) {
        String errorMsg = "Unable to read metadata from server";
        log.error(errorMsg, e);
        throw new MetadataProviderException(errorMsg, e);
    } catch (UnmarshallingException e) {
        String errorMsg = "Unable to unmarshall metadata";
        log.error(errorMsg, e);
        throw new MetadataProviderException(errorMsg, e);
    } catch (FilterException e) {
        String errorMsg = "Unable to filter metadata";
        log.error(errorMsg, e);
        throw new MetadataProviderException(errorMsg, e);
    }
}

From source file:org.opensaml.soap.wssecurity.messaging.impl.AddTimestampHandler.java

License:Open Source License

/**
 * Get the Expires value./*from  w  w w . j a v  a 2s. c  o  m*/
 * 
 * @param messageContext the current message context
 * @param created the created value, if any
 * 
 * @return the effective Expires DateTime value to use
 */
@Nullable
protected DateTime getExpiresValue(@Nonnull final MessageContext messageContext,
        @Nullable final DateTime created) {
    DateTime value = null;
    WSSecurityContext security = messageContext.getSubcontext(WSSecurityContext.class, false);
    if (security != null) {
        value = security.getTimestampExpires();
    }

    if (value == null && getExpiresLookup() != null) {
        value = getExpiresLookup().apply(messageContext);
    }

    if (value == null) {
        if (getExpiresOffsetFromCreated() != null && created != null) {
            return created.plus(getExpiresOffsetFromCreated());
        }
    }
    return value;
}