Search in sources :

Example 1 with TypedValue

use of com.evolveum.midpoint.schema.expression.TypedValue in project midpoint by Evolveum.

the class VariablesUtil method addDerivedVariables.

private static void addDerivedVariables(VariablesMap resultingVariables, ScriptingVariablesDefinitionType definitions, VariableResolutionContext ctx, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
    if (definitions == null) {
        return;
    }
    for (ScriptingVariableDefinitionType definition : definitions.getVariable()) {
        if (definition.getExpression() == null) {
            // todo or throw an exception?
            continue;
        }
        String shortDesc = "scripting variable " + definition.getName();
        TypedValue valueAndDef;
        if (definition.getExpression().getExpressionEvaluator().size() == 1 && QNameUtil.match(SchemaConstantsGenerated.C_PATH, definition.getExpression().getExpressionEvaluator().get(0).getName())) {
            valueAndDef = variableFromPathExpression(resultingVariables, definition.getExpression().getExpressionEvaluator().get(0), ctx, shortDesc, result);
        } else {
            valueAndDef = variableFromOtherExpression(resultingVariables, definition, ctx, shortDesc, result);
        }
        putImmutableValue(resultingVariables, definition.getName(), valueAndDef);
    }
}
Also used : ScriptingVariableDefinitionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingVariableDefinitionType) TypedValue(com.evolveum.midpoint.schema.expression.TypedValue)

Example 2 with TypedValue

use of com.evolveum.midpoint.schema.expression.TypedValue in project midpoint by Evolveum.

the class FocalMappingSetEvaluation method createFocusMapping.

private <V extends PrismValue, D extends ItemDefinition<?>, AH extends AssignmentHolderType, T extends AssignmentHolderType> MappingImpl<V, D> createFocusMapping(LensContext<AH> context, FocalMappingEvaluationRequest<?, ?> request, ObjectDeltaObject<AH> focusOdo, @NotNull PrismObject<T> targetContext, Integer iteration, String iterationToken, PrismObject<SystemConfigurationType> configuration, XMLGregorianCalendar now, String contextDesc, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
    MappingType mappingBean = request.getMapping();
    MappingKindType mappingKind = request.getMappingKind();
    ObjectType originObject = request.getOriginObject();
    Source<V, D> defaultSource = request.constructDefaultSource(focusOdo);
    AssignmentPathVariables assignmentPathVariables = request.getAssignmentPathVariables();
    if (!MappingImpl.isApplicableToChannel(mappingBean, context.getChannel())) {
        LOGGER.trace("Mapping {} not applicable to channel {}, skipping.", mappingBean, context.getChannel());
        return null;
    }
    ConfigurableValuePolicySupplier valuePolicySupplier = new ConfigurableValuePolicySupplier() {

        private ItemDefinition<?> outputDefinition;

        @Override
        public void setOutputDefinition(ItemDefinition<?> outputDefinition) {
            this.outputDefinition = outputDefinition;
        }

        @Override
        public ValuePolicyType get(OperationResult result) {
            // TODO need to switch to ObjectValuePolicyEvaluator
            if (outputDefinition.getItemName().equals(PasswordType.F_VALUE)) {
                return beans.credentialsProcessor.determinePasswordPolicy(context.getFocusContext());
            }
            if (mappingBean.getExpression() != null) {
                List<JAXBElement<?>> evaluators = mappingBean.getExpression().getExpressionEvaluator();
                if (evaluators != null) {
                    for (JAXBElement jaxbEvaluator : evaluators) {
                        Object object = jaxbEvaluator.getValue();
                        if (object instanceof GenerateExpressionEvaluatorType && ((GenerateExpressionEvaluatorType) object).getValuePolicyRef() != null) {
                            ObjectReferenceType ref = ((GenerateExpressionEvaluatorType) object).getValuePolicyRef();
                            try {
                                ValuePolicyType valuePolicyType = beans.mappingFactory.getObjectResolver().resolve(ref, ValuePolicyType.class, null, "resolving value policy for generate attribute " + outputDefinition.getItemName() + " value", task, result);
                                if (valuePolicyType != null) {
                                    return valuePolicyType;
                                }
                            } catch (CommonException ex) {
                                throw new SystemException(ex.getMessage(), ex);
                            }
                        }
                    }
                }
            }
            return null;
        }
    };
    VariablesMap variables = new VariablesMap();
    variables.put(ExpressionConstants.VAR_FOCUS, focusOdo, focusOdo.getDefinition());
    variables.put(ExpressionConstants.VAR_USER, focusOdo, focusOdo.getDefinition());
    variables.registerAlias(ExpressionConstants.VAR_USER, ExpressionConstants.VAR_FOCUS);
    variables.put(ExpressionConstants.VAR_ITERATION, iteration, Integer.class);
    variables.put(ExpressionConstants.VAR_ITERATION_TOKEN, iterationToken, String.class);
    variables.put(ExpressionConstants.VAR_CONFIGURATION, configuration, SystemConfigurationType.class);
    variables.put(ExpressionConstants.VAR_OPERATION, context.getFocusContext().getOperation().getValue(), String.class);
    variables.put(ExpressionConstants.VAR_SOURCE, originObject, ObjectType.class);
    PrismContext prismContext = beans.prismContext;
    TypedValue<PrismObject<T>> defaultTargetContext = new TypedValue<>(targetContext);
    Collection<V> targetValues = ExpressionUtil.computeTargetValues(mappingBean.getTarget(), defaultTargetContext, variables, beans.mappingFactory.getObjectResolver(), contextDesc, prismContext, task, result);
    MappingSpecificationType specification = new MappingSpecificationType(prismContext).mappingName(mappingBean.getName()).definitionObjectRef(ObjectTypeUtil.createObjectRef(originObject, prismContext)).assignmentId(createAssignmentId(assignmentPathVariables));
    MappingBuilder<V, D> mappingBuilder = beans.mappingFactory.<V, D>createMappingBuilder(mappingBean, contextDesc).sourceContext(focusOdo).defaultSource(defaultSource).targetContext(targetContext.getDefinition()).variablesFrom(variables).variablesFrom(LensUtil.getAssignmentPathVariablesMap(assignmentPathVariables, prismContext)).originalTargetValues(targetValues).mappingKind(mappingKind).originType(OriginType.USER_POLICY).originObject(originObject).valuePolicySupplier(valuePolicySupplier).rootNode(focusOdo).mappingPreExpression(// Used to populate autoassign assignments
    request.getMappingPreExpression()).mappingSpecification(specification).now(now);
    MappingImpl<V, D> mapping = mappingBuilder.build();
    ItemPath itemPath = mapping.getOutputPath();
    if (itemPath == null) {
        // no output element, i.e. this is a "validation mapping"
        return mapping;
    }
    Item<V, D> existingTargetItem = targetContext.findItem(itemPath);
    if (existingTargetItem != null && !existingTargetItem.isEmpty() && mapping.getStrength() == MappingStrengthType.WEAK) {
        LOGGER.trace("Mapping {} is weak and target already has a value {}, skipping.", mapping, existingTargetItem);
        return null;
    }
    return mapping;
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) TypedValue(com.evolveum.midpoint.schema.expression.TypedValue) ConfigurableValuePolicySupplier(com.evolveum.midpoint.repo.common.expression.ConfigurableValuePolicySupplier) JAXBElement(javax.xml.bind.JAXBElement) ObjectDeltaObject(com.evolveum.midpoint.prism.util.ObjectDeltaObject) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 3 with TypedValue

use of com.evolveum.midpoint.schema.expression.TypedValue in project midpoint by Evolveum.

the class ExecuteScriptExecutor method executeForWholeInput.

private void executeForWholeInput(PipelineData input, PipelineData output, Parameters parameters, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException {
    OperationResult result = operationsHelper.createActionResult(null, this, globalResult);
    context.checkTaskStop();
    try {
        TypedValue<PipelineData> inputTypedValue = new TypedValue<>(input, PipelineData.class);
        Object outObject = executeScript(parameters.scriptExpression, inputTypedValue, context.getInitialVariables(), context, result);
        if (outObject != null) {
            addToData(outObject, PipelineData.newOperationResult(), output);
        } else {
            // (actually, null definition with non-null outObject should not occur)
            if (parameters.outputDefinition == null) {
                output.addAllFrom(input);
            }
        }
        if (!parameters.quiet) {
            context.println("Executed script on the pipeline");
        }
    } catch (Throwable ex) {
        // TODO value for error reporting (3rd parameter)
        Throwable exception = processActionException(ex, NAME, null, context);
        context.println("Failed to execute script on the pipeline" + exceptionSuffix(exception));
    }
    operationsHelper.trimAndCloneResult(result, null);
}
Also used : PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) TypedValue(com.evolveum.midpoint.schema.expression.TypedValue)

Example 4 with TypedValue

use of com.evolveum.midpoint.schema.expression.TypedValue in project midpoint by Evolveum.

the class SandboxTypeCheckingExtension method handleUnresolvedVariableExpression.

@Override
public boolean handleUnresolvedVariableExpression(VariableExpression vexp) {
    String variableName = vexp.getName();
    ScriptExpressionEvaluationContext context = getContext();
    String contextDescription = context.getContextDescription();
    if (!isDynamic(vexp)) {
        LOGGER.error("Unresolved script variable {} because it is not dynamic, in {}", variableName, contextDescription);
        return false;
    }
    VariablesMap variables = context.getVariables();
    if (variables != null) {
        TypedValue variableTypedValue = variables.get(variableName);
        if (variableTypedValue != null) {
            Class variableClass;
            try {
                variableClass = variableTypedValue.determineClass();
            } catch (SchemaException e) {
                String msg = "Cannot determine type of variable '" + variableName + "' (" + variableTypedValue + ") in " + contextDescription + ": " + e.getMessage();
                LOGGER.error("{}", msg);
                throw new IllegalStateException(msg, e);
            }
            LOGGER.trace("Determine script variable {} as expression variable, class {} in {}", variableName, variableClass, contextDescription);
            storeType(vexp, ClassHelper.make(variableClass));
            setHandled(true);
            return true;
        }
    }
    Collection<FunctionLibrary> functions = context.getFunctions();
    if (functions != null) {
        for (FunctionLibrary function : functions) {
            if (function.getVariableName().equals(variableName)) {
                Class functionClass = function.getGenericFunctions().getClass();
                LOGGER.trace("Determine script variable {} as function library, class {} in {}", variableName, functionClass, contextDescription);
                storeType(vexp, ClassHelper.make(functionClass));
                setHandled(true);
                return true;
            }
        }
    }
    LOGGER.error("Unresolved script variable {} because no declaration for it cannot be found in {}", variableName, contextDescription);
    return false;
}
Also used : ScriptExpressionEvaluationContext(com.evolveum.midpoint.model.common.expression.script.ScriptExpressionEvaluationContext) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) FunctionLibrary(com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) TypedValue(com.evolveum.midpoint.schema.expression.TypedValue)

Example 5 with TypedValue

use of com.evolveum.midpoint.schema.expression.TypedValue in project midpoint by Evolveum.

the class CommandLineScriptExecutor method expandMacros.

private String expandMacros(CommandLineScriptType scriptType, VariablesMap variables, String shortDesc, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
    String code = scriptType.getCode();
    for (ProvisioningScriptArgumentType macroDef : scriptType.getMacro()) {
        String macroName = macroDef.getName();
        QName macroQName = new QName(SchemaConstants.NS_C, macroName);
        String expressionOutput = "";
        MutablePrismPropertyDefinition<String> outputDefinition = prismContext.definitionFactory().createPropertyDefinition(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING);
        outputDefinition.setMaxOccurs(1);
        Expression<PrismPropertyValue<String>, PrismPropertyDefinition<String>> expression = expressionFactory.makeExpression(macroDef, outputDefinition, MiscSchemaUtil.getExpressionProfile(), shortDesc, task, result);
        Collection<Source<?, ?>> sources = new ArrayList<>(1);
        ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables, shortDesc, task);
        TypedValue defaultObjectValAndDef = variables.get(macroName);
        if (defaultObjectValAndDef != null) {
            Object defaultObjectVal = defaultObjectValAndDef.getValue();
            Item sourceItem;
            if (defaultObjectVal instanceof Item) {
                sourceItem = (Item) defaultObjectVal;
            } else if (defaultObjectVal instanceof String) {
                MutablePrismPropertyDefinition<String> sourceDefinition = prismContext.definitionFactory().createPropertyDefinition(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING);
                sourceDefinition.setMaxOccurs(1);
                PrismProperty<String> sourceProperty = sourceDefinition.instantiate();
                sourceProperty.setRealValue(defaultObjectVal.toString());
                sourceItem = sourceProperty;
            } else {
                sourceItem = null;
            }
            Source<?, ?> defaultSource = new Source<>(sourceItem, null, sourceItem, macroQName, defaultObjectValAndDef.getDefinition());
            context.setDefaultSource(defaultSource);
            sources.add(defaultSource);
        }
        PrismValueDeltaSetTriple<PrismPropertyValue<String>> outputTriple = expression.evaluate(context, result);
        LOGGER.trace("Result of the expression evaluation: {}", outputTriple);
        if (outputTriple != null) {
            Collection<PrismPropertyValue<String>> nonNegativeValues = outputTriple.getNonNegativeValues();
            if (!nonNegativeValues.isEmpty()) {
                Collection<String> expressionOutputs = PrismValueCollectionsUtil.getRealValuesOfCollection((Collection) nonNegativeValues);
                if (!expressionOutputs.isEmpty()) {
                    expressionOutput = StringUtils.join(expressionOutputs, ",");
                }
            }
        }
        code = replaceMacro(code, macroDef.getName(), expressionOutput);
    }
    return code;
}
Also used : ExpressionEvaluationContext(com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) ProvisioningScriptArgumentType(com.evolveum.midpoint.xml.ns._public.common.common_3.ProvisioningScriptArgumentType) Source(com.evolveum.midpoint.repo.common.expression.Source) TypedValue(com.evolveum.midpoint.schema.expression.TypedValue)

Aggregations

TypedValue (com.evolveum.midpoint.schema.expression.TypedValue)15 VariablesMap (com.evolveum.midpoint.schema.expression.VariablesMap)5 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)4 ObjectDeltaObject (com.evolveum.midpoint.prism.util.ObjectDeltaObject)4 ItemDeltaItem (com.evolveum.midpoint.prism.util.ItemDeltaItem)3 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)3 QName (javax.xml.namespace.QName)3 FunctionLibrary (com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary)2 Source (com.evolveum.midpoint.repo.common.expression.Source)2 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 JAXBElement (javax.xml.bind.JAXBElement)2 NotNull (org.jetbrains.annotations.NotNull)2 ScriptExpressionEvaluationContext (com.evolveum.midpoint.model.common.expression.script.ScriptExpressionEvaluationContext)1 MappingBuilder (com.evolveum.midpoint.model.common.mapping.MappingBuilder)1 MappingImpl (com.evolveum.midpoint.model.common.mapping.MappingImpl)1 ModelBeans (com.evolveum.midpoint.model.impl.ModelBeans)1 InboundMappingInContext (com.evolveum.midpoint.model.impl.lens.projector.focus.inbounds.InboundMappingInContext)1 PipelineData (com.evolveum.midpoint.model.impl.scripting.PipelineData)1