/**
* Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
* @throws ScriptException
* @throws InterruptedException
*/
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
for (int i = 0; i < 100; i++) {
final Bindings b = e.createBindings();
final ScriptContext ctxt = new SimpleScriptContext();
ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
assertEquals(e.eval("a", ctxt), 1);
assertEquals(b.get("a"), 1);
assertEquals(e.eval("b", ctxt), 3);
assertEquals(b.get("b"), 3);
assertEquals(e.eval("c", ctxt), 10);
assertEquals(b.get("c"), 10);
}
}
java类javax.script.ScriptContext的实例源码
ScopeTest.java 文件源码
项目:openjdk-jdk10
阅读 20
收藏 0
点赞 0
评论 0
ScriptExecutor.java 文件源码
项目:neoscada
阅读 25
收藏 0
点赞 0
评论 0
protected Map<String, Object> applyVars ( final ScriptContext context, final Map<String, Object> scriptObjects )
{
if ( scriptObjects == null || scriptObjects.isEmpty () )
{
return null;
}
final Map<String, Object> replaced = new HashMap<String, Object> ();
for ( final Map.Entry<String, Object> entry : scriptObjects.entrySet () )
{
final Object original = context.getAttribute ( entry.getKey (), ScriptContext.ENGINE_SCOPE );
replaced.put ( entry.getKey (), original );
context.setAttribute ( entry.getKey (), entry.getValue (), ScriptContext.ENGINE_SCOPE );
}
return replaced;
}
Global.java 文件源码
项目:openjdk-jdk10
阅读 22
收藏 0
点赞 0
评论 0
private Object printImpl(final boolean newLine, final Object... objects) {
final ScriptContext sc = currentContext();
@SuppressWarnings("resource")
final PrintWriter out = sc != null? new PrintWriter(sc.getWriter()) : getContext().getEnv().getOut();
final StringBuilder sb = new StringBuilder();
for (final Object obj : objects) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(JSType.toString(obj));
}
// Print all at once to ensure thread friendly result.
if (newLine) {
out.println(sb.toString());
} else {
out.print(sb.toString());
}
out.flush();
return UNDEFINED;
}
ScriptVisibilityProviderImpl.java 文件源码
项目:neoscada
阅读 16
收藏 0
点赞 0
评论 0
public ScriptVisibilityProviderImpl ( final ScriptEngineManager scriptEngineManager, final ScriptContext scriptContext, String engineName, final String scriptCode )
{
fireChange ( false );
if ( engineName == null || engineName.isEmpty () )
{
engineName = "JavaScript";
}
try
{
final ScriptExecutor executor = new ScriptExecutor ( scriptEngineManager, engineName, scriptCode, Activator.class.getClassLoader () );
fireChange ( makeResult ( executor.execute ( scriptContext ) ) );
}
catch ( final Exception e )
{
logger.warn ( "Failed to eval visibility", e );
}
}
ScriptObjectMirrorTest.java 文件源码
项目:openjdk-jdk10
阅读 17
收藏 0
点赞 0
评论 0
@Test
public void mapScriptObjectMirrorCallsiteTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine engine = m.getEngineByName("nashorn");
final String TEST_SCRIPT = "typeof obj.foo";
final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
engine.eval("var obj = java.util.Collections.emptyMap()");
// this will drive callsite "obj.foo" of TEST_SCRIPT
// to use "obj instanceof Map" as it's guard
engine.eval(TEST_SCRIPT, global);
// redefine 'obj' to be a script object
engine.eval("obj = {}");
final Bindings newGlobal = engine.createBindings();
// transfer 'obj' from default global to new global
// new global will get a ScriptObjectMirror wrapping 'obj'
newGlobal.put("obj", global.get("obj"));
// Every ScriptObjectMirror is a Map! If callsite "obj.foo"
// does not see the new 'obj' is a ScriptObjectMirror, it'll
// continue to use Map's get("obj.foo") instead of ScriptObjectMirror's
// getMember("obj.foo") - thereby getting null instead of undefined
assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal));
}
ExporterInterceptorHandler.java 文件源码
项目:neoscada
阅读 13
收藏 0
点赞 0
评论 0
@Override
protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties )
{
final ExporterItemInterceptor interceptor = (ExporterItemInterceptor)interceptorElement;
final Script script = interceptor.getScript ();
final ScriptEngineManager manager = new ScriptEngineManager ();
try
{
final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null );
final ScriptContext context = new SimpleScriptContext ();
final IEC60870Processor modbus = new IEC60870Processor ( this, interceptor, masterContext, item );
context.setAttribute ( "IEC60870", modbus, ScriptContext.ENGINE_SCOPE );
context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE );
context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE );
executor.execute ( context );
}
catch ( final Exception e )
{
throw new RuntimeException ( "Failed to process script", e );
}
return true;
}
ScriptCustomizationPipelineImpl.java 文件源码
项目:neoscada
阅读 14
收藏 0
点赞 0
评论 0
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void customize ( final CustomizationRequest request )
{
// FIXME: we should somehow take this out of here
try
{
if ( this.executor == null )
{
final String resource = eResource ().getURI ().toString ();
this.executor = new ScriptExecutor ( getScriptEngine (), this.code, ScriptCustomizationPipelineImpl.class.getClassLoader (), resource );
}
final SimpleScriptContext ctx = new SimpleScriptContext ();
ctx.setAttribute ( "request", request, ScriptContext.ENGINE_SCOPE );
this.executor.execute ( ctx );
}
catch ( final Exception e )
{
throw new RuntimeException ( e );
}
}
ModbusExporterInterceptorHandler.java 文件源码
项目:neoscada
阅读 14
收藏 0
点赞 0
评论 0
@Override
protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties )
{
final ModbusExporterInterceptor interceptor = (ModbusExporterInterceptor)interceptorElement;
final Script script = interceptor.getScript ();
final ScriptEngineManager manager = new ScriptEngineManager ();
try
{
final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null );
final ScriptContext context = new SimpleScriptContext ();
final ModbusProcessor modbus = new ModbusProcessor ( this, interceptor, masterContext, item );
context.setAttribute ( "MODBUS", modbus, ScriptContext.ENGINE_SCOPE );
context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE );
context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE );
executor.execute ( context );
}
catch ( final Exception e )
{
throw new RuntimeException ( "Failed to process script", e );
}
return true;
}
SetExternalNameWizard.java 文件源码
项目:neoscada
阅读 20
收藏 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 ();
}
ScriptEventHandler.java 文件源码
项目:neoscada
阅读 18
收藏 0
点赞 0
评论 0
@Override
public Event handleEvent ( final Event event, final InjectionContext context )
{
final ScriptContext scriptContext = new SimpleScriptContext ();
try
{
scriptContext.setAttribute ( "event", event, ScriptContext.GLOBAL_SCOPE );
scriptContext.setAttribute ( "logger", logger, ScriptContext.GLOBAL_SCOPE );
scriptContext.setAttribute ( "injector", this.injector, ScriptContext.GLOBAL_SCOPE );
final Object result = this.script.execute ( scriptContext );
final Event resultEvent = convert ( result, event );
logger.debug ( "Result: {}", resultEvent );
return resultEvent;
}
catch ( final Exception e )
{
return event;
}
}
InvocableTest.java 文件源码
项目:openjdk-jdk10
阅读 15
收藏 0
点赞 0
评论 0
@Test
/**
* Check that we can get interface out of a script object even after
* switching to use different ScriptContext.
*/
public void getInterfaceDifferentContext() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
final Object obj = e.eval("({ run: function() { } })");
// change script context
final ScriptContext ctxt = new SimpleScriptContext();
ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
e.setContext(ctxt);
final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
r.run();
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
ScriptDataSource.java 文件源码
项目:neoscada
阅读 18
收藏 0
点赞 0
评论 0
/**
* Handle data change
*/
@Override
protected synchronized void handleChange ( final Map<String, DataSourceHandler> sources )
{
// calculate
// gather all data
final Map<String, DataItemValue> values = new HashMap<String, DataItemValue> ();
for ( final Map.Entry<String, DataSourceHandler> entry : sources.entrySet () )
{
values.put ( entry.getKey (), entry.getValue ().getValue () );
}
this.scriptContext.setAttribute ( "data", values, ScriptContext.ENGINE_SCOPE );
this.scriptContext.setAttribute ( "writer", this.writer, ScriptContext.ENGINE_SCOPE );
this.scriptContext.setAttribute ( "eventProcessor", this.eventProcessor, ScriptContext.ENGINE_SCOPE );
executeScript ( this.updateCommand );
}
NashornScriptEngine.java 文件源码
项目:OpenJSharp
阅读 33
收藏 0
点赞 0
评论 0
private static Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
ctxtGlobal.setScriptContext(ctxt);
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
NashornScriptEngine.java 文件源码
项目:OpenJSharp
阅读 28
收藏 0
点赞 0
评论 0
private static Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
if (script == null) {
return null;
}
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
ctxtGlobal.setScriptContext(ctxt);
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
InvocableTest.java 文件源码
项目:openjdk-jdk10
阅读 14
收藏 0
点赞 0
评论 0
@Test
/**
* Check that we can call invokeMethod on an object that we got by
* evaluating script with different Context set.
*/
public void invokeMethodDifferentContextTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
// define an object with method on it
final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");
final ScriptContext ctxt = new SimpleScriptContext();
ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
e.setContext(ctxt);
// invoke 'func' on obj - but with current script context changed
final Object res = ((Invocable) e).invokeMethod(obj, "hello");
assertEquals(res, "Hello World!");
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
ScriptEnginePool.java 文件源码
项目:jaffa-framework
阅读 16
收藏 0
点赞 0
评论 0
/**
* Clears the script engine of all previous state except, if it is a BeanShell interpreter,
* the engine is left
*
* @param scriptEngine ScriptEngine to clear
*/
private void clearEngine(String language, ScriptEngine scriptEngine) {
// Clear everything except the BeanShell engine ("bsh" in the binding)
// This will clear all imported class, methods, and variables
List<String> itemsToRemove = new ArrayList<String>();
for (Map.Entry<String, Object> bindingEntry : scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).entrySet()) {
if (language.equalsIgnoreCase(BEANSHELL) && bindingEntry.getKey().equalsIgnoreCase(BEANSHELL_ENGINE_NAME)) {
continue;
}
itemsToRemove.add(bindingEntry.getKey());
}
for (String value : itemsToRemove) {
scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove(value);
}
// Clear entire global scope
scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
}
Test3.java 文件源码
项目:openjdk-jdk10
阅读 26
收藏 0
点赞 0
评论 0
public static void main(String[] args) throws Exception {
System.out.println("\nTest3\n");
final Reader reader = new FileReader(
new File(System.getProperty("test.src", "."), "Test3.js"));
ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine engine = Helper.getJsEngine(m);
if (engine == null) {
System.out.println("Warning: No js engine found; test vacuously passes.");
return;
}
Bindings en = new SimpleBindings();
engine.setBindings(en, ScriptContext.ENGINE_SCOPE);
en.put("key", "engine value");
Bindings gn = new SimpleBindings();
engine.setBindings(gn, ScriptContext.GLOBAL_SCOPE);
gn.put("key", "global value");
engine.eval(reader);
}
L2ScriptEngineManager.java 文件源码
项目:L2jBrasil
阅读 18
收藏 0
点赞 0
评论 0
public ScriptContext getScriptContext(String engineName)
{
ScriptEngine engine = this.getEngineByName(engineName);
if (engine == null)
throw new IllegalStateException("No engine registered with name (" + engineName + ")");
else
return this.getScriptContext(engine);
}
L2ScriptEngineManager.java 文件源码
项目:L2jBrasil
阅读 20
收藏 0
点赞 0
评论 0
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
{
if (engine instanceof Compilable && ATTEMPT_COMPILATION)
{
Compilable eng = (Compilable) engine;
CompiledScript cs = eng.compile(script);
return context != null ? cs.eval(context) : cs.eval();
} else
return context != null ? engine.eval(script, context) : engine.eval(script);
}
L2ScriptEngineManager.java 文件源码
项目:L2jBrasil
阅读 64
收藏 0
点赞 0
评论 0
public Object eval(String engineName, String script, ScriptContext context) throws ScriptException
{
ScriptEngine engine = this.getEngineByName(engineName);
if (engine == null)
throw new ScriptException("No engine registered with name (" + engineName + ")");
else
return this.eval(engine, script, context);
}
CoreTask.java 文件源码
项目:greycat
阅读 15
收藏 0
点赞 0
评论 0
/**
* @native ts
* var print = console.log;
* var println = console.log;
* var ctx = context;
* return eval(script);
*/
private static boolean executeScript(String script, TaskContext context) {
ScriptContext scriptCtx = new SimpleScriptContext();
scriptCtx.setAttribute("ctx", context, ScriptContext.ENGINE_SCOPE);
try {
return (boolean) TaskHelper.SCRIPT_ENGINE.eval(script, scriptCtx);
} catch (ScriptException | ClassCastException e) {
e.printStackTrace();
return false;
}
}
ActionSelect.java 文件源码
项目:greycat
阅读 16
收藏 0
点赞 0
评论 0
/**
* @native ts
* var print = console.log;
* return eval(this._script);
*/
private boolean callScript(Node node, TaskContext context) {
ScriptContext scriptCtx = new SimpleScriptContext();
scriptCtx.setAttribute("node", node, ScriptContext.ENGINE_SCOPE);
scriptCtx.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
try {
return (boolean) TaskHelper.SCRIPT_ENGINE.eval(_script, scriptCtx);
} catch (ScriptException | ClassCastException e) {
throw new RuntimeException(e);
}
}
JSnview.java 文件源码
项目:8ComicSDK-JAVA
阅读 36
收藏 0
点赞 0
评论 0
private List<String> invokeJS(String js, int y, int ch) {
ArrayList<String> pagsList = new ArrayList<String>();
String str = js.substring(0, js.indexOf("var pt="));
str = str.replace("ge('TheImg').src", "var src");
String unuseScript = StringUtility.substring(str, "\'.jpg\';", "break;");
str = str.replace(unuseScript, "");
String varSrc = null;
if(str.indexOf("ci = i;") != -1){
varSrc = StringUtility.substring(str, "ci = i;", "break;");
}else if(str.indexOf("ci=i;") != -1){
varSrc = StringUtility.substring(str, "ci=i;", "break;");
}
String getPageJS = String.format(buildGetPagesJS(), varSrc);
str = str.replace(varSrc, "");
str = str.replace("break;", getPageJS);
String script = "function sp2(ch, y){" + str + "} " + buildNviewJS();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
Bindings bind = engine.createBindings();
bind.put("pagsList", pagsList);
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
engine.eval(script);
Invocable inv = (Invocable) engine;
inv.invokeFunction("sp2", ch, y);
} catch (Exception e) {
e.printStackTrace();
}
return pagsList;
}
ScopeTest.java 文件源码
项目:openjdk-jdk10
阅读 18
收藏 0
点赞 0
评论 0
/**
* Test multi-threaded access to defined global variables for shared script classes with multiple globals.
*/
@Test
public static void multiThreadedVarTest() throws ScriptException, InterruptedException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final Bindings b = e.createBindings();
final ScriptContext origContext = e.getContext();
final ScriptContext newCtxt = new SimpleScriptContext();
newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
final String sharedScript = "foo";
assertEquals(e.eval("var foo = 'original context';", origContext), null);
assertEquals(e.eval("var foo = 'new context';", newCtxt), null);
final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
t1.start();
t2.start();
t1.join();
t2.join();
assertEquals(e.eval("var foo = 'newer context';", newCtxt), null);
final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));
t3.start();
t4.start();
t3.join();
t4.join();
assertEquals(e.eval(sharedScript), "original context");
assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}
ScopeTest.java 文件源码
项目:openjdk-jdk10
阅读 19
收藏 0
点赞 0
评论 0
@Test
public void userEngineScopeBindingsNoLeakTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final ScriptContext newContext = new SimpleScriptContext();
newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
e.eval("function foo() {}", newContext);
// in the default context's ENGINE_SCOPE, 'foo' shouldn't exist
assertTrue(e.eval("typeof foo").equals("undefined"));
}
RsrcLoader.java 文件源码
项目:incubator-netbeans
阅读 21
收藏 0
点赞 0
评论 0
RsrcLoader(FileObject fo, ScriptContext map) {
this.fo = fo;
this.map = map;
this.engineScope = map.getBindings(ScriptContext.ENGINE_SCOPE);
setTemplateLoader(this);
setTemplateExceptionHandler(this);
Logger.getLogger("freemarker.runtime").setLevel(Level.OFF);
}
SpeedTest.java 文件源码
项目:incubator-netbeans
阅读 20
收藏 0
点赞 0
评论 0
@Override
protected void setUp() throws Exception {
clearWorkDir();
FileWriter w = new FileWriter(new File(getWorkDir(), "template.txt"));
w.write("<html><h1>${title}</h1></html>");
w.close();
parameters = new HashMap<String,String>();
parameters.put("title", "SOME_TITLE");
LocalFileSystem lfs = new LocalFileSystem();
lfs.setRootDirectory(getWorkDir());
fo = lfs.findResource("template.txt");
ScriptEngineManager mgr = new ScriptEngineManager();
eng = mgr.getEngineByName("freemarker");
assertNotNull("We do have such engine", eng);
eng.getContext().setAttribute(FileObject.class.getName(), fo, ScriptContext.ENGINE_SCOPE);
eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(parameters);
whereTo = new File[10000];
for (int i = 0; i < whereTo.length; i++) {
whereTo[i] = new File(getWorkDir(), "outFile"+i+".txt");
}
}
ProcessorTest.java 文件源码
项目:incubator-netbeans
阅读 23
收藏 0
点赞 0
评论 0
static void apply(FileObject template, Writer w, Map<String,? extends Object> values, TemplateExceptionHandler teh) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine eng = mgr.getEngineByName("freemarker");
assertNotNull("We do have such engine", eng);
eng.getContext().setWriter(w);
eng.getContext().setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(values);
if (teh != null) {
eng.getContext().setAttribute("org.netbeans.libs.freemarker.exceptionHandler", teh, ScriptContext.ENGINE_SCOPE);
}
eng.eval(new InputStreamReader(template.getInputStream()));
}
SpeedTest.java 文件源码
项目:incubator-netbeans
阅读 18
收藏 0
点赞 0
评论 0
@Override
protected void setUp() throws Exception {
clearWorkDir();
FileWriter w = new FileWriter(new File(getWorkDir(), "template.txt"));
w.write("<html><h1>${title}</h1></html>");
w.close();
parameters = new HashMap<String,String>();
parameters.put("title", "SOME_TITLE");
LocalFileSystem lfs = new LocalFileSystem();
lfs.setRootDirectory(getWorkDir());
target = DataFolder.findFolder(lfs.getRoot());
FileObject fo = lfs.findResource("template.txt");
obj = DataObject.find(fo);
obj.setTemplate(true);
obj.getPrimaryFile().setAttribute("javax.script.ScriptEngine", "freemarker");
ScriptEngineManager mgr = new ScriptEngineManager();
eng = mgr.getEngineByName("freemarker");
assertNotNull("We do have such engine", eng);
eng.getContext().setAttribute(FileObject.class.getName(), fo, ScriptContext.ENGINE_SCOPE);
eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(parameters);
whereTo = new File[10000];
for (int i = 0; i < whereTo.length; i++) {
whereTo[i] = new File(getWorkDir(), "outFile"+i+".txt");
}
}
ScopeTest.java 文件源码
项目:openjdk-jdk10
阅读 16
收藏 0
点赞 0
评论 0
/**
* Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
*/
@Test
public static void getterSetter2Test() throws ScriptException, InterruptedException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final Bindings b = e.createBindings();
final ScriptContext origContext = e.getContext();
final ScriptContext newCtxt = new SimpleScriptContext();
newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
final String sharedScript = "accessor2";
e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
assertEquals(e.eval("accessor2 = 1;"), 1);
assertEquals(e.eval(sharedScript), 1);
e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
assertEquals(e.eval("accessor2 = 2;", newCtxt), 2);
assertEquals(e.eval(sharedScript, newCtxt), 2);
final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000));
final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000));
t1.start();
t2.start();
t1.join();
t2.join();
assertEquals(e.eval(sharedScript), 1);
assertEquals(e.eval(sharedScript, newCtxt), 2);
assertEquals(e.eval("x"), 1);
assertEquals(e.eval("x", newCtxt), 2);
}