Example usage for javax.xml.datatype XMLGregorianCalendar compare

List of usage examples for javax.xml.datatype XMLGregorianCalendar compare

Introduction

In this page you can find the example usage for javax.xml.datatype XMLGregorianCalendar compare.

Prototype

public abstract int compare(XMLGregorianCalendar xmlGregorianCalendar);

Source Link

Document

Compare two instances of W3C XML Schema 1.0 date/time datatypes according to partial order relation defined in <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.3, <i>Order relation on dateTime</i></a>.

Usage

From source file:com.evolveum.midpoint.model.common.mapping.Mapping.java

private void parseTimeConstraints(Task task, OperationResult result)
        throws SchemaException, ObjectNotFoundException {
    MappingTimeDeclarationType timeFromType = mappingType.getTimeFrom();
    MappingTimeDeclarationType timeToType = mappingType.getTimeTo();
    if (timeFromType == null && timeToType == null) {
        timeConstraintValid = true;/* w w w  . jav a 2 s.  c o  m*/
        return;
    }

    XMLGregorianCalendar timeFrom = parseTime(timeFromType, task, result);
    if (timeFrom == null && timeFromType != null) {
        // Time is specified but there is no value for it.
        // This means that event that should start validity haven't happened yet
        // therefore the mapping is not yet valid. 
        timeConstraintValid = false;
        return;
    }
    XMLGregorianCalendar timeTo = parseTime(timeToType, task, result);

    if (timeFrom != null && timeFrom.compare(now) == DatatypeConstants.GREATER) {
        // before timeFrom
        nextRecomputeTime = timeFrom;
        timeConstraintValid = false;
        return;
    }

    if (timeTo == null && timeToType != null) {
        // Time is specified but there is no value for it.
        // This means that event that should stop validity haven't happened yet
        // therefore the mapping is still valid. 
        timeConstraintValid = true;
        return;
    }

    if (timeTo != null && timeTo.compare(now) == DatatypeConstants.GREATER) {
        // between timeFrom and timeTo (also no timeFrom and before timeTo)
        nextRecomputeTime = timeTo;
        timeConstraintValid = true;
        return;
    }

    if (timeTo == null) {
        // after timeFrom and no timeTo
        // no nextRecomputeTime set, there is nothing to recompute in the future
        timeConstraintValid = true;
        return;

    } else {
        // after timeTo
        // no nextRecomputeTime set, there is nothing to recompute in the future
        timeConstraintValid = false;
        return;
    }

}

From source file:com.evolveum.midpoint.model.impl.lens.projector.ObjectTemplateProcessor.java

private <F extends FocusType> XMLGregorianCalendar collectTripleFromTemplate(LensContext<F> context,
        ObjectTemplateType objectTemplateType, ObjectTemplateMappingEvaluationPhaseType phase,
        ObjectDeltaObject<F> focusOdo,
        Map<ItemPath, DeltaSetTriple<? extends ItemValueWithOrigin<?, ?>>> outputTripleMap, int iteration,
        String iterationToken, XMLGregorianCalendar now, String contextDesc, Task task, OperationResult result)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException,
        PolicyViolationException {//from   www  .j  a v a  2s. co m

    XMLGregorianCalendar nextRecomputeTime = null;

    // Process includes
    for (ObjectReferenceType includeRef : objectTemplateType.getIncludeRef()) {
        PrismObject<ObjectTemplateType> includeObject = includeRef.asReferenceValue().getObject();
        if (includeObject == null) {
            ObjectTemplateType includeObjectType = modelObjectResolver.resolve(includeRef,
                    ObjectTemplateType.class, null,
                    "include reference in " + objectTemplateType + " in " + contextDesc, task, result);
            includeObject = includeObjectType.asPrismObject();
            // Store resolved object for future use (e.g. next waves).
            includeRef.asReferenceValue().setObject(includeObject);
        }
        LOGGER.trace("Including template {}", includeObject);
        ObjectTemplateType includeObjectType = includeObject.asObjectable();
        XMLGregorianCalendar includeNextRecomputeTime = collectTripleFromTemplate(context, includeObjectType,
                phase, focusOdo, outputTripleMap, iteration, iterationToken, now,
                "include " + includeObject + " in " + objectTemplateType + " in " + contextDesc, task, result);
        if (includeNextRecomputeTime != null) {
            if (nextRecomputeTime == null
                    || nextRecomputeTime.compare(includeNextRecomputeTime) == DatatypeConstants.GREATER) {
                nextRecomputeTime = includeNextRecomputeTime;
            }
        }
    }

    // Process own mappings
    List<ObjectTemplateMappingType> mappings = collectMappings(objectTemplateType);
    List<ObjectTemplateMappingType> sortedMappings = sortMappingsByDependencies(mappings);
    XMLGregorianCalendar templateNextRecomputeTime = collectTripleFromMappings(sortedMappings, phase, context,
            objectTemplateType, focusOdo, outputTripleMap, iteration, iterationToken, now, contextDesc, task,
            result);
    if (templateNextRecomputeTime != null) {
        if (nextRecomputeTime == null
                || nextRecomputeTime.compare(templateNextRecomputeTime) == DatatypeConstants.GREATER) {
            nextRecomputeTime = templateNextRecomputeTime;
        }
    }

    return nextRecomputeTime;
}

From source file:com.evolveum.midpoint.model.impl.lens.projector.ObjectTemplateProcessor.java

private <V extends PrismValue, D extends ItemDefinition, F extends FocusType> XMLGregorianCalendar collectTripleFromMappings(
        Collection<ObjectTemplateMappingType> mappings, ObjectTemplateMappingEvaluationPhaseType phase,
        LensContext<F> context, ObjectTemplateType objectTemplateType, ObjectDeltaObject<F> focusOdo,
        Map<ItemPath, DeltaSetTriple<? extends ItemValueWithOrigin<?, ?>>> outputTripleMap, int iteration,
        String iterationToken, XMLGregorianCalendar now, String contextDesc, Task task, OperationResult result)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException,
        PolicyViolationException {//from ww w.j a va  2s.c  o  m

    XMLGregorianCalendar nextRecomputeTime = null;

    for (ObjectTemplateMappingType mappingType : mappings) {
        ObjectTemplateMappingEvaluationPhaseType mappingPhase = mappingType.getEvaluationPhase();
        if (mappingPhase == null) {
            mappingPhase = ObjectTemplateMappingEvaluationPhaseType.BEFORE_ASSIGNMENTS;
        }
        if (mappingPhase != phase) {
            continue;
        }
        LOGGER.trace("Starting evaluation of mapping '{}' in {}", mappingType.getName(), contextDesc);
        ObjectDeltaObject<F> updatedFocusOdo = getUpdatedFocusOdo(context, focusOdo, outputTripleMap,
                mappingType, contextDesc); // for mapping chaining

        Mapping<V, D> mapping = mappingEvaluator.createFocusMapping(mappingFactory, context, mappingType,
                objectTemplateType, updatedFocusOdo, null, iteration, iterationToken,
                context.getSystemConfiguration(), now, contextDesc, task, result);
        if (mapping == null) {
            continue;
        }

        Boolean timeConstraintValid = mapping.evaluateTimeConstraintValid(task, result);

        if (timeConstraintValid != null && !timeConstraintValid) {
            // Delayed mapping. Just schedule recompute time
            XMLGregorianCalendar mappingNextRecomputeTime = mapping.getNextRecomputeTime();
            LOGGER.trace("Evaluation of mapping {} delayed to {}", mapping, mappingNextRecomputeTime);
            if (mappingNextRecomputeTime != null) {
                if (nextRecomputeTime == null
                        || nextRecomputeTime.compare(mappingNextRecomputeTime) == DatatypeConstants.GREATER) {
                    nextRecomputeTime = mappingNextRecomputeTime;
                }
            }
            continue;
        }

        mappingEvaluator.evaluateMapping(mapping, context, task, result);

        ItemPath itemPath = mapping.getOutputPath();
        if (itemPath == null) {
            continue;
        }
        DeltaSetTriple<ItemValueWithOrigin<V, D>> outputTriple = ItemValueWithOrigin
                .createOutputTriple(mapping);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Output triple for {}:\n{}", mapping, DebugUtil.debugDump(outputTriple));
        }
        if (outputTriple == null) {
            continue;
        }
        DeltaSetTriple<ItemValueWithOrigin<V, D>> mapTriple = (DeltaSetTriple<ItemValueWithOrigin<V, D>>) outputTripleMap
                .get(itemPath);
        if (mapTriple == null) {
            outputTripleMap.put(itemPath, outputTriple);
        } else {
            mapTriple.merge(outputTriple);
        }
    }

    return nextRecomputeTime;
}

From source file:com.evolveum.midpoint.model.impl.lens.projector.focus.ObjectTemplateProcessor.java

private <V extends PrismValue, D extends ItemDefinition, F extends FocusType, T extends FocusType> XMLGregorianCalendar collectTripleFromMappings(
        LensContext<F> context, List<FocalMappingSpec> mappings, ObjectTemplateMappingEvaluationPhaseType phase,
        ObjectDeltaObject<F> focusOdo, PrismObject<T> target,
        Map<ItemPath, DeltaSetTriple<? extends ItemValueWithOrigin<?, ?>>> outputTripleMap, int iteration,
        String iterationToken, XMLGregorianCalendar now, Task task, OperationResult result)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException,
        PolicyViolationException, SecurityViolationException, ConfigurationException, CommunicationException {

    List<FocalMappingSpec> sortedMappings = sortMappingsByDependencies(mappings);

    XMLGregorianCalendar nextRecomputeTime = null;

    for (FocalMappingSpec mappingSpec : sortedMappings) {
        ObjectTemplateMappingEvaluationPhaseType mappingPhase = mappingSpec.getEvaluationPhase();
        if (phase != null && mappingPhase != phase) {
            continue;
        }/* w  w w  .j a  v a  2  s  .  com*/
        String mappingDesc = mappingSpec.shortDump();
        LOGGER.trace("Starting evaluation of {}", mappingDesc);
        ObjectDeltaObject<F> updatedFocusOdo = getUpdatedFocusOdo(context, focusOdo, outputTripleMap,
                mappingSpec, mappingDesc); // for mapping chaining

        MappingImpl<V, D> mapping = mappingEvaluator.createFocusMapping(mappingFactory, context,
                mappingSpec.getMappingType(), mappingSpec.getOriginObject(), updatedFocusOdo,
                mappingSpec.getDefaultSource(focusOdo), target, null, iteration, iterationToken,
                context.getSystemConfiguration(), now, mappingDesc, task, result);
        if (mapping == null) {
            continue;
        }

        Boolean timeConstraintValid = mapping.evaluateTimeConstraintValid(task, result);

        if (timeConstraintValid != null && !timeConstraintValid) {
            // Delayed mapping. Just schedule recompute time
            XMLGregorianCalendar mappingNextRecomputeTime = mapping.getNextRecomputeTime();
            LOGGER.trace("Evaluation of mapping {} delayed to {}", mapping, mappingNextRecomputeTime);
            if (mappingNextRecomputeTime != null) {
                if (nextRecomputeTime == null
                        || nextRecomputeTime.compare(mappingNextRecomputeTime) == DatatypeConstants.GREATER) {
                    nextRecomputeTime = mappingNextRecomputeTime;
                }
            }
            continue;
        }

        mappingEvaluator.evaluateMapping(mapping, context, task, result);

        ItemPath itemPath = mapping.getOutputPath();
        if (itemPath == null) {
            continue;
        }
        DeltaSetTriple<ItemValueWithOrigin<V, D>> outputTriple = ItemValueWithOrigin
                .createOutputTriple(mapping);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Output triple for {}:\n{}", mapping, DebugUtil.debugDump(outputTriple));
        }
        if (outputTriple == null) {
            continue;
        }
        DeltaSetTriple<ItemValueWithOrigin<V, D>> mapTriple = (DeltaSetTriple<ItemValueWithOrigin<V, D>>) outputTripleMap
                .get(itemPath);
        if (mapTriple == null) {
            outputTripleMap.put(itemPath, outputTriple);
        } else {
            mapTriple.merge(outputTriple);
        }
    }

    return nextRecomputeTime;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Returns a positive integer if ts1 depicts a time after ts2 (ts1 > ts2), 0 if ts1 and ts2 depict the same time
 * (ts1 == ts2), and a negative integer if if ts1 depicts a time before ts2 (ts1 < ts2).
 * //  ww w. j a v  a  2s  .  com
 * @param ts1
 *            The first timestamp.
 * @param ts2
 *            The second timestamp.
 * @return The comparison result.
 * @throws Exception
 *             If anything fails (e.g. one timstamp has incorrect format).
 */
public static int compareTimestamps(final String ts1, final String ts2) throws Exception {

    int result = 0;

    XMLGregorianCalendar date1 = DatatypeFactory.newInstance().newXMLGregorianCalendar(ts1);
    XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(ts2);

    int diff = date1.compare(date2);
    if (diff == DatatypeConstants.LESSER) {
        result = -1;
    } else if (diff == DatatypeConstants.GREATER) {
        result = 1;
    } else if (diff == DatatypeConstants.EQUAL) {
        result = 0;
    } else if (diff == DatatypeConstants.INDETERMINATE) {
        throw new Exception("Date comparing: INDETERMINATE");
    }

    return result;
}

From source file:com.evolveum.midpoint.model.impl.lens.projector.MappingEvaluationHelper.java

/**
 * strongMappingWasUsed: Returns true here if the value was (at least partly) determined by a strong mapping.
 * Used to know whether (when doing reconciliation) this value should be forcibly put onto the resource, even
 * if it was not changed (i.e. if it's only in the zero set).
 *///from  www.j a  va 2  s  . c o m
//   public <V extends PrismValue, F extends FocusType, O extends ObjectType> void evaluateMappingSetProjection(
//         Collection<MappingType> mappingTypes, String mappingDesc,
//         XMLGregorianCalendar now, MappingInitializer<V> initializer, MappingOutputProcessor<V> processor,
//         Item<V> aPrioriValue, ItemDelta<V> aPrioriDelta, PrismObject<? extends ObjectType> aPrioriObject,
//         Boolean evaluateCurrent, MutableBoolean strongMappingWasUsed,
//         LensContext<F> context, LensElementContext<O> targetContext, 
//         Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {

public <V extends PrismValue, T extends ObjectType, F extends FocusType> void evaluateMappingSetProjection(
        MappingEvaluatorHelperParams<V, T, F> params, Task task, OperationResult result)
        throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {

    String mappingDesc = params.getMappingDesc();
    LensElementContext<T> targetContext = params.getTargetContext();
    PrismObjectDefinition<T> targetObjectDefinition = targetContext.getObjectDefinition();
    ItemPath defaultTargetItemPath = params.getDefaultTargetItemPath();

    Map<ItemPath, MappingOutputStruct<V>> outputTripleMap = new HashMap<>();
    XMLGregorianCalendar nextRecomputeTime = null;
    Collection<MappingType> mappingTypes = params.getMappingTypes();
    Collection<Mapping<V>> mappings = new ArrayList<Mapping<V>>(mappingTypes.size());

    for (MappingType mappingType : mappingTypes) {

        Mapping<V> mapping = mappingFactory.createMapping(mappingType, mappingDesc);

        if (!mapping.isApplicableToChannel(params.getContext().getChannel())) {
            continue;
        }

        mapping.setNow(params.getNow());
        if (defaultTargetItemPath != null && targetObjectDefinition != null) {
            ItemDefinition defaultTargetItemDef = targetObjectDefinition
                    .findItemDefinition(defaultTargetItemPath);
            mapping.setDefaultTargetDefinition(defaultTargetItemDef);
            mapping.setDefaultTargetPath(defaultTargetItemPath);
        } else {
            mapping.setDefaultTargetDefinition(params.getTargetItemDefinition());
            mapping.setDefaultTargetPath(defaultTargetItemPath);
        }
        mapping.setTargetContext(targetObjectDefinition);

        // Initialize mapping (using Inversion of Control)
        params.getInitializer().initialize(mapping);

        Boolean timeConstraintValid = mapping.evaluateTimeConstraintValid(result);

        if (params.getEvaluateCurrent() != null) {
            if (params.getEvaluateCurrent() && !timeConstraintValid) {
                continue;
            }
            if (!params.getEvaluateCurrent() && timeConstraintValid) {
                continue;
            }
        }

        mappings.add(mapping);
    }

    for (Mapping<V> mapping : mappings) {

        if (mapping.getStrength() == MappingStrengthType.WEAK) {
            // Evaluate weak mappings in a second run.
            continue;
        }

        ItemPath mappingOutputPath = mapping.getOutputPath();
        if (params.isFixTarget() && mappingOutputPath != null && defaultTargetItemPath != null
                && !mappingOutputPath.equivalent(defaultTargetItemPath)) {
            throw new ExpressionEvaluationException("Target cannot be overridden in " + mappingDesc);
        }

        if (params.getAPrioriTargetDelta() != null && mappingOutputPath != null) {
            ItemDelta<PrismValue> aPrioriItemDelta = params.getAPrioriTargetDelta()
                    .findItemDelta(mappingOutputPath);
            if (mapping.getStrength() != MappingStrengthType.STRONG) {
                if (aPrioriItemDelta != null && !aPrioriItemDelta.isEmpty()) {
                    continue;
                }
            }
        }

        LensUtil.evaluateMapping(mapping, params.getContext(), task, result);

        PrismValueDeltaSetTriple<V> mappingOutputTriple = mapping.getOutputTriple();
        if (mappingOutputTriple != null) {

            MappingOutputStruct<V> mappingOutputStruct = outputTripleMap.get(mappingOutputPath);
            if (mappingOutputStruct == null) {
                mappingOutputStruct = new MappingOutputStruct<>();
                outputTripleMap.put(mappingOutputPath, mappingOutputStruct);
            }

            if (mapping.getStrength() == MappingStrengthType.STRONG) {
                mappingOutputStruct.setStrongMappingWasUsed(true);
            }

            PrismValueDeltaSetTriple<V> outputTriple = mappingOutputStruct.getOutputTriple();
            if (outputTriple == null) {
                mappingOutputStruct.setOutputTriple(mappingOutputTriple);
            } else {
                outputTriple.merge(mappingOutputTriple);
            }
        }

    }

    // Second pass, evaluate only weak mappings
    for (Mapping<V> mapping : mappings) {

        ItemPath mappingOutputPath = mapping.getOutputPath();
        if (params.isFixTarget() && mappingOutputPath != null && defaultTargetItemPath != null
                && !mappingOutputPath.equivalent(defaultTargetItemPath)) {
            throw new ExpressionEvaluationException("Target cannot be overridden in " + mappingDesc);
        }

        MappingOutputStruct<V> mappingOutputStruct = outputTripleMap.get(mappingOutputPath);
        if (mappingOutputStruct == null) {
            mappingOutputStruct = new MappingOutputStruct<>();
            outputTripleMap.put(mappingOutputPath, mappingOutputStruct);
        }

        PrismValueDeltaSetTriple<V> outputTriple = mappingOutputStruct.getOutputTriple();

        Item<?> aPrioriTargetItem = null;
        PrismObject<T> aPrioriTargetObject = params.getAPrioriTargetObject();
        if (aPrioriTargetObject != null && mappingOutputPath != null) {
            aPrioriTargetItem = aPrioriTargetObject.findItem(mappingOutputPath);
        }
        if ((aPrioriTargetItem == null || aPrioriTargetItem.isEmpty()) && outputTriple == null) {

            if (mapping.getStrength() != MappingStrengthType.WEAK) {
                continue;
            }

            LensUtil.evaluateMapping(mapping, params.getContext(), task, result);

            PrismValueDeltaSetTriple<V> mappingOutputTriple = mapping.getOutputTriple();
            if (mappingOutputTriple != null) {
                if (outputTriple == null) {
                    mappingOutputStruct.setOutputTriple(mappingOutputTriple);
                } else {
                    outputTriple.merge(mappingOutputTriple);
                }
            }

        }
    }

    MappingOutputProcessor<V> processor = params.getProcessor();
    for (Entry<ItemPath, MappingOutputStruct<V>> outputTripleMapEntry : outputTripleMap.entrySet()) {
        ItemPath mappingOutputPath = outputTripleMapEntry.getKey();
        MappingOutputStruct<V> mappingOutputStruct = outputTripleMapEntry.getValue();
        PrismValueDeltaSetTriple<V> outputTriple = mappingOutputStruct.getOutputTriple();

        if (processor != null) {
            processor.process(mappingOutputPath, outputTriple);
        } else {

            if (outputTriple == null) {
                LOGGER.trace("{} expression resulted in null triple for {}, skipping", mappingDesc,
                        targetContext);
                continue;
            }

            ItemDefinition targetItemDefinition = null;
            if (mappingOutputPath != null) {
                targetItemDefinition = targetObjectDefinition.findItemDefinition(mappingOutputPath);
                if (targetItemDefinition == null) {
                    throw new SchemaException(
                            "No definition for item " + mappingOutputPath + " in " + targetObjectDefinition);
                }
            } else {
                targetItemDefinition = params.getTargetItemDefinition();
            }
            ItemDelta<V> targetItemDelta = targetItemDefinition.createEmptyDelta(mappingOutputPath);

            Item<V> aPrioriTargetItem = null;
            PrismObject<T> aPrioriTargetObject = params.getAPrioriTargetObject();
            if (aPrioriTargetObject != null) {
                aPrioriTargetItem = (Item<V>) aPrioriTargetObject.findItem(mappingOutputPath);
            }

            if (targetContext.isAdd()) {

                Collection<V> nonNegativeValues = outputTriple.getNonNegativeValues();
                if (nonNegativeValues == null || nonNegativeValues.isEmpty()) {
                    LOGGER.trace("{} resulted in null or empty value for {}, skipping", mappingDesc,
                            targetContext);
                    continue;
                }
                targetItemDelta.setValuesToReplace(PrismValue.cloneCollection(nonNegativeValues));

            } else {

                // if we have fresh information (full shadow) AND the mapping used to derive the information was strong,
                // we will consider all values (zero & plus sets) -- otherwise, we take only the "plus" (i.e. changed) set

                // the first case is necessary, because in some situations (e.g. when mapping is changed)
                // the evaluator sees no differences w.r.t. real state, even if there is a difference
                // - and we must have a way to push new information onto the resource

                Collection<V> valuesToReplace;

                if (params.hasFullTargetObject() && mappingOutputStruct.isStrongMappingWasUsed()) {
                    valuesToReplace = outputTriple.getNonNegativeValues();
                } else {
                    valuesToReplace = outputTriple.getPlusSet();
                }

                if (valuesToReplace != null && !valuesToReplace.isEmpty()) {

                    // if what we want to set is the same as is already in the shadow, we skip that
                    // (we insist on having full shadow, to be sure we work with current data)

                    if (params.hasFullTargetObject() && targetContext.isFresh() && aPrioriTargetItem != null) {
                        Collection<V> valuesPresent = aPrioriTargetItem.getValues();
                        if (PrismValue.equalsRealValues(valuesPresent, valuesToReplace)) {
                            LOGGER.trace("{} resulted in existing values for {}, skipping creation of a delta",
                                    mappingDesc, targetContext);
                            continue;
                        }
                    }
                    targetItemDelta.setValuesToReplace(PrismValue.cloneCollection(valuesToReplace));
                }

            }

            if (targetItemDelta.isEmpty()) {
                continue;
            }

            LOGGER.trace("{} adding new delta for {}: {}",
                    new Object[] { mappingDesc, targetContext, targetItemDelta });
            targetContext.swallowToSecondaryDelta(targetItemDelta);
        }

    }

    // Figure out recompute time

    for (Mapping<V> mapping : mappings) {
        XMLGregorianCalendar mappingNextRecomputeTime = mapping.getNextRecomputeTime();
        if (mappingNextRecomputeTime != null) {
            if (nextRecomputeTime == null
                    || nextRecomputeTime.compare(mappingNextRecomputeTime) == DatatypeConstants.GREATER) {
                nextRecomputeTime = mappingNextRecomputeTime;
            }
        }
    }

    if (nextRecomputeTime != null) {

        boolean alreadyHasTrigger = false;
        if (params.getAPrioriTargetObject() != null) {
            for (TriggerType trigger : params.getAPrioriTargetObject().asObjectable().getTrigger()) {
                if (RecomputeTriggerHandler.HANDLER_URI.equals(trigger.getHandlerUri())
                        && nextRecomputeTime.equals(trigger.getTimestamp())) {
                    alreadyHasTrigger = true;
                    break;
                }
            }
        }

        if (!alreadyHasTrigger) {
            PrismContainerDefinition<TriggerType> triggerContDef = targetObjectDefinition
                    .findContainerDefinition(ObjectType.F_TRIGGER);
            ContainerDelta<TriggerType> triggerDelta = triggerContDef
                    .createEmptyDelta(new ItemPath(ObjectType.F_TRIGGER));
            PrismContainerValue<TriggerType> triggerCVal = triggerContDef.createValue();
            triggerDelta.addValueToAdd(triggerCVal);
            TriggerType triggerType = triggerCVal.asContainerable();
            triggerType.setTimestamp(nextRecomputeTime);
            triggerType.setHandlerUri(RecomputeTriggerHandler.HANDLER_URI);

            targetContext.swallowToSecondaryDelta(triggerDelta);
        }
    }
}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java

private void validateAssertionConditions(ResponseType response, ConditionsType conditions)
        throws SSOException, SSOResponseException {

    if (conditions == null)
        return;/*from w  w  w.  ja v a 2 s.co  m*/

    long tolerance = ((AbstractSSOMediator) channel.getIdentityMediator()).getTimestampValidationTolerance();
    Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() == null && conditions.getNotBefore() == null
            && conditions.getNotOnOrAfter() == null) {
        return;
    }

    logger.debug("Current time (UTC): " + utcCalendar.toString());

    XMLGregorianCalendar notBeforeUTC = null;
    XMLGregorianCalendar notOnOrAfterUTC = null;

    if (conditions.getNotBefore() != null) {
        //normalize to UTC         
        logger.debug("Conditions.NotBefore: " + conditions.getNotBefore());

        notBeforeUTC = conditions.getNotBefore().normalize();
        logger.debug("Conditions.NotBefore normalized: " + notBeforeUTC.toString());

        if (!notBeforeUTC.isValid()) {
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE,
                    notBeforeUTC.toString());
        } else {

            Calendar notBefore = notBeforeUTC.toGregorianCalendar();
            notBefore.add(Calendar.MILLISECOND, (int) tolerance * -1);

            if (utcCalendar.before(notBefore))

                throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                        StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_BEFORE_VIOLATED,
                        notBeforeUTC.toString());
        }
    }

    // Make sure that the NOT ON OR AFTER is not violated, give a five minutes tolerance (should be configurable)
    if (conditions.getNotOnOrAfter() != null) {
        //normalize to UTC
        logger.debug("Conditions.NotOnOrAfter: " + conditions.getNotOnOrAfter().toString());
        notOnOrAfterUTC = conditions.getNotOnOrAfter().normalize();
        logger.debug("Conditions.NotOnOrAfter normalized: " + notOnOrAfterUTC.toString());
        if (!notOnOrAfterUTC.isValid()) {
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE,
                    notOnOrAfterUTC.toString());

        } else {

            // diff in millis
            Calendar notOnOrAfter = notOnOrAfterUTC.toGregorianCalendar();
            notOnOrAfter.add(Calendar.MILLISECOND, (int) tolerance);

            if (utcCalendar.after(notOnOrAfter))
                throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                        StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_ONORAFTER_VIOLATED,
                        notOnOrAfterUTC.toString());
        }
    }

    if (notBeforeUTC != null && notOnOrAfterUTC != null && notOnOrAfterUTC.compare(notBeforeUTC) <= 0) {

        throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_CONDITION,
                "'Not On or After' earlier that 'Not Before'");
    }

    // Our SAMLR2 Enityt ID should be part of the audience
    CircleOfTrustMemberDescriptor sp = this.getCotMemberDescriptor();
    MetadataEntry spMd = sp.getMetadata();

    if (spMd == null || spMd.getEntry() == null)
        throw new SSOException("No metadata descriptor found for SP " + sp);

    EntityDescriptorType md = null;
    if (spMd.getEntry() instanceof EntityDescriptorType) {
        md = (EntityDescriptorType) spMd.getEntry();
    } else
        throw new SSOException("Unsupported Metadata type " + md + ", SAML 2 Metadata expected");

    if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() != null) {
        boolean audienceRestrictionValid = false;
        boolean spInAllAudiences = false;
        boolean initState = true;
        for (ConditionAbstractType conditionAbs : conditions.getConditionOrAudienceRestrictionOrOneTimeUse()) {
            if (conditionAbs instanceof AudienceRestrictionType) {
                AudienceRestrictionType audienceRestriction = (AudienceRestrictionType) conditionAbs;
                if (audienceRestriction.getAudience() != null) {
                    boolean spInAudience = false;
                    for (String audience : audienceRestriction.getAudience()) {
                        if (audience.equals(md.getEntityID())) {
                            spInAudience = true;
                            break;
                        }
                    }
                    spInAllAudiences = (initState ? spInAudience : spInAllAudiences && spInAudience);
                    initState = false;
                }
            }
            audienceRestrictionValid = audienceRestrictionValid || spInAllAudiences;
        }
        if (!audienceRestrictionValid) {
            logger.error("SP is not in Audience list.");
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_IN_AUDIENCE);
        }
    }

}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java

private Calendar getSessionNotOnOrAfter(AssertionType assertion) {

    XMLGregorianCalendar sessionNotOnOrAfter = null;
    List<AuthnStatementType> authnStatements = getAuthnStatements(assertion);

    for (AuthnStatementType authnStatement : authnStatements) {

        if (authnStatement.getSessionNotOnOrAfter() != null) {
            if (sessionNotOnOrAfter == null)
                sessionNotOnOrAfter = authnStatement.getSessionNotOnOrAfter();
            else if (sessionNotOnOrAfter
                    .compare(authnStatement.getSessionNotOnOrAfter()) == DatatypeConstants.LESSER) {
                sessionNotOnOrAfter = authnStatement.getSessionNotOnOrAfter();
            }/*from w ww . j  a v a 2s  .  c  o  m*/
        }
    }

    if (sessionNotOnOrAfter != null)
        return sessionNotOnOrAfter.toGregorianCalendar();

    return null;
}