Search in sources :

Example 36 with SynapseXPath

use of org.apache.synapse.util.xpath.SynapseXPath in project wso2-synapse by wso2.

the class ValueFactory method createTextValue.

/**
 * Create a key instance
 *
 * @param elem OMElement
 * @return Key
 */
public Value createTextValue(OMElement elem) {
    Value key = null;
    // OMAttribute attKey = elem.getAttribute(new QName(name));
    String textValue = elem.getText();
    if (textValue != null) {
        boolean hasEscape = isEscapedExpression(textValue);
        if (!hasEscape && isDynamicKey(textValue)) {
            // Filter json-eval expressions
            if (textValue.startsWith("{json-eval(")) {
                // Get the JSON expression in-between "{}"
                textValue = textValue.substring(1, textValue.length() - 1);
                SynapseJsonPath synJsonPath = createSynJsonPath(textValue);
                key = new Value(synJsonPath);
            } else {
                SynapseXPath synXpath = createSynXpath(elem, textValue);
                key = new Value(synXpath);
            }
        } else if (hasEscape) {
            /**
             * escaped expr
             */
            key = new Value(getEscapedExpression(textValue));
            key.setNamespaces(elem);
        } else {
            /**
             * static key
             */
            key = new Value(textValue);
        }
    } else {
        handleException("Text value is required for the element '" + elem.getLocalName() + "'");
    }
    return key;
}
Also used : SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) SynapseJsonPath(org.apache.synapse.util.xpath.SynapseJsonPath) Value(org.apache.synapse.mediators.Value)

Example 37 with SynapseXPath

use of org.apache.synapse.util.xpath.SynapseXPath in project wso2-synapse by wso2.

the class PayloadFactoryMediatorFactory method createSpecificMediator.

public Mediator createSpecificMediator(OMElement elem, Properties properties) {
    PayloadFactoryMediator payloadFactoryMediator = new PayloadFactoryMediator();
    processAuditStatus(payloadFactoryMediator, elem);
    String mediaTypeValue = elem.getAttributeValue(TYPE_Q);
    // for the backward compatibility.
    if (mediaTypeValue != null) {
        // set the mediaType for the PF
        payloadFactoryMediator.setType(mediaTypeValue);
    } else {
        payloadFactoryMediator.setType(XML_TYPE);
    }
    OMElement formatElem = elem.getFirstChildWithName(FORMAT_Q);
    if (formatElem != null) {
        OMAttribute n = formatElem.getAttribute(ATT_KEY);
        if (n == null) {
            // OMElement copy = formatElem.getFirstElement().cloneOMElement();
            OMElement copy = formatElem.cloneOMElement();
            removeIndentations(copy);
            if (mediaTypeValue != null && (mediaTypeValue.contains(JSON_TYPE) || mediaTypeValue.contains(TEXT_TYPE))) {
                payloadFactoryMediator.setFormat(copy.getText());
            } else {
                payloadFactoryMediator.setFormat(copy.getFirstElement().toString());
            }
        } else {
            ValueFactory keyFac = new ValueFactory();
            Value generatedKey = keyFac.createValue(XMLConfigConstants.KEY, formatElem);
            payloadFactoryMediator.setFormatKey(generatedKey);
            payloadFactoryMediator.setFormatDynamic(true);
        }
    } else {
        handleException("format element of payloadFactoryMediator is required");
    }
    OMElement argumentsElem = elem.getFirstChildWithName(ARGS_Q);
    if (argumentsElem != null) {
        Iterator itr = argumentsElem.getChildElements();
        while (itr.hasNext()) {
            OMElement argElem = (OMElement) itr.next();
            Argument arg = new Argument();
            String value;
            boolean isLiteral = false;
            String isLiteralString = argElem.getAttributeValue(ATT_LITERAL);
            if (isLiteralString != null) {
                // if literal is 'true' then set literal to true. defaults to false.
                isLiteral = Boolean.parseBoolean(isLiteralString);
            }
            arg.setLiteral(isLiteral);
            if ((value = argElem.getAttributeValue(ATT_VALUE)) != null) {
                arg.setValue(value);
                arg.setExpression(null);
                payloadFactoryMediator.addPathArgument(arg);
            } else if ((value = argElem.getAttributeValue(ATT_EXPRN)) != null) {
                if (value.trim().length() == 0) {
                    handleException("Attribute value for xpath cannot be empty");
                } else {
                    try {
                        // set the evaluator
                        String evaluator = argElem.getAttributeValue(ATT_EVAL);
                        if (evaluator != null && evaluator.equals(JSON_TYPE)) {
                            if (value.startsWith("json-eval(")) {
                                value = value.substring(10, value.length() - 1);
                            }
                            arg.setExpression(SynapseJsonPathFactory.getSynapseJsonPath(value));
                            // we have to explicitly define the path type since we are not going to mark
                            // JSON Path's with prefix "json-eval(".
                            arg.getExpression().setPathType(SynapsePath.JSON_PATH);
                            payloadFactoryMediator.addPathArgument(arg);
                        } else {
                            SynapseXPath sxp = SynapseXPathFactory.getSynapseXPath(argElem, ATT_EXPRN);
                            // we need to disable stream Xpath forcefully
                            sxp.setForceDisableStreamXpath(Boolean.TRUE);
                            arg.setExpression(sxp);
                            arg.getExpression().setPathType(SynapsePath.X_PATH);
                            payloadFactoryMediator.addPathArgument(arg);
                        }
                    } catch (JaxenException e) {
                        handleException("Invalid XPath expression for attribute expression : " + value, e);
                    }
                }
            } else {
                handleException("Unsupported arg type. value or expression attribute required");
            }
        }
    }
    return payloadFactoryMediator;
}
Also used : SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) Argument(org.apache.synapse.mediators.transform.Argument) PayloadFactoryMediator(org.apache.synapse.mediators.transform.PayloadFactoryMediator) JaxenException(org.jaxen.JaxenException) Value(org.apache.synapse.mediators.Value) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 38 with SynapseXPath

use of org.apache.synapse.util.xpath.SynapseXPath in project wso2-synapse by wso2.

the class IterateMediatorFactory method createSpecificMediator.

/**
 * This method will create the IterateMediator by parsing the given xml configuration
 *
 * @param elem OMElement describing the configuration of the IterateMediaotr
 * @param properties properties passed
 * @return IterateMediator created from the given configuration
 */
public Mediator createSpecificMediator(OMElement elem, Properties properties) {
    IterateMediator mediator = new IterateMediator();
    processAuditStatus(mediator, elem);
    OMAttribute id = elem.getAttribute(ID_Q);
    if (id != null) {
        mediator.setId(id.getAttributeValue());
    }
    OMAttribute continueParent = elem.getAttribute(ATT_CONTPAR);
    if (continueParent != null) {
        mediator.setContinueParent(Boolean.valueOf(continueParent.getAttributeValue()));
    }
    OMAttribute preservePayload = elem.getAttribute(ATT_PREPLD);
    if (preservePayload != null) {
        mediator.setPreservePayload(Boolean.valueOf(preservePayload.getAttributeValue()));
    }
    OMAttribute expression = elem.getAttribute(ATT_EXPRN);
    if (expression != null) {
        try {
            mediator.setExpression(SynapseXPathFactory.getSynapseXPath(elem, ATT_EXPRN));
        } catch (JaxenException e) {
            handleException("Unable to build the IterateMediator. " + "Invalid XPATH " + expression.getAttributeValue(), e);
        }
    } else {
        handleException("XPATH expression is required " + "for an IterateMediator under the \"expression\" attribute");
    }
    OMAttribute attachPath = elem.getAttribute(ATT_ATTACHPATH);
    String attachPathValue = ".";
    if (attachPath != null && !mediator.isPreservePayload()) {
        handleException("Wrong configuration for the iterate mediator :: if the iterator " + "should not preserve payload, then attachPath can not be present");
    } else if (attachPath != null) {
        attachPathValue = attachPath.getAttributeValue();
    }
    try {
        SynapseXPath xp = new SynapseXPath(attachPathValue);
        OMElementUtils.addNameSpaces(xp, elem, log);
        mediator.setAttachPath(xp);
    } catch (JaxenException e) {
        handleException("Unable to build the IterateMediator. Invalid XPATH " + attachPathValue, e);
    }
    boolean asynchronous = true;
    OMAttribute asynchronousAttr = elem.getAttribute(ATT_SEQUENCIAL);
    if (asynchronousAttr != null && asynchronousAttr.getAttributeValue().equals("true")) {
        asynchronous = false;
    }
    OMElement targetElement = elem.getFirstChildWithName(TARGET_Q);
    if (targetElement != null) {
        Target target = TargetFactory.createTarget(targetElement, properties);
        if (target != null) {
            target.setAsynchronous(asynchronous);
            mediator.setTarget(target);
        }
    } else {
        handleException("Target for an iterate mediator is required :: missing target");
    }
    addAllCommentChildrenToList(elem, mediator.getCommentsList());
    return mediator;
}
Also used : SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) Target(org.apache.synapse.mediators.eip.Target) JaxenException(org.jaxen.JaxenException) OMElement(org.apache.axiom.om.OMElement) IterateMediator(org.apache.synapse.mediators.eip.splitter.IterateMediator) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 39 with SynapseXPath

use of org.apache.synapse.util.xpath.SynapseXPath in project wso2-synapse by wso2.

the class AnnotatedCommandMediator method mediate.

@Override
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : POJOCommand mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Creating a new instance of POJO class : " + getCommand().getClass());
    }
    Object commandObject = null;
    try {
        // instantiate a new command object each time
        commandObject = getCommand().newInstance();
    } catch (Exception e) {
        handleException("Error creating an instance of the POJO command class : " + getCommand().getClass(), e, synCtx);
    }
    synLog.traceOrDebug("Instance created, setting static and dynamic properties");
    // then set the static/constant properties first
    for (Iterator iter = getStaticSetterProperties().keySet().iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        PropertyHelper.setInstanceProperty(name, getStaticSetterProperties().get(name), commandObject);
    }
    for (Field f : beforeFields.keySet()) {
        SynapseXPath xpath = beforeFields.get(f);
        Object v;
        if (f.getType().equals(String.class)) {
            v = xpath.stringValueOf(synCtx);
        } else {
            throw new UnsupportedOperationException("non-String types not supportted yet");
        }
        try {
            f.set(commandObject, v);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    for (Method m : beforeMethods.keySet()) {
        SynapseXPath xpath = beforeMethods.get(m);
        Object v;
        if (m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(String.class)) {
            v = xpath.stringValueOf(synCtx);
        } else {
            throw new UnsupportedOperationException("non-String types not supportted yet");
        }
        try {
            m.invoke(commandObject, v);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    synLog.traceOrDebug("POJO initialized successfully, invoking the execute() method");
    // then call the execute method if the Command interface is implemented
    if (commandObject instanceof Command) {
        try {
            ((Command) commandObject).execute();
        } catch (Exception e) {
            handleException("Error invoking POJO command class : " + getCommand().getClass(), e, synCtx);
        }
    } else {
        Method exeMethod = null;
        try {
            exeMethod = getCommand().getMethod("execute", new Class[] {});
            exeMethod.invoke(commandObject, new Object[] {});
        } catch (NoSuchMethodException e) {
            handleException("Cannot locate an execute() method on POJO class : " + getCommand().getClass(), e, synCtx);
        } catch (Exception e) {
            handleException("Error invoking the execute() method on POJO class : " + getCommand().getClass(), e, synCtx);
        }
    }
    // TODO: now update the MessageContext from the commandObject
    synLog.traceOrDebug("End : POJOCommand mediator");
    return true;
}
Also used : Field(java.lang.reflect.Field) SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) SynapseLog(org.apache.synapse.SynapseLog) Command(org.apache.synapse.Command) Iterator(java.util.Iterator) Method(java.lang.reflect.Method) JaxenException(org.jaxen.JaxenException)

Example 40 with SynapseXPath

use of org.apache.synapse.util.xpath.SynapseXPath in project wso2-synapse by wso2.

the class POJOCommandMediator method mediate.

/**
 * Implements the mediate method of the Mediator interface. This method will instantiate
 * a new instance of the POJO class, set all specified properties from the current runtime
 * state (and message context) and call the execute method of the Command object.
 *
 * @param synCtx - Synapse MessageContext to be mediated
 * @return boolean true since this will not stop exection chain
 */
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : POJOCommand mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Creating a new instance of POJO class : " + command.getClass());
    }
    Object commandObject = null;
    try {
        // instantiate a new command object each time
        commandObject = command.newInstance();
    } catch (Exception e) {
        handleException("Error creating an instance of the POJO command class : " + command.getClass(), e, synCtx);
    }
    synLog.traceOrDebug("Instance created, setting static and dynamic properties");
    // then set the static/constant properties first
    for (String name : staticSetterProperties.keySet()) {
        PropertyHelper.setInstanceProperty(name, staticSetterProperties.get(name), commandObject);
    }
    // now set the any dynamic properties from the message context properties
    for (String name : contextSetterProperties.keySet()) {
        PropertyHelper.setInstanceProperty(name, synCtx.getProperty(contextSetterProperties.get(name)), commandObject);
    }
    // now set the any dynamic properties evaluating XPath's on the current message
    for (String name : messageSetterProperties.keySet()) {
        SynapseXPath xpath = messageSetterProperties.get(name);
        String value = xpath.stringValueOf(synCtx);
        PropertyHelper.setInstanceProperty(name, value, commandObject);
    }
    synLog.traceOrDebug("POJO initialized successfully, invoking the execute() method");
    // then call the execute method if the Command interface is implemented
    if (commandObject instanceof Command) {
        try {
            ((Command) commandObject).execute();
        } catch (Exception e) {
            handleException("Error invoking POJO command class : " + command.getClass(), e, synCtx);
        }
    } else {
        try {
            Method exeMethod = command.getMethod("execute");
            exeMethod.invoke(commandObject);
        } catch (NoSuchMethodException e) {
            handleException("Cannot locate an execute() method on POJO class : " + command.getClass(), e, synCtx);
        } catch (Exception e) {
            handleException("Error invoking the execute() method on POJO class : " + command.getClass(), e, synCtx);
        }
    }
    // then set the context properties back to the messageContext from the command
    for (String name : contextGetterProperties.keySet()) {
        synCtx.setProperty(contextGetterProperties.get(name), getInstanceProperty(name, commandObject, synCtx));
    }
    // to the message from the command
    for (String name : messageGetterProperties.keySet()) {
        SynapseXPath xpath = messageGetterProperties.get(name);
        Object resultValue = getInstanceProperty(name, commandObject, synCtx);
        try {
            List list = EIPUtils.getMatchingElements(synCtx.getEnvelope(), xpath);
            if (list.size() > 0) {
                Object o = list.get(0);
                if (resultValue instanceof String) {
                    OMAbstractFactory.getOMFactory().createOMText(((OMNode) o).getParent(), (String) resultValue);
                    ((OMNode) o).detach();
                } else if (resultValue instanceof OMNode) {
                    ((OMNode) o).insertSiblingAfter((OMNode) resultValue);
                    ((OMNode) o).detach();
                }
            } else {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Unable to set the message property " + resultValue + "back to the message : Specified element by the xpath " + xpath + " can not be found");
                }
            }
        } catch (JaxenException e) {
            handleException("Unable to set the command property " + name + " back to the message", e, synCtx);
        }
    }
    synLog.traceOrDebug("End : POJOCommand mediator");
    return true;
}
Also used : SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) OMNode(org.apache.axiom.om.OMNode) SynapseLog(org.apache.synapse.SynapseLog) Command(org.apache.synapse.Command) JaxenException(org.jaxen.JaxenException) List(java.util.List) Method(java.lang.reflect.Method) JaxenException(org.jaxen.JaxenException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

SynapseXPath (org.apache.synapse.util.xpath.SynapseXPath)68 MessageContext (org.apache.synapse.MessageContext)24 JaxenException (org.jaxen.JaxenException)20 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)15 OMElement (org.apache.axiom.om.OMElement)14 OMAttribute (org.apache.axiom.om.OMAttribute)11 Value (org.apache.synapse.mediators.Value)9 TestMessageContext (org.apache.synapse.TestMessageContext)8 Pattern (java.util.regex.Pattern)6 Iterator (java.util.Iterator)5 QName (javax.xml.namespace.QName)5 EndpointReference (org.apache.axis2.addressing.EndpointReference)4 SynapseException (org.apache.synapse.SynapseException)4 TestMessageContextBuilder (org.apache.synapse.TestMessageContextBuilder)4 SynapseJsonPath (org.apache.synapse.util.xpath.SynapseJsonPath)4 Method (java.lang.reflect.Method)3 Map (java.util.Map)3 MediatorProperty (org.apache.synapse.mediators.MediatorProperty)3 Field (java.lang.reflect.Field)2 List (java.util.List)2