Search in sources :

Example 1 with ScriptReader

use of org.jaggeryjs.jaggery.core.ScriptReader in project jaggery by wso2.

the class WebAppSessionListener method sessionDestroyed.

@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    ServletContext ctx = httpSessionEvent.getSession().getServletContext();
    List<Object> jsListeners = (List<Object>) ctx.getAttribute(JaggeryCoreConstants.JS_DESTROYED_LISTENERS);
    if (jsListeners == null) {
        return;
    }
    JaggeryContext shared = WebAppManager.sharedJaggeryContext(ctx);
    Context cx = shared.getEngine().enterContext();
    JaggeryContext context = CommonManager.getJaggeryContext();
    if (CommonManager.getJaggeryContext() == null) {
        context = WebAppManager.clonedJaggeryContext(ctx);
        CommonManager.setJaggeryContext(context);
    }
    RhinoEngine engine = context.getEngine();
    ScriptableObject clonedScope = context.getScope();
    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(cx.newObject(clonedScope, "Session", new Object[] { httpSessionEvent.getSession() }));
    session.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(clonedScope, session);
    for (Object jsListener : jsListeners) {
        CommonManager.getCallstack(context).push((String) jsListener);
        try {
            ScriptReader sr = new ScriptReader(ctx.getResourceAsStream((String) jsListener)) {

                @Override
                protected void build() throws IOException {
                    try {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    } catch (ScriptException e) {
                        throw new IOException(e);
                    }
                }
            };
            engine.exec(sr, clonedScope, null);
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            CommonManager.getCallstack(context).pop();
        }
    }
    Context.exit();
}
Also used : JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) Context(org.mozilla.javascript.Context) ServletContext(javax.servlet.ServletContext) ScriptableObject(org.mozilla.javascript.ScriptableObject) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) IOException(java.io.IOException) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) JavaScriptProperty(org.jaggeryjs.scriptengine.engine.JavaScriptProperty) StringReader(java.io.StringReader) ServletContext(javax.servlet.ServletContext) List(java.util.List) ScriptableObject(org.mozilla.javascript.ScriptableObject) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader)

Example 2 with ScriptReader

use of org.jaggeryjs.jaggery.core.ScriptReader in project jaggery by wso2.

the class CommandLineExecutor method parseJaggeryScript.

/**
     * Parse Jaggery scripts resides in the file path
     *
     * @param fileURL url of the file
     */
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
static void parseJaggeryScript(final String fileURL) {
    FileInputStream fstream = null;
    try {
        //Initialize the Rhino context
        RhinoEngine.enterGlobalContext();
        fstream = new FileInputStream(fileURL);
        final RhinoEngine engine = CommandLineManager.getCommandLineEngine();
        final ScriptableObject scope = engine.getRuntimeScope();
        //initialize JaggeryContext
        final JaggeryContext jaggeryContext = new JaggeryContext();
        jaggeryContext.setTenantDomain(DEFAULT_TENANTDOMAIN);
        jaggeryContext.setEngine(engine);
        jaggeryContext.setScope(scope);
        jaggeryContext.addProperty(CommonManager.JAGGERY_OUTPUT_STREAM, System.out);
        RhinoEngine.putContextProperty("jaggeryContext", jaggeryContext);
        //Parsing the script
        final Reader source = new ScriptReader(new BufferedInputStream(fstream));
        out.println("\n");
        ShellUtilityService.initializeUtilityServices();
        engine.exec(source, scope, null);
        ShellUtilityService.destroyUtilityServices();
        out.flush();
        out.println("\n");
    } catch (Exception e) {
        out.println("\n");
        out.println("Error: " + e.getMessage());
        out.println("\n");
    } finally {
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException ignored) {
            }
        }
    }
}
Also used : ScriptableObject(org.mozilla.javascript.ScriptableObject) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 3 with ScriptReader

use of org.jaggeryjs.jaggery.core.ScriptReader in project jaggery by wso2.

the class JaggeryDeployerManager method executeScripts.

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext.getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();
            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantDomain(), parts[0], parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {

                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                        // throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}
Also used : ScriptCachingContext(org.jaggeryjs.scriptengine.cache.ScriptCachingContext) ScriptableObject(org.mozilla.javascript.ScriptableObject) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) IOException(java.io.IOException) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) StringReader(java.io.StringReader) ServletContext(javax.servlet.ServletContext) JSONObject(org.json.simple.JSONObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) LogHostObject(org.jaggeryjs.hostobjects.log.LogHostObject) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader)

Example 4 with ScriptReader

use of org.jaggeryjs.jaggery.core.ScriptReader in project jaggery by wso2.

the class WebAppManager method exec.

private static void exec(HttpServletRequest request, HttpServletResponse response) throws IOException {
    InputStream sourceIn;
    Context cx;
    JaggeryContext context;
    RhinoEngine engine = null;
    ServletContext servletContext = request.getServletContext();
    try {
        engine = CommonManager.getInstance().getEngine();
        cx = engine.enterContext();
        String scriptPath = getScriptPath(request);
        OutputStream out = response.getOutputStream();
        context = createJaggeryContext(cx, out, scriptPath, request, response);
        context.addProperty(FileHostObject.JAVASCRIPT_FILE_MANAGER, new WebAppFileManager(request.getServletContext()));
        if (ModuleManager.isModuleRefreshEnabled()) {
            //reload init scripts
            refreshServletContext(servletContext);
            InputStream jaggeryConf = servletContext.getResourceAsStream(JaggeryCoreConstants.JAGGERY_CONF_FILE);
            if (jaggeryConf != null) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(jaggeryConf, writer, null);
                String jsonString = writer.toString();
                JSONObject conf = (JSONObject) JSONValue.parse(jsonString);
                JSONArray initScripts = (JSONArray) conf.get(JaggeryCoreConstants.JaggeryConfigParams.INIT_SCRIPTS);
                if (initScripts != null) {
                    JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(servletContext);
                    ScriptableObject sharedScope = sharedContext.getScope();
                    Object[] scripts = initScripts.toArray();
                    for (Object script : scripts) {
                        if (!(script instanceof String)) {
                            log.error("Invalid value for initScripts in jaggery.conf : " + script);
                            continue;
                        }
                        String path = (String) script;
                        path = path.startsWith("/") ? path : "/" + path;
                        Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                        callstack.push(path);
                        engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {

                            @Override
                            protected void build() throws IOException {
                                try {
                                    sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                                } catch (ScriptException e) {
                                    throw new IOException(e);
                                }
                            }
                        }, sharedScope, null);
                        callstack.pop();
                    }
                }
            }
        }
        Object serveFunction = request.getServletContext().getAttribute(SERVE_FUNCTION_JAGGERY);
        if (serveFunction != null) {
            Function function = (Function) serveFunction;
            ScriptableObject scope = context.getScope();
            function.call(cx, scope, scope, new Object[] { scope.get("request", scope), scope.get("response", scope), scope.get("session", scope) });
        } else {
            //resource rendering model proceeding
            sourceIn = request.getServletContext().getResourceAsStream(scriptPath);
            if (sourceIn == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
                return;
            }
            CommonManager.getInstance().getEngine().exec(new ScriptReader(sourceIn), context.getScope(), getScriptCachingContext(request, scriptPath));
        }
    } catch (ScriptException e) {
        String msg = e.getMessage();
        log.error(msg, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } catch (Error e) {
        //Rhino doesn't catch Error instances and it is been used to stop the script execution
        //from any specific place. Hence, Error exception propagates up to Java and we silently
        //ignore it, assuming it was initiated by an exit() method call.
        log.debug("Script has called exit() method", e);
    } finally {
        // Exiting from the context
        if (engine != null) {
            RhinoEngine.exitContext();
        }
    }
}
Also used : ScriptCachingContext(org.jaggeryjs.scriptengine.cache.ScriptCachingContext) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) ServletContext(javax.servlet.ServletContext) WebAppFileManager(org.jaggeryjs.jaggery.core.plugins.WebAppFileManager) JSONArray(org.json.simple.JSONArray) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) JSONObject(org.json.simple.JSONObject) ServletContext(javax.servlet.ServletContext) JSONObject(org.json.simple.JSONObject) LogHostObject(org.jaggeryjs.hostobjects.log.LogHostObject) FileHostObject(org.jaggeryjs.hostobjects.file.FileHostObject) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader)

Example 5 with ScriptReader

use of org.jaggeryjs.jaggery.core.ScriptReader in project jaggery by wso2.

the class WebAppManager method executeScript.

private static ScriptableObject executeScript(JaggeryContext jaggeryContext, ScriptableObject scope, String fileURL, final boolean isJSON, boolean isBuilt, boolean isIncludeOnce) throws ScriptException {
    Stack<String> includesCallstack = CommonManager.getCallstack(jaggeryContext);
    Map<String, Boolean> includedScripts = CommonManager.getIncludes(jaggeryContext);
    ServletContext context = (ServletContext) jaggeryContext.getProperty(Constants.SERVLET_CONTEXT);
    String parent = includesCallstack.lastElement();
    String[] keys = WebAppManager.getKeys(context.getContextPath(), parent, fileURL);
    fileURL = getNormalizedScriptPath(keys);
    if (includesCallstack.search(fileURL) != -1) {
        return scope;
    }
    if (isIncludeOnce && includedScripts.get(fileURL) != null) {
        return scope;
    }
    ScriptReader source;
    RhinoEngine engine = jaggeryContext.getEngine();
    if (isBuilt) {
        source = new ScriptReader(context.getResourceAsStream(fileURL)) {

            @Override
            protected void build() throws IOException {
                try {
                    if (isJSON) {
                        sourceReader = new StringReader("(" + HostObjectUtil.streamToString(sourceIn) + ")");
                    } else {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    }
                } catch (ScriptException e) {
                    throw new IOException(e);
                }
            }
        };
    } else {
        source = new ScriptReader(context.getResourceAsStream(fileURL));
    }
    ScriptCachingContext sctx = new ScriptCachingContext(jaggeryContext.getTenantDomain(), keys[0], keys[1], keys[2]);
    sctx.setSecurityDomain(new JaggerySecurityDomain(fileURL, context));
    long lastModified = WebAppManager.getScriptLastModified(context, fileURL);
    sctx.setSourceModifiedTime(lastModified);
    includedScripts.put(fileURL, true);
    includesCallstack.push(fileURL);
    if (isJSON) {
        scope = (ScriptableObject) engine.eval(source, scope, sctx);
    } else {
        engine.exec(source, scope, sctx);
    }
    includesCallstack.pop();
    return scope;
}
Also used : ScriptCachingContext(org.jaggeryjs.scriptengine.cache.ScriptCachingContext) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ServletContext(javax.servlet.ServletContext) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader)

Aggregations

ScriptReader (org.jaggeryjs.jaggery.core.ScriptReader)10 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)9 ScriptableObject (org.mozilla.javascript.ScriptableObject)8 RhinoEngine (org.jaggeryjs.scriptengine.engine.RhinoEngine)6 ServletContext (javax.servlet.ServletContext)5 JaggeryContext (org.jaggeryjs.scriptengine.engine.JaggeryContext)5 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)3 IOException (java.io.IOException)3 StringReader (java.io.StringReader)3 ScriptCachingContext (org.jaggeryjs.scriptengine.cache.ScriptCachingContext)3 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 List (java.util.List)2 LogHostObject (org.jaggeryjs.hostobjects.log.LogHostObject)2 JavaScriptProperty (org.jaggeryjs.scriptengine.engine.JavaScriptProperty)2 JSONObject (org.json.simple.JSONObject)2 Context (org.mozilla.javascript.Context)2 FileHostObject (org.jaggeryjs.hostobjects.file.FileHostObject)1 WebAppFileManager (org.jaggeryjs.jaggery.core.plugins.WebAppFileManager)1 JSONArray (org.json.simple.JSONArray)1