Search in sources :

Example 61 with ExpressionVariables

use of com.evolveum.midpoint.repo.common.expression.ExpressionVariables in project midpoint by Evolveum.

the class ExpressionHandler method evaluateExpression.

public String evaluateExpression(ShadowType shadow, ExpressionType expressionType, String shortDesc, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    Validate.notNull(shadow, "Resource object shadow must not be null.");
    Validate.notNull(expressionType, "Expression must not be null.");
    Validate.notNull(result, "Operation result must not be null.");
    ResourceType resource = resolveResource(shadow, result);
    ExpressionVariables variables = getDefaultXPathVariables(null, shadow, resource);
    PrismPropertyDefinition<String> outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING, prismContext);
    Expression<PrismPropertyValue<String>, PrismPropertyDefinition<String>> expression = expressionFactory.makeExpression(expressionType, outputDefinition, shortDesc, task, result);
    ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, variables, shortDesc, task, result);
    PrismValueDeltaSetTriple<PrismPropertyValue<String>> outputTriple = ModelExpressionThreadLocalHolder.evaluateExpressionInContext(expression, params, task, result);
    if (outputTriple == null) {
        return null;
    }
    Collection<PrismPropertyValue<String>> nonNegativeValues = outputTriple.getNonNegativeValues();
    if (nonNegativeValues == null || nonNegativeValues.isEmpty()) {
        return null;
    }
    if (nonNegativeValues.size() > 1) {
        throw new ExpressionEvaluationException("Expression returned more than one value (" + nonNegativeValues.size() + ") in " + shortDesc);
    }
    return nonNegativeValues.iterator().next().getValue();
}
Also used : ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) ExpressionEvaluationContext(com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext) PrismPropertyDefinitionImpl(com.evolveum.midpoint.prism.PrismPropertyDefinitionImpl) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 62 with ExpressionVariables

use of com.evolveum.midpoint.repo.common.expression.ExpressionVariables in project midpoint by Evolveum.

the class PrepareForTaskCreation method execute.

public void execute(DelegateExecution execution) {
    PrismContext prismContext = getPrismContext();
    OperationResult result = new OperationResult(PrepareForTaskCreation.class.getName() + ".execute");
    Task wfTask = ActivitiUtil.getTask(execution, result);
    Task opTask = getTaskManager().createTaskInstance();
    ApprovalStageDefinitionType stageDef = ActivitiUtil.getAndVerifyCurrentStage(execution, wfTask, true, prismContext);
    LightweightObjectRef approverRef = getRequiredVariable(execution, ProcessVariableNames.APPROVER_REF, LightweightObjectRef.class, prismContext);
    String assignee = null;
    String candidateGroups = null;
    if (approverRef.getType() == null || QNameUtil.match(UserType.COMPLEX_TYPE, approverRef.getType())) {
        assignee = MiscDataUtil.refToString(new ObjectReferenceType().oid(approverRef.getOid()).type(UserType.COMPLEX_TYPE));
    } else if (QNameUtil.match(RoleType.COMPLEX_TYPE, approverRef.getType()) || QNameUtil.match(OrgType.COMPLEX_TYPE, approverRef.getType()) || QNameUtil.match(ServiceType.COMPLEX_TYPE, approverRef.getType())) {
        candidateGroups = MiscDataUtil.refToString(approverRef.toObjectReferenceType());
    } else {
        throw new IllegalStateException("Unsupported type of the approver: " + approverRef.getType());
    }
    // TODO optimize by using setVariablesLocal
    execution.setVariableLocal(ProcessVariableNames.ASSIGNEE, assignee);
    execution.setVariableLocal(ProcessVariableNames.CANDIDATE_GROUPS, candidateGroups);
    List<?> additionalInformation;
    if (stageDef.getAdditionalInformation() != null) {
        try {
            WfExpressionEvaluationHelper evaluator = SpringApplicationContextHolder.getExpressionEvaluationHelper();
            ExpressionVariables variables = evaluator.getDefaultVariables(execution, wfTask, result);
            additionalInformation = evaluator.evaluateExpression(stageDef.getAdditionalInformation(), variables, "additional information expression", Object.class, DOMUtil.XSD_STRING, null, opTask, result);
        } catch (Throwable t) {
            throw new SystemException("Couldn't evaluate additional information expression in " + execution, t);
        }
    } else {
        additionalInformation = new AdditionalInformationGenerator().getDefaultAdditionalInformation(wfTask, stageDef.getNumber());
    }
    if (additionalInformation != null && !additionalInformation.isEmpty()) {
        execution.setVariableLocal(CommonProcessVariableNames.ADDITIONAL_INFORMATION, new SingleItemSerializationSafeContainerImpl<>(wrapAdditionalInformationIfNeeded(additionalInformation), prismContext));
    }
    LOGGER.debug("Creating work item for assignee={}, candidateGroups={}, additionalInformation='{}'", assignee, candidateGroups, additionalInformation);
}
Also used : ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) Task(com.evolveum.midpoint.task.api.Task) SpringApplicationContextHolder.getPrismContext(com.evolveum.midpoint.wf.impl.processes.common.SpringApplicationContextHolder.getPrismContext) PrismContext(com.evolveum.midpoint.prism.PrismContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SystemException(com.evolveum.midpoint.util.exception.SystemException)

Example 63 with ExpressionVariables

use of com.evolveum.midpoint.repo.common.expression.ExpressionVariables in project midpoint by Evolveum.

the class InitializeLoopThroughApproversInStage method execute.

public void execute(DelegateExecution execution) {
    PrismContext prismContext = getPrismContext();
    WfExpressionEvaluationHelper evaluationHelper = SpringApplicationContextHolder.getExpressionEvaluationHelper();
    LOGGER.trace("Executing the delegate; execution = {}", execution);
    OperationResult opResult = new OperationResult(InitializeLoopThroughApproversInStage.class.getName() + ".execute");
    Task opTask = getTaskManager().createTaskInstance();
    Task wfTask = ActivitiUtil.getTask(execution, opResult);
    ApprovalStageDefinitionType stageDef = ActivitiUtil.getAndVerifyCurrentStage(execution, wfTask, false, prismContext);
    int stageNumber = stageDef.getNumber();
    opTask.setChannel(wfTask.getChannel());
    ExpressionVariables expressionVariables = null;
    ApprovalLevelOutcomeType predeterminedOutcome = null;
    if (stageDef.getAutomaticallyApproved() != null) {
        try {
            expressionVariables = evaluationHelper.getDefaultVariables(execution, wfTask, opResult);
            boolean preApproved = evaluationHelper.evaluateBooleanExpression(stageDef.getAutomaticallyApproved(), expressionVariables, "automatic approval expression", opTask, opResult);
            LOGGER.trace("Pre-approved = {} for stage {}", preApproved, stageDef);
            if (preApproved) {
                predeterminedOutcome = APPROVE;
                recordAutoCompletionDecision(wfTask.getOid(), APPROVE, AUTO_COMPLETION_CONDITION, stageNumber, opResult);
            }
        } catch (Exception e) {
            // todo
            throw new SystemException("Couldn't evaluate auto-approval expression", e);
        }
    }
    if (predeterminedOutcome == null && stageDef.getAutomaticallyCompleted() != null) {
        try {
            if (expressionVariables == null) {
                expressionVariables = evaluationHelper.getDefaultVariables(execution, wfTask, opResult);
            }
            List<String> outcomes = evaluationHelper.evaluateExpression(stageDef.getAutomaticallyCompleted(), expressionVariables, "automatic completion expression", String.class, DOMUtil.XSD_STRING, WfExpressionEvaluationHelper.createOutcomeConvertor(), opTask, opResult);
            LOGGER.trace("Pre-completed = {} for stage {}", outcomes, stageDef);
            Set<String> distinctOutcomes = new HashSet<>(outcomes);
            if (distinctOutcomes.size() > 1) {
                throw new IllegalStateException("Ambiguous result from 'automatically completed' expression: " + distinctOutcomes);
            } else if (!distinctOutcomes.isEmpty()) {
                predeterminedOutcome = ApprovalUtils.approvalLevelOutcomeFromUri(distinctOutcomes.iterator().next());
                if (predeterminedOutcome != null && predeterminedOutcome != SKIP) {
                    recordAutoCompletionDecision(wfTask.getOid(), predeterminedOutcome, AUTO_COMPLETION_CONDITION, stageNumber, opResult);
                }
            }
        } catch (Exception e) {
            // todo
            throw new SystemException("Couldn't evaluate auto-approval expression", e);
        }
    }
    Set<ObjectReferenceType> approverRefs = new HashSet<>();
    if (predeterminedOutcome == null) {
        approverRefs.addAll(CloneUtil.cloneCollectionMembers(stageDef.getApproverRef()));
        if (!stageDef.getApproverExpression().isEmpty()) {
            try {
                if (expressionVariables == null) {
                    expressionVariables = evaluationHelper.getDefaultVariables(execution, wfTask, opResult);
                }
                approverRefs.addAll(evaluationHelper.evaluateRefExpressions(stageDef.getApproverExpression(), expressionVariables, "resolving approver expression", opTask, opResult));
            } catch (ExpressionEvaluationException | ObjectNotFoundException | SchemaException | RuntimeException e) {
                throw new SystemException("Couldn't evaluate approvers expressions", e);
            }
        }
        LOGGER.trace("Approvers at the stage {} (before potential group expansion) are: {}", stageDef, approverRefs);
        if (stageDef.getGroupExpansion() == GroupExpansionType.ON_WORK_ITEM_CREATION) {
            approverRefs = MidpointUtil.expandGroups(approverRefs);
            LOGGER.trace("Approvers at the stage {} (after group expansion) are: {}", stageDef, approverRefs);
        }
        if (approverRefs.isEmpty()) {
            LOGGER.debug("No approvers at the stage '{}' for process {} (id {}) - response is {}", stageDef.getName(), execution.getVariable(CommonProcessVariableNames.VARIABLE_PROCESS_INSTANCE_NAME), execution.getProcessInstanceId(), stageDef.getOutcomeIfNoApprovers());
            predeterminedOutcome = stageDef.getOutcomeIfNoApprovers();
            switch(predeterminedOutcome) {
                case APPROVE:
                    recordAutoCompletionDecision(wfTask.getOid(), APPROVE, NO_ASSIGNEES_FOUND, stageNumber, opResult);
                    break;
                case REJECT:
                    recordAutoCompletionDecision(wfTask.getOid(), REJECT, NO_ASSIGNEES_FOUND, stageNumber, opResult);
                    break;
                case SKIP:
                    // do nothing, just silently skip the stage
                    break;
                default:
                    throw new IllegalStateException("Unexpected outcome: " + stageDef.getOutcomeIfNoApprovers() + " in " + stageDef);
            }
        }
    }
    Boolean stop;
    if (predeterminedOutcome != null) {
        stop = Boolean.TRUE;
    } else {
        stop = Boolean.FALSE;
    }
    execution.setVariable(CommonProcessVariableNames.VARIABLE_STAGE_NUMBER, stageNumber);
    execution.setVariable(CommonProcessVariableNames.VARIABLE_STAGE_NAME, stageDef.getName());
    execution.setVariable(CommonProcessVariableNames.VARIABLE_STAGE_DISPLAY_NAME, stageDef.getDisplayName());
    execution.setVariableLocal(ProcessVariableNames.APPROVERS_IN_STAGE, ActivitiUtil.toLightweightReferences(approverRefs));
    execution.setVariableLocal(ProcessVariableNames.LOOP_APPROVERS_IN_STAGE_STOP, stop);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Approval process instance {} (id {}), stage {}: predetermined outcome: {}, approvers: {}", execution.getVariable(CommonProcessVariableNames.VARIABLE_PROCESS_INSTANCE_NAME), execution.getProcessInstanceId(), WfContextUtil.getStageDiagName(stageDef), predeterminedOutcome, approverRefs);
    }
    // store stage information in midPoint task
    getActivitiInterface().notifyMidpointAboutProcessEvent(execution);
}
Also used : ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Task(com.evolveum.midpoint.task.api.Task) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) PrismContext(com.evolveum.midpoint.prism.PrismContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) SystemException(com.evolveum.midpoint.util.exception.SystemException) SystemException(com.evolveum.midpoint.util.exception.SystemException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException)

Example 64 with ExpressionVariables

use of com.evolveum.midpoint.repo.common.expression.ExpressionVariables in project midpoint by Evolveum.

the class GcpExpressionHelper method evaluateActivationCondition.

boolean evaluateActivationCondition(GeneralChangeProcessorScenarioType scenarioType, ModelContext context, Task taskFromModel, OperationResult result) throws SchemaException {
    ExpressionType conditionExpression = scenarioType.getActivationCondition();
    if (conditionExpression == null) {
        return true;
    }
    ExpressionVariables variables = new ExpressionVariables();
    variables.addVariableDefinition(new QName(SchemaConstants.NS_C, "context"), context);
    boolean start;
    try {
        start = evaluateBooleanExpression(conditionExpression, variables, "workflow activation condition", taskFromModel, result);
    } catch (ObjectNotFoundException | ExpressionEvaluationException e) {
        throw new SystemException("Couldn't evaluate generalChangeProcessor activation condition", e);
    }
    return start;
}
Also used : ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) SystemException(com.evolveum.midpoint.util.exception.SystemException) QName(javax.xml.namespace.QName) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ExpressionType(com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType)

Example 65 with ExpressionVariables

use of com.evolveum.midpoint.repo.common.expression.ExpressionVariables in project midpoint by Evolveum.

the class BasePrimaryChangeAspect method resolveReferenceFromFilter.

private <O extends ObjectType, F extends ObjectType> List<ObjectReferenceType> resolveReferenceFromFilter(Class<O> clazz, SearchFilterType filter, String sourceDescription, LensContext<F> lensContext, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
    ExpressionEnvironment<F> env = new ExpressionEnvironment<>();
    env.setLensContext(lensContext);
    env.setCurrentResult(result);
    env.setCurrentTask(task);
    ModelExpressionThreadLocalHolder.pushExpressionEnvironment(env);
    try {
        PrismObject<SystemConfigurationType> systemConfiguration = systemObjectCache.getSystemConfiguration(result);
        ExpressionVariables variables = Utils.getDefaultExpressionVariables(getFocusObjectable(lensContext), null, null, systemConfiguration.asObjectable());
        ObjectFilter origFilter = QueryConvertor.parseFilter(filter, clazz, prismContext);
        ObjectFilter evaluatedFilter = ExpressionUtil.evaluateFilterExpressions(origFilter, variables, mappingFactory.getExpressionFactory(), prismContext, " evaluating approverRef filter expression ", task, result);
        if (evaluatedFilter == null) {
            throw new SchemaException("Filter could not be evaluated in approverRef in " + sourceDescription + "; original filter = " + origFilter);
        }
        SearchResultList<PrismObject<O>> targets = repositoryService.searchObjects(clazz, ObjectQuery.createObjectQuery(evaluatedFilter), null, result);
        return targets.stream().map(ObjectTypeUtil::createObjectRef).collect(Collectors.toList());
    } finally {
        ModelExpressionThreadLocalHolder.popExpressionEnvironment();
    }
}
Also used : ExpressionEnvironment(com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment) ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) PrismObject(com.evolveum.midpoint.prism.PrismObject) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter)

Aggregations

ExpressionVariables (com.evolveum.midpoint.repo.common.expression.ExpressionVariables)65 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)17 QName (javax.xml.namespace.QName)15 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)10 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)10 Test (org.testng.annotations.Test)10 AbstractInternalModelIntegrationTest (com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)9 PrismPropertyValue (com.evolveum.midpoint.prism.PrismPropertyValue)9 ExpressionEvaluationContext (com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext)9 Task (com.evolveum.midpoint.task.api.Task)8 ArrayList (java.util.ArrayList)8 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)7 PrismObject (com.evolveum.midpoint.prism.PrismObject)6 PrismPropertyDefinitionImpl (com.evolveum.midpoint.prism.PrismPropertyDefinitionImpl)6 ExpressionType (com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType)6 PrismContext (com.evolveum.midpoint.prism.PrismContext)5 ObjectFilter (com.evolveum.midpoint.prism.query.ObjectFilter)5 SystemException (com.evolveum.midpoint.util.exception.SystemException)5 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)5 ScriptExpression (com.evolveum.midpoint.model.common.expression.script.ScriptExpression)4