Search in sources :

Example 71 with PrismPropertyValue

use of com.evolveum.midpoint.prism.PrismPropertyValue in project midpoint by Evolveum.

the class GenerateExpressionEvaluator method evaluate.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.evolveum.midpoint.common.expression.ExpressionEvaluator#evaluate(java
	 * .util.Collection, java.util.Map, boolean, java.lang.String,
	 * com.evolveum.midpoint.schema.result.OperationResult)
	 */
@Override
public PrismValueDeltaSetTriple<V> evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
    StringPolicyType stringPolicyType = null;
    ObjectReferenceType generateEvaluatorValuePolicyRef = generateEvaluatorType.getValuePolicyRef();
    if (generateEvaluatorValuePolicyRef != null) {
        if (generateEvaluatorType.getValuePolicyRef() != null) {
            ValuePolicyType valuePolicyType = objectResolver.resolve(generateEvaluatorValuePolicyRef, ValuePolicyType.class, null, "resolving value policy reference in generateExpressionEvaluator", context.getTask(), context.getResult());
            stringPolicyType = valuePolicyType.getStringPolicy();
        }
    }
    // would be generated
    if (stringPolicyType == null) {
        StringPolicyResolver stringPolicyResolver = context.getStringPolicyResolver();
        if (stringPolicyResolver != null) {
            stringPolicyType = stringPolicyResolver.resolve();
        }
    }
    elementStringPolicy = stringPolicyType;
    // } else {
    // stringPolicyType = elementStringPolicy;
    // }
    //
    String stringValue = null;
    GenerateExpressionEvaluatorModeType mode = generateEvaluatorType.getMode();
    Item<V, D> output = outputDefinition.instantiate();
    if (mode == null || mode == GenerateExpressionEvaluatorModeType.POLICY) {
        PrismObject<? extends ObjectType> object = getObject(context);
        // TODO: generate value based on stringPolicyType (if not null)
        if (stringPolicyType != null) {
            if (isNotEmptyMinLength(stringPolicyType)) {
                stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, true, object, context.getContextDescription(), context.getTask(), context.getResult());
            } else {
                stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, false, object, context.getContextDescription(), context.getTask(), context.getResult());
            }
            context.getResult().computeStatus();
            if (context.getResult().isError()) {
                throw new ExpressionEvaluationException("Failed to generate value according to policy: " + stringPolicyType.getDescription() + ". " + context.getResult().getMessage());
            }
        }
        if (stringValue == null) {
            int length = DEFAULT_LENGTH;
            RandomString randomString = new RandomString(length);
            stringValue = randomString.nextString();
        }
    } else if (mode == GenerateExpressionEvaluatorModeType.UUID) {
        UUID randomUUID = UUID.randomUUID();
        stringValue = randomUUID.toString();
    } else {
        throw new ExpressionEvaluationException("Unknown mode for generate expression: " + mode);
    }
    Object value = ExpressionUtil.convertToOutputValue(stringValue, outputDefinition, protector);
    if (output instanceof PrismProperty) {
        PrismPropertyValue<Object> pValue = new PrismPropertyValue<Object>(value);
        ((PrismProperty<Object>) output).add(pValue);
    } else {
        throw new UnsupportedOperationException("Can only generate values of property, not " + output.getClass());
    }
    return ItemDelta.toDeltaSetTriple(output, null);
}
Also used : StringPolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) UUID(java.util.UUID) RandomString(com.evolveum.midpoint.util.RandomString) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) RandomString(com.evolveum.midpoint.util.RandomString) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) PrismObject(com.evolveum.midpoint.prism.PrismObject) UUID(java.util.UUID) GenerateExpressionEvaluatorModeType(com.evolveum.midpoint.xml.ns._public.common.common_3.GenerateExpressionEvaluatorModeType) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 72 with PrismPropertyValue

use of com.evolveum.midpoint.prism.PrismPropertyValue in project midpoint by Evolveum.

the class LazyXPathVariableResolver method convertToXml.

// May return primitive types or DOM Node
public static Object convertToXml(Object variableValue, QName variableName, final PrismContext prismContext, String contextDescription) throws SchemaException {
    try {
        if (variableValue instanceof Objectable) {
            variableValue = ((Objectable) variableValue).asPrismObject();
        }
        if (variableValue instanceof PrismObject) {
            PrismObject<?> prismObject = (PrismObject<?>) variableValue;
            variableValue = prismObject.getPrismContext().domSerializer().serialize(prismObject);
        } else if (variableValue instanceof PrismProperty<?>) {
            PrismProperty<?> prismProperty = (PrismProperty<?>) variableValue;
            final List<Element> elementList = new ArrayList<Element>();
            for (PrismPropertyValue<?> value : prismProperty.getValues()) {
                Element valueElement = prismContext.domSerializer().serialize(value, prismProperty.getElementName());
                elementList.add(valueElement);
            }
            NodeList nodeList = new AdHocNodeList(elementList);
            variableValue = nodeList;
        } else if (variableValue instanceof PrismValue) {
            PrismValue pval = (PrismValue) variableValue;
            if (pval.getParent() == null) {
                // Set a fake parent to allow serialization
                pval.setParent(new AdHocItemable(prismContext));
            }
            variableValue = prismContext.domSerializer().serialize(pval, variableName);
        }
        if (!((variableValue instanceof Node) || variableValue instanceof NodeList) && !(variableValue.getClass().getPackage().getName().startsWith("java."))) {
            throw new SchemaException("Unable to convert value of variable " + variableName + " to XML, still got " + variableValue.getClass().getName() + ":" + variableValue + " value at the end");
        }
        return variableValue;
    } catch (SchemaException e) {
        if (variableValue != null && variableValue instanceof DebugDumpable) {
            LOGGER.trace("Value of variable {}:\n{}", variableName, ((DebugDumpable) variableValue).debugDump());
        }
        throw new SchemaException(e.getMessage() + " while processing variable " + variableName + " with value " + variableValue + " in " + contextDescription, e);
    } catch (RuntimeException e) {
        if (variableValue != null && variableValue instanceof DebugDumpable) {
            LOGGER.trace("Value of variable {}:\n{}", variableName, ((DebugDumpable) variableValue).debugDump());
        }
        throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + " while processing variable " + variableName + " with value " + variableValue + " in " + contextDescription, e);
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) DebugDumpable(com.evolveum.midpoint.util.DebugDumpable) PrismValue(com.evolveum.midpoint.prism.PrismValue) PrismObject(com.evolveum.midpoint.prism.PrismObject) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) Objectable(com.evolveum.midpoint.prism.Objectable) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 73 with PrismPropertyValue

use of com.evolveum.midpoint.prism.PrismPropertyValue in project midpoint by Evolveum.

the class XPathScriptEvaluator method evaluate.

@Override
public <T, V extends PrismValue> List<V> evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, Function<Object, Object> additionalConvertor, ScriptExpressionReturnTypeType suggestedReturnType, ObjectResolver objectResolver, Collection<FunctionLibrary> functions, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException {
    String codeString = expressionType.getCode();
    if (codeString == null) {
        throw new ExpressionEvaluationException("No script code in " + contextDescription);
    }
    Class<T> type = null;
    if (outputDefinition != null) {
        QName xsdReturnType = outputDefinition.getTypeName();
        // may return null if unknown
        type = XsdTypeMapper.toJavaType(xsdReturnType);
    }
    if (type == null) {
        // actually, if outputDefinition is null, the return value is of no interest for us
        type = (Class<T>) Element.class;
    }
    QName returnType = determineRerturnType(type, expressionType, outputDefinition, suggestedReturnType);
    Object evaluatedExpression = evaluate(returnType, codeString, variables, objectResolver, functions, contextDescription, result);
    List<V> propertyValues;
    boolean scalar = !outputDefinition.isMultiValue();
    if (expressionType.getReturnType() != null) {
        scalar = isScalar(expressionType.getReturnType());
    } else if (suggestedReturnType != null) {
        scalar = isScalar(suggestedReturnType);
    }
    if (scalar) {
        if (evaluatedExpression instanceof NodeList) {
            NodeList evaluatedExpressionNodeList = (NodeList) evaluatedExpression;
            if (evaluatedExpressionNodeList.getLength() > 1) {
                throw new ExpressionEvaluationException("Expected scalar expression result but got a list result with " + evaluatedExpressionNodeList.getLength() + " elements in " + contextDescription);
            }
            if (evaluatedExpressionNodeList.getLength() == 0) {
                evaluatedExpression = null;
            } else {
                evaluatedExpression = evaluatedExpressionNodeList.item(0);
            }
        }
        propertyValues = new ArrayList<V>(1);
        V pval = convertScalar(type, returnType, evaluatedExpression, contextDescription);
        if (pval instanceof PrismPropertyValue && !isNothing(((PrismPropertyValue<T>) pval).getValue())) {
            propertyValues.add(pval);
        }
    } else {
        if (!(evaluatedExpression instanceof NodeList)) {
            throw new IllegalStateException("The expression " + contextDescription + " resulted in " + evaluatedExpression.getClass().getName() + " while exprecting NodeList in " + contextDescription);
        }
        propertyValues = convertList(type, (NodeList) evaluatedExpression, contextDescription);
    }
    return (List<V>) PrismValue.cloneCollection(propertyValues);
}
Also used : ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 74 with PrismPropertyValue

use of com.evolveum.midpoint.prism.PrismPropertyValue in project midpoint by Evolveum.

the class AbstractValueTransformationExpressionEvaluator method evaluateScriptExpression.

private Collection<V> evaluateScriptExpression(Collection<Source<?, ?>> sources, ExpressionVariables variables, String contextDescription, boolean useNew, ExpressionEvaluationContext params, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    ExpressionVariables scriptVariables = new ExpressionVariables();
    if (useNew) {
        scriptVariables.addVariableDefinitionsNew(variables);
    } else {
        scriptVariables.addVariableDefinitionsOld(variables);
    }
    if (sources != null) {
        // Add sources to variables
        for (Source<?, ?> source : sources) {
            LOGGER.trace("source: {}", source);
            QName name = source.getName();
            if (name == null) {
                if (sources.size() == 1) {
                    name = ExpressionConstants.VAR_INPUT;
                } else {
                    throw new ExpressionSyntaxException("No name definition for source in " + contextDescription);
                }
            }
            Object value = null;
            if (useNew) {
                value = getRealContent(source.getItemNew(), source.getResidualPath());
            } else {
                value = getRealContent(source.getItemOld(), source.getResidualPath());
            }
            scriptVariables.addVariableDefinition(name, value);
        }
    }
    List<V> scriptResults = transformSingleValue(scriptVariables, null, useNew, params, (useNew ? "(new) " : "(old) ") + contextDescription, task, result);
    if (scriptResults == null || scriptResults.isEmpty()) {
        return null;
    }
    Collection<V> outputSet = new ArrayList<V>(scriptResults.size());
    for (V pval : scriptResults) {
        if (pval instanceof PrismPropertyValue<?>) {
            if (((PrismPropertyValue<?>) pval).getValue() == null) {
                continue;
            }
            Object realValue = ((PrismPropertyValue<?>) pval).getValue();
            if (realValue instanceof String) {
                if (((String) realValue).isEmpty()) {
                    continue;
                }
            }
            if (realValue instanceof PolyString) {
                if (((PolyString) realValue).isEmpty()) {
                    continue;
                }
            }
        }
        outputSet.add(pval);
    }
    return outputSet;
}
Also used : ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) QName(javax.xml.namespace.QName) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ObjectDeltaObject(com.evolveum.midpoint.repo.common.expression.ObjectDeltaObject) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ExpressionSyntaxException(com.evolveum.midpoint.repo.common.expression.ExpressionSyntaxException) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 75 with PrismPropertyValue

use of com.evolveum.midpoint.prism.PrismPropertyValue in project midpoint by Evolveum.

the class OutboundProcessor method processOutbound.

public <F extends FocusType> void processOutbound(LensContext<F> context, LensProjectionContext projCtx, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
    ResourceShadowDiscriminator discr = projCtx.getResourceShadowDiscriminator();
    ObjectDelta<ShadowType> projectionDelta = projCtx.getDelta();
    if (projectionDelta != null && projectionDelta.getChangeType() == ChangeType.DELETE) {
        LOGGER.trace("Processing outbound expressions for {} skipped, DELETE account delta", discr);
        // No point in evaluating outbound
        return;
    }
    LOGGER.trace("Processing outbound expressions for {} starting", discr);
    RefinedObjectClassDefinition rOcDef = projCtx.getStructuralObjectClassDefinition();
    if (rOcDef == null) {
        LOGGER.error("Definition for {} not found in the context, but it should be there, dumping context:\n{}", discr, context.debugDump());
        throw new IllegalStateException("Definition for " + discr + " not found in the context, but it should be there");
    }
    ObjectDeltaObject<F> focusOdo = context.getFocusContext().getObjectDeltaObject();
    ObjectDeltaObject<ShadowType> projectionOdo = projCtx.getObjectDeltaObject();
    Construction<F> outboundConstruction = new Construction<>(null, projCtx.getResource());
    outboundConstruction.setRefinedObjectClassDefinition(rOcDef);
    Collection<RefinedObjectClassDefinition> auxiliaryObjectClassDefinitions = rOcDef.getAuxiliaryObjectClassDefinitions();
    if (auxiliaryObjectClassDefinitions != null) {
        for (RefinedObjectClassDefinition auxiliaryObjectClassDefinition : auxiliaryObjectClassDefinitions) {
            outboundConstruction.addAuxiliaryObjectClassDefinition(auxiliaryObjectClassDefinition);
        }
    }
    String operation = projCtx.getOperation().getValue();
    for (QName attributeName : rOcDef.getNamesOfAttributesWithOutboundExpressions()) {
        RefinedAttributeDefinition<?> refinedAttributeDefinition = rOcDef.findAttributeDefinition(attributeName);
        final MappingType outboundMappingType = refinedAttributeDefinition.getOutboundMappingType();
        if (outboundMappingType == null) {
            continue;
        }
        if (refinedAttributeDefinition.isIgnored(LayerType.MODEL)) {
            LOGGER.trace("Skipping processing outbound mapping for attribute {} because it is ignored", attributeName);
            continue;
        }
        Mapping.Builder<PrismPropertyValue<?>, RefinedAttributeDefinition<?>> builder = mappingFactory.createMappingBuilder(outboundMappingType, "outbound mapping for " + PrettyPrinter.prettyPrint(refinedAttributeDefinition.getName()) + " in " + rOcDef.getResourceType());
        builder = builder.originObject(rOcDef.getResourceType()).originType(OriginType.OUTBOUND);
        Mapping<PrismPropertyValue<?>, RefinedAttributeDefinition<?>> evaluatedMapping = evaluateMapping(builder, attributeName, refinedAttributeDefinition, focusOdo, projectionOdo, operation, rOcDef, null, context, projCtx, task, result);
        if (evaluatedMapping != null) {
            outboundConstruction.addAttributeMapping(evaluatedMapping);
        }
    }
    for (QName assocName : rOcDef.getNamesOfAssociationsWithOutboundExpressions()) {
        RefinedAssociationDefinition associationDefinition = rOcDef.findAssociationDefinition(assocName);
        final MappingType outboundMappingType = associationDefinition.getOutboundMappingType();
        if (outboundMappingType == null) {
            continue;
        }
        //			if (associationDefinition.isIgnored(LayerType.MODEL)) {
        //				LOGGER.trace("Skipping processing outbound mapping for attribute {} because it is ignored", assocName);
        //				continue;
        //			}
        Mapping.Builder<PrismContainerValue<ShadowAssociationType>, PrismContainerDefinition<ShadowAssociationType>> mappingBuilder = mappingFactory.createMappingBuilder(outboundMappingType, "outbound mapping for " + PrettyPrinter.prettyPrint(associationDefinition.getName()) + " in " + rOcDef.getResourceType());
        PrismContainerDefinition<ShadowAssociationType> outputDefinition = getAssociationContainerDefinition();
        Mapping<PrismContainerValue<ShadowAssociationType>, PrismContainerDefinition<ShadowAssociationType>> evaluatedMapping = (Mapping) evaluateMapping(mappingBuilder, assocName, outputDefinition, focusOdo, projectionOdo, operation, rOcDef, associationDefinition.getAssociationTarget(), context, projCtx, task, result);
        if (evaluatedMapping != null) {
            outboundConstruction.addAssociationMapping(evaluatedMapping);
        }
    }
    projCtx.setOutboundConstruction(outboundConstruction);
}
Also used : MappingType(com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType) Mapping(com.evolveum.midpoint.model.common.mapping.Mapping) RefinedAssociationDefinition(com.evolveum.midpoint.common.refinery.RefinedAssociationDefinition) RefinedObjectClassDefinition(com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition) RefinedAttributeDefinition(com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition) ShadowAssociationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) Construction(com.evolveum.midpoint.model.impl.lens.Construction) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) QName(javax.xml.namespace.QName) PrismContainerDefinition(com.evolveum.midpoint.prism.PrismContainerDefinition) ResourceShadowDiscriminator(com.evolveum.midpoint.schema.ResourceShadowDiscriminator)

Aggregations

PrismPropertyValue (com.evolveum.midpoint.prism.PrismPropertyValue)176 PrismPropertyDefinition (com.evolveum.midpoint.prism.PrismPropertyDefinition)93 Test (org.testng.annotations.Test)83 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)81 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)81 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)60 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)43 QName (javax.xml.namespace.QName)35 PrismObject (com.evolveum.midpoint.prism.PrismObject)29 PrismPropertyDefinitionImpl (com.evolveum.midpoint.prism.PrismPropertyDefinitionImpl)19 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)17 ArrayList (java.util.ArrayList)16 Task (com.evolveum.midpoint.task.api.Task)12 ExpressionEvaluationContext (com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext)11 PropertyDelta (com.evolveum.midpoint.prism.delta.PropertyDelta)10 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)9 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)9 PrismProperty (com.evolveum.midpoint.prism.PrismProperty)8 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)8 File (java.io.File)8