Search in sources :

Example 46 with FocusType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType in project midpoint by Evolveum.

the class AbstractWfTestPolicy method executeTest.

protected <F extends FocusType> void executeTest(String testName, TestDetails testDetails, int expectedSubTaskCount) throws Exception {
    // GIVEN
    prepareNotifications();
    dummyAuditService.clear();
    Task modelTask = taskManager.createTaskInstance(AbstractWfTestPolicy.class.getName() + "." + testName);
    modelTask.setOwner(userAdministrator);
    OperationResult result = new OperationResult("execution");
    LensContext<F> modelContext = testDetails.createModelContext(result);
    display("Model context at test start", modelContext);
    // this has problems with deleting assignments by ID
    //assertFocusModificationSanity(modelContext);
    // WHEN
    HookOperationMode mode = clockwork.run(modelContext, modelTask, result);
    // THEN
    display("Model context after first clockwork.run", modelContext);
    assertEquals("Unexpected state of the context", ModelState.PRIMARY, modelContext.getState());
    assertEquals("Wrong mode after clockwork.run in " + modelContext.getState(), HookOperationMode.BACKGROUND, mode);
    modelTask.refresh(result);
    display("Model task after first clockwork.run", modelTask);
    String rootTaskOid = wfTaskUtil.getRootTaskOid(modelTask);
    assertNotNull("Root task OID is not set in model task", rootTaskOid);
    Task rootTask = taskManager.getTask(rootTaskOid, result);
    assertTrue("Root task is not persistent", rootTask.isPersistent());
    UriStack uriStack = rootTask.getOtherHandlersUriStack();
    if (!testDetails.executeImmediately()) {
        assertEquals("Invalid handler at stack position 0", ModelOperationTaskHandler.MODEL_OPERATION_TASK_URI, uriStack.getUriStackEntry().get(0).getHandlerUri());
    } else {
        assertTrue("There should be no handlers for root tasks with immediate execution mode", uriStack == null || uriStack.getUriStackEntry().isEmpty());
    }
    ModelContext rootModelContext = testDetails.executeImmediately() ? null : wfTaskUtil.getModelContext(rootTask, result);
    if (!testDetails.executeImmediately()) {
        assertNotNull("Model context is not present in root task", rootModelContext);
    } else {
        assertNull("Model context is present in root task (execution mode = immediate)", rootModelContext);
    }
    List<Task> subtasks = rootTask.listSubtasks(result);
    Task task0 = findAndRemoveTask0(subtasks, testDetails);
    assertEquals("Incorrect number of subtasks", expectedSubTaskCount, subtasks.size());
    final Collection<SelectorOptions<GetOperationOptions>> options1 = resolveItemsNamed(new ItemPath(T_PARENT, F_OBJECT_REF), new ItemPath(T_PARENT, F_TARGET_REF), F_ASSIGNEE_REF, F_ORIGINAL_ASSIGNEE_REF, new ItemPath(T_PARENT, F_REQUESTER_REF));
    List<WorkItemType> workItems = modelService.searchContainers(WorkItemType.class, null, options1, modelTask, result);
    testDetails.afterFirstClockworkRun(rootTask, subtasks, workItems, result);
    if (testDetails.executeImmediately()) {
        if (task0 != null) {
            waitForTaskClose(task0, 20000);
        }
        testDetails.afterTask0Finishes(rootTask, result);
    }
    for (int i = 0; i < subtasks.size(); i++) {
        Task subtask = subtasks.get(i);
        PrismProperty<ObjectTreeDeltasType> deltas = subtask.getTaskPrismObject().findProperty(new ItemPath(F_WORKFLOW_CONTEXT, F_PROCESSOR_SPECIFIC_STATE, F_DELTAS_TO_PROCESS));
        assertNotNull("There are no modifications in subtask #" + i + ": " + subtask, deltas);
        assertEquals("Incorrect number of modifications in subtask #" + i + ": " + subtask, 1, deltas.getRealValues().size());
        // todo check correctness of the modification?
        // now check the workflow state
        String pid = wfTaskUtil.getProcessId(subtask);
        assertNotNull("Workflow process instance id not present in subtask " + subtask, pid);
        List<org.activiti.engine.task.Task> tasks = activitiEngine.getTaskService().createTaskQuery().processInstanceId(pid).list();
        assertFalse("activiti task not found", tasks.isEmpty());
        for (org.activiti.engine.task.Task task : tasks) {
            String executionId = task.getExecutionId();
            display("Execution id = " + executionId);
            Boolean approve = testDetails.decideOnApproval(executionId, task);
            if (approve != null) {
                workflowManager.completeWorkItem(task.getId(), approve, null, null, null, result);
                login(userAdministrator);
                break;
            }
        }
    }
    // alternative way of approvals executions
    if (CollectionUtils.isNotEmpty(testDetails.getApprovalSequence())) {
        List<ApprovalInstruction> instructions = new ArrayList<>(testDetails.getApprovalSequence());
        while (!instructions.isEmpty()) {
            List<WorkItemType> currentWorkItems = modelService.searchContainers(WorkItemType.class, null, options1, modelTask, result);
            boolean matched = false;
            main: for (ApprovalInstruction approvalInstruction : instructions) {
                for (WorkItemType workItem : currentWorkItems) {
                    if (approvalInstruction.matches(workItem)) {
                        if (approvalInstruction.beforeApproval != null) {
                            approvalInstruction.beforeApproval.run();
                        }
                        login(getUserFromRepo(approvalInstruction.approverOid));
                        workflowManager.completeWorkItem(workItem.getExternalId(), approvalInstruction.approval, null, null, null, result);
                        if (approvalInstruction.afterApproval != null) {
                            approvalInstruction.afterApproval.run();
                        }
                        login(userAdministrator);
                        matched = true;
                        instructions.remove(approvalInstruction);
                        break main;
                    }
                }
            }
            if (!matched) {
                fail("None of approval instructions " + instructions + " matched any of current work items: " + currentWorkItems);
            }
        }
    }
    waitForTaskClose(rootTask, 60000);
    subtasks = rootTask.listSubtasks(result);
    findAndRemoveTask0(subtasks, testDetails);
    testDetails.afterRootTaskFinishes(rootTask, subtasks, result);
    notificationManager.setDisabled(true);
    // Check audit
    display("Audit", dummyAuditService);
    display("Output context", modelContext);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) HookOperationMode(com.evolveum.midpoint.model.api.hooks.HookOperationMode) WorkItemType(com.evolveum.midpoint.xml.ns._public.common.common_3.WorkItemType) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 47 with FocusType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType in project midpoint by Evolveum.

the class ObjectUpdater method modifyObjectAttempt.

public <T extends ObjectType> void modifyObjectAttempt(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, RepoModifyOptions modifyOptions, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SerializationRelatedException {
    // clone - because some certification and lookup table related methods manipulate this collection and even their constituent deltas
    // TODO clone elements only if necessary
    modifications = CloneUtil.cloneCollectionMembers(modifications);
    //modifications = new ArrayList<>(modifications);
    LOGGER.debug("Modifying object '{}' with oid '{}'.", new Object[] { type.getSimpleName(), oid });
    LOGGER_PERFORMANCE.debug("> modify object {}, oid={}, modifications={}", type.getSimpleName(), oid, modifications);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Modifications:\n{}", DebugUtil.debugDump(modifications));
    }
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    try {
        session = baseHelper.beginTransaction();
        closureContext = closureManager.onBeginTransactionModify(session, type, oid, modifications);
        Collection<? extends ItemDelta> lookupTableModifications = lookupTableHelper.filterLookupTableModifications(type, modifications);
        Collection<? extends ItemDelta> campaignCaseModifications = caseHelper.filterCampaignCaseModifications(type, modifications);
        if (!modifications.isEmpty() || RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
            // JpegPhoto (RFocusPhoto) is a special kind of entity. First of all, it is lazily loaded, because photos are really big.
            // Each RFocusPhoto naturally belongs to one RFocus, so it would be appropriate to set orphanRemoval=true for focus-photo
            // association. However, this leads to a strange problem when merging in-memory RFocus object with the database state:
            // If in-memory RFocus object has no photo associated (because of lazy loading), then the associated RFocusPhoto is deleted.
            //
            // To prevent this behavior, we've set orphanRemoval to false. Fortunately, the remove operation on RFocus
            // seems to be still cascaded to RFocusPhoto. What we have to implement ourselves, however, is removal of RFocusPhoto
            // _without_ removing of RFocus. In order to know whether the photo has to be removed, we have to retrieve
            // its value, apply the delta (e.g. if the delta is a DELETE VALUE X, we have to know whether X matches current
            // value of the photo), and if the resulting value is empty, we have to manually delete the RFocusPhoto instance.
            //
            // So the first step is to retrieve the current value of photo - we obviously do this only if the modifications
            // deal with the jpegPhoto property.
            Collection<SelectorOptions<GetOperationOptions>> options;
            boolean containsFocusPhotoModification = FocusType.class.isAssignableFrom(type) && containsPhotoModification(modifications);
            if (containsFocusPhotoModification) {
                options = Collections.singletonList(SelectorOptions.create(FocusType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)));
            } else {
                options = null;
            }
            // get object
            PrismObject<T> prismObject = objectRetriever.getObjectInternal(session, type, oid, options, true, result);
            // apply diff
            LOGGER.trace("OBJECT before:\n{}", prismObject.debugDumpLazily());
            PrismObject<T> originalObject = null;
            if (closureManager.isEnabled()) {
                originalObject = prismObject.clone();
            }
            ItemDelta.applyTo(modifications, prismObject);
            LOGGER.trace("OBJECT after:\n{}", prismObject.debugDumpLazily());
            // Continuing the photo treatment: should we remove the (now obsolete) focus photo?
            // We have to test prismObject at this place, because updateFullObject (below) removes photo property from the prismObject.
            boolean shouldPhotoBeRemoved = containsFocusPhotoModification && ((FocusType) prismObject.asObjectable()).getJpegPhoto() == null;
            // merge and update object
            LOGGER.trace("Translating JAXB to data type.");
            ObjectTypeUtil.normalizeAllRelations(prismObject);
            RObject rObject = createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY);
            rObject.setVersion(rObject.getVersion() + 1);
            updateFullObject(rObject, prismObject);
            LOGGER.trace("Starting merge.");
            session.merge(rObject);
            if (closureManager.isEnabled()) {
                closureManager.updateOrgClosure(originalObject, modifications, session, oid, type, OrgClosureManager.Operation.MODIFY, closureContext);
            }
            // we have to remove the photo manually.
            if (shouldPhotoBeRemoved) {
                Query query = session.createQuery("delete RFocusPhoto where ownerOid = :oid");
                query.setParameter("oid", prismObject.getOid());
                query.executeUpdate();
                LOGGER.trace("Focus photo for {} was deleted", prismObject.getOid());
            }
        }
        if (LookupTableType.class.isAssignableFrom(type)) {
            lookupTableHelper.updateLookupTableData(session, oid, lookupTableModifications);
        }
        if (AccessCertificationCampaignType.class.isAssignableFrom(type)) {
            caseHelper.updateCampaignCases(session, oid, campaignCaseModifications, modifyOptions);
        }
        LOGGER.trace("Before commit...");
        session.getTransaction().commit();
        LOGGER.trace("Committed!");
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (ConstraintViolationException ex) {
        handleConstraintViolationException(session, ex, result);
        baseHelper.rollbackTransaction(session, ex, result, true);
        LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex);
        //todo improve (we support only 5 DB, so we should probably do some hacking in here)
        throw new ObjectAlreadyExistsException(ex);
    } catch (SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
        LOGGER.trace("Session cleaned up.");
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) SQLQuery(org.hibernate.SQLQuery) Query(org.hibernate.Query) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) Session(org.hibernate.Session)

Example 48 with FocusType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType in project midpoint by Evolveum.

the class TestActivation method assertValidity.

private <F extends FocusType> void assertValidity(PrismObject<F> focus, TimeIntervalStatusType expectedValidityStatus) {
    ActivationType activation = focus.asObjectable().getActivation();
    assertNotNull("No activation in " + focus, activation);
    assertEquals("Unexpected validity status in " + focus, expectedValidityStatus, activation.getValidityStatus());
}
Also used : ActivationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType)

Example 49 with FocusType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType in project midpoint by Evolveum.

the class RFocus method copyFromJAXB.

public static <T extends FocusType> void copyFromJAXB(FocusType jaxb, RFocus<T> repo, RepositoryContext repositoryContext, IdGeneratorResult generatorResult) throws DtoTranslationException {
    RObject.copyFromJAXB(jaxb, repo, repositoryContext, generatorResult);
    repo.getLinkRef().addAll(RUtil.safeListReferenceToSet(jaxb.getLinkRef(), repositoryContext.prismContext, repo, RReferenceOwner.USER_ACCOUNT));
    repo.getRoleMembershipRef().addAll(RUtil.safeListReferenceToSet(jaxb.getRoleMembershipRef(), repositoryContext.prismContext, repo, RReferenceOwner.ROLE_MEMBER));
    repo.getDelegatedRef().addAll(RUtil.safeListReferenceToSet(jaxb.getDelegatedRef(), repositoryContext.prismContext, repo, RReferenceOwner.DELEGATED));
    repo.getPersonaRef().addAll(RUtil.safeListReferenceToSet(jaxb.getPersonaRef(), repositoryContext.prismContext, repo, RReferenceOwner.PERSONA));
    repo.setPolicySituation(RUtil.listToSet(jaxb.getPolicySituation()));
    for (AssignmentType assignment : jaxb.getAssignment()) {
        RAssignment rAssignment = new RAssignment(repo, RAssignmentOwner.FOCUS);
        RAssignment.copyFromJAXB(assignment, rAssignment, jaxb, repositoryContext, generatorResult);
        repo.getAssignments().add(rAssignment);
    }
    if (jaxb.getActivation() != null) {
        RActivation activation = new RActivation();
        RActivation.copyFromJAXB(jaxb.getActivation(), activation, repositoryContext);
        repo.setActivation(activation);
    }
    if (jaxb.getJpegPhoto() != null) {
        RFocusPhoto photo = new RFocusPhoto();
        photo.setOwner(repo);
        photo.setPhoto(jaxb.getJpegPhoto());
        repo.getJpegPhoto().add(photo);
        repo.setHasPhoto(true);
    }
}
Also used : RAssignment(com.evolveum.midpoint.repo.sql.data.common.container.RAssignment) RActivation(com.evolveum.midpoint.repo.sql.data.common.embedded.RActivation) AssignmentType(com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType)

Example 50 with FocusType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType in project midpoint by Evolveum.

the class TestReconScript method test006TestReconDelete.

@Test
public void test006TestReconDelete() throws Exception {
    final String TEST_NAME = "test006TestReconDelete";
    TestUtil.displayTestTile(this, TEST_NAME);
    PrismObject<TaskType> task = getTask(TASK_RECON_DUMMY_OID);
    OperationResult parentResult = new OperationResult(TEST_NAME);
    PropertyDelta dryRunDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_DRY_RUN), task.getDefinition(), false);
    Collection<PropertyDelta> modifications = new ArrayList<>();
    modifications.add(dryRunDelta);
    repositoryService.modifyObject(TaskType.class, TASK_RECON_DUMMY_OID, modifications, parentResult);
    //		dummyResource.deleteAccount("beforeScript");
    // WHEN
    TestUtil.displayWhen(TEST_NAME);
    waitForTaskStart(TASK_RECON_DUMMY_OID, false);
    waitForTaskNextRunAssertSuccess(TASK_RECON_DUMMY_OID, false);
    waitForTaskFinish(TASK_RECON_DUMMY_OID, false);
    // THEN
    TestUtil.displayThen(TEST_NAME);
    try {
        PrismObject<ShadowType> shadow = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult);
        display("Unexpected shadow", shadow);
        AssertJUnit.fail("Expected object not found, but haven't got one");
    } catch (ObjectNotFoundException ex) {
    //this is ok
    }
    PrismObject<FocusType> user = repositoryService.searchShadowOwner(ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult);
    display("Unexpected owner", user);
    AssertJUnit.assertNull("Owner for account " + ACCOUNT_BEFORE_SCRIPT_OID + " was found, but it should be not.", user);
}
Also used : ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) TaskType(com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) Test(org.testng.annotations.Test) AbstractInternalModelIntegrationTest(com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)

Aggregations

ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)27 ObjectReferenceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType)25 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)23 FocusType (com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType)22 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)21 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)18 PrismObject (com.evolveum.midpoint.prism.PrismObject)16 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)15 ArrayList (java.util.ArrayList)15 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)14 AssignmentType (com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType)12 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)10 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)9 LensProjectionContext (com.evolveum.midpoint.model.impl.lens.LensProjectionContext)8 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)8 QName (javax.xml.namespace.QName)8 PropertyDelta (com.evolveum.midpoint.prism.delta.PropertyDelta)7 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)7 PolicyViolationException (com.evolveum.midpoint.util.exception.PolicyViolationException)7 ActivationStatusType (com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType)7