Search in sources :

Example 11 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class XQueryMediator method performQuery.

/**
 * Perform the quering and get the result and attached to the target node
 *
 * @param synCtx The current MessageContext
 * @param synLog the Synapse log to use
 */
private void performQuery(MessageContext synCtx, SynapseLog synLog) {
    boolean reLoad = false;
    boolean needSet = false;
    XQueryEvaluator queryEvaluator = null;
    String generatedQueryKey = null;
    XQueryExecutable xQueryExecutable = null;
    XdmValue xdmValue;
    boolean isQueryKeyGenerated = false;
    if (queryKey != null) {
        // Derive actual key from xpath or get static key
        generatedQueryKey = queryKey.evaluateValue(synCtx);
    }
    if (generatedQueryKey != null) {
        isQueryKeyGenerated = true;
    }
    if (generatedQueryKey != null && !"".equals(generatedQueryKey)) {
        Entry dp = synCtx.getConfiguration().getEntryDefinition(generatedQueryKey);
        // if the queryKey refers to a dynamic resource
        if (dp != null && dp.isDynamic()) {
            if (!dp.isCached() || dp.isExpired()) {
                reLoad = true;
            }
        }
    }
    try {
        synchronized (resourceLock) {
            // creating processor
            if (cachedProcessor == null) {
                cachedProcessor = new Processor(false);
                // setting up the properties to the Processor
                if (processorProperties != null && !processorProperties.isEmpty()) {
                    synLog.traceOrDebug("Setting up properties to the XQDataSource");
                    for (MediatorProperty processorProperty : processorProperties) {
                        if (processorProperty != null) {
                            cachedProcessor.setConfigurationProperty(processorProperty.getName(), processorProperty.getValue());
                        }
                    }
                }
            }
            // creating XQueryCompiler
            if (cachedQueryCompiler == null) {
                synLog.traceOrDebug("Creating a compiler from the Processor ");
                cachedQueryCompiler = cachedProcessor.newXQueryCompiler();
            }
            // If already cached evaluator then load it from cachedXQueryEvaluatorMap
            if (isQueryKeyGenerated) {
                queryEvaluator = cachedXQueryEvaluatorMap.get(generatedQueryKey);
            }
            if (reLoad || queryEvaluator == null) {
                if (querySource != null && !"".equals(querySource)) {
                    if (synLog.isTraceOrDebugEnabled()) {
                        synLog.traceOrDebug("Using in-lined query source - " + querySource);
                        synLog.traceOrDebug("Prepare an expression for the query ");
                    }
                    xQueryExecutable = cachedQueryCompiler.compile(querySource);
                    queryEvaluator = xQueryExecutable.load();
                    // if queryEvaluator is created then put it in to cachedXQueryEvaluatorMap
                    if (isQueryKeyGenerated) {
                        cachedXQueryEvaluatorMap.put(generatedQueryKey, queryEvaluator);
                    }
                    // need set because the expression just has recreated
                    needSet = true;
                } else {
                    Object o = synCtx.getEntry(generatedQueryKey);
                    if (o == null) {
                        if (synLog.isTraceOrDebugEnabled()) {
                            synLog.traceOrDebug("Couldn't find the xquery source with a key " + queryKey);
                        }
                        throw new SynapseException("No object found for the key '" + generatedQueryKey + "'");
                    }
                    String sourceCode = null;
                    InputStream inputStream = null;
                    if (o instanceof OMElement) {
                        sourceCode = ((OMElement) (o)).getText();
                    } else if (o instanceof String) {
                        sourceCode = (String) o;
                    } else if (o instanceof OMText) {
                        DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
                        if (dataHandler != null) {
                            try {
                                inputStream = dataHandler.getInputStream();
                                if (inputStream == null) {
                                    if (synLog.isTraceOrDebugEnabled()) {
                                        synLog.traceOrDebug("Couldn't get" + " the stream from the xquery source with a key " + queryKey);
                                    }
                                    return;
                                }
                            } catch (IOException e) {
                                handleException("Error in reading content as a stream ");
                            }
                        }
                    }
                    if ((sourceCode == null || "".equals(sourceCode)) && inputStream == null) {
                        if (synLog.isTraceOrDebugEnabled()) {
                            synLog.traceOrDebug("Couldn't find the xquery source with a key " + queryKey);
                        }
                        return;
                    }
                    if (synLog.isTraceOrDebugEnabled()) {
                        synLog.traceOrDebug("Picked up the xquery source from the " + "key " + queryKey);
                        synLog.traceOrDebug("Prepare an expression for the query ");
                    }
                    try {
                        if (sourceCode != null) {
                            // create an xQueryExecutable using the query source
                            xQueryExecutable = cachedQueryCompiler.compile(sourceCode);
                        } else {
                            xQueryExecutable = cachedQueryCompiler.compile(inputStream);
                        }
                    } catch (IOException e) {
                        handleException("Error during the query inputStream compilation");
                    }
                    queryEvaluator = xQueryExecutable.load();
                    // if queryEvaluator is created then put it in to cachedXQueryEvaluatorMap
                    if (isQueryKeyGenerated) {
                        cachedXQueryEvaluatorMap.put(generatedQueryKey, queryEvaluator);
                    }
                    // need set because the evaluator just has recreated
                    needSet = true;
                }
            }
            // Set the external variables to the queryEvaluator
            if (variables != null && !variables.isEmpty()) {
                synLog.traceOrDebug("Binding  external variables to the DynamicContext");
                for (MediatorVariable variable : variables) {
                    if (variable != null) {
                        boolean hasValueChanged = variable.evaluateValue(synCtx);
                        // if the value has changed or need set because the evaluator has recreated
                        if (hasValueChanged || needSet) {
                            // Set the external variable to the queryEvaluator
                            setVariable(queryEvaluator, variable, synLog);
                        }
                    }
                }
            }
            // executing the query
            xdmValue = queryEvaluator.evaluate();
        }
        if (queryEvaluator == null) {
            synLog.traceOrDebug("Result Sequence is null");
            return;
        }
        // processing the result
        for (XdmItem xdmItem : xdmValue) {
            if (xdmItem == null) {
                return;
            }
            XdmNodeKind xdmNodeKind = null;
            ItemType itemType = null;
            if (xdmItem.isAtomicValue()) {
                itemType = getItemType(xdmItem, cachedProcessor);
                if (itemType == null) {
                    return;
                }
            } else {
                xdmNodeKind = ((XdmNode) xdmItem).getNodeKind();
            }
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("The XQuery Result " + xdmItem.toString());
            }
            // The target node that is going to modify
            OMNode destination = target.selectOMNode(synCtx, synLog);
            if (destination != null) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("The target node " + destination);
                }
                // If the result is XML
                if (XdmNodeKind.DOCUMENT == xdmNodeKind || XdmNodeKind.ELEMENT == xdmNodeKind) {
                    StAXOMBuilder builder = new StAXOMBuilder(XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xdmItem.toString())));
                    OMElement resultOM = builder.getDocumentElement();
                    if (resultOM != null) {
                        // replace the target node from the result
                        destination.insertSiblingAfter(resultOM);
                        destination.detach();
                    }
                } else if (ItemType.INTEGER == itemType || ItemType.INT == itemType) {
                    // replace the text value of the target node by the result ,If the result is
                    // a basic type
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getDecimalValue().intValue()));
                } else if (ItemType.BOOLEAN == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getBooleanValue()));
                } else if (ItemType.DOUBLE == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getDoubleValue()));
                } else if (ItemType.FLOAT == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getDecimalValue().floatValue()));
                } else if (ItemType.LONG == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getLongValue()));
                } else if (ItemType.SHORT == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getDecimalValue().shortValue()));
                } else if (ItemType.BYTE == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getDecimalValue().byteValue()));
                } else if (ItemType.STRING == itemType) {
                    ((OMElement) destination).setText(String.valueOf(((XdmAtomicValue) xdmItem).getValue()));
                }
            } else if (null == target.getXPath() && null == destination) {
                // In the case soap body doesn't have the first element --> Empty soap body
                destination = synCtx.getEnvelope().getBody();
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("The target node " + destination);
                }
                // If the result is XML
                if (XdmNodeKind.ELEMENT == xdmNodeKind || XdmNodeKind.DOCUMENT == xdmNodeKind) {
                    StAXOMBuilder builder = new StAXOMBuilder(XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xdmItem.toString())));
                    OMElement resultOM = builder.getDocumentElement();
                    if (resultOM != null) {
                        ((OMElement) destination).addChild(resultOM);
                    }
                }
            // No else part since soap body could have only XML part not text values
            }
            // Only take the *first* value of the result sequence
            break;
        }
        // closing the result sequence
        queryEvaluator.close();
    } catch (SaxonApiException e) {
        handleException("Error during the querying " + e.getMessage(), e);
    } catch (XMLStreamException e) {
        handleException("Error during retrieving  the Document Node as  the result " + e.getMessage(), e);
    }
}
Also used : SynapseException(org.apache.synapse.SynapseException) OMElement(org.apache.axiom.om.OMElement) DataHandler(javax.activation.DataHandler) Entry(org.apache.synapse.config.Entry) OMText(org.apache.axiom.om.OMText) StringReader(java.io.StringReader) InputStream(java.io.InputStream) IOException(java.io.IOException) OMNode(org.apache.axiom.om.OMNode) MediatorProperty(org.apache.synapse.mediators.MediatorProperty) XMLStreamException(javax.xml.stream.XMLStreamException) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder)

Example 12 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class ValidateMediatorSerializer method serializeSpecificMediator.

public OMElement serializeSpecificMediator(Mediator m) {
    if (!(m instanceof ValidateMediator)) {
        handleException("Unsupported mediator passed in for serialization : " + m.getType());
    }
    ValidateMediator mediator = (ValidateMediator) m;
    OMElement validate = fac.createOMElement("validate", synNS);
    saveTracingState(validate, mediator);
    if (mediator.getSource() != null) {
        SynapsePathSerializer.serializePath(mediator.getSource(), validate, "source");
    }
    for (Value key : mediator.getSchemaKeys()) {
        OMElement schema = fac.createOMElement("schema", synNS, validate);
        // Serialize Value using ValueSerializer
        ValueSerializer keySerializer = new ValueSerializer();
        keySerializer.serializeValue(key, XMLConfigConstants.KEY, schema);
    }
    ResourceMapSerializer.serializeResourceMap(validate, mediator.getResourceMap());
    List<MediatorProperty> features = mediator.getFeatures();
    if (!features.isEmpty()) {
        for (MediatorProperty mp : features) {
            OMElement feature = fac.createOMElement("feature", synNS, validate);
            if (mp.getName() != null) {
                feature.addAttribute(fac.createOMAttribute("name", nullNS, mp.getName()));
            } else {
                handleException("The Feature name is missing");
            }
            if (mp.getValue() != null) {
                feature.addAttribute(fac.createOMAttribute("value", nullNS, mp.getValue()));
            } else {
                handleException("The Feature value is missing");
            }
        }
    }
    OMElement onFail = fac.createOMElement("on-fail", synNS, validate);
    serializeChildren(onFail, mediator.getList());
    OMAttribute cacheSchemaAtt = fac.createOMAttribute("cache-schema", nullNS, String.valueOf(mediator.isCacheSchema()));
    validate.addAttribute(cacheSchemaAtt);
    return validate;
}
Also used : MediatorProperty(org.apache.synapse.mediators.MediatorProperty) ValidateMediator(org.apache.synapse.mediators.builtin.ValidateMediator) Value(org.apache.synapse.mediators.Value) OMElement(org.apache.axiom.om.OMElement) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 13 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class MediatorPropertySerializerTest method testSerializeMediatorProperties.

/**
 * Test SerializeMediatorProperties for correct insertion of properties.
 *
 * @throws XMLStreamException
 */
@Test
public void testSerializeMediatorProperties() throws XMLStreamException {
    OMElement element = AXIOMUtil.stringToOM(XML);
    List<MediatorProperty> propertyList = new ArrayList<>();
    MediatorProperty property = new MediatorProperty();
    property.setName(NAME);
    property.setValue(VALUE);
    propertyList.add(property);
    MediatorPropertySerializer.serializeMediatorProperties(element, propertyList);
    OMElement firstElement = element.getFirstElement();
    Assert.assertEquals("name of property must be added as an attribute", NAME, firstElement.getAttribute(new QName("name")).getAttributeValue());
    Assert.assertEquals("value of property must be added as an attribute", VALUE, firstElement.getAttribute(new QName("value")).getAttributeValue());
}
Also used : MediatorProperty(org.apache.synapse.mediators.MediatorProperty) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) OMElement(org.apache.axiom.om.OMElement) Test(org.junit.Test)

Example 14 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class MediatorPropertySerializerTest method testSerializeWithoutPropertyName.

/**
 * Test SerializeMediatorProperties for a property without name.
 *
 * @throws XMLStreamException
 */
@Test
public void testSerializeWithoutPropertyName() throws XMLStreamException {
    OMElement element = AXIOMUtil.stringToOM(XML);
    List<MediatorProperty> propertyList = new ArrayList<>();
    MediatorProperty property = new MediatorProperty();
    propertyList.add(property);
    thrown.expect(SynapseException.class);
    thrown.expectMessage("Mediator property name missing");
    MediatorPropertySerializer.serializeMediatorProperties(element, propertyList);
}
Also used : MediatorProperty(org.apache.synapse.mediators.MediatorProperty) ArrayList(java.util.ArrayList) OMElement(org.apache.axiom.om.OMElement) Test(org.junit.Test)

Example 15 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class MediatorPropertySerializerTest method testSerializeWithoutPropertyValue.

/**
 * Test SerializeMediatorProperties for a property without value.
 *
 * @throws XMLStreamException
 */
@Test
public void testSerializeWithoutPropertyValue() throws XMLStreamException {
    OMElement element = AXIOMUtil.stringToOM(XML);
    List<MediatorProperty> propertyList = new ArrayList<>();
    MediatorProperty property = new MediatorProperty();
    property.setName(NAME);
    propertyList.add(property);
    thrown.expect(SynapseException.class);
    thrown.expectMessage("Mediator property must have a literal value or be an expression");
    MediatorPropertySerializer.serializeMediatorProperties(element, propertyList);
}
Also used : MediatorProperty(org.apache.synapse.mediators.MediatorProperty) ArrayList(java.util.ArrayList) OMElement(org.apache.axiom.om.OMElement) Test(org.junit.Test)

Aggregations

MediatorProperty (org.apache.synapse.mediators.MediatorProperty)21 OMElement (org.apache.axiom.om.OMElement)8 SynapseException (org.apache.synapse.SynapseException)8 ArrayList (java.util.ArrayList)5 Endpoint (org.apache.synapse.endpoints.Endpoint)4 AddressEndpoint (org.apache.synapse.endpoints.AddressEndpoint)3 SynapseXPath (org.apache.synapse.util.xpath.SynapseXPath)3 Test (org.junit.Test)3 Iterator (java.util.Iterator)2 QName (javax.xml.namespace.QName)2 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2 OMAttribute (org.apache.axiom.om.OMAttribute)2 PropertyInclude (org.apache.synapse.PropertyInclude)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 LoadbalanceEndpoint (org.apache.synapse.endpoints.LoadbalanceEndpoint)2 Value (org.apache.synapse.mediators.Value)2 UriTemplate (com.damnhandy.uri.template.UriTemplate)1 ExpressionParseException (com.damnhandy.uri.template.impl.ExpressionParseException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1