@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
final ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
final CompiledScript compiledScript = ((Compilable)engine).compile(script);
final Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
java类javax.script.CompiledScript的实例源码
ScopeTest.java 文件源码
项目:openjdk-jdk10
阅读 25
收藏 0
点赞 0
评论 0
OQLEngineImpl.java 文件源码
项目:incubator-netbeans
阅读 15
收藏 0
点赞 0
评论 0
private void init(Snapshot snapshot) throws RuntimeException {
this.snapshot = snapshot;
try {
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript"); // NOI18N
InputStream strm = getInitStream();
CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
cs.eval();
Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
engine.put("heap", heap); // NOI18N
engine.put("cancelled", cancelled); // NOI18N
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Error initializing snapshot", ex); // NOI18N
throw new RuntimeException(ex);
}
}
SetExternalNameWizard.java 文件源码
项目:neoscada
阅读 17
收藏 0
点赞 0
评论 0
public void setExternalName ( final CompiledScript script ) throws Exception
{
final CompoundManager manager = new CompoundManager ();
for ( final ExternalValue v : SelectionHelper.iterable ( this.selection, ExternalValue.class ) )
{
final EditingDomain domain = AdapterFactoryEditingDomain.getEditingDomainFor ( v );
if ( domain == null )
{
continue;
}
final String name = evalName ( script, v );
manager.append ( domain, SetCommand.create ( domain, v, ComponentPackage.Literals.EXTERNAL_VALUE__SOURCE_NAME, name ) );
}
manager.executeAll ();
}
SetExternalNameWizard.java 文件源码
项目:neoscada
阅读 17
收藏 0
点赞 0
评论 0
public static String evalName ( final CompiledScript script, final ExternalValue v ) throws Exception
{
final SimpleScriptContext ctx = new SimpleScriptContext ();
ctx.setAttribute ( "item", v, ScriptContext.ENGINE_SCOPE ); //$NON-NLS-1$
final Object result = Scripts.executeWithClassLoader ( Activator.class.getClassLoader (), new Callable<Object> () {
@Override
public Object call () throws Exception
{
return script.eval ( ctx );
}
} );
if ( result == null )
{
return null;
}
return result.toString ();
}
Java8Tester.java 文件源码
项目:mynlp
阅读 15
收藏 0
点赞 0
评论 0
public static void main(String args[]) throws Exception {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
String name = "Mahesh";
System.out.println(nashorn.getClass());
Integer result = null;
try {
nashorn.eval("print('" + name + "')");
result = (Integer) nashorn.eval("10 + 2");
} catch (ScriptException e) {
System.out.println("Error executing script: " + e.getMessage());
}
jdk.nashorn.api.scripting.NashornScriptEngine x = (jdk.nashorn.api.scripting.NashornScriptEngine)
nashorn;
CompiledScript v = x.compile("1+2");
System.out.println(v.eval());
}
VirtualChestItem.java 文件源码
项目:VirtualChest
阅读 16
收藏 0
点赞 0
评论 0
public static VirtualChestItem deserialize(VirtualChestPlugin plugin, DataView data) throws InvalidDataException
{
DataView serializedStack = data.getView(ITEM).orElseThrow(() -> new InvalidDataException("Expected Item"));
String requirementString = data.getString(REQUIREMENTS).orElse("");
Tuple<String, CompiledScript> requirements = plugin.getScriptManager().prepare(requirementString);
List<DataView> primaryList = getViewListOrSingletonList(PRIMARY_ACTION, data);
VirtualChestActionDispatcher primaryAction = new VirtualChestActionDispatcher(primaryList);
List<DataView> secondaryList = getViewListOrSingletonList(SECONDARY_ACTION, data);
VirtualChestActionDispatcher secondaryAction = new VirtualChestActionDispatcher(secondaryList);
List<DataView> primaryShiftList = getViewListOrSingletonList(PRIMARY_SHIFT_ACTION, data);
List<DataView> primaryShiftListFinal = primaryShiftList.isEmpty() ? primaryList : primaryShiftList;
VirtualChestActionDispatcher primaryShiftAction = new VirtualChestActionDispatcher(primaryShiftListFinal);
List<DataView> secondaryShiftList = getViewListOrSingletonList(SECONDARY_SHIFT_ACTION, data);
List<DataView> secondaryShiftListFinal = secondaryShiftList.isEmpty() ? secondaryList : secondaryShiftList;
VirtualChestActionDispatcher secondaryShiftAction = new VirtualChestActionDispatcher(secondaryShiftListFinal);
List<String> ignoredPermissions = data.getStringList(IGNORED_PERMISSIONS).orElse(ImmutableList.of());
return new VirtualChestItem(plugin, serializedStack, requirements,
primaryAction, secondaryAction, primaryShiftAction, secondaryShiftAction, ignoredPermissions);
}
VirtualChestItem.java 文件源码
项目:VirtualChest
阅读 17
收藏 0
点赞 0
评论 0
private VirtualChestItem(
VirtualChestPlugin plugin,
DataView serializedStack,
Tuple<String, CompiledScript> requirements,
VirtualChestActionDispatcher primaryAction,
VirtualChestActionDispatcher secondaryAction,
VirtualChestActionDispatcher primaryShiftAction,
VirtualChestActionDispatcher secondaryShiftAction,
List<String> ignoredPermissions)
{
this.plugin = plugin;
this.serializer = new VirtualChestItemStackSerializer(plugin);
this.serializedStack = serializedStack;
this.requirements = requirements;
this.primaryAction = primaryAction;
this.secondaryAction = secondaryAction;
this.primaryShiftAction = primaryShiftAction;
this.secondaryShiftAction = secondaryShiftAction;
this.ignoredPermissions = ignoredPermissions;
}
ScriptUtil.java 文件源码
项目:scipio-erp
阅读 26
收藏 0
点赞 0
评论 0
/**
* Executes a compiled script and returns the result.
*
* @param script Compiled script.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @return The script result.
* @throws IllegalArgumentException
*/
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
Assert.notNull("script", script, "scriptContext", scriptContext);
Object result = script.eval(scriptContext);
if (UtilValidate.isNotEmpty(functionName)) {
if (Debug.verboseOn()) {
Debug.logVerbose("Invoking function/method " + functionName, module);
}
ScriptEngine engine = script.getEngine();
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
ScriptEngineTest.java 文件源码
项目:csvsum
阅读 19
收藏 0
点赞 0
评论 0
@Test
public final void test() throws Exception {
String csvMapperScript = "mapFunction = function(inputHeaders, inputField, inputValue, outputField, line) return inputValue end";
String simpleScript = "return inputValue";
CompiledScript compiledScript = (CompiledScript) ((Compilable) scriptEngine).compile(simpleScript);
Bindings bindings = scriptEngine.createBindings();
// inputHeaders, inputField, inputValue, outputField, line
bindings.put("inputHeaders", "");
bindings.put("inputField", "");
bindings.put("inputValue", "testreturnvalue");
bindings.put("outputField", "");
bindings.put("line", "");
String result = (String) compiledScript.eval(bindings);
System.out.println(result);
assertEquals("testreturnvalue", result);
}
BaseRaptureScript.java 文件源码
项目:Rapture
阅读 15
收藏 0
点赞 0
评论 0
@SuppressWarnings("unchecked")
@Override
public List<Object> runMap(CallingContext context, RaptureScript script, RaptureDataContext data, Map<String, Object> parameters) {
try {
ScriptEngine engine = engineRef.get();
CompiledScript cScript = getMapScript(engine, script);
addStandardContext(context, engine);
engine.put(PARAMS, parameters);
engine.put(DATA, JacksonUtil.getHashFromObject(data));
Kernel.getKernel().getStat().registerRunScript();
return (List<Object>) cScript.eval();
} catch (ScriptException e) {
Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);
}
}
BaseRaptureScript.java 文件源码
项目:Rapture
阅读 16
收藏 0
点赞 0
评论 0
@Override
public String runOperation(CallingContext context, RaptureScript script, String ctx, Map<String, Object> params) {
// Get the script from the implementation bit, set up the helpers into
// the context and execute...
try {
ScriptEngine engine = engineRef.get();
CompiledScript cScript = getOperationScript(engine, script);
addStandardContext(context, engine);
engine.put(PARAMS, params);
engine.put(CTX, ctx);
Kernel.getKernel().getStat().registerRunScript();
return JacksonUtil.jsonFromObject(cScript.eval());
} catch (ScriptException e) {
Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);
}
}
BaseRaptureScript.java 文件源码
项目:Rapture
阅读 15
收藏 0
点赞 0
评论 0
@Override
public String runProgram(CallingContext context, IActivityInfo activity, RaptureScript script, Map<String, Object> extraParams) {
try {
ScriptEngine engine = engineRef.get();
CompiledScript cScript = getProgramScript(engine, script);
addStandardContext(context, engine);
for (Map.Entry<String, ?> entry : extraParams.entrySet()) {
engine.put(entry.getKey(), entry.getValue());
}
if (Kernel.getKernel().getStat() != null) {
Kernel.getKernel().getStat().registerRunScript();
}
return JacksonUtil.jsonFromObject(cScript.eval());
} catch (ScriptException e) {
Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);
}
}
ScopeTest.java 文件源码
项目:lookaside_java-1.8.0-openjdk
阅读 17
收藏 0
点赞 0
评论 0
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
CompiledScript compiledScript = ((Compilable)engine).compile(script);
Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
ScopeTest.java 文件源码
项目:jdk8u_nashorn
阅读 17
收藏 0
点赞 0
评论 0
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
CompiledScript compiledScript = ((Compilable)engine).compile(script);
Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
Activator.java 文件源码
项目:step
阅读 18
收藏 0
点赞 0
评论 0
public static Boolean evaluateActivationExpression(Bindings bindings, Expression activationExpression) {
Boolean expressionResult;
if(activationExpression!=null) {
CompiledScript script = activationExpression.compiledScript;
if(script!=null) {
try {
Object evaluationResult = script.eval(bindings);
if(evaluationResult instanceof Boolean) {
expressionResult = (Boolean) evaluationResult;
} else {
expressionResult = false;
}
} catch (ScriptException e) {
expressionResult = false;
}
} else {
expressionResult = true;
}
} else {
expressionResult = true;
}
return expressionResult;
}
ExpressionLanguageScriptEngineImpl.java 文件源码
项目:oval
阅读 15
收藏 0
点赞 0
评论 0
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
LOG.debug("Evaluating JavaScript expression: {1}", expression);
try {
final Bindings scope = engine.createBindings();
for (final Entry<String, ?> entry : values.entrySet()) {
scope.put(entry.getKey(), entry.getValue());
}
if (compilable != null) {
CompiledScript compiled = compiledCache.get(expression);
if (compiled == null) {
compiled = compilable.compile(expression);
compiledCache.put(expression, compiled);
}
return compiled.eval(scope);
}
return engine.eval(expression, scope);
} catch (final ScriptException ex) {
throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex);
}
}
EBusTelegramParser.java 文件源码
项目:openhab-hdl
阅读 18
收藏 0
点赞 0
评论 0
/**
* Evaluates the compiled script of a entry.
* @param entry The configuration entry to evaluate
* @param scopeValues All known values for script scope
* @return The computed value
* @throws ScriptException
*/
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> scopeValues) throws ScriptException {
Object value = null;
// executes compiled script
if(entry.getValue().containsKey("cscript")) {
CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");
// Add global variables thisValue and keyName to JavaScript context
Bindings bindings = cscript.getEngine().createBindings();
bindings.putAll(scopeValues);
value = cscript.eval(bindings);
}
// try to convert the returned value to BigDecimal
value = ObjectUtils.defaultIfNull(
NumberUtils.toBigDecimal(value), value);
// round to two digits, maybe not optimal for any result
if(value instanceof BigDecimal) {
((BigDecimal)value).setScale(2, BigDecimal.ROUND_HALF_UP);
}
return value;
}
ExpressionCachingTest.java 文件源码
项目:camunda-engine-dmn
阅读 16
收藏 0
点赞 0
评论 0
@Test
public void testCompiledScriptCaching() throws ScriptException {
// given
DmnExpressionImpl expression = createExpression("1 > 2", "groovy");
// when
expressionEvaluationHandler.evaluateExpression("groovy", expression, emptyVariableContext());
// then
InOrder inOrder = inOrder(expression, scriptEngineSpy);
inOrder.verify(expression, atLeastOnce()).getCachedCompiledScript();
inOrder.verify(compilableSpy, times(1)).compile(anyString());
inOrder.verify(expression, times(1)).cacheCompiledScript(any(CompiledScript.class));
// when (2)
expressionEvaluationHandler.evaluateExpression("groovy", expression, emptyVariableContext());
// then (2)
inOrder.verify(expression, atLeastOnce()).getCachedCompiledScript();
inOrder.verify(compilableSpy, times(0)).compile(anyString());
}
ObjectExecution.java 文件源码
项目:teiid
阅读 15
收藏 0
点赞 0
评论 0
@Override
public List<Object> next() throws TranslatorException,
DataNotAvailableException {
// create and return one row at a time for your resultset.
if (resultsIt.hasNext()) {
List<Object> r = new ArrayList<Object>(projects.size());
Object o = resultsIt.next();
sc.setAttribute(OBJECT_NAME, o, ScriptContext.ENGINE_SCOPE);
for (CompiledScript cs : this.projects) {
if (cs == null) {
r.add(o);
continue;
}
try {
r.add(cs.eval(sc));
} catch (ScriptException e) {
throw new TranslatorException(e);
}
}
return r;
}
return null;
}
KotlinScriptEngineTest.java 文件源码
项目:dynkt
阅读 16
收藏 0
点赞 0
评论 0
@Test
public void testCompileFromFile2() throws FileNotFoundException, ScriptException {
InputStreamReader code = getStream("nameread.kt");
CompiledScript result = ((Compilable) engine).compile(code);
assertNotNull(result);
// First time
Bindings bnd1 = engine.createBindings();
StringWriter ret1;
bnd1.put("out", new PrintWriter(ret1 = new StringWriter()));
assertNotNull(result.eval(bnd1));
assertEquals("Provide a name", ret1.toString().trim());
// Second time
Bindings bnd2 = engine.createBindings();
bnd2.put(ScriptEngine.ARGV, new String[] { "Amadeus" });
StringWriter ret2;
bnd2.put("out", new PrintWriter(ret2 = new StringWriter()));
assertNotNull(result.eval(bnd2));
assertEquals("Hello, Amadeus!", ret2.toString().trim());
}
JavaScriptParser.java 文件源码
项目:AutoLoadCache
阅读 25
收藏 0
点赞 0
评论 0
@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);
}
}
JavaScriptEngine.java 文件源码
项目:jsen-js
阅读 29
收藏 0
点赞 0
评论 0
@Override
public CompiledScript compile(Reader script) throws ScriptException {
CompiledScript compiledScript = null;
Context cx = enterContext();
try {
String filename = getFilenameFromReader(script);
Script rhinoScript = cx.compileReader(script, filename, 1, null);
compiledScript = new CompiledJavaScript(this, rhinoScript);
} catch (Exception e) {
throwWrappedScriptException(e);
} finally {
exitContext();
}
return compiledScript;
}
ScriptUtil.java 文件源码
项目:elpi
阅读 25
收藏 0
点赞 0
评论 0
/**
* Executes a compiled script and returns the result.
*
* @param script Compiled script.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @return The script result.
* @throws IllegalArgumentException
*/
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
Assert.notNull("script", script, "scriptContext", scriptContext);
Object result = script.eval(scriptContext);
if (UtilValidate.isNotEmpty(functionName)) {
if (Debug.verboseOn()) {
Debug.logVerbose("Invoking function/method " + functionName, module);
}
ScriptEngine engine = script.getEngine();
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
RhinoScriptEngine.java 文件源码
项目:ef-orm
阅读 26
收藏 0
点赞 0
评论 0
@SuppressWarnings("deprecation")
public CompiledScript compile(java.io.Reader script) throws ScriptException {
CompiledScript ret = null;
Context cx = enterContext();
try {
String fileName = (String) get(ScriptEngine.FILENAME);
if (fileName == null) {
fileName = "<Unknown Source>";
}
Scriptable scope = getRuntimeScope(context);
Script scr = cx.compileReader(scope, script, fileName, 1, null);
ret = new RhinoCompiledScript(this, scr);
} catch (Exception e) {
throw new ScriptException(e);
} finally {
Context.exit();
}
return ret;
}
NashornTests.java 文件源码
项目:elasticsearch-lang-javascript-nashorn
阅读 35
收藏 0
点赞 0
评论 0
@Test
public void intArrayLengthTest() throws ScriptException {
Map<String, Object> vars = new HashMap<String, Object>();
Integer[] l = new Integer[] { 1,2,3 };
vars.put("l", l);
String script = "l.length";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
ScriptContext context = engine.getContext();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.putAll(vars);
Compilable compilable = (Compilable)engine;
CompiledScript compiledScript = compilable.compile(script);
Object o = compiledScript.eval();
assertThat(((Number) o).intValue(), equalTo(3));
}
NashornTests.java 文件源码
项目:elasticsearch-lang-javascript-nashorn
阅读 15
收藏 0
点赞 0
评论 0
@Test
public void objectArrayTest() throws ScriptException {
Map<String, Object> vars = new HashMap<String, Object>();
final Map<String, Object> obj2 = new HashMap<String,Object>() {{
put("prop2", "value2");
}};
final Map<String, Object> obj1 = new HashMap<String,Object>() {{
put("prop1", "value1");
put("obj2", obj2);
}};
vars.put("l", new Object[] { "1", "2", "3", obj1 });
String script = "l.length";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.putAll(vars);
Compilable compilable = (Compilable)engine;
CompiledScript compiledScript = compilable.compile(script);
Object o = compiledScript.eval(bindings);
assertThat(((Number) o).intValue(), equalTo(4));
}
ScriptUtil.java 文件源码
项目:o3erp
阅读 28
收藏 0
点赞 0
评论 0
/**
* Executes a compiled script and returns the result.
*
* @param script Compiled script.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @return The script result.
* @throws IllegalArgumentException
*/
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
Assert.notNull("script", script, "scriptContext", scriptContext);
Object result = script.eval(scriptContext);
if (UtilValidate.isNotEmpty(functionName)) {
if (Debug.verboseOn()) {
Debug.logVerbose("Invoking function/method " + functionName, module);
}
ScriptEngine engine = script.getEngine();
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
V8EngineTest.java 文件源码
项目:gameserver
阅读 14
收藏 0
点赞 0
评论 0
public void testInvoke() throws Exception {
eng = new ScriptEngineManager().getEngineByName("jav8");
Compilable compiler = (Compilable) this.eng;
CompiledScript script = compiler.compile(calcFunction);
int max = 100000;
Bindings binding = this.eng.getBindings(ScriptContext.GLOBAL_SCOPE);
binding.put("num", 3);
Object r = script.eval(binding);
System.out.println(r);
long startM = System.currentTimeMillis();
for ( int i=0; i<max; i++ ) {
script.eval(binding);
}
long endM = System.currentTimeMillis();
System.out.println(" V8 engine loop " + max + ":" + (endM-startM));
}
NashornScriptEngine.java 文件源码
项目:OLD-OpenJDK8
阅读 46
收藏 0
点赞 0
评论 0
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
final ScriptFunction func = compileImpl(source, context);
return new CompiledScript() {
@Override
public Object eval(final ScriptContext ctxt) throws ScriptException {
final ScriptObject globalObject = getNashornGlobalFrom(ctxt);
// Are we running the script in the correct global?
if (func.getScope() == globalObject) {
return evalImpl(func, ctxt, globalObject);
}
// ScriptContext with a different global. Compile again!
// Note that we may still hit per-global compilation cache.
return evalImpl(compileImpl(source, ctxt), ctxt, globalObject);
}
@Override
public ScriptEngine getEngine() {
return NashornScriptEngine.this;
}
};
}
ScriptRunner.java 文件源码
项目:fixprotocol-test-suite
阅读 24
收藏 0
点赞 0
评论 0
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval(new FileReader("src/main/javascript/Example.js"));
Compilable compilingEngine = (Compilable) engine;
CompiledScript script = compilingEngine.compile(new FileReader(
"src/main/javascript/Function.js"));
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("date", new Date());
bindings.put("out", System.out);
for (Map.Entry me : bindings.entrySet()) {
System.out.printf("%s: %s\n", me.getKey(),
String.valueOf(me.getValue()));
}
script.eval(bindings);
Invocable invocable = (Invocable) script.getEngine();
invocable.invokeFunction("sayhello", "Jose");
}