Search in sources :

Example 1 with ExecutionContext

use of com.evolveum.midpoint.model.impl.scripting.ExecutionContext in project midpoint by Evolveum.

the class SearchEvaluator method evaluate.

public <T extends ObjectType> PipelineData evaluate(SearchExpressionType searchExpression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException {
    Validate.notNull(searchExpression.getType());
    boolean noFetch = expressionHelper.getArgumentAsBoolean(searchExpression.getParameter(), PARAM_NO_FETCH, input, context, false, "search", globalResult);
    @SuppressWarnings({ "unchecked", "raw" }) Class<T> objectClass = (Class<T>) ObjectTypes.getObjectTypeFromTypeQName(searchExpression.getType()).getClassDefinition();
    ObjectQuery objectQuery = null;
    if (searchExpression.getQuery() != null) {
        try {
            objectQuery = QueryJaxbConvertor.createObjectQuery(objectClass, searchExpression.getQuery(), prismContext);
        } catch (SchemaException e) {
            throw new ScriptExecutionException("Couldn't parse object query due to schema exception", e);
        }
    } else if (searchExpression.getSearchFilter() != null) {
        // todo resolve variable references in the filter
        objectQuery = new ObjectQuery();
        try {
            ObjectFilter filter = QueryConvertor.parseFilter(searchExpression.getSearchFilter(), objectClass, prismContext);
            objectQuery.setFilter(filter);
        } catch (SchemaException e) {
            throw new ScriptExecutionException("Couldn't parse object filter due to schema exception", e);
        }
    }
    final String variableName = searchExpression.getVariable();
    final PipelineData oldVariableValue = variableName != null ? context.getVariable(variableName) : null;
    final PipelineData outputData = PipelineData.createEmpty();
    final MutableBoolean atLeastOne = new MutableBoolean(false);
    ResultHandler<T> handler = (object, parentResult) -> {
        context.checkTaskStop();
        atLeastOne.setValue(true);
        if (searchExpression.getScriptingExpression() != null) {
            if (variableName != null) {
                context.setVariable(variableName, PipelineData.create(object.getValue()));
            }
            JAXBElement<?> childExpression = searchExpression.getScriptingExpression();
            try {
                outputData.addAllFrom(scriptingExpressionEvaluator.evaluateExpression((ScriptingExpressionType) childExpression.getValue(), PipelineData.create(object.getValue()), context, globalResult));
                globalResult.setSummarizeSuccesses(true);
                globalResult.summarize();
            } catch (ScriptExecutionException e) {
                // todo think about this
                if (context.isContinueOnAnyError()) {
                    LoggingUtils.logUnexpectedException(LOGGER, "Exception when evaluating item from search result list.", e);
                } else {
                    throw new SystemException(e);
                }
            }
        } else {
            outputData.addValue(object.getValue());
        }
        return true;
    };
    try {
        Collection<SelectorOptions<GetOperationOptions>> options = operationsHelper.createGetOptions(searchExpression.getOptions(), noFetch);
        modelService.searchObjectsIterative(objectClass, objectQuery, handler, options, context.getTask(), globalResult);
    } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
        // TODO continue on any error?
        throw new ScriptExecutionException("Couldn't execute searchObjects operation: " + e.getMessage(), e);
    }
    if (atLeastOne.isFalse()) {
        String matching = objectQuery != null ? "matching " : "";
        // temporary hack, this will be configurable
        context.println("Warning: no " + matching + searchExpression.getType().getLocalPart() + " object found");
    }
    if (variableName != null) {
        context.setVariable(variableName, oldVariableValue);
    }
    return outputData;
}
Also used : ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) OperationsHelper(com.evolveum.midpoint.model.impl.scripting.helpers.OperationsHelper) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) Trace(com.evolveum.midpoint.util.logging.Trace) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) ExpressionHelper(com.evolveum.midpoint.model.impl.scripting.helpers.ExpressionHelper) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ScriptExecutionException(com.evolveum.midpoint.model.api.ScriptExecutionException) JAXBElement(javax.xml.bind.JAXBElement) Collection(java.util.Collection) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) QueryConvertor(com.evolveum.midpoint.prism.marshaller.QueryConvertor) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) QueryJaxbConvertor(com.evolveum.midpoint.prism.query.QueryJaxbConvertor) Component(org.springframework.stereotype.Component) ScriptingExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) MutableBoolean(org.apache.commons.lang.mutable.MutableBoolean) ObjectTypes(com.evolveum.midpoint.schema.constants.ObjectTypes) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SearchExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.SearchExpressionType) Validate(org.apache.commons.lang.Validate) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) ScriptExecutionException(com.evolveum.midpoint.model.api.ScriptExecutionException) MutableBoolean(org.apache.commons.lang.mutable.MutableBoolean) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) JAXBElement(javax.xml.bind.JAXBElement) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Example 2 with ExecutionContext

use of com.evolveum.midpoint.model.impl.scripting.ExecutionContext in project midpoint by Evolveum.

the class TestScriptingBasic method test110EmptyPipeline.

@Test
public void test110EmptyPipeline() throws Exception {
    final String TEST_NAME = "test110EmptyPipeline";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = createTask(DOT_CLASS + TEST_NAME);
    OperationResult result = task.getResult();
    ExpressionPipelineType pipeline = new ExpressionPipelineType();
    // WHEN
    ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(pipeline, task, result);
    // THEN
    dumpOutput(output, result);
    assertNoOutputData(output);
    result.computeStatus();
    TestUtil.assertSuccess(result);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Test(org.testng.annotations.Test) AbstractInitializedModelIntegrationTest(com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)

Example 3 with ExecutionContext

use of com.evolveum.midpoint.model.impl.scripting.ExecutionContext in project midpoint by Evolveum.

the class TestScriptingBasic method test540SearchUserResolveNamesForRoleMembershipRef.

@Test
public void test540SearchUserResolveNamesForRoleMembershipRef() throws Exception {
    final String TEST_NAME = "test540SearchUserResolveNamesForRoleMembershipRef";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = createTask(DOT_CLASS + TEST_NAME);
    OperationResult result = task.getResult();
    PrismProperty<SearchExpressionType> expression = parseAnyData(SEARCH_FOR_USERS_RESOLVE_NAMES_FOR_ROLE_MEMBERSHIP_REF_FILE);
    // WHEN
    ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result);
    // THEN
    dumpOutput(output, result);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    assertEquals(2, output.getFinalOutput().getData().size());
    for (PipelineItem item : output.getFinalOutput().getData()) {
        PrismAsserts.assertHasTargetName((PrismContainerValue) item.getValue(), new ItemPath(UserType.F_ROLE_MEMBERSHIP_REF));
        PrismAsserts.assertHasNoTargetName((PrismContainerValue) item.getValue(), new ItemPath(UserType.F_LINK_REF));
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) Test(org.testng.annotations.Test) AbstractInitializedModelIntegrationTest(com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)

Example 4 with ExecutionContext

use of com.evolveum.midpoint.model.impl.scripting.ExecutionContext in project midpoint by Evolveum.

the class TestScriptingBasic method test510GeneratePasswords.

@Test
public void test510GeneratePasswords() throws Exception {
    final String TEST_NAME = "test510GeneratePasswords";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = createTask(DOT_CLASS + TEST_NAME);
    OperationResult result = task.getResult();
    PrismProperty<ScriptingExpressionType> expression = parseAnyData(GENERATE_PASSWORDS_FILE);
    addObject(PASSWORD_POLICY_GLOBAL_FILE);
    List<ItemDelta<?, ?>> itemDeltas = DeltaBuilder.deltaFor(SecurityPolicyType.class, prismContext).item(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_PASSWORD_POLICY_REF).add(new PrismReferenceValue(PASSWORD_POLICY_GLOBAL_OID)).asItemDeltas();
    modifySystemObjectInRepo(SecurityPolicyType.class, SECURITY_POLICY_OID, itemDeltas, result);
    // WHEN
    ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result);
    // THEN
    dumpOutput(output, result);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    PipelineData data = output.getFinalOutput();
    assertEquals("Unexpected # of items in output", 5, data.getData().size());
    Set<String> realOids = new HashSet<>();
    for (PipelineItem item : data.getData()) {
        PrismValue value = item.getValue();
        UserType user = ((PrismObjectValue<UserType>) value).asObjectable();
        ProtectedStringType passwordValue = user.getCredentials().getPassword().getValue();
        assertNotNull("clearValue for password not set", passwordValue.getClearValue());
        realOids.add(user.getOid());
    }
    assertEquals("Unexpected OIDs in output", Sets.newHashSet(Arrays.asList(USER_ADMINISTRATOR_OID, USER_JACK_OID, USER_BARBOSSA_OID, USER_GUYBRUSH_OID, USER_ELAINE_OID)), realOids);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) HashSet(java.util.HashSet) Test(org.testng.annotations.Test) AbstractInitializedModelIntegrationTest(com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)

Example 5 with ExecutionContext

use of com.evolveum.midpoint.model.impl.scripting.ExecutionContext in project midpoint by Evolveum.

the class TestScriptingBasic method test310EnableJack.

@Test
public void test310EnableJack() throws Exception {
    final String TEST_NAME = "test310EnableJack";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    Task task = createTask(DOT_CLASS + TEST_NAME);
    OperationResult result = task.getResult();
    PrismProperty<ScriptingExpressionType> expression = parseAnyData(ENABLE_JACK_FILE);
    // WHEN
    ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result);
    // THEN
    dumpOutput(output, result);
    assertOutputData(output, 1, OperationResultStatus.SUCCESS);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    assertEquals("Enabled user:c0c010c0-d34d-b33f-f00d-111111111111(jack)\n", output.getConsoleOutput());
    assertAdministrativeStatusEnabled(searchObjectByName(UserType.class, "jack"));
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Test(org.testng.annotations.Test) AbstractInitializedModelIntegrationTest(com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)

Aggregations

ExecutionContext (com.evolveum.midpoint.model.impl.scripting.ExecutionContext)31 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)29 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)28 Task (com.evolveum.midpoint.task.api.Task)28 Test (org.testng.annotations.Test)28 PipelineItem (com.evolveum.midpoint.model.api.PipelineItem)6 PipelineData (com.evolveum.midpoint.model.impl.scripting.PipelineData)6 Message (com.evolveum.midpoint.notifications.api.transports.Message)2 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)2 HashSet (java.util.HashSet)2 ScriptExecutionException (com.evolveum.midpoint.model.api.ScriptExecutionException)1 ExpressionHelper (com.evolveum.midpoint.model.impl.scripting.helpers.ExpressionHelper)1 OperationsHelper (com.evolveum.midpoint.model.impl.scripting.helpers.OperationsHelper)1 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)1 QueryConvertor (com.evolveum.midpoint.prism.marshaller.QueryConvertor)1 ObjectFilter (com.evolveum.midpoint.prism.query.ObjectFilter)1 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)1 QueryJaxbConvertor (com.evolveum.midpoint.prism.query.QueryJaxbConvertor)1 GetOperationOptions (com.evolveum.midpoint.schema.GetOperationOptions)1 ResultHandler (com.evolveum.midpoint.schema.ResultHandler)1