Search in sources :

Example 31 with ResultHandler

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

the class TestBrokenResources method testListResources.

public void testListResources(final String TEST_NAME, int expectedNumber, Collection<SelectorOptions<GetOperationOptions>> options) throws Exception {
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN (1)
    Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();
    // WHEN (1)
    final SearchResultList<PrismObject<ResourceType>> resources = modelService.searchObjects(ResourceType.class, null, options, task, result);
    // THEN (1)
    result.computeStatus();
    display("getObject result", result);
    if (options == null) {
        assertEquals("Expected partial error (search)", OperationResultStatus.PARTIAL_ERROR, result.getStatus());
    } else if (GetOperationOptions.isNoFetch(SelectorOptions.findRootOptions(options))) {
        TestUtil.assertSuccess(result);
    } else {
        AssertJUnit.fail("unexpected");
    }
    display("Got resources: " + resources);
    assertEquals("Wrong number of resources", expectedNumber, resources.size());
    // GIVEN (2)
    resources.clear();
    task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "." + TEST_NAME);
    result = task.getResult();
    ResultHandler<ResourceType> handler = new ResultHandler<ResourceType>() {

        @Override
        public boolean handle(PrismObject<ResourceType> object, OperationResult parentResult) {
            resources.add(object);
            return true;
        }
    };
    // WHEN (2)
    modelService.searchObjectsIterative(ResourceType.class, null, handler, options, task, result);
    // THEN (2)
    result.computeStatus();
    display("getObject result", result);
    if (options == null) {
        assertEquals("Expected partial error (searchIterative)", OperationResultStatus.PARTIAL_ERROR, result.getStatus());
    } else if (GetOperationOptions.isNoFetch(SelectorOptions.findRootOptions(options))) {
        TestUtil.assertSuccess(result);
    } else {
        AssertJUnit.fail("unexpected");
    }
    display("Got resources: " + resources);
    assertEquals("Wrong number of resources", expectedNumber, resources.size());
}
Also used : PrismObject(com.evolveum.midpoint.prism.PrismObject) Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResourceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType) ResultHandler(com.evolveum.midpoint.schema.ResultHandler)

Example 32 with ResultHandler

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

the class AbstractSecurityTest method assertSearch.

protected <O extends ObjectType> void assertSearch(Class<O> type, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, int expectedResults) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertSearchObjects");
    OperationResult result = task.getResult();
    try {
        logAttempt("search", type, query);
        List<PrismObject<O>> objects = modelService.searchObjects(type, query, options, task, result);
        display("Search returned", objects.toString());
        if (objects.size() > expectedResults) {
            failDeny("search", type, query, expectedResults, objects.size());
        } else if (objects.size() < expectedResults) {
            failAllow("search", type, query, expectedResults, objects.size());
        }
        result.computeStatus();
        TestUtil.assertSuccess(result);
    } catch (SecurityViolationException e) {
        // this should not happen
        result.computeStatus();
        TestUtil.assertFailure(result);
        failAllow("search", type, query, e);
    }
    task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertSearchObjectsIterative");
    result = task.getResult();
    try {
        logAttempt("searchIterative", type, query);
        final List<PrismObject<O>> objects = new ArrayList<>();
        ResultHandler<O> handler = new ResultHandler<O>() {

            @Override
            public boolean handle(PrismObject<O> object, OperationResult parentResult) {
                objects.add(object);
                return true;
            }
        };
        modelService.searchObjectsIterative(type, query, handler, options, task, result);
        display("Search iterative returned", objects.toString());
        if (objects.size() > expectedResults) {
            failDeny("searchIterative", type, query, expectedResults, objects.size());
        } else if (objects.size() < expectedResults) {
            failAllow("searchIterative", type, query, expectedResults, objects.size());
        }
        result.computeStatus();
        TestUtil.assertSuccess(result);
    } catch (SecurityViolationException e) {
        // this should not happen
        result.computeStatus();
        TestUtil.assertFailure(result);
        failAllow("searchIterative", type, query, e);
    }
    task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertSearchObjects.count");
    result = task.getResult();
    try {
        logAttempt("count", type, query);
        int numObjects = modelService.countObjects(type, query, options, task, result);
        display("Count returned", numObjects);
        if (numObjects > expectedResults) {
            failDeny("count", type, query, expectedResults, numObjects);
        } else if (numObjects < expectedResults) {
            failAllow("count", type, query, expectedResults, numObjects);
        }
        result.computeStatus();
        TestUtil.assertSuccess(result);
    } catch (SecurityViolationException e) {
        // this should not happen
        result.computeStatus();
        TestUtil.assertFailure(result);
        failAllow("search", type, query, e);
    }
}
Also used : PrismObject(com.evolveum.midpoint.prism.PrismObject) Task(com.evolveum.midpoint.task.api.Task) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler)

Example 33 with ResultHandler

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

the class AccCertCaseOperationsHelper method getDeltasToCreateCases.

<F extends FocusType> List<ItemDelta<?, ?>> getDeltasToCreateCases(final AccessCertificationCampaignType campaign, AccessCertificationStageType stage, final CertificationHandler handler, final Task task, final OperationResult result) throws SchemaException, ObjectNotFoundException {
    final List<ItemDelta<?, ?>> rv = new ArrayList<>();
    final String campaignShortName = toShortString(campaign);
    final AccessCertificationScopeType scope = campaign.getScopeDefinition();
    LOGGER.trace("Creating cases for scope {} in campaign {}", scope, campaignShortName);
    if (scope != null && !(scope instanceof AccessCertificationObjectBasedScopeType)) {
        throw new IllegalStateException("Unsupported access certification scope type: " + scope.getClass() + " for campaign " + campaignShortName);
    }
    final AccessCertificationObjectBasedScopeType objectBasedScope = (AccessCertificationObjectBasedScopeType) scope;
    final List<AccessCertificationCaseType> existingCases = queryHelper.searchCases(campaign.getOid(), null, null, result);
    if (!existingCases.isEmpty()) {
        throw new IllegalStateException("Unexpected " + existingCases.size() + " certification case(s) in campaign object " + campaignShortName + ". At this time there should be none.");
    }
    // create a query to find target objects from which certification cases will be created
    final ObjectQuery query = new ObjectQuery();
    final QName scopeDeclaredObjectType;
    if (objectBasedScope != null) {
        scopeDeclaredObjectType = objectBasedScope.getObjectType();
    } else {
        scopeDeclaredObjectType = null;
    }
    final QName objectType;
    if (scopeDeclaredObjectType != null) {
        objectType = scopeDeclaredObjectType;
    } else {
        objectType = handler.getDefaultObjectType();
    }
    if (objectType == null) {
        throw new IllegalStateException("Unspecified object type (and no default one provided) for campaign " + campaignShortName);
    }
    @SuppressWarnings({ "unchecked", "raw" }) final Class<F> objectClass = (Class<F>) prismContext.getSchemaRegistry().getCompileTimeClassForObjectType(objectType);
    if (objectClass == null) {
        throw new IllegalStateException("Object class not found for object type " + objectType + " in campaign " + campaignShortName);
    }
    final SearchFilterType searchFilter = objectBasedScope != null ? objectBasedScope.getSearchFilter() : null;
    if (searchFilter != null) {
        ObjectFilter filter = QueryConvertor.parseFilter(searchFilter, objectClass, prismContext);
        query.setFilter(filter);
    }
    final List<AccessCertificationCaseType> caseList = new ArrayList<>();
    // create certification cases by executing the query and caseExpression on its results
    // here the subclasses of this class come into play
    ResultHandler<F> resultHandler = (object, parentResult) -> {
        try {
            caseList.addAll(handler.createCasesForObject(object, campaign, task, parentResult));
        } catch (ExpressionEvaluationException | ObjectNotFoundException | SchemaException e) {
            // TODO process the exception more intelligently
            throw new SystemException("Cannot create certification case for object " + toShortString(object.asObjectable()) + ": " + e.getMessage(), e);
        }
        return true;
    };
    repositoryService.searchObjectsIterative(objectClass, query, resultHandler, null, false, result);
    AccessCertificationReviewerSpecificationType reviewerSpec = reviewersHelper.findReviewersSpecification(campaign, 1, task, result);
    ContainerDelta<AccessCertificationCaseType> caseDelta = ContainerDelta.createDelta(F_CASE, AccessCertificationCampaignType.class, prismContext);
    for (AccessCertificationCaseType _case : caseList) {
        _case.setStageNumber(1);
        _case.setCurrentStageCreateTimestamp(stage.getStartTimestamp());
        _case.setCurrentStageDeadline(stage.getDeadline());
        List<ObjectReferenceType> reviewers = reviewersHelper.getReviewersForCase(_case, campaign, reviewerSpec, task, result);
        _case.getWorkItem().addAll(createWorkItems(reviewers, 1));
        String currentStageOutcome = OutcomeUtils.toUri(computationHelper.computeOutcomeForStage(_case, campaign, 1));
        _case.setCurrentStageOutcome(currentStageOutcome);
        _case.setOutcome(OutcomeUtils.toUri(computationHelper.computeOverallOutcome(_case, campaign, currentStageOutcome)));
        @SuppressWarnings({ "raw", "unchecked" }) PrismContainerValue<AccessCertificationCaseType> caseCVal = _case.asPrismContainerValue();
        caseDelta.addValueToAdd(caseCVal);
        LOGGER.trace("Adding certification case:\n{}", caseCVal.debugDumpLazily());
    }
    rv.add(caseDelta);
    LOGGER.trace("Created {} deltas to create {} cases for campaign {}", rv.size(), caseList.size(), campaignShortName);
    return rv;
}
Also used : java.util(java.util) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SecurityEnforcer(com.evolveum.midpoint.security.api.SecurityEnforcer) Autowired(org.springframework.beans.factory.annotation.Autowired) Trace(com.evolveum.midpoint.util.logging.Trace) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectTypeUtil(com.evolveum.midpoint.schema.util.ObjectTypeUtil) PrismContext(com.evolveum.midpoint.prism.PrismContext) Qualifier(org.springframework.beans.factory.annotation.Qualifier) F_CASE(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_CASE) RepositoryService(com.evolveum.midpoint.repo.api.RepositoryService) ContainerDelta(com.evolveum.midpoint.prism.delta.ContainerDelta) CloneUtil(com.evolveum.midpoint.prism.util.CloneUtil) XmlTypeConverter(com.evolveum.midpoint.prism.xml.XmlTypeConverter) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) DeltaBuilder(com.evolveum.midpoint.prism.delta.builder.DeltaBuilder) IdItemPathSegment(com.evolveum.midpoint.prism.path.IdItemPathSegment) Task(com.evolveum.midpoint.task.api.Task) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) CertCampaignTypeUtil(com.evolveum.midpoint.schema.util.CertCampaignTypeUtil) ObjectUtils(org.apache.commons.lang.ObjectUtils) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) QueryConvertor(com.evolveum.midpoint.prism.marshaller.QueryConvertor) Objects(java.util.Objects) Component(org.springframework.stereotype.Component) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) NameItemPathSegment(com.evolveum.midpoint.prism.path.NameItemPathSegment) SearchFilterType(com.evolveum.prism.xml.ns._public.query_3.SearchFilterType) CertificationHandler(com.evolveum.midpoint.certification.impl.handlers.CertificationHandler) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) QName(javax.xml.namespace.QName) NotNull(org.jetbrains.annotations.NotNull) Clock(com.evolveum.midpoint.common.Clock) AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) OutcomeUtils(com.evolveum.midpoint.certification.api.OutcomeUtils) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) ObjectTypeUtil.toShortString(com.evolveum.midpoint.schema.util.ObjectTypeUtil.toShortString) AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectTypeUtil.toShortString(com.evolveum.midpoint.schema.util.ObjectTypeUtil.toShortString) SearchFilterType(com.evolveum.prism.xml.ns._public.query_3.SearchFilterType) QName(javax.xml.namespace.QName) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery)

Example 34 with ResultHandler

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

the class TestDummy method testSeachIterative.

private void testSeachIterative(final String TEST_NAME, ObjectFilter attrFilter, GetOperationOptions rootOptions, final boolean fullShadow, boolean useObjectClassFilter, final boolean useRepo, String... expectedAccountNames) throws Exception {
    OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME);
    ObjectQuery query;
    if (useObjectClassFilter) {
        query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext);
        if (attrFilter != null) {
            AndFilter filter = (AndFilter) query.getFilter();
            filter.getConditions().add(attrFilter);
        }
    } else {
        query = ObjectQueryUtil.createResourceQuery(RESOURCE_DUMMY_OID, prismContext);
        if (attrFilter != null) {
            query.setFilter(AndFilter.createAnd(query.getFilter(), attrFilter));
        }
    }
    display("Query", query);
    final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar();
    final List<PrismObject<ShadowType>> foundObjects = new ArrayList<PrismObject<ShadowType>>();
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {

        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            foundObjects.add(shadow);
            XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar();
            assertTrue(shadow.canRepresent(ShadowType.class));
            if (!useRepo) {
                try {
                    checkAccountShadow(shadow, parentResult, fullShadow, startTs, endTs);
                } catch (SchemaException e) {
                    throw new SystemException(e.getMessage(), e);
                }
            }
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(rootOptions);
    // WHEN
    if (useRepo) {
        repositoryService.searchObjectsIterative(ShadowType.class, query, handler, null, false, result);
    } else {
        provisioningService.searchObjectsIterative(ShadowType.class, query, options, handler, null, result);
    }
    // THEN
    result.computeStatus();
    display("searchObjectsIterative result", result);
    TestUtil.assertSuccess(result);
    display("found shadows", foundObjects);
    for (String expectedAccountId : expectedAccountNames) {
        boolean found = false;
        for (PrismObject<ShadowType> foundObject : foundObjects) {
            if (expectedAccountId.equals(foundObject.asObjectable().getName().getOrig())) {
                found = true;
                break;
            }
        }
        if (!found) {
            AssertJUnit.fail("Account " + expectedAccountId + " was expected to be found but it was not found (found " + foundObjects.size() + ", expected " + expectedAccountNames.length + ")");
        }
    }
    assertEquals("Wrong number of found objects (" + foundObjects + "): " + foundObjects, expectedAccountNames.length, foundObjects.size());
    if (!useRepo) {
        checkConsistency(foundObjects);
    }
    assertSteadyResource();
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) AndFilter(com.evolveum.midpoint.prism.query.AndFilter) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) PrismObject(com.evolveum.midpoint.prism.PrismObject) SystemException(com.evolveum.midpoint.util.exception.SystemException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Example 35 with ResultHandler

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

the class TestDummy method test111SeachIterativeNoFetch.

@Test
public void test111SeachIterativeNoFetch() throws Exception {
    final String TEST_NAME = "test111SeachIterativeNoFetch";
    TestUtil.displayTestTile(TEST_NAME);
    // GIVEN
    OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME);
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext);
    final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar();
    final List<PrismObject<ShadowType>> foundObjects = new ArrayList<PrismObject<ShadowType>>();
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {

        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            foundObjects.add(shadow);
            assertTrue(shadow.canRepresent(ShadowType.class));
            try {
                checkCachedAccountShadow(shadow, parentResult, false, null, startTs);
            } catch (SchemaException e) {
                throw new SystemException(e.getMessage(), e);
            }
            assertRepoCachingMetadata(shadow, null, startTs);
            if (shadow.asObjectable().getName().getOrig().equals("meathook")) {
                assertRepoShadowCachedAttributeValue(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Sea Monkey");
            }
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch());
    rememberShadowFetchOperationCount();
    // WHEN
    provisioningService.searchObjectsIterative(ShadowType.class, query, options, handler, null, result);
    // THEN
    result.computeStatus();
    display("searchObjectsIterative result", result);
    TestUtil.assertSuccess(result);
    assertShadowFetchOperationCountIncrement(0);
    display("Found shadows", foundObjects);
    assertEquals(4, foundObjects.size());
    checkConsistency(foundObjects);
    // MID-1640
    assertProtected(foundObjects, 1);
    assertSteadyResource();
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) PrismObject(com.evolveum.midpoint.prism.PrismObject) SystemException(com.evolveum.midpoint.util.exception.SystemException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Test(org.testng.annotations.Test)

Aggregations

ResultHandler (com.evolveum.midpoint.schema.ResultHandler)54 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)53 PrismObject (com.evolveum.midpoint.prism.PrismObject)39 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)33 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)29 Test (org.testng.annotations.Test)29 ArrayList (java.util.ArrayList)24 SystemException (com.evolveum.midpoint.util.exception.SystemException)23 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)22 Task (com.evolveum.midpoint.task.api.Task)19 QName (javax.xml.namespace.QName)19 DirtiesContext (org.springframework.test.annotation.DirtiesContext)19 ContextConfiguration (org.springframework.test.context.ContextConfiguration)19 AssertJUnit (org.testng.AssertJUnit)17 RepositoryService (com.evolveum.midpoint.repo.api.RepositoryService)16 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)16 List (java.util.List)16 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)15 SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)14 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)13