use of org.apache.axiom.om.OMText in project wso2-synapse by wso2.
the class ScriptMediator method prepareExternalScript.
/**
* Prepares the mediator for the invocation of an external script
*
* @param synCtx MessageContext script
* @throws ScriptException For any errors , when compile the script
*/
protected ScriptEngineWrapper prepareExternalScript(MessageContext synCtx) throws ScriptException {
// Derive actual key from xpath expression or get static key
String generatedScriptKey = key.evaluateValue(synCtx);
Entry entry = synCtx.getConfiguration().getEntryDefinition(generatedScriptKey);
boolean needsReload = (entry != null) && entry.isDynamic() && (!entry.isCached() || entry.isExpired());
ScriptEngineWrapper sew = getNewScriptEngine();
Bindings engineBinding = sew.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
// if we don't do this, previous state can affect successive executions! ESBJAVA-4583
engineBinding.clear();
if (scriptSourceCode == null || needsReload || !sew.isInitialized()) {
Object o = synCtx.getEntry(generatedScriptKey);
if (o instanceof OMElement) {
scriptSourceCode = ((OMElement) (o)).getText();
sew.getEngine().eval(scriptSourceCode, engineBinding);
} else if (o instanceof String) {
scriptSourceCode = (String) o;
sew.getEngine().eval(scriptSourceCode, engineBinding);
} else if (o instanceof OMText) {
DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
if (dataHandler != null) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
StringBuilder scriptSB = new StringBuilder();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
scriptSB.append(currentLine).append('\n');
}
scriptSourceCode = scriptSB.toString();
sew.getEngine().eval(scriptSourceCode, engineBinding);
} catch (IOException e) {
handleException("Error in reading script as a stream ", e, synCtx);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
handleException("Error in closing input stream ", e, synCtx);
}
}
}
}
}
} else {
// Will drop TPS, but is required for ESBJAVA-4583
sew.getEngine().eval(scriptSourceCode, engineBinding);
}
// load <include /> scripts; reload each script if needed
for (Value includeKey : includes.keySet()) {
String includeSourceCode = (String) includes.get(includeKey);
String generatedKey = includeKey.evaluateValue(synCtx);
Entry includeEntry = synCtx.getConfiguration().getEntryDefinition(generatedKey);
boolean includeEntryNeedsReload = (includeEntry != null) && includeEntry.isDynamic() && (!includeEntry.isCached() || includeEntry.isExpired());
if (includeSourceCode == null || includeEntryNeedsReload || !sew.isInitialized()) {
log.debug("Re-/Loading the include script with key " + includeKey);
Object o = synCtx.getEntry(generatedKey);
if (o instanceof OMElement) {
includeSourceCode = ((OMElement) (o)).getText();
sew.getEngine().eval(includeSourceCode, engineBinding);
} else if (o instanceof String) {
includeSourceCode = (String) o;
sew.getEngine().eval(includeSourceCode, engineBinding);
} else if (o instanceof OMText) {
DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
if (dataHandler != null) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
StringBuilder scriptSB = new StringBuilder();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
scriptSB.append(currentLine).append('\n');
}
includeSourceCode = scriptSB.toString();
sew.getEngine().eval(includeSourceCode, engineBinding);
} catch (IOException e) {
handleException("Error in reading script as a stream ", e, synCtx);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
handleException("Error in closing input" + " stream ", e, synCtx);
}
}
}
}
}
includes.put(includeKey, includeSourceCode);
} else {
// Will drop TPS, but required for ESBJAVA-4583
sew.getEngine().eval(includeSourceCode, engineBinding);
}
}
sew.setInitialized(true);
return sew;
}
use of org.apache.axiom.om.OMText 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);
}
}
use of org.apache.axiom.om.OMText in project wso2-synapse by wso2.
the class HessianMessageBuilderTest method test.
private MessageContext test(String testMessageName, SynapseEnvironment synEnv) throws IOException {
HessianTestHelper hessianTestHelper = new HessianTestHelper();
MessageContext msgContext = hessianTestHelper.createAxis2MessageContext(synEnv);
OMElement element = hessianTestHelper.buildHessianTestMessage(testMessageName, msgContext);
OMNode hessianNode = element.getFirstOMChild();
OMText hessianTextNode = (OMText) hessianNode;
SynapseBinaryDataSource synapseBinaryDataSource = (SynapseBinaryDataSource) ((DataHandler) hessianTextNode.getDataHandler()).getDataSource();
InputStream inputStream = synapseBinaryDataSource.getInputStream();
byte[] originalByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(testMessageName));
byte[] builderByteArray = IOUtils.toByteArray(inputStream);
assertTrue(Arrays.equals(originalByteArray, builderByteArray));
return msgContext;
}
use of org.apache.axiom.om.OMText 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.axiom.om.OMText in project wso2-synapse by wso2.
the class HessianMessageBuilder method processDocument.
/**
* Returns an OMElement from a Hessian encoded message
*
* @param inputStream stream containing the Hessian message to be built
* @param contentType content type of the message
* @param messageContext message to which the hessian message has to be attached
* @return OMElement containing Hessian data handler keeping the message
* @throws AxisFault in case of a failure in building the hessian message
*
* @see org.apache.axis2.builder.Builder#processDocument(java.io.InputStream,
* String, org.apache.axis2.context.MessageContext)
*/
public OMElement processDocument(final InputStream inputStream, final String contentType, final MessageContext messageContext) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Start building the hessian message in to a HessianDataSource");
}
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace ns = factory.createOMNamespace(HessianConstants.HESSIAN_NAMESPACE_URI, HessianConstants.HESSIAN_NS_PREFIX);
OMElement element = factory.createOMElement(HessianConstants.HESSIAN_ELEMENT_LOCAL_NAME, ns);
try {
Parameter synEnv = messageContext.getConfigurationContext().getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
PushbackInputStream pis = detectAndMarkMessageFault(messageContext, inputStream);
DataHandler dataHandler;
if (synEnv != null && synEnv.getValue() != null) {
dataHandler = new DataHandler(new SynapseBinaryDataSource(pis, contentType, (SynapseEnvironment) synEnv.getValue()));
} else {
// add Hessian data inside a data handler
dataHandler = new DataHandler(new SynapseBinaryDataSource(pis, contentType));
}
OMText textData = factory.createOMText(dataHandler, true);
element.addChild(textData);
// indicate that message faults shall be handled as http 200
messageContext.setProperty(NhttpConstants.FAULTS_AS_HTTP_200, NhttpConstants.TRUE);
} catch (IOException e) {
String msg = "Unable to create the HessianDataSource";
log.error(msg, e);
throw new AxisFault(msg, e);
}
if (log.isDebugEnabled()) {
log.debug("Building the hessian message using HessianDataSource is successful");
}
return element;
}
Aggregations