package org.wso2.carbon.event.broker.utils;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import javax.xml.stream.XMLStreamException;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.wso2.event.exceptions.EventException;
public class JavaScriptExecuter {
private ConfigurationContext context;
private SystemWrapper systemWrapper;
public JavaScriptExecuter(ConfigurationContext context){
systemWrapper = new SystemWrapper(context);
}
public void execuateScript(String script, String methodName, Object[] args){
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Object wrappedOut = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", wrappedOut);
Object wrappedSystem = Context.javaToJS(systemWrapper, scope);
ScriptableObject.putProperty(scope, "system", wrappedSystem);
// Now evaluate the string we've collected. We'll ignore the result.
cx.evaluateString(scope, script, "<cmd>", 1, null);
// Call function "f('my arg')" and print its result.
Object fObj = scope.get(methodName, scope);
if (!(fObj instanceof Function)) {
System.out.println("f is undefined or not a function.");
} else {
Function f = (Function)fObj;
Object result = f.call(cx, scope, scope, args);
//String report = "f('my args') = " + Context.toString(result);
//System.out.println(report);
}
} finally {
Context.exit();
}
}
public class SystemWrapper{
public SystemWrapper(ConfigurationContext context){
}
public void sendMessage(String toAddress, String messageAsStr)throws EventException{
try {
ServiceClient client = new ServiceClient(context, null);
client.getOptions().setTo(new EndpointReference(toAddress));
client.getOptions().setAction("Event");
ByteArrayInputStream in = new ByteArrayInputStream(messageAsStr.getBytes());
client.sendReceive(new StAXOMBuilder(in).getDocumentElement());
} catch (AxisFault e) {
throw new EventException("Error sending a message from java script",e);
} catch (XMLStreamException e) {
throw new EventException("Error sending a message from java script", e);
}
}
}
}