Search in sources :

Example 46 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class TestEditSchema method test121LookupLanguagesGetByKeyStartingWith.

@Test
public void test121LookupLanguagesGetByKeyStartingWith() throws Exception {
    final String TEST_NAME = "test121LookupLanguagesGetByKeyStartingWith";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();
    // WHEN
    TestUtil.displayWhen(TEST_NAME);
    RelationalValueSearchQuery query = new RelationalValueSearchQuery(LookupTableRowType.F_KEY, "e", RelationalValueSearchType.STARTS_WITH);
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(LookupTableType.F_ROW, GetOperationOptions.createRetrieve(query));
    PrismObject<LookupTableType> lookup = modelService.getObject(LookupTableType.class, LOOKUP_LANGUAGES_OID, options, task, result);
    // THEN
    TestUtil.displayThen(TEST_NAME);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    checkLookupResult(lookup, new String[] { "en_US", "en", "English (US)" }, new String[] { "en_PR", "en", "English (pirate)" });
}
Also used : Task(com.evolveum.midpoint.task.api.Task) RelationalValueSearchQuery(com.evolveum.midpoint.schema.RelationalValueSearchQuery) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LookupTableType(com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType) Test(org.testng.annotations.Test)

Example 47 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class TestEditSchema method test102LookupLanguagesGetExclude.

@Test
public void test102LookupLanguagesGetExclude() throws Exception {
    final String TEST_NAME = "test102LookupLanguagesGetExclude";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.EXCLUDE));
    // WHEN
    TestUtil.displayWhen(TEST_NAME);
    PrismObject<LookupTableType> lookup = modelService.getObject(LookupTableType.class, LOOKUP_LANGUAGES_OID, options, task, result);
    // THEN
    TestUtil.displayThen(TEST_NAME);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    IntegrationTestTools.display("Languages", lookup);
    assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig());
    PrismContainer<LookupTableRowType> tableContainer = lookup.findContainer(LookupTableType.F_ROW);
    assertNull("Table container sneaked in", tableContainer);
    assertSteadyResources();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LookupTableRowType(com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType) LookupTableType(com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType) Test(org.testng.annotations.Test)

Example 48 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions 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 49 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions 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 50 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class LookupTableHelper method findLookupTableGetOption.

public GetOperationOptions findLookupTableGetOption(Collection<SelectorOptions<GetOperationOptions>> options) {
    final ItemPath tablePath = new ItemPath(LookupTableType.F_ROW);
    Collection<SelectorOptions<GetOperationOptions>> filtered = SelectorOptions.filterRetrieveOptions(options);
    for (SelectorOptions<GetOperationOptions> option : filtered) {
        ObjectSelector selector = option.getSelector();
        if (selector == null) {
            // apply to lookup table
            continue;
        }
        ItemPath selected = selector.getPath();
        if (tablePath.equivalent(selected)) {
            return option.getOptions();
        }
    }
    return null;
}
Also used : GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) ObjectSelector(com.evolveum.midpoint.schema.ObjectSelector) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Aggregations

SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)127 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)106 Task (com.evolveum.midpoint.task.api.Task)82 Test (org.testng.annotations.Test)47 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)34 GetOperationOptions (com.evolveum.midpoint.schema.GetOperationOptions)31 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)31 PrismObject (com.evolveum.midpoint.prism.PrismObject)28 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)28 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)28 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)23 ResourceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType)21 ArrayList (java.util.ArrayList)19 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)17 QName (javax.xml.namespace.QName)17 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)16 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)16 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)14 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)14 ResultHandler (com.evolveum.midpoint.schema.ResultHandler)12