use of javax.script.ScriptContext in project ofbiz-framework by apache.
the class GroovyUtil method getBinding.
/**
* Returns a <code>Binding</code> instance initialized with the
* variables contained in <code>context</code>. If <code>context</code>
* is <code>null</code>, an empty <code>Binding</code> is returned.
* <p>The expression is parsed to initiate non existing variable
* in <code>Binding</code> to null for GroovyShell evaluation.
* <p>The <code>context Map</code> is added to the <code>Binding</code>
* as a variable called "context" so that variables can be passed
* back to the caller. Any variables that are created in the script
* are lost when the script ends unless they are copied to the
* "context" <code>Map</code>.</p>
*
* @param context A <code>Map</code> containing initial variables
* @return A <code>Binding</code> instance
*/
public static Binding getBinding(Map<String, Object> context, String expression) {
Map<String, Object> vars = new HashMap<>();
if (context != null) {
vars.putAll(context);
if (UtilValidate.isNotEmpty(expression)) {
// analyse expression to find variables by split non alpha, ignoring "_" to allow my_variable usage
String[] variables = expression.split("[\\P{Alpha}&&[^_]]+");
for (String variable : variables) {
if (!vars.containsKey(variable)) {
vars.put(variable, null);
}
}
}
vars.put("context", context);
if (vars.get(ScriptUtil.SCRIPT_HELPER_KEY) == null) {
ScriptContext scriptContext = ScriptUtil.createScriptContext(context);
ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
if (scriptHelper != null) {
vars.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
}
}
}
return new Binding(vars);
}
use of javax.script.ScriptContext in project ofbiz-framework by apache.
the class ScriptEventHandler method invoke.
@Override
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
try {
Map<String, Object> context = new HashMap<String, Object>();
context.put("request", request);
context.put("response", response);
HttpSession session = request.getSession();
context.put("session", session);
context.put("dispatcher", request.getAttribute("dispatcher"));
context.put("delegator", request.getAttribute("delegator"));
context.put("security", request.getAttribute("security"));
context.put("locale", UtilHttp.getLocale(request));
context.put("timeZone", UtilHttp.getTimeZone(request));
context.put("userLogin", session.getAttribute("userLogin"));
context.put(ScriptUtil.PARAMETERS_KEY, UtilHttp.getCombinedMap(request, UtilMisc.toSet("delegator", "dispatcher", "security", "locale", "timeZone", "userLogin")));
Object result = null;
try {
ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys);
result = ScriptUtil.executeScript(event.path, event.invoke, scriptContext, null);
if (result == null) {
result = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
}
} catch (Exception e) {
Debug.logWarning(e, "Error running event " + event.path + ": ", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
if (result instanceof Map) {
Map resultMap = (Map) result;
String successMessage = (String) resultMap.get("_event_message_");
if (successMessage != null) {
request.setAttribute("_EVENT_MESSAGE_", successMessage);
}
String errorMessage = (String) resultMap.get("_error_message_");
if (errorMessage != null) {
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
}
return (String) resultMap.get("_response_code_");
}
if (result != null && !(result instanceof String)) {
throw new EventHandlerException("Event did not return a String result, it returned a " + result.getClass().getName());
}
return (String) result;
} catch (Exception e) {
throw new EventHandlerException("Error running event " + event.path, e);
}
}
use of javax.script.ScriptContext in project tomee by apache.
the class ScriptLoginModule method login.
@Override
public boolean login() throws LoginException {
File script = getScriptFile((String) this.options.get("scriptURI"));
if (script == null) {
script = getScriptFile(JavaSecurityManagers.getSystemProperty("openejb.ScriptLoginModule.scriptURI"));
if (script == null) {
script = getScriptFile(null);
}
}
if (script == null) {
throw new LoginException("No login script defined");
}
final String scriptText;
try {
scriptText = new Scanner(script).useDelimiter("\\Z").next();
} catch (final FileNotFoundException e) {
throw new LoginException("Invalid login script URI.");
}
this.userData = getUserData();
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName((String) this.options.get("engineName"));
// new context for the execution of this script
final ScriptContext newContext = new SimpleScriptContext();
// creating the bidings object for the current execution
final Bindings bindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("user", this.userData.user);
bindings.put("password", this.userData.pass);
final List<String> myGroups;
try {
myGroups = (List) engine.eval(scriptText, newContext);
} catch (final ScriptException e) {
throw new LoginException("Cannot execute login script. Msg: " + e.getMessage());
}
this.userData.groups.addAll(myGroups);
return true;
}
use of javax.script.ScriptContext in project vcell by virtualcell.
the class ScriptingPanel method run.
private void run() {
// create scripting engine
ScriptEngineManager manager = new ScriptEngineManager();
// ScriptEngine engine = manager.getEngineByName("JavaScript");
ScriptEngine engine = manager.getEngineByName("jython");
// create environment for the script to run in.
// 1) capture stdout and send to the resultsTextField
// 2) predefine variables for windowManager, bioModel, model, and current selections
//
ScriptContext scriptContext = new SimpleScriptContext();
scriptContext.setBindings(new SimpleBindings(), ScriptContext.GLOBAL_SCOPE);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
scriptContext.setWriter(printWriter);
Bindings globals = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
// }
if (getBioModel() != null) {
globals.put("biomodel", getBioModel());
globals.put("model", getBioModel().getModel());
}
engine.setContext(scriptContext);
//
try {
String fullScript = getPredefinedJythonFunctions();
fullScript += scriptTextArea.getText();
System.out.println(fullScript);
engine.eval(fullScript);
try {
Bindings engineBindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
printWriter.println("\n\n\nengine variable bindings: ");
for (Map.Entry<String, Object> entry : engineBindings.entrySet()) {
if (entry.getKey().equals("__builtins__")) {
continue;
}
printWriter.println(" " + entry.getKey() + " : " + entry.getValue());
}
Bindings globalBindings = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
printWriter.println("\nglobal variable bindings: ");
for (Map.Entry<String, Object> entry : globalBindings.entrySet()) {
printWriter.println(" " + entry.getKey() + " : " + entry.getValue());
}
printWriter.flush();
resultsTextArea.append(stringWriter.getBuffer().toString());
// scroll to bottom.
resultsTextArea.scrollRectToVisible(new Rectangle(0, resultsTextArea.getHeight() - 2, 1, 1));
} catch (RuntimeException e1) {
e1.printStackTrace();
}
} catch (ScriptException e1) {
e1.printStackTrace();
}
}
use of javax.script.ScriptContext in project es6draft by anba.
the class CompilableTest method compileStringWithContextAndBindings.
@Test
public void compileStringWithContextAndBindings() throws ScriptException {
CompiledScript script = compilable.compile("numberVal * 2");
ScriptContext context = new SimpleScriptContext();
Bindings bindings = engine.createBindings();
bindings.put("numberVal", 8);
context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
assertThat(script.eval(context), instanceOfWith(Number.class, is(numberCloseTo(16))));
}
Aggregations