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();
}
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);
}
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);
}
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;
}
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();
}
}
Aggregations