static void nashornCompiledScript(String code) throws ScriptException, NoSuchMethodException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("nashorn"); CompiledScript compiled = ((Compilable) engine).compile(code); Object result = null; ScriptContext context = new SimpleScriptContext(); Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE); long total = 0; for (int i = 0; i < RUNS; ++i) { long start = System.nanoTime(); for (int j = 0; j < BATCH; ++j) { engineScope.put("value", "12345678"); result = compiled.eval(context); } long stop = System.nanoTime(); System.out.println( "Run " + (i * BATCH + 1) + "-" + ((i + 1) * BATCH) + ": " + Math.round((stop - start) / BATCH / 1000) + " us"); total += (stop - start); } System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us"); System.out.println( "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString()); }
public void testAllOpsDisabled() throws Exception { ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings settings = Settings.builder() .put("script.engine." + MockScriptEngine.NAME + ".file.aggs", false) .put("script.engine." + MockScriptEngine.NAME + ".file.search", false) .put("script.engine." + MockScriptEngine.NAME + ".file.mapping", false) .put("script.engine." + MockScriptEngine.NAME + ".file.update", false) .put("script.engine." + MockScriptEngine.NAME + ".file.ingest", false) .build(); ScriptService scriptService = makeScriptService(settings); Script script = new Script("script1", ScriptService.ScriptType.FILE, MockScriptEngine.NAME, null); for (ScriptContext context : ScriptContext.Standard.values()) { try { scriptService.compile(script, context, contextAndHeaders, Collections.emptyMap()); fail(context.getKey() + " script should have been rejected"); } catch (Exception e) { assertTrue( e.getMessage(), e.getMessage() .contains( "scripts of type [file], operation [" + context.getKey() + "] and lang [" + MockScriptEngine.NAME + "] are disabled")); } } }
@Override public final void run() { final Locus locus = context.getLocus(); final Bundle bundle = context.getBundle(); final Alerts alerts = context.getAlerts(); final File file = context.getFile(); final String href = context.getHref(); try { logger.entering(getClass().getName(), Runnable.class.getName()); script.start(); runInner(); } catch (IOException e) { alerts.add(new Alert(Alert.Severity.ERR, e.getMessage(), e.getClass().getSimpleName())); } finally { script.finish(); } try { new ScriptWriter(script, locus).writeTo(file); new AlertWriter(bundle, alerts).write("command.finished", "results.view", href); } catch (IOException e) { alerts.add(new Alert(Alert.Severity.ERR, e.getMessage())); } finally { logger.exiting(getClass().getName(), Runnable.class.getName()); } }
/* Utility functions for the binding classes */ protected static ScriptEngine createScriptEngine(String language) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(language); ScriptContext scriptContext = engine.getContext(); Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(new JSFBindings(bindings), ScriptContext.ENGINE_SCOPE); return engine; }
private static GremlinScriptContext convertContext(final ScriptContext context) { if (context instanceof GremlinScriptContext) return (GremlinScriptContext) context; else { GremlinScriptContext context2 = new GremlinScriptContext(); for (int scope : context.getScopes()) { context2.setBindings(context.getBindings(scope), scope); } return context2; } }
private void runCommand(final CommandToDo commandToDo) throws IOException { final SSHConnection sshConnection = context.getSSHConnection(); final String requestPTY = context.getRequestPTY(); final Session session = sshConnection.getConnection().openSession(); try { if (requestPTY != null) { session.requestPTY(requestPTY, Const.TERMINAL_WIDTH, Const.TERMINAL_HEIGHT, 0, 0, null); } runCommand(commandToDo, session); } finally { session.close(); } }
private static void typeCastContextBindings(final ScriptContext context) { for (int scope : context.getScopes()) { Bindings bindings = context.getBindings(scope); if (!(bindings instanceof VariableLibrary) && null != bindings) { for (String key : bindings.keySet()) { Object object = bindings.get(key); if (object instanceof Atom) { bindings.put(key, ((Atom) object).getValue()); } } } } }
private String evaluateExpression( Execution execution, String scriptToExecute, JCRSessionWrapper session) throws RepositoryException, ScriptException { ScriptContext scriptContext = scriptEngine.getContext(); if (bindings == null) { bindings = getBindings(execution, session); } scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(scriptToExecute, bindings); String error = scriptContext.getErrorWriter().toString(); if (error.length() > 0) { logger.error("Scripting error : " + error); } return scriptContext.getWriter().toString().trim(); }
public Object eval(final Reader reader, final ScriptContext context) { String line; Iterable result; StringBuilder script = new StringBuilder(); BufferedReader bReader = new BufferedReader(reader); try { // read whole script before evaluation while ((line = bReader.readLine()) != null) { script.append(line).append("\n"); } // evaluate script result = this.evaluate(script.toString(), convertContext(context)); // flushing output streams context.getWriter().flush(); typeCastContextBindings(context); } catch (SyntaxErrorException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return result; }
/** * Executes the program stored in the <code>CompiledScript</code> object using the supplied <code> * Bindings</code> of attributes as the <code>ENGINE_SCOPE</code> of the associated <code> * ScriptEngine</code> during script execution. If bindings is null, then the effect of calling * this method is same as that of eval(getEngine().getContext()). * * <p>. The <code>GLOBAL_SCOPE</code> <code>Bindings</code>, <code>Reader</code> and <code>Writer * </code> associated with the default <code>ScriptContext</code> of the associated <code> * ScriptEngine</code> are used. * * @param bindings The bindings of attributes used for the <code>ENGINE_SCOPE</code>. * @return The return value from the script execution * @throws ScriptException if an error occurs. */ public Object eval(Bindings bindings) throws ScriptException { ScriptContext ctxt = getEngine().getContext(); if (bindings != null) { SimpleScriptContext tempctxt = new SimpleScriptContext(); tempctxt.setBindings(bindings, ScriptContext.ENGINE_SCOPE); tempctxt.setBindings( ctxt.getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); tempctxt.setWriter(ctxt.getWriter()); tempctxt.setReader(ctxt.getReader()); tempctxt.setErrorWriter(ctxt.getErrorWriter()); ctxt = tempctxt; } return eval(ctxt); }
/** * Creates script context, sets the root context. Adds child context if needed * * @param root file that will be threated as root for compiler * @param parent parent of new ScriptContext * @return ScriptContext with presetted root file * @throws InstantiationException if java compiler is not aviable */ public static ScriptContext getScriptContext(File root, ScriptContext parent) throws InstantiationException { ScriptContextImpl ctx; if (parent == null) { ctx = new ScriptContextImpl(root); } else { ctx = new ScriptContextImpl(root, parent); parent.addChildScriptContext(ctx); } return ctx; }
public Object evaluateReader( LocalhostConnector connector, Path locator, FileReader reader, String filename, int lineno, Object security) throws Exception { ScriptContext.get().setCurrentScriptPath(Paths.get(filename)); final PyCode code = interpreter.compile(reader, filename); return interpreter.eval(code); }
@SuppressWarnings({"PMD.GuardLogStatementJavaUtil", "PMD.GuardLogStatement"}) private Integer monitorCommand(final CommandWork commandWork, final Session session) throws IOException { final ExecutorService executorStream = context.getExecutorStream(); final long pollInterval = context.getPollInterval(); final ByteBuffer bufferStdin = commandWork.getByteBufferStdin(); final ByteBuffer bufferStdout = commandWork.getByteBufferStdout(); final ByteBuffer bufferStderr = commandWork.getByteBufferStderr(); final OutputStream stdin = session.getStdin(); final InputStream stdout = session.getStdout(); final InputStream stderr = session.getStderr(); // allow for supplemental process input final OutputStreamRunnable runnableStdin = new OutputStreamRunnable(stdin, bufferStdin, pollInterval); executorStream.execute(runnableStdin); // monitor process final InputStreamRunnable runnableStdout = new InputStreamRunnable(stdout, bufferStdout, pollInterval); final InputStreamRunnable runnableStderr = new InputStreamRunnable(stderr, bufferStderr, pollInterval); final InputStreamRunnable[] streams = {runnableStdout, runnableStderr}; for (final InputStreamRunnable stream : streams) { executorStream.execute(stream); } // monitor process final int conditionExit = session.waitForCondition(ChannelCondition.EXIT_STATUS, 0L); logger.finest("conditionExitStatus/" + conditionExit); // i18n log final int conditionData = waitForData(session, runnableStdout.getPollInterval()); logger.finest("conditionData/" + conditionData); // i18n log final Integer exitValue = session.getExitStatus(); // allow process complete runnableStdin.stop(); for (final InputStreamRunnable stream : streams) { stream.waitForComplete(); } // notify caller thread MutexU.notifyAll(this); return exitValue; }
private void runCommand(final CommandToDo commandToDo, final Session session) throws IOException { final CommandWork commandWork = script.startCommand(commandToDo, UTF8Codec.Const.UTF8, null); Integer exitValue = null; try { session.execCommand(commandWork.getStdin()); exitValue = monitorCommand(commandWork, session); } catch (IOException e) { commandWork.getByteBufferStderr().addString(e.getMessage()); } finally { script.finishCommand(commandWork, exitValue); context.getSSHConnection().update(commandWork.getStart()); } }
PageInfo getPageInfo(ScriptContext context, String path) throws IOException { PageInfo info = null; if (pageInfoCache != null) info = this.pageInfoCache.get(path); if (info == null) { String file = prefix + path + suffix; String actualPath = FileHelper.findRecursive(file); String source = FileHelper.read(actualPath); Object object = context.evaluate(source, path); info = new PageInfo((BaseFunction) object, actualPath); if (pageInfoCache != null) pageInfoCache.put(path, info); } return info; }
void serve( HttpServletRequest request, HttpServletResponse response, ScriptContext context, String path, Exception error) throws IOException { PageInfo info = getPageInfo(context, path); context.put("request", request); context.put("response", response); context.put("path", path); context.put("servlet", this); context.put("__filename", info.path); context.put("__pagepath", getPagePath(info.path)); if (error != null) context.put("error", error); context.call(info.function); }
@Expose public ScriptingLogger(String name) { // When generating documentation, the script context is not defined super(ScriptContext.get() == null ? null : ScriptContext.get().getLogger(name)); }
public Object eval(ScriptContext context) throws ScriptException { return eval(((LuajContext) context).globals, context.getBindings(ScriptContext.ENGINE_SCOPE)); }
@Override public void close() throws Exception { interpreter.close(); scriptContext.close(); staticContext.close(); }
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (Config.SCRIPT_DEBUG) { _log.info("Loading Script: " + file.getAbsolutePath()); } if (Config.SCRIPT_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && Config.SCRIPT_ALLOW_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute( "mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (Config.SCRIPT_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute( "mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); } } }