use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.
the class ScriptMediatorTest method testExternalScriptWithComments.
/**
* Test functionality of mediate with external script in js.
*
* @throws Exception
*/
public void testExternalScriptWithComments() 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("js", 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);
}
use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.
the class NashornJavaScriptMessageContext method setProperty.
/**
* Add a new property to the message.
*
* @param key unique identifier of property
* @param value value of property
* @param scope scope of the property
*/
public void setProperty(String key, Object value, String scope) {
if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
setProperty(key, value);
} else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope)) {
// Setting property into the Axis2 Message Context
Axis2MessageContext axis2smc = (Axis2MessageContext) mc;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2MessageCtx.setProperty(key, value);
handleSpecialProperties(key, value, axis2MessageCtx);
} else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)) {
// Setting Transport Headers
Axis2MessageContext axis2smc = (Axis2MessageContext) mc;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headers != null && headers instanceof Map) {
Map headersMap = (Map) headers;
headersMap.put(key, value);
}
if (headers == null) {
Map headersMap = new HashMap();
headersMap.put(key, value);
axis2MessageCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
}
} else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope)) {
Axis2MessageContext axis2smc = (Axis2MessageContext) mc;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
axis2MessageCtx.getOperationContext().setProperty(key, value);
}
}
use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.
the class SynapseXPath method stringValueOf.
/**
* <P>Evaluates the XPath expression against the MessageContext of the current message and
* returns a String representation of the result</p>
*
* @param synCtx the source message which holds the MessageContext against full context
* @return a String representation of the result of evaluation
*/
public String stringValueOf(MessageContext synCtx) {
try {
if (forceFailoverEvaluation) {
if (log.isDebugEnabled()) {
log.debug("Forced evaluation of the expression with the DOM parser by bypassing the Jaxen: " + getExpression());
}
throw new UnresolvableException("Forced to evaluate with DOM parser bypassing Jaxen");
}
InputStream inputStream = null;
Object result = null;
org.apache.axis2.context.MessageContext axis2MC = null;
if (!forceDisableStreamXpath && "true".equals(enableStreamingXpath) && streamingXPATH != null && (((Axis2MessageContext) synCtx).getEnvelope() == null || ((Axis2MessageContext) synCtx).getEnvelope().getBody().getFirstElement() == null)) {
try {
axis2MC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
String contentType = (String) axis2MC.getProperty(SynapseConstants.AXIS2_PROPERTY_CONTENT_TYPE);
if (!isStreamingXpathSupportedContentType(contentType) && !Boolean.TRUE.equals(PassThroughConstants.MESSAGE_BUILDER_INVOKED)) {
RelayUtils.buildMessage(axis2MC);
} else {
inputStream = getMessageInputStreamPT(axis2MC);
}
} catch (XMLStreamException e) {
handleException("Error occurred while building the message from the message context", e);
} catch (IOException e) {
log.error("Error occurred while obtaining input stream from the message context", e);
}
if (inputStream != null) {
try {
result = streamingXPATH.getStringValue(inputStream);
} catch (XMLStreamException e) {
handleException("Error occurred while parsing the XPATH String", e);
} catch (StreamingXPATHException e) {
handleException("Error occurred while parsing the XPATH String", e);
}
} else {
try {
result = streamingXPATH.getStringValue(synCtx.getEnvelope());
} catch (XMLStreamException e) {
handleException("Error occurred while parsing the XPATH String", e);
} catch (StreamingXPATHException e) {
handleException("Error occurred while parsing the XPATH String", e);
}
}
} else {
result = evaluate(synCtx);
}
if (result == null) {
return null;
}
StringBuffer textValue = new StringBuffer();
if (result instanceof List) {
List list = (List) result;
for (Object o : list) {
if (o == null && list.size() == 1) {
return null;
}
if (o instanceof OMTextImpl) {
textValue.append(((OMTextImpl) o).getText());
} else if (o instanceof OMElementImpl) {
String s = ((OMElementImpl) o).getText();
// We use StringUtils.trim as String.trim does not remove U+00A0 (int 160) (No-break space)
if (s.replace(String.valueOf((char) 160), " ").trim().length() == 0) {
s = o.toString();
}
textValue.append(s);
} else if (o instanceof OMDocumentImpl) {
textValue.append(((OMDocumentImpl) o).getOMDocumentElement().toString());
} else if (o instanceof OMAttribute) {
textValue.append(((OMAttribute) o).getAttributeValue());
} else if (o instanceof SynapseXPath) {
textValue.append(((SynapseXPath) o).stringValueOf(synCtx));
}
}
} else if ("true".equals(enableStreamingXpath) && streamingXPATH != null) {
if (!"".equals((String) result)) {
OMElement re = AXIOMUtil.stringToOM((String) result);
if (re != null) {
textValue.append(re.getText());
} else {
textValue.append(result.toString());
}
}
} else {
textValue.append(result.toString());
}
return textValue.toString();
} catch (UnresolvableException ex) {
// xpath processing in DOM fashion which can support XPATH2.0 with supported XAPTH engine like SAXON
if ("true".equals(domXpathConfig)) {
if (log.isDebugEnabled()) {
log.debug("AXIOM xpath evaluation failed with UnresolvableException, " + "trying to perform DOM based XPATH", ex);
}
try {
return evaluateDOMXPath(synCtx);
} catch (Exception e) {
handleException("Evaluation of the XPath expression " + this.toString() + " resulted in an error", e);
}
} else {
handleException("Evaluation of the XPath expression " + this.toString() + " resulted in an error", ex);
}
} catch (JaxenException je) {
handleException("Evaluation of the XPath expression " + this.toString() + " resulted in an error", je);
} catch (XMLStreamException e) {
handleException("Evaluation of the XPath expression " + this.toString() + " resulted in an error", e);
}
return null;
}
use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.
the class SynapseXPathVariableContext method getVariableValue.
/**
* Gets the variable values resolved from the context. This includes the
* <dl>
* <dt><tt>body</tt></dt>
* <dd>The SOAP 1.1 or 1.2 body element.</dd>
* <dt><tt>header</tt></dt>
* <dd>The SOAP 1.1 or 1.2 header element.</dd>
* </dl>
* and the following variable prefixes
* <dl>
* <dt><tt>ctx</tt></dt>
* <dd>Prefix for Synapse MessageContext properties</dd>
* <dt><tt>axis2</tt></dt>
* <dd>Prefix for Axis2 MessageContext properties</dd>
* <dt><tt>trp</tt></dt>
* <dd>Prefix for the transport headers</dd>
* </dl>
* If the variable is unknown, this method attempts to resolve it using
* the parent variable context.
*
* @param namespaceURI namespaces for the variable resolution
* @param prefix string prefix for the variable resolution
* @param localName string local name for the variable resolution
* @return Resolved variable value
* @throws UnresolvableException if the variable specified does not found
*/
public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException {
if (namespaceURI == null) {
if (env != null) {
if (SynapseXPathConstants.SOAP_BODY_VARIABLE.equals(localName)) {
return env.getBody();
} else if (SynapseXPathConstants.SOAP_HEADER_VARIABLE.equals(localName)) {
return env.getHeader();
} else if (SynapseXPathConstants.SOAP_ENVELOPE_VARIABLE.equals(localName)) {
return env;
}
}
if (prefix != null && !"".equals(prefix) && synCtx != null) {
if (SynapseXPathConstants.MESSAGE_CONTEXT_VARIABLE_PREFIX.equals(prefix)) {
return synCtx.getProperty(localName);
} else if (SynapseXPathConstants.AXIS2_CONTEXT_VARIABLE_PREFIX.equals(prefix)) {
return ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(localName);
} else if (SynapseXPathConstants.FUNC_CONTEXT_VARIABLE_PREFIX.equals(prefix)) {
Stack<TemplateContext> functionStack = (Stack) synCtx.getProperty(SynapseConstants.SYNAPSE__FUNCTION__STACK);
TemplateContext topCtxt = functionStack.peek();
if (topCtxt != null) {
Object result = topCtxt.getParameterValue(localName);
if (result != null && result instanceof SynapseXPath && env != null) {
SynapseXPath expression = (SynapseXPath) topCtxt.getParameterValue(localName);
try {
return expression.evaluate(env);
} catch (JaxenException e) {
return null;
}
} else {
return result;
}
}
} else if (SynapseXPathConstants.TRANSPORT_VARIABLE_PREFIX.equals(prefix)) {
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
Object headers = axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headers != null && headers instanceof Map) {
Map headersMap = (Map) headers;
return headersMap.get(localName);
} else {
return null;
}
} else if (SynapseXPathConstants.URL_VARIABLE_PREFIX.equals(prefix)) {
EndpointReference toEPR = synCtx.getTo();
if (toEPR != null) {
String completeURL = toEPR.getAddress();
AxisBindingOperation axisBindingOperation = (AxisBindingOperation) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.AXIS_BINDING_OPERATION);
String queryParameterSeparator = null;
if (axisBindingOperation != null) {
queryParameterSeparator = (String) axisBindingOperation.getProperty(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR);
}
if (queryParameterSeparator == null) {
queryParameterSeparator = WSDL20DefaultValueHolder.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR_DEFAULT;
}
int i = completeURL.indexOf("?");
if (i > -1) {
String queryString = completeURL.substring(i + 1);
if (queryString != null && !queryString.equals("")) {
String[] params = queryString.split(queryParameterSeparator);
if (params == null || params.length == 0) {
return "";
}
for (String param : params) {
String[] temp = param.split("=");
if (temp != null && temp.length >= 1) {
if (temp[0].equalsIgnoreCase(localName)) {
try {
return temp.length > 1 ? URIEncoderDecoder.decode(temp[1]) : "";
} catch (UnsupportedEncodingException e) {
String msg = "Couldn't decode the URL parameter " + "value " + temp[1] + " with name " + localName;
log.error(msg, e);
throw new UnresolvableException(msg + e.getMessage());
}
}
}
}
}
}
}
return "";
} else if (SynapseXPathConstants.OPERATION_SCOPE_VARIABLE_PREFIX.equals(prefix)) {
Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
return axis2smc.getAxis2MessageContext().getOperationContext().getProperty(localName);
} else if (SynapseXPathConstants.SYSTEM_SCOPE_VARIABLE_PREFIX.equals(prefix)) {
String propVal = System.getProperty(localName);
if (propVal != null) {
return propVal;
} else {
return "";
}
} else {
Object o = synCtx.getProperty(prefix);
if (o instanceof Map) {
Object valueObject = ((Map) o).get(localName);
if (valueObject != null) {
return valueObject.toString();
}
}
}
}
}
// try resolving using available custom extensions
Object obj = XpathExtensionUtil.resolveVariableContext(synCtx, namespaceURI, prefix, localName);
if (obj != null) {
return obj;
}
return parent.getVariableValue(namespaceURI, prefix, localName);
}
use of org.apache.synapse.core.axis2.Axis2MessageContext in project wso2-synapse by wso2.
the class TestMessageContextBuilder method build.
/**
* Build the test message context.
* This method returns a new (and independent) instance on every invocation.
*
* @return
* @throws Exception
*/
public MessageContext build() throws Exception {
SynapseConfiguration testConfig = new SynapseConfiguration();
// TODO: check whether we need a SynapseEnvironment in all cases
SynapseEnvironment synEnv = new Axis2SynapseEnvironment(new ConfigurationContext(new AxisConfiguration()), testConfig);
MessageContext synCtx;
if (requireAxis2MessageContext) {
synCtx = new Axis2MessageContext(new org.apache.axis2.context.MessageContext(), testConfig, synEnv);
} else {
synCtx = new TestMessageContext();
synCtx.setEnvironment(synEnv);
synCtx.setConfiguration(testConfig);
}
for (Map.Entry<String, Entry> mapEntry : entries.entrySet()) {
testConfig.addEntry(mapEntry.getKey(), mapEntry.getValue());
}
XMLStreamReader parser = null;
if (contentString != null) {
parser = StAXUtils.createXMLStreamReader(new StringReader(contentString));
} else if (contentFile != null) {
parser = StAXUtils.createXMLStreamReader(new FileInputStream(contentFile));
} else if (contentStringJson != null) {
// synCtx = new Axis2MessageContext(null, testConfig, synEnv);
SOAPEnvelope envelope = OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope();
synCtx.setEnvelope(envelope);
JsonUtil.getNewJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext(), contentStringJson, true, true);
return synCtx;
}
SOAPEnvelope envelope;
if (parser != null) {
if (contentIsEnvelope) {
envelope = new StAXSOAPModelBuilder(parser).getSOAPEnvelope();
} else {
envelope = OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope();
// TODO: don't know why this is here, but without it some unit tests fail...
OMDocument omDoc = OMAbstractFactory.getSOAP11Factory().createOMDocument();
omDoc.addChild(envelope);
SOAPBody body = envelope.getBody();
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement bodyElement = builder.getDocumentElement();
if (addTextAroundBody) {
OMFactory fac = OMAbstractFactory.getOMFactory();
body.addChild(fac.createOMText("\n"));
body.addChild(bodyElement);
body.addChild(fac.createOMText("\n"));
} else {
body.addChild(bodyElement);
}
}
} else {
envelope = OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope();
}
synCtx.setEnvelope(envelope);
return synCtx;
}
Aggregations