Example usage for javax.script ScriptEngine getContext

List of usage examples for javax.script ScriptEngine getContext

Introduction

In this page you can find the example usage for javax.script ScriptEngine getContext.

Prototype

public ScriptContext getContext();

Source Link

Document

Returns the default ScriptContext of the ScriptEngine whose Bindings, Reader and Writers are used for script executions when no ScriptContext is specified.

Usage

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performShellExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ShellSession session = getSession(request.getParameter("sid"));
    if (session == null) {
        response.setStatus(410);// Http status GONE
        return;/*w w w. j a  v a 2  s . c o  m*/
    }
    ScriptEngine engine = session.getEngine();

    String action = request.getParameter("action");
    if (action == null) {
        StringWriter responseWriter = new StringWriter();
        engine.getContext().setWriter(responseWriter);
        engine.getContext().setErrorWriter(response.getWriter());
        String script = toString(request.getInputStream(), charset);
        JSONObject json = new JSONObject();
        try {
            try {
                Object result = engine.eval(script);
                json.put("result", String.valueOf(result));
                response.setStatus(200);
                json.put("response", responseWriter.getBuffer().toString());
            } catch (ScriptException e) {
                log.log(Level.SEVERE, "Error while running shell command:" + script, e);
                response.setStatus(500);
                e.getCause().printStackTrace(response.getWriter());
                return;
            }
        } catch (JSONException e) {
            log.log(Level.SEVERE, "Error while running shell command:" + script, e);
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
            return;
        }
        response.getWriter().write(json.toString());
    } else {
        Invocable invocable = (Invocable) engine;
        try {
            invocable.invokeFunction("shellAction", action);
        } catch (ScriptException e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        } catch (NoSuchMethodException e) {
            response.setStatus(500);
            response.getWriter().println("Action not supported");
        } catch (Exception e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        }
    }

}

From source file:org.jahia.utils.ScriptEngineUtils.java

private void initEngine(ScriptEngine engine) {
    if (engine.getFactory().getNames().contains("velocity")) {
        final Properties velocityProperties = new Properties();
        final String key = "runtime.log.logsystem.log4j.logger";
        final String log4jLoggerProp = System.getProperty(key);
        if (log4jLoggerProp != null) {
            velocityProperties.setProperty(key, log4jLoggerProp);
        } else {//from  ww  w . ja va  2s.  co m
            velocityProperties.setProperty(key, "root");
        }
        engine.getContext().setAttribute("com.sun.script.velocity.properties", velocityProperties,
                ScriptContext.GLOBAL_SCOPE);
    }
}

From source file:org.unitime.timetable.server.script.ScriptExecution.java

@Override
protected void execute() throws Exception {
    org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession();

    Transaction tx = hibSession.beginTransaction();
    try {/*from  w  w  w .  ja  va2  s .c  o m*/
        setStatus("Starting up...", 3);

        Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession);

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(script.getEngine());
        engine.put("hibSession", hibSession);
        engine.put("session", SessionDAO.getInstance().get(getSessionId()));
        engine.put("log", this);

        incProgress();

        engine.getContext().setWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    info(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });
        engine.getContext().setErrorWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    warn(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });

        incProgress();

        debug("Engine: " + engine.getFactory().getEngineName() + " (ver. "
                + engine.getFactory().getEngineVersion() + ")");
        debug("Language: " + engine.getFactory().getLanguageName() + " (ver. "
                + engine.getFactory().getLanguageVersion() + ")");

        for (ScriptParameter parameter : script.getParameters()) {
            String value = iRequest.getParameters().get(parameter.getName());

            if ("file".equals(parameter.getType()) && iFile != null) {
                debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)");
                engine.put(parameter.getName(), iFile);
                continue;
            }

            if (value == null)
                value = parameter.getDefaultValue();
            if (value == null) {
                engine.put(parameter.getName(), null);
                continue;
            }
            debug(parameter.getName() + ": " + value);

            if (parameter.getType().equalsIgnoreCase("boolean")) {
                engine.put(parameter.getName(), "true".equalsIgnoreCase(value));
            } else if (parameter.getType().equalsIgnoreCase("long")) {
                engine.put(parameter.getName(), Long.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("int")
                    || parameter.getType().equalsIgnoreCase("integer")) {
                engine.put(parameter.getName(), Integer.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("double")) {
                engine.put(parameter.getName(), Double.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("float")) {
                engine.put(parameter.getName(), Float.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("short")) {
                engine.put(parameter.getName(), Short.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("byte")) {
                engine.put(parameter.getName(), Byte.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("department")) {
                engine.put(parameter.getName(),
                        DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("departments")) {
                List<Department> departments = new ArrayList<Department>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), departments);
            } else if (parameter.getType().equalsIgnoreCase("subject")) {
                engine.put(parameter.getName(),
                        SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("subjects")) {
                List<SubjectArea> subjects = new ArrayList<SubjectArea>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), subjects);
            } else if (parameter.getType().equalsIgnoreCase("building")) {
                engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("buildings")) {
                List<Building> buildings = new ArrayList<Building>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), buildings);
            } else if (parameter.getType().equalsIgnoreCase("room")) {
                engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("rooms")) {
                List<Room> rooms = new ArrayList<Room>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), rooms);
            } else if (parameter.getType().equalsIgnoreCase("location")) {
                engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("locations")) {
                List<Location> locations = new ArrayList<Location>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), locations);
            } else {
                engine.put(parameter.getName(), value);
            }
        }

        incProgress();

        if (engine instanceof Compilable) {
            setStatus("Compiling script...", 1);
            CompiledScript compiled = ((Compilable) engine).compile(script.getScript());
            incProgress();
            setStatus("Running script...", 100);
            compiled.eval();
        } else {
            setStatus("Running script...", 100);
            engine.eval(script.getScript());
        }

        hibSession.flush();
        tx.commit();

        setStatus("All done.", 1);
        incProgress();
    } catch (Exception e) {
        tx.rollback();
        error("Execution failed: " + e.getMessage(), e);
    } finally {
        hibSession.close();
    }
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

@SuppressWarnings({ "SameParameterValue" })
private void updateBindings(ScriptEngine engine, int scope, Map<String, ?> mergeValues) {
    Bindings bindings = engine.getContext().getBindings(scope);
    if (bindings == null) {
        bindings = engine.createBindings();
        engine.getContext().setBindings(bindings, scope);
    }//from  w w w .j  ava  2 s  . c o m
    bindings.putAll(mergeValues);
}

From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java

@Test
public void testNashornWithCompile() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);// w  w  w  . j av a 2  s.  c  o m

    Compilable compiler = (Compilable) engine;
    assertNotNull(compiler);

    InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js");
    assertNotNull(stream);
    String js = IOUtils.toString(stream);

    CompiledScript compiled = compiler.compile(new StringReader(js));

    engine.put("mapper", new Mapper());

    compiled.eval(engine.getContext());
    assertEquals("1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]"
            + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string"
            + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2"
            + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}"
            + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString());
}

From source file:org.ngrinder.operation.cotroller.ScriptConsoleController.java

/**
 * Run the given script. The run result is stored in "result" of the given model.
 *
 * @param script script/*from  w w  w . j a  v  a2s  .  c  om*/
 * @param model  model
 * @return operation/script_console
 */
@RequestMapping("")
public String run(@RequestParam(value = "script", defaultValue = "") String script, Model model) {
    if (StringUtils.isNotBlank(script)) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
        engine.put("applicationContext", this.applicationContext);
        engine.put("agentManager", this.agentManager);
        engine.put("agentManagerService", this.agentManagerService);
        engine.put("regionService", this.regionService);
        engine.put("consoleManager", this.consoleManager);
        engine.put("userService", this.userService);
        engine.put("perfTestService", this.perfTestService);
        engine.put("tagService", this.tagService);
        engine.put("fileEntryService", this.fileEntryService);
        engine.put("config", getConfig());
        engine.put("pluginManager", this.pluginManager);
        engine.put("cacheManager", this.cacheManager);
        engine.put("user", getCurrentUser());
        final StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        engine.getContext().setWriter(writer);
        engine.getContext().setErrorWriter(writer);
        try {
            Object result = engine.eval(script);
            result = out.toString() + "\n" + ObjectUtils.defaultIfNull(result, "");
            model.addAttribute("result", result);
        } catch (ScriptException e) {
            model.addAttribute("result", out.toString() + "\n" + e.getMessage());
        }
    }
    model.addAttribute("script", script);
    return "operation/script_console";
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ScriptEngine createScriptEngine(String scriptLanguage, Script script) {
    ScriptEngine engine = engineByLanguage(scriptLanguage);
    if (engine == null) {
        throw new IllegalStateException(
                String.format("Language '%s' script engine could not be found", scriptLanguage));
    }// w w w  . j a v  a2 s .co m
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {
            put("log", LOG);
            put("selfScriptRunner", ScriptRunner.this);
        }
    });

    engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName(script.getFilename()),
            ScriptContext.ENGINE_SCOPE);
    engine.getContext().setAttribute(ScriptEngine.ARGV, getArgvs(script.getArgv()), ScriptContext.ENGINE_SCOPE);

    return engine;
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ConsoleOutputBean eval(ScriptEngine engine, String evalScript, Map<String, ?> bindings,
        final ConsoleOutputBean consoleOutputBean) throws ScriptException {
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {//  w w  w .  jav  a2  s . com
            put("out", new PrintWriter(consoleOutputBean.getOut(), true));
            put("err", new PrintWriter(consoleOutputBean.getErr(), true));
        }
    });

    if (bindings != null && !bindings.isEmpty()) {
        updateBindings(engine, ScriptContext.ENGINE_SCOPE, bindings);
    }

    engine.getContext().setWriter(consoleOutputBean.getOut());
    engine.getContext().setErrorWriter(consoleOutputBean.getErr());
    engine.getContext().setReader(new NullReader(0));

    consoleOutputBean.setEvalResult(engine.eval(evalScript, engine.getContext()));

    return consoleOutputBean;
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;//from ww w  .j a v  a 2 s. co  m
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // The following binding is necessary for Javascript, which doesn't offer a console by default.
                bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                        ScriptContext.GLOBAL_SCOPE);
                scriptEngine.eval(scriptContent, scriptContext);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}