Refine search
private SelectorFunction compileSelectorFunction() { final ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); try { ((Compilable) engine).compile("var apply = " + function).eval(); return ((Invocable) engine).getInterface(SelectorFunction.class); } catch (ScriptException e) { throw new RuntimeException(e); } }
@Override public void writeGraph(OutputStream os) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); super.writeGraph(baos); try { StringBuilder builder = new StringBuilder(); builder.append(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("vizjs/viz.js"))); builder.append("var result = new Viz(dotGraph);"); String script = builder.toString(); ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); Compilable compilingEngine = (Compilable) engine; CompiledScript cscript = compilingEngine.compile(script); //Bindings bindings = cscript.getEngine().createBindings(); Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); for(Map.Entry me : bindings.entrySet()) { System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue())); } bindings.put("dotGraph", baos.toString()); //cscript.eval(); Object result = cscript.eval(bindings); LOG.info("Result:" +ReflectionToStringBuilder.toString(result)); } catch (Exception e) { throw new IOException("Exception generating graph.", e); } } }
import java.util.*; import javax.script.*; public class TestBindings { public static void main(String args[]) throws Exception { String script = "function doSomething() {var d = date}"; ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); Compilable compilingEngine = (Compilable) engine; CompiledScript cscript = compilingEngine.compile(script); //Bindings bindings = cscript.getEngine().createBindings(); Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); for(Map.Entry me : bindings.entrySet()) { System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue())); } bindings.put("date", new Date()); //cscript.eval(); cscript.eval(bindings); Invocable invocable = (Invocable) cscript.getEngine(); invocable.invokeFunction("doSomething"); } }
ScriptEngineManager mgr = new ScriptEngineManager(); engineName = cl.getOptionValue(engine.getOpt()); ScriptEngine engine = mgr.getEngineByName(engineName); if (engine == null) { shellState.printException(new Exception(engineName + " not found")); Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); putConnector(b, shellState.getAccumuloClient()); b.put("client", shellState.getAccumuloClient()); engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
@Override public void onEvent(String name, String xmlns, Element event) { try { Bindings bindings = engine.createBindings(); bindings.put("event", event); bindings.put("eventName", name); bindings.put("eventXMLNS", xmlns); bindings.put("context", context); if (this.compiledScript != null) { this.compiledScript.eval(bindings); } else { this.engine.eval(scriptContent, bindings); } } catch (Exception e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") @Override public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception { Bindings bindings = new SimpleBindings(); bindings.put(TARGET, target); bindings.put(ARGS, arguments); if (hasRetVal) { bindings.put(RET_VAL, retVal); } CompiledScript script = expCache.get(exp); if (null != script) { return (T) script.eval(bindings); } if (engine instanceof Compilable) { Compilable compEngine = (Compilable) engine; script = compEngine.compile(funcs + exp); expCache.put(exp, script); return (T) script.eval(bindings); } else { return (T) engine.eval(funcs + exp, bindings); } }
/** * Evaluate the script using the given bindings. * * @param script the script to evaluate * @param bindings the context-aware bindings * @return the result object * @throws ScriptException if an error occurs in script. */ public Object evaluate(Script script, Bindings bindings) throws ScriptException { // Always look for a compiled script in our cache. CompiledScript compiledScript = compiledScripts.get(script); // No compiled script found? if (compiledScript == null) { String source = script.getSource(); ScriptEngine scriptEngine = scriptEngines.computeIfAbsent(script.getEngine(), this::createScriptEngine); if (!(scriptEngine instanceof Compilable) || forceScriptEvaluation) { return scriptEngine.eval(source, bindings); } // Compile and store it in our cache. Fall-through for execution compiledScript = ((Compilable) scriptEngine).compile(source); compiledScripts.putIfAbsent(script, compiledScript); } // Let the cached compiled script do its work. return compiledScript.eval(bindings); }
JavaScriptLoader(String name, String script) throws RedPenException { this.name = name; setValidatorName(name); ScriptEngine engine = manager.getEngineByName("nashorn"); try { engine.put("redpenToBeBound", this); for (String methodToBeExposed : methodsToBeExposedToJS) { engine.eval(String.format( "var %s = Function.prototype.bind.call(redpenToBeBound.%s, redpenToBeBound);", methodToBeExposed, methodToBeExposed)); } try { engine.eval("var _JavaScriptValidatorTest = Java.type('cc.redpen.validator.JavaScriptValidatorTest');"); } catch (RuntimeException e) { if (!(e.getCause() instanceof ClassNotFoundException)) { throw e; } } engine.eval("java = undefined; javax = undefined; Java = undefined; load = undefined; redpenToBeBound = undefined;"); CompiledScript compiledScript = ((Compilable) engine).compile(script); compiledScript.eval(); this.message = (String) engine.get("message"); this.invocable = (Invocable) engine; } catch (ScriptException e) { throw new RedPenException(e); } }
protected Object evaluateScriptExpression(String expressionLanguage, VariableContext variableContext, String expressionText, CachedCompiledScriptSupport cachedCompiledScriptSupport) { ScriptEngine scriptEngine = getScriptEngineForName(expressionLanguage); // wrap script engine bindings + variable context and pass enhanced // bindings to the script engine. Bindings bindings = VariableContextScriptBindings.wrap(scriptEngine.createBindings(), variableContext); bindings.put("variableContext", variableContext); try { if (scriptEngine instanceof Compilable) { CompiledScript compiledScript = cachedCompiledScriptSupport.getCachedCompiledScript(); if (compiledScript == null) { synchronized (cachedCompiledScriptSupport) { compiledScript = cachedCompiledScriptSupport.getCachedCompiledScript(); if(compiledScript == null) { Compilable compilableScriptEngine = (Compilable) scriptEngine; compiledScript = compilableScriptEngine.compile(expressionText); cachedCompiledScriptSupport.cacheCompiledScript(compiledScript); } } } return compiledScript.eval(bindings); } else { return scriptEngine.eval(expressionText, bindings); } } catch (ScriptException e) { throw LOG.unableToEvaluateExpression(expressionText, scriptEngine.getFactory().getLanguageName(), e); } }
// move this into initialization part so that you do not call this every time. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("groovy"); CompiledScript script = ((Compilable) engine).compile(urlGeneratorScript); //the code below will use the precompiled script code Bindings bindings = new Bindings(); bindings.put("state", state; bindings.put("zipcode", zip); bindings.put("url", locationAwareAd.getLocationData().getGeneratedUrl()); url = script.eval(bindings);
private static final String FUNCTIONS = "function() {" + " return \"Hello\";" + "}"; public static void main(String... args) throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByMimeType("text/javascript"); // Compile common functions once CompiledScript compiled = ((Compilable) engine).compile(FUNCTIONS); Object sayHello = compiled.eval(); // Load users' script each time SimpleBindings global = new SimpleBindings(); global.put("sayHello", sayHello); String script = "sayHello()"; System.out.println(engine.eval(script, global)); }
protected Object evaluateExpression(Object expression, Map<String, Object> parameters) { try { Object result = null; StringWriter writer = new StringWriter(); ScriptContext context = new SimpleScriptContext(); for (Map.Entry<String, Object> property : engineProperties.entrySet()) { context.setAttribute(property.getKey(), property.getValue(), ScriptContext.ENGINE_SCOPE); } Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.putAll(parameters); context.setBindings(bindings, ScriptContext.ENGINE_SCOPE); context.setWriter(writer); if (expression instanceof CompiledScript) { logger.debug("About to evaluate compiled expression {} with bindings {} on engine", expression, parameters, scriptEngine); result = ((CompiledScript) expression).eval(context); } else { logger.debug("About to evaluate expression {} with bindings {} on engine", expression, parameters, scriptEngine); result = scriptEngine.eval(expression.toString(), context); } if (result == null) { result = writer.toString(); } return result; } catch (ScriptException e) { throw new RuntimeException("Error when evaluating script", e); } }
public boolean check(Adaptable context) { try { if (engine == null) { comp = compile(type, script); } Bindings bindings = new SimpleBindings(); bindings.put("Context", context); bindings.put("doc", context.getAdapter(DocumentModel.class)); bindings.put("session", context.getAdapter(CoreSession.class)); bindings.put("principal", context.getAdapter(Principal.class)); Object result = null; if (comp != null) { result = comp.eval(bindings); if (result == null) { result = bindings.get("__result__"); } } else { result = engine.eval(new StringReader(script), bindings); } return booleanValue(result); } catch (ScriptException e) { log.error(e, e); return false; } }
@Override public Object evaluate(final String scriptId, final String script, final Map<String, Object> variables) throws JPPFScriptingException { if (engine == null) return null; Bindings bindings = engine.createBindings(); bindings.putAll(variables); CompiledScript cs = null; if ((scriptId != null) && (engine instanceof Compilable)) { String key = new StringBuilder().append(language).append(':').append(scriptId).toString(); cs = map.get(key); if (cs == null) { try { cs = ((Compilable) engine).compile(script); if (cs != null) map.put(key, cs); } catch (Exception e) { throw buildScriptingException(e); } } } try { Object res = (cs != null) ? cs.eval(bindings) : engine.eval(script, bindings); return res; } catch(Exception e) { throw buildScriptingException(e); } }
MangoJavaScriptResult result, boolean testRun) throws ScriptException { Bindings engineScope = script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE); if(setter == null) setter = createValidationSetter(result, permissions); util.setScriptLog(log); util.setResult(result); util.takeContext(script.getEngine(), engineScope, setter, importExclusions, testRun); engineScope.put(util.getContextKey(), util); util.setScriptLog(log); util.setResult(result); util.takeContext(script.getEngine(), engineScope, setter, importExclusions, testRun); engineScope.put(util.getContextKey(), util); List<String> points = getPointList(script.getEngine()); if(context != null) { for (String varName : context.keySet()) { IDataPointValueSource point = context.get(varName); engineScope.put(varName, wrapPoint(script.getEngine(), point, setter)); if (points != null) points.add(varName); script.getEngine().getContext().setWriter(log.getStdOutWriter()); engineScope.put(ScriptLog.CONTEXT_KEY, log); script.getEngine().eval(getGlobalFunctions());
@Override public boolean nextKeyValue() throws IOException { while (true) { if (!this.lineRecordReader.nextKeyValue()) return false; try { final Bindings bindings = this.engine.createBindings(); final StarGraph graph = StarGraph.open(); bindings.put(GRAPH, graph); bindings.put(LINE, this.lineRecordReader.getCurrentValue().toString()); final StarGraph.StarVertex sv = (StarGraph.StarVertex) script.eval(bindings); if (sv != null) { final Optional<StarGraph.StarVertex> vertex = sv.applyGraphFilter(this.graphFilter); if (vertex.isPresent()) { this.vertexWritable.set(vertex.get()); return true; } } } catch (final ScriptException e) { throw new IOException(e.getMessage()); } } }
data.scope = data.cx.getBindings( ScriptContext.ENGINE_SCOPE ); data.scope.put( "_step_", this ); data.scope.put( jsScripts[ i ].getScriptName(), jsScripts[ i ].getScript() ); data.scope.put( "_TransformationName_", this.getStepname() ); CompiledScript startScript = ( (Compilable) data.cx ).compile( strStartScript ); startScript.eval( data.scope ); if ( log.isDetailed() ) { logDetailed( ( "Start Script found!" ) ); data.script = ( (Compilable) data.cx ).compile( strTransformScript ); } catch ( Exception e ) { throw new KettleValueException( BaseMessages.getString( PKG, "Script.Log.CouldNotCompileJavascript" ), e ); data.script.eval( data.scope );
@Override public Serializable doSend(final Message message, final MeasurementUnit measurementUnit) throws Exception { final Bindings b = compiledScript.getEngine().createBindings(); b.put("message", message); b.put("measurementUnit", measurementUnit); b.put("log", log); return (Serializable) compiledScript.eval(b); }