Search in sources :

Example 16 with LensContext

use of com.evolveum.midpoint.model.impl.lens.LensContext in project midpoint by Evolveum.

the class TestUserChangeApprovalLegacy method test040UserModifyPasswordChangeBlocked.

@Test(enabled = true)
public void test040UserModifyPasswordChangeBlocked() throws Exception {
    TestUtil.displayTestTile(this, "test040UserModifyPasswordChangeBlocked");
    login(userAdministrator);
    PrismObject<UserType> jack = getUser(USER_JACK_OID);
    final ProtectedStringType originalPasswordValue = jack.asObjectable().getCredentials().getPassword().getValue();
    LOGGER.trace("password before test = " + originalPasswordValue);
    executeTest("test040UserModifyPasswordChangeBlocked", USER_JACK_OID, new TestDetails() {

        @Override
        int subtaskCount() {
            return 1;
        }

        @Override
        boolean immediate() {
            return false;
        }

        @Override
        boolean checkObjectOnSubtasks() {
            return true;
        }

        @Override
        public LensContext createModelContext(Task task, OperationResult result) throws Exception {
            LensContext<UserType> context = createUserLensContext();
            fillContextWithUser(context, USER_JACK_OID, result);
            encryptAndAddFocusModificationToContext(context, REQ_USER_JACK_MODIFY_CHANGE_PASSWORD);
            //context.setOptions(ModelExecuteOptions.createNoCrypt());
            return context;
        }

        @Override
        public void assertsAfterClockworkRun(Task rootTask, List<Task> wfSubtasks, OperationResult result) throws Exception {
            ModelContext taskModelContext = wfTaskUtil.getModelContext(rootTask, result);
            assertEquals("There are modifications left in primary focus delta", 0, taskModelContext.getFocusContext().getPrimaryDelta().getModifications().size());
        }

        @Override
        void assertsRootTaskFinishes(Task task, List<Task> subtasks, OperationResult result) throws Exception {
            PrismObject<UserType> jack = getUser(USER_JACK_OID);
            ProtectedStringType afterTestPasswordValue = jack.asObjectable().getCredentials().getPassword().getValue();
            LOGGER.trace("password after test = " + afterTestPasswordValue);
            //assertNotNull("password was not set", afterTestPasswordValue.getEncryptedData());
            assertTrue("password was changed", originalPasswordValue.getEncryptedDataType().equals(afterTestPasswordValue.getEncryptedDataType()));
            checkDummyTransportMessages("simpleUserNotifier", 0);
        // we don't check for modifyApproverRef because in this test the value was not changed (no change was executed)
        }

        @Override
        boolean decideOnApproval(String executionId) throws Exception {
            login(getUser(USER_ADMINISTRATOR_OID));
            return false;
        }
    });
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) JAXBException(javax.xml.bind.JAXBException) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) Test(org.testng.annotations.Test)

Example 17 with LensContext

use of com.evolveum.midpoint.model.impl.lens.LensContext in project midpoint by Evolveum.

the class TestUserChangeApprovalLegacy method test095UserModifyModifyResourceAssignmentConstruction.

/**
     * User modification: modifying attribute of single security-sensitive resource assignment.
     *
     * User primary delta:
     *  ObjectDelta<UserType>(UserType:377205db-33d1-47e5-bf96-bbe2a7d1222e,MODIFY):
     *  assignment/[1]/construction/attribute
     *  ADD: ResourceAttributeDefinitionType(ref=ItemPathType{itemPath=lastname}...)
     *  DELETE: ResourceAttributeDefinitionType(ref=ItemPathType{itemPath=lastname}...)
     *
     */
@Test(enabled = true)
public void test095UserModifyModifyResourceAssignmentConstruction() throws Exception {
    final String TEST_NAME = "test095UserModifyModifyResourceAssignmentConstruction";
    TestUtil.displayTestTile(this, TEST_NAME);
    login(userAdministrator);
    executeTest(TEST_NAME, USER_JACK_OID, new TestDetails() {

        @Override
        int subtaskCount() {
            return 1;
        }

        @Override
        boolean immediate() {
            return false;
        }

        @Override
        boolean checkObjectOnSubtasks() {
            return true;
        }

        @Override
        boolean removeAssignmentsBeforeTest() {
            return false;
        }

        @Override
        public LensContext createModelContext(Task task, OperationResult result) throws Exception {
            LensContext<UserType> context = createUserLensContext();
            fillContextWithUser(context, USER_JACK_OID, result);
            UserType jack = context.getFocusContext().getObjectOld().asObjectable();
            modifyAssignmentConstruction(context, jack, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "water", true);
            return context;
        }

        @Override
        public void assertsAfterClockworkRun(Task rootTask, List<Task> wfSubtasks, OperationResult result) throws Exception {
            ModelContext taskModelContext = wfTaskUtil.getModelContext(rootTask, result);
            assertEquals("There are modifications left in primary focus delta", 0, taskModelContext.getFocusContext().getPrimaryDelta().getModifications().size());
            UserType jack = getUser(USER_JACK_OID).asObjectable();
            checkNoAssignmentConstruction(jack, "drink");
        }

        @Override
        void assertsRootTaskFinishes(Task task, List<Task> subtasks, OperationResult result) throws Exception {
            assertAssignedResource(USER_JACK_OID, RESOURCE_DUMMY_OID, task, result);
            UserType jack = getUser(USER_JACK_OID).asObjectable();
            checkAssignmentConstruction(jack, "drink", "water");
            checkDummyTransportMessages("simpleUserNotifier", 1);
            //checkWorkItemAuditRecords(createResultMap(ROLE_R1_OID, WorkflowResult.APPROVED));
            checkUserApprovers(USER_JACK_OID, Arrays.asList(DUMMYBOSS_OID), result);
        }

        @Override
        boolean decideOnApproval(String executionId) throws Exception {
            login(getUser(DUMMYBOSS_OID));
            return true;
        }
    });
}
Also used : ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) JAXBException(javax.xml.bind.JAXBException) Test(org.testng.annotations.Test)

Example 18 with LensContext

use of com.evolveum.midpoint.model.impl.lens.LensContext in project midpoint by Evolveum.

the class ConsolidationProcessor method consolidateValuesToModifyDelta.

private <F extends FocusType> ObjectDelta<ShadowType> consolidateValuesToModifyDelta(LensContext<F> context, LensProjectionContext projCtx, boolean addUnchangedValues, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException {
    // "Squeeze" all the relevant mappings into a data structure that we can process conveniently. We want to have all the
    // (meta)data about relevant for a specific attribute in one data structure, not spread over several account constructions.
    Map<QName, DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<?>, PrismPropertyDefinition<?>>>> squeezedAttributes = sqeeze(projCtx, construction -> (Collection) construction.getAttributeMappings());
    projCtx.setSqueezedAttributes(squeezedAttributes);
    Map<QName, DeltaSetTriple<ItemValueWithOrigin<PrismContainerValue<ShadowAssociationType>, PrismContainerDefinition<ShadowAssociationType>>>> squeezedAssociations = sqeeze(projCtx, construction -> construction.getAssociationMappings());
    projCtx.setSqueezedAssociations(squeezedAssociations);
    // So, we do it here - once and for all.
    if (!squeezedAssociations.isEmpty()) {
        fillInAssociationNames(squeezedAssociations);
    }
    MappingExtractor<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>, F> auxiliaryObjectClassExtractor = construction -> {
        PrismValueDeltaSetTripleProducer<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>> prod = new PrismValueDeltaSetTripleProducer<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>>() {

            @Override
            public QName getMappingQName() {
                return ShadowType.F_AUXILIARY_OBJECT_CLASS;
            }

            @Override
            public PrismValueDeltaSetTriple<PrismPropertyValue<QName>> getOutputTriple() {
                PrismValueDeltaSetTriple<PrismPropertyValue<QName>> triple = new PrismValueDeltaSetTriple<>();
                if (construction.getAuxiliaryObjectClassDefinitions() != null) {
                    for (RefinedObjectClassDefinition auxiliaryObjectClassDefinition : construction.getAuxiliaryObjectClassDefinitions()) {
                        triple.addToZeroSet(new PrismPropertyValue<QName>(auxiliaryObjectClassDefinition.getTypeName()));
                    }
                }
                return triple;
            }

            @Override
            public MappingStrengthType getStrength() {
                return MappingStrengthType.STRONG;
            }

            @Override
            public PrismValueDeltaSetTripleProducer<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>> clone() {
                return this;
            }

            @Override
            public boolean isExclusive() {
                return false;
            }

            @Override
            public boolean isAuthoritative() {
                return true;
            }

            @Override
            public boolean isSourceless() {
                return false;
            }
        };
        Collection<PrismValueDeltaSetTripleProducer<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>>> col = new ArrayList<>(1);
        col.add(prod);
        return col;
    };
    Map<QName, DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>>>> squeezedAuxiliaryObjectClasses = sqeeze(projCtx, auxiliaryObjectClassExtractor);
    projCtx.setSqueezedAuxiliaryObjectClasses(squeezedAuxiliaryObjectClasses);
    ResourceShadowDiscriminator discr = projCtx.getResourceShadowDiscriminator();
    ObjectDelta<ShadowType> objectDelta = new ObjectDelta<ShadowType>(ShadowType.class, ChangeType.MODIFY, prismContext);
    objectDelta.setOid(projCtx.getOid());
    // Let's be very very lazy about fetching the account from the resource.
    if (!projCtx.hasFullShadow() && (hasActiveWeakMapping(squeezedAttributes, projCtx) || hasActiveWeakMapping(squeezedAssociations, projCtx) || (hasActiveStrongMapping(squeezedAttributes, projCtx) || hasActiveStrongMapping(squeezedAssociations, projCtx)))) {
        // Full account was not yet loaded. This will cause problems as
        // the weak mapping may be applied even though it should not be
        // applied
        // and also same changes may be discarded because of unavailability
        // of all
        // account's attributes.Therefore load the account now, but with
        // doNotDiscovery options..
        // We also need to get account if there are strong mappings. Strong mappings
        // should always be applied. So reading the account now will indirectly
        // trigger reconciliation which makes sure that the strong mappings are
        // applied.
        // By getting accounts from provisioning, there might be a problem with
        // resource availability. We need to know, if the account was read full
        // or we have only the shadow from the repository. If we have only
        // shadow, the weak mappings may applied even if they should not be. 
        contextLoader.loadFullShadow(context, projCtx, "weak or strong mapping", task, result);
        if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
            return null;
        }
    }
    boolean completeAccount = projCtx.hasFullShadow();
    ObjectDelta<ShadowType> existingDelta = projCtx.getDelta();
    // AUXILIARY OBJECT CLASSES
    ItemPath auxiliaryObjectClassItemPath = new ItemPath(ShadowType.F_AUXILIARY_OBJECT_CLASS);
    PrismPropertyDefinition<QName> auxiliaryObjectClassPropertyDef = projCtx.getObjectDefinition().findPropertyDefinition(auxiliaryObjectClassItemPath);
    PropertyDelta<QName> auxiliaryObjectClassAPrioriDelta = null;
    RefinedResourceSchema refinedSchema = projCtx.getRefinedResourceSchema();
    List<QName> auxOcNames = new ArrayList<>();
    List<RefinedObjectClassDefinition> auxOcDefs = new ArrayList<>();
    ObjectDelta<ShadowType> projDelta = projCtx.getDelta();
    if (projDelta != null) {
        auxiliaryObjectClassAPrioriDelta = projDelta.findPropertyDelta(auxiliaryObjectClassItemPath);
    }
    for (Entry<QName, DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>>>> entry : squeezedAuxiliaryObjectClasses.entrySet()) {
        DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>>> ivwoTriple = entry.getValue();
        LOGGER.trace("CONSOLIDATE auxiliary object classes ({})", new Object[] { discr });
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Auxiliary object class triple:\n{}", ivwoTriple.debugDump());
        }
        for (ItemValueWithOrigin<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>> ivwo : ivwoTriple.getAllValues()) {
            QName auxObjectClassName = ivwo.getItemValue().getValue();
            if (auxOcNames.contains(auxObjectClassName)) {
                continue;
            }
            auxOcNames.add(auxObjectClassName);
            RefinedObjectClassDefinition auxOcDef = refinedSchema.getRefinedDefinition(auxObjectClassName);
            if (auxOcDef == null) {
                LOGGER.error("Auxiliary object class definition {} for {} not found in the schema, but it should be there, dumping context:\n{}", auxObjectClassName, discr, context.debugDump());
                throw new IllegalStateException("Auxiliary object class definition " + auxObjectClassName + " for " + discr + " not found in the context, but it should be there");
            }
            auxOcDefs.add(auxOcDef);
        }
        ItemDelta<PrismPropertyValue<QName>, PrismPropertyDefinition<QName>> itemDelta = LensUtil.consolidateTripleToDelta(auxiliaryObjectClassItemPath, ivwoTriple, auxiliaryObjectClassPropertyDef, auxiliaryObjectClassAPrioriDelta, projCtx.getObjectNew(), null, null, addUnchangedValues, completeAccount, false, discr.toHumanReadableDescription(), false);
        PropertyDelta<QName> propDelta = (PropertyDelta) itemDelta;
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Auxiliary object class delta:\n{}", propDelta.debugDump());
        }
        if (!propDelta.isEmpty()) {
            objectDelta.addModification(propDelta);
        }
    }
    RefinedObjectClassDefinition structuralObjectClassDefinition = projCtx.getStructuralObjectClassDefinition();
    if (structuralObjectClassDefinition == null) {
        LOGGER.error("Structural object class definition for {} not found in the context, but it should be there, dumping context:\n{}", discr, context.debugDump());
        throw new IllegalStateException("Structural object class definition for " + discr + " not found in the context, but it should be there");
    }
    RefinedObjectClassDefinition rOcDef = new CompositeRefinedObjectClassDefinitionImpl(structuralObjectClassDefinition, auxOcDefs);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Object class definition for {} consolidation:\n{}", discr, rOcDef.debugDump());
    }
    // with the data in ItemValueWithOrigin triples.
    for (Map.Entry<QName, DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<?>, PrismPropertyDefinition<?>>>> entry : squeezedAttributes.entrySet()) {
        QName attributeName = entry.getKey();
        DeltaSetTriple<ItemValueWithOrigin<PrismPropertyValue<?>, PrismPropertyDefinition<?>>> triple = entry.getValue();
        PropertyDelta<?> propDelta = consolidateAttribute(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeAccount, attributeName, (DeltaSetTriple) triple);
        if (propDelta != null) {
            objectDelta.addModification(propDelta);
        }
    }
    // ASSOCIATIONS
    for (Entry<QName, DeltaSetTriple<ItemValueWithOrigin<PrismContainerValue<ShadowAssociationType>, PrismContainerDefinition<ShadowAssociationType>>>> entry : squeezedAssociations.entrySet()) {
        QName associationName = entry.getKey();
        DeltaSetTriple<ItemValueWithOrigin<PrismContainerValue<ShadowAssociationType>, PrismContainerDefinition<ShadowAssociationType>>> triple = entry.getValue();
        ContainerDelta<ShadowAssociationType> containerDelta = consolidateAssociation(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeAccount, associationName, triple);
        if (containerDelta != null) {
            objectDelta.addModification(containerDelta);
        }
    }
    return objectDelta;
}
Also used : PrismValue(com.evolveum.midpoint.prism.PrismValue) Construction(com.evolveum.midpoint.model.impl.lens.Construction) ChangeType(com.evolveum.midpoint.prism.delta.ChangeType) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Autowired(org.springframework.beans.factory.annotation.Autowired) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) com.evolveum.midpoint.common.refinery(com.evolveum.midpoint.common.refinery) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) Map(java.util.Map) PrismValueDeltaSetTripleProducer(com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) Mapping(com.evolveum.midpoint.model.common.mapping.Mapping) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) InternalsConfig.consistencyChecks(com.evolveum.midpoint.schema.internals.InternalsConfig.consistencyChecks) Collection(java.util.Collection) Task(com.evolveum.midpoint.task.api.Task) MatchingRuleRegistry(com.evolveum.midpoint.prism.match.MatchingRuleRegistry) ObjectUtils(org.apache.commons.lang.ObjectUtils) ResourceShadowDiscriminator(com.evolveum.midpoint.schema.ResourceShadowDiscriminator) List(java.util.List) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) Entry(java.util.Map.Entry) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) QName(javax.xml.namespace.QName) MappingStrengthType(com.evolveum.midpoint.xml.ns._public.common.common_3.MappingStrengthType) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemDefinition(com.evolveum.midpoint.prism.ItemDefinition) Trace(com.evolveum.midpoint.util.logging.Trace) HashMap(java.util.HashMap) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ArrayList(java.util.ArrayList) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) DeltaSetTriple(com.evolveum.midpoint.prism.delta.DeltaSetTriple) PrismContext(com.evolveum.midpoint.prism.PrismContext) PrismContainerDefinition(com.evolveum.midpoint.prism.PrismContainerDefinition) ItemValueWithOrigin(com.evolveum.midpoint.model.impl.lens.ItemValueWithOrigin) ContainerDelta(com.evolveum.midpoint.prism.delta.ContainerDelta) LensUtil(com.evolveum.midpoint.model.impl.lens.LensUtil) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) Iterator(java.util.Iterator) ShadowAssociationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType) PrismObject(com.evolveum.midpoint.prism.PrismObject) SynchronizationPolicyDecision(com.evolveum.midpoint.model.api.context.SynchronizationPolicyDecision) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) LensProjectionContext(com.evolveum.midpoint.model.impl.lens.LensProjectionContext) Component(org.springframework.stereotype.Component) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) LayerType(com.evolveum.midpoint.xml.ns._public.common.common_3.LayerType) PrismReference(com.evolveum.midpoint.prism.PrismReference) Comparator(java.util.Comparator) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) DeltaSetTriple(com.evolveum.midpoint.prism.delta.DeltaSetTriple) ArrayList(java.util.ArrayList) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) MappingStrengthType(com.evolveum.midpoint.xml.ns._public.common.common_3.MappingStrengthType) ItemValueWithOrigin(com.evolveum.midpoint.model.impl.lens.ItemValueWithOrigin) Collection(java.util.Collection) ResourceShadowDiscriminator(com.evolveum.midpoint.schema.ResourceShadowDiscriminator) Map(java.util.Map) HashMap(java.util.HashMap) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) PrismValueDeltaSetTripleProducer(com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) ShadowAssociationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) QName(javax.xml.namespace.QName) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) PrismContainerDefinition(com.evolveum.midpoint.prism.PrismContainerDefinition) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 19 with LensContext

use of com.evolveum.midpoint.model.impl.lens.LensContext in project midpoint by Evolveum.

the class TestClockwork method test010SerializeAddUserBarbossa.

// tests specific bug dealing with preservation of null values in focus secondary deltas
@Test(enabled = true)
public void test010SerializeAddUserBarbossa() throws Exception {
    final String TEST_NAME = "test010SerializeAddUserBarbossa";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = taskManager.createTaskInstance(TestClockwork.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();
    LensContext<UserType> context = createUserLensContext();
    PrismObject<UserType> bill = prismContext.parseObject(USER_BARBOSSA_FILE);
    fillContextWithAddUserDelta(context, bill);
    // WHEN
    // one round - compute projections
    clockwork.click(context, task, result);
    System.out.println("Context before serialization = " + context.debugDump());
    PrismContainer<LensContextType> lensContextType = context.toPrismContainer();
    String xml = prismContext.xmlSerializer().serialize(lensContextType.getValue(), lensContextType.getElementName());
    display("Serialized form", xml);
    LensContextType unmarshalledContainer = prismContext.parserFor(xml).xml().parseRealValue(LensContextType.class);
    LensContext context2 = LensContext.fromLensContextType(unmarshalledContainer, context.getPrismContext(), provisioningService, task, result);
    display("Context after deserialization", context);
    // THEN
    assertEquals("Secondary deltas are not preserved - their number differs", context.getFocusContext().getSecondaryDeltas().size(), context2.getFocusContext().getSecondaryDeltas().size());
    for (int i = 0; i < context.getFocusContext().getSecondaryDeltas().size(); i++) {
        assertEquals("Secondary delta #" + i + " is not preserved correctly", context.getFocusContext().getSecondaryDelta(i).debugDump(), context2.getFocusContext().getSecondaryDelta(i).debugDump());
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) Test(org.testng.annotations.Test)

Example 20 with LensContext

use of com.evolveum.midpoint.model.impl.lens.LensContext in project midpoint by Evolveum.

the class ModelOperationTaskHandler method run.

@Override
public TaskRunResult run(Task task) {
    OperationResult result = task.getResult().createSubresult(DOT_CLASS + "run");
    TaskRunResult runResult = new TaskRunResult();
    LensContextType contextType = task.getModelOperationContext();
    if (contextType == null) {
        LOGGER.trace("No model context found, skipping the model operation execution.");
        if (result.isUnknown()) {
            result.computeStatus();
        }
        runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.FINISHED);
    } else {
        LensContext context;
        try {
            context = LensContext.fromLensContextType(contextType, prismContext, provisioningService, task, result);
        } catch (SchemaException e) {
            throw new SystemException("Cannot recover model context from task " + task + " due to schema exception", e);
        } catch (ObjectNotFoundException | ConfigurationException | ExpressionEvaluationException e) {
            throw new SystemException("Cannot recover model context from task " + task, e);
        } catch (CommunicationException e) {
            // todo wait and retry
            throw new SystemException("Cannot recover model context from task " + task, e);
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Context to be executed = {}", context.debugDump());
        }
        try {
            // here we brutally remove all the projection contexts -- because if we are continuing after rejection of a role/resource assignment
            // that resulted in such projection contexts, we DO NOT want them to appear in the context any more
            context.rot();
            Iterator<LensProjectionContext> projectionIterator = context.getProjectionContextsIterator();
            while (projectionIterator.hasNext()) {
                LensProjectionContext projectionContext = projectionIterator.next();
                if (projectionContext.getPrimaryDelta() != null && !projectionContext.getPrimaryDelta().isEmpty()) {
                    // don't remove client requested actions!
                    continue;
                }
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Removing projection context {}", projectionContext.getHumanReadableName());
                }
                projectionIterator.remove();
            }
            if (task.getChannel() == null) {
                task.setChannel(context.getChannel());
            }
            clockwork.run(context, task, result);
            task.setModelOperationContext(context.toLensContextType());
            task.savePendingModifications(result);
            if (result.isUnknown()) {
                result.computeStatus();
            }
            runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.FINISHED);
        } catch (RuntimeException | CommonException e) {
            String message = "An exception occurred within model operation, in task " + task;
            LoggingUtils.logUnexpectedException(LOGGER, message, e);
            result.recordPartialError(message, e);
            // TODO: here we do not know whether the error is temporary or permanent (in the future we could discriminate on the basis of particular exception caught)
            runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.TEMPORARY_ERROR);
        }
    }
    task.getResult().recomputeStatus();
    runResult.setOperationResult(task.getResult());
    return runResult;
}
Also used : LensProjectionContext(com.evolveum.midpoint.model.impl.lens.LensProjectionContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) LensContextType(com.evolveum.midpoint.xml.ns._public.common.common_3.LensContextType) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult)

Aggregations

LensContext (com.evolveum.midpoint.model.impl.lens.LensContext)21 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)15 Task (com.evolveum.midpoint.task.api.Task)13 Test (org.testng.annotations.Test)9 ModelContext (com.evolveum.midpoint.model.api.context.ModelContext)8 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)6 JAXBException (javax.xml.bind.JAXBException)6 LensProjectionContext (com.evolveum.midpoint.model.impl.lens.LensProjectionContext)5 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)4 ResourceShadowDiscriminator (com.evolveum.midpoint.schema.ResourceShadowDiscriminator)4 ModelProjectionContext (com.evolveum.midpoint.model.api.context.ModelProjectionContext)3 LensFocusContext (com.evolveum.midpoint.model.impl.lens.LensFocusContext)3 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)3 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)3 SynchronizationPolicyDecision (com.evolveum.midpoint.model.api.context.SynchronizationPolicyDecision)2 HookOperationMode (com.evolveum.midpoint.model.api.hooks.HookOperationMode)2 ItemDefinition (com.evolveum.midpoint.prism.ItemDefinition)2 PrismContainerValue (com.evolveum.midpoint.prism.PrismContainerValue)2 PrismContext (com.evolveum.midpoint.prism.PrismContext)2 PrismObject (com.evolveum.midpoint.prism.PrismObject)2