Search in sources :

Example 31 with ScriptContext

use of javax.script.ScriptContext in project ofbiz-framework by apache.

the class ScriptUtil method evaluate.

/**
 * Executes a script <code>String</code> and returns the result.
 *
 * @param language
 * @param script
 * @param scriptClass
 * @param context
 * @return The script result.
 * @throws Exception
 */
public static Object evaluate(String language, String script, Class<?> scriptClass, Map<String, Object> context) throws Exception {
    Assert.notNull("context", context);
    if (scriptClass != null) {
        return InvokerHelper.createScript(scriptClass, GroovyUtil.getBinding(context)).run();
    }
    try {
        CompiledScript compiledScript = compileScriptString(language, script);
        if (compiledScript != null) {
            return executeScript(compiledScript, null, createScriptContext(context), null);
        }
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(language);
        if (engine == null) {
            throw new IllegalArgumentException("The script type is not supported for language: " + language);
        }
        if (Debug.verboseOn()) {
            Debug.logVerbose("Begin processing script [" + script + "] using engine " + engine.getClass().getName(), module);
        }
        ScriptContext scriptContext = createScriptContext(context);
        return engine.eval(script, scriptContext);
    } catch (Exception e) {
        String errMsg = "Error running " + language + " script [" + script + "]: " + e.toString();
        Debug.logWarning(e, errMsg, module);
        throw new IllegalArgumentException(errMsg);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptEngineManager(javax.script.ScriptEngineManager) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) IOException(java.io.IOException)

Example 32 with ScriptContext

use of javax.script.ScriptContext in project ofbiz-framework by apache.

the class ScriptUtil method createScriptContext.

/**
 * Returns a <code>ScriptContext</code> that contains the members of <code>context</code>.
 * <p>If a <code>CompiledScript</code> instance is to be shared by multiple threads, then
 * each thread must create its own <code>ScriptContext</code> and pass it to the
 * <code>CompiledScript</code> eval method.</p>
 *
 * @param context
 * @param protectedKeys
 * @return
 */
public static ScriptContext createScriptContext(Map<String, Object> context, Set<String> protectedKeys) {
    Assert.notNull("context", context, "protectedKeys", protectedKeys);
    Map<String, Object> localContext = new HashMap<>(context);
    localContext.put(WIDGET_CONTEXT_KEY, context);
    localContext.put("context", context);
    ScriptContext scriptContext = new SimpleScriptContext();
    Bindings bindings = new ProtectedBindings(localContext, Collections.unmodifiableSet(protectedKeys));
    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    ScriptHelper helper = createScriptHelper(scriptContext);
    if (helper != null) {
        localContext.put(SCRIPT_HELPER_KEY, helper);
    }
    return scriptContext;
}
Also used : HashMap(java.util.HashMap) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings)

Example 33 with ScriptContext

use of javax.script.ScriptContext in project ofbiz-framework by apache.

the class GroovyEventHandler method invoke.

public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        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);
            ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
            if (scriptHelper != null) {
                context.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
            }
            Script script = InvokerHelper.createScript(GroovyUtil.getScriptClassFromLocation(event.path), GroovyUtil.getBinding(context));
            if (UtilValidate.isEmpty(event.invoke)) {
                result = script.run();
            } else {
                result = script.invokeMethod(event.invoke, EMPTY_ARGS);
            }
            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";
        }
        // check the result
        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("Groovy Event Error", e);
    } finally {
        try {
            TransactionUtil.commit(beganTransaction);
        } catch (GenericTransactionException e) {
            Debug.logError(e, module);
        }
    }
}
Also used : Script(groovy.lang.Script) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ScriptContext(javax.script.ScriptContext) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ScriptHelper(org.apache.ofbiz.base.util.ScriptHelper) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)

Example 34 with ScriptContext

use of javax.script.ScriptContext in project ofbiz-framework by apache.

the class GroovyEngine method serviceInvoker.

private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException {
    if (UtilValidate.isEmpty(modelService.location)) {
        throw new GenericServiceException("Cannot run Groovy service with empty location");
    }
    Map<String, Object> params = new HashMap<>();
    params.putAll(context);
    Map<String, Object> gContext = new HashMap<>();
    gContext.putAll(context);
    gContext.put(ScriptUtil.PARAMETERS_KEY, params);
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    gContext.put("dctx", dctx);
    gContext.put("security", dctx.getSecurity());
    gContext.put("dispatcher", dctx.getDispatcher());
    gContext.put("delegator", dispatcher.getDelegator());
    try {
        ScriptContext scriptContext = ScriptUtil.createScriptContext(gContext, protectedKeys);
        ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
        if (scriptHelper != null) {
            gContext.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
        }
        Script script = InvokerHelper.createScript(GroovyUtil.getScriptClassFromLocation(this.getLocation(modelService)), GroovyUtil.getBinding(gContext));
        Object resultObj = null;
        if (UtilValidate.isEmpty(modelService.invoke)) {
            resultObj = script.run();
        } else {
            resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS);
        }
        if (resultObj == null) {
            resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
        }
        if (resultObj != null && resultObj instanceof Map<?, ?>) {
            return cast(resultObj);
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.putAll(modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), ModelService.OUT_PARAM));
        return result;
    } catch (GeneralException ge) {
        throw new GenericServiceException(ge);
    } catch (Exception e) {
        // make spotting problems very difficult.  Disabling this for now in favor of returning a proper exception.
        throw new GenericServiceException("Error running Groovy method [" + modelService.invoke + "] in Groovy file [" + modelService.location + "]: ", e);
    }
}
Also used : DispatchContext(org.apache.ofbiz.service.DispatchContext) Script(groovy.lang.Script) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ScriptContext(javax.script.ScriptContext) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ScriptHelper(org.apache.ofbiz.base.util.ScriptHelper) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Example 35 with ScriptContext

use of javax.script.ScriptContext in project ofbiz-framework by apache.

the class ScriptEngine method runSync.

@Override
public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException {
    Assert.notNull("localName", localName, "modelService.location", modelService.location, "context", context);
    Map<String, Object> params = new HashMap<>();
    params.putAll(context);
    context.put(ScriptUtil.PARAMETERS_KEY, params);
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    context.put("dctx", dctx);
    context.put("dispatcher", dctx.getDispatcher());
    context.put("delegator", dispatcher.getDelegator());
    try {
        ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys);
        Object resultObj = ScriptUtil.executeScript(getLocation(modelService), modelService.invoke, scriptContext, null);
        if (resultObj == null) {
            resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
        }
        if (resultObj != null && resultObj instanceof Map<?, ?>) {
            return cast(resultObj);
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.putAll(modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), ModelService.OUT_PARAM));
        return result;
    } catch (ScriptException se) {
        return ServiceUtil.returnError(se.getMessage());
    } catch (Exception e) {
        Debug.logWarning(e, "Error invoking service " + modelService.name + ": ", module);
        throw new GenericServiceException(e);
    }
}
Also used : DispatchContext(org.apache.ofbiz.service.DispatchContext) ScriptException(javax.script.ScriptException) HashMap(java.util.HashMap) ScriptContext(javax.script.ScriptContext) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ScriptException(javax.script.ScriptException)

Aggregations

ScriptContext (javax.script.ScriptContext)124 SimpleScriptContext (javax.script.SimpleScriptContext)81 Bindings (javax.script.Bindings)33 Test (org.junit.Test)30 SimpleBindings (javax.script.SimpleBindings)28 Test (org.junit.jupiter.api.Test)19 ScriptException (javax.script.ScriptException)17 ScriptEngine (javax.script.ScriptEngine)16 HashMap (java.util.HashMap)13 CompiledScript (javax.script.CompiledScript)11 IOException (java.io.IOException)8 Map (java.util.Map)8 ScriptEngineManager (javax.script.ScriptEngineManager)8 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)7 Test (org.testng.annotations.Test)7 StringWriter (java.io.StringWriter)6 NashornScriptEngine (jdk.nashorn.api.scripting.NashornScriptEngine)6 XWikiException (com.xpn.xwiki.XWikiException)5 Reader (java.io.Reader)5 StringReader (java.io.StringReader)5