Search in sources :

Example 11 with Value

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

the class NashornJavaScriptMediatorTest method testExternalScriptWithCommentsOnNashornEngine.

/**
 * Test functionality of mediate with external script in nashornJS.
 *
 * @throws Exception
 */
public void testExternalScriptWithCommentsOnNashornEngine() throws Exception {
    String request = "{\n" + "    \"results\": [\n" + "        {\n" + "            \"geometry\": {\n" + "                \"location\": {\n" + "                    \"lat\": -33.86726,\n" + "                    \"lng\": 151.195813\n" + "                }\n" + "            },\n" + "            \"icon\": \"bar-71.png\",\n" + "            \"id\": \"7eaf7\",\n" + "            \"name\": \"Biaggio Cafe\",\n" + "            \"opening_hours\": {\n" + "                \"open_now\": true\n" + "            },\n" + "            \"photos\": [\n" + "                {\n" + "                    \"height\": 600,\n" + "                    \"html_attributions\": [],\n" + "                    \"photo_reference\": \"CoQBegAAAI\",\n" + "                    \"width\": 900\n" + "                }\n" + "            ],\n" + "            \"price_level\": 1,\n" + "            \"reference\": \"CnRqAAAAtz\",\n" + "            \"types\": [\n" + "                \"bar\",\n" + "                \"restaurant\",\n" + "                \"food\",\n" + "                \"establishment\"\n" + "            ],\n" + "            \"vicinity\": \"48 Pirrama Road, Pyrmont\"\n" + "        },\n" + "        {\n" + "            \"geometry\": {\n" + "                \"location\": {\n" + "                    \"lat\": -33.866804,\n" + "                    \"lng\": 151.195579\n" + "                }\n" + "            },\n" + "            \"icon\": \"generic_business-71.png\",\n" + "            \"id\": \"3ef98\",\n" + "            \"name\": \"Doltone House\",\n" + "            \"photos\": [\n" + "                {\n" + "                    \"height\": 600,\n" + "                    \"html_attributions\": [],\n" + "                    \"photo_reference\": \"CqQBmgAAAL\",\n" + "                    \"width\": 900\n" + "                }\n" + "            ],\n" + "            \"reference\": \"CnRrAAAAV\",\n" + "            \"types\": [\n" + "                \"food\",\n" + "                \"establishment\"\n" + "            ],\n" + "            \"vicinity\": \"48 Pirrama Road, Pyrmont\"\n" + "        }\n" + "    ],\n" + "    \"status\": \"OK\"\n" + "}";
    MessageContext mc = TestUtils.getTestContextJson(request, null);
    String scriptSrc = "function transform(mc) {\n" + "    payload = mc.getPayloadJSON();\n" + "    results = payload.results;\n" + "    var response = new Array();\n" + "    for (i = 0; i < results.length; ++i) {\n" + "        // this is a comment\n" + "        location_object = results[i];\n" + "        l = new Object();\n" + "        l.name = location_object.name;\n" + "        l.tags = location_object.types;\n" + "        l.id = \"ID:\" + (location_object.id);\n" + "        response[i] = l;\n" + "    }\n" + "    mc.setPayloadJSON(response);\n" + "}";
    String scriptSrcKey = "conf:/repository/esb/transform.js";
    Entry e = new Entry();
    DataSource dataSource = new ByteArrayDataSource(scriptSrc.getBytes());
    DataHandler dataHandler = new DataHandler(dataSource);
    OMText text = OMAbstractFactory.getOMFactory().createOMText(dataHandler, true);
    e.setKey(scriptSrcKey);
    e.setValue(text);
    mc.getConfiguration().addEntry(scriptSrcKey, e);
    Value v = new Value(scriptSrcKey);
    ScriptMediator mediator = new ScriptMediator("nashornJs", new LinkedHashMap<Value, Object>(), v, "transform", null);
    boolean result = mediator.mediate(mc);
    String response = JsonUtil.jsonPayloadToString(((Axis2MessageContext) mc).getAxis2MessageContext());
    String expectedResponse = "[{\"name\":\"Biaggio Cafe\",\"tags\":[\"bar\",\"restaurant\",\"food\"," + "\"establishment\"],\"id\":\"ID:7eaf7\"},{\"name\":\"Doltone House\",\"tags\":[\"food\"," + "\"establishment\"],\"id\":\"ID:3ef98\"}]";
    assertEquals(expectedResponse, response);
    assertEquals(true, result);
}
Also used : Entry(org.apache.synapse.config.Entry) ScriptMediator(org.apache.synapse.mediators.bsf.ScriptMediator) OMText(org.apache.axiom.om.OMText) Value(org.apache.synapse.mediators.Value) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(org.apache.axiom.attachments.ByteArrayDataSource) ByteArrayDataSource(org.apache.axiom.attachments.ByteArrayDataSource) DataSource(javax.activation.DataSource)

Example 12 with Value

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

the class MediatorFactoryFinder method buildParamteres.

private void buildParamteres(OMElement connectorElem, InvokeMediator invokeMediator) {
    Iterator parameters = connectorElem.getChildElements();
    while (parameters.hasNext()) {
        OMNode paramNode = (OMNode) parameters.next();
        if (paramNode instanceof OMElement) {
            // ((OMElement) paramNode).getAttributeValue(new QName("name"));
            String paramName = ((OMElement) paramNode).getLocalName();
            // ((OMElement) paramNode).getAttributeValue(new QName("value"));
            String paramValueStr = ((OMElement) paramNode).getText();
            if (paramName != null && !paramName.equals("") && paramValueStr != null && !paramValueStr.equals("")) {
                Value paramValue = new ValueFactory().createTextValue((OMElement) paramNode);
                invokeMediator.addExpressionForParamName(paramName, paramValue);
            }
        }
    }
}
Also used : OMNode(org.apache.axiom.om.OMNode) Iterator(java.util.Iterator) Value(org.apache.synapse.mediators.Value) OMElement(org.apache.axiom.om.OMElement)

Example 13 with Value

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

the class MediatorFactoryFinder method getDynamicInvokeMediator.

public InvokeMediator getDynamicInvokeMediator(OMElement connectorElem, String libraryName) {
    InvokeMediator invokeMediator = new InvokeMediator();
    if (connectorElem.getLocalName() != null && libraryName != null && !libraryName.equals("")) {
        invokeMediator.setTargetTemplate(libraryName + "." + connectorElem.getLocalName());
    }
    // load configuration based references for the given connector
    OMAttribute config_key = connectorElem.getAttribute(new QName(XMLConfigConstants.CONFIG_REF));
    if (config_key != null) {
        // ValueFactory for creating dynamic or static Value
        ValueFactory keyFac = new ValueFactory();
        // create dynamic or static key based on OMElement
        Value generatedKey = keyFac.createValue(XMLConfigConstants.CONFIG_REF, connectorElem);
        // setKey
        invokeMediator.setKey(generatedKey);
    }
    buildParamteres(connectorElem, invokeMediator);
    invokeMediator.setPackageName(libraryName);
    invokeMediator.setDynamicMediator(true);
    return invokeMediator;
}
Also used : QName(javax.xml.namespace.QName) InvokeMediator(org.apache.synapse.mediators.template.InvokeMediator) Value(org.apache.synapse.mediators.Value) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 14 with Value

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

the class ValidateMediatorFactory method createSpecificMediator.

public Mediator createSpecificMediator(OMElement elem, Properties properties) {
    ValidateMediator validateMediator = new ValidateMediator();
    // process schema element definitions and create DynamicProperties
    List<Value> schemaKeys = new ArrayList<Value>();
    Iterator schemas = elem.getChildrenWithName(SCHEMA_Q);
    while (schemas.hasNext()) {
        Object o = schemas.next();
        if (o instanceof OMElement) {
            OMElement omElem = (OMElement) o;
            OMAttribute keyAtt = omElem.getAttribute(ATT_KEY);
            if (keyAtt != null) {
                // ValueFactory for creating dynamic or static Value
                ValueFactory keyFac = new ValueFactory();
                // create dynamic or static key based on OMElement
                Value generatedKey = keyFac.createValue(XMLConfigConstants.KEY, omElem);
                schemaKeys.add(generatedKey);
            } else {
                handleException("A 'schema' definition must contain a local property 'key'");
            }
        } else {
            handleException("Invalid 'schema' declaration for validate mediator");
        }
    }
    if (schemaKeys.size() == 0) {
        handleException("No schema specified for the validate mediator");
    } else {
        validateMediator.setSchemaKeys(schemaKeys);
    }
    // process source XPath attribute if present
    OMAttribute attSource = elem.getAttribute(ATT_SOURCE);
    if (attSource != null) {
        try {
            if (attSource.getAttributeValue() != null) {
                validateMediator.setSource(SynapsePathFactory.getSynapsePath(elem, ATT_SOURCE));
            }
        } catch (JaxenException e) {
            handleException("Invalid XPath expression specified for attribute 'source'", e);
        }
    }
    // process schema cacheability.
    OMAttribute attSchemaCache = elem.getAttribute(ATT_CACHE_SCHEMA);
    if (attSchemaCache != null) {
        final boolean cacheSchema = Boolean.parseBoolean(attSchemaCache.getAttributeValue());
        if (log.isDebugEnabled()) {
            log.debug("Schema cached: " + cacheSchema);
        }
        validateMediator.setCacheSchema(cacheSchema);
    }
    // process external schema resources
    validateMediator.setResourceMap(ResourceMapFactory.createResourceMap(elem));
    // process on-fail
    OMElement onFail = null;
    Iterator iterator = elem.getChildrenWithName(ON_FAIL_Q);
    if (iterator.hasNext()) {
        onFail = (OMElement) iterator.next();
    }
    if (onFail != null && onFail.getChildElements().hasNext()) {
        addChildren(onFail, validateMediator, properties);
    } else {
        handleException("A non-empty <on-fail> child element is required for " + "the <validate> mediator");
    }
    // after successfully creating the mediator
    // set its common attributes such as tracing etc
    processAuditStatus(validateMediator, elem);
    // set the features
    for (Map.Entry<String, String> entry : collectNameValuePairs(elem, FEATURE_Q).entrySet()) {
        String value = entry.getValue();
        boolean isFeatureEnabled;
        if ("true".equals(value)) {
            isFeatureEnabled = true;
        } else if ("false".equals(value)) {
            isFeatureEnabled = false;
        } else {
            handleException("The feature must have value true or false");
            break;
        }
        try {
            validateMediator.addFeature(entry.getKey(), isFeatureEnabled);
        } catch (SAXException e) {
            handleException("Error setting validation feature : " + entry.getKey() + " to : " + value, e);
        }
    }
    addAllCommentChildrenToMediator(elem, validateMediator);
    return validateMediator;
}
Also used : ValidateMediator(org.apache.synapse.mediators.builtin.ValidateMediator) OMElement(org.apache.axiom.om.OMElement) SAXException(org.xml.sax.SAXException) JaxenException(org.jaxen.JaxenException) Value(org.apache.synapse.mediators.Value) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 15 with Value

use of org.apache.synapse.mediators.Value 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)

Aggregations

Value (org.apache.synapse.mediators.Value)38 OMElement (org.apache.axiom.om.OMElement)18 OMAttribute (org.apache.axiom.om.OMAttribute)12 QName (javax.xml.namespace.QName)9 SynapseXPath (org.apache.synapse.util.xpath.SynapseXPath)9 SynapseException (org.apache.synapse.SynapseException)7 Iterator (java.util.Iterator)6 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)6 JaxenException (org.jaxen.JaxenException)6 MessageContext (org.apache.synapse.MessageContext)5 Entry (org.apache.synapse.config.Entry)5 ValueFactory (org.apache.synapse.config.xml.ValueFactory)5 Test (org.junit.Test)4 DataHandler (javax.activation.DataHandler)3 OMText (org.apache.axiom.om.OMText)3 Endpoint (org.apache.synapse.endpoints.Endpoint)3 IOException (java.io.IOException)2 InputStreamReader (java.io.InputStreamReader)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2