Java Code Examples for javax.script.ScriptException

The following examples show how to use javax.script.ScriptException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void accessFieldChar() throws ScriptException {
    e.eval("var p_char = o.publicChar;");
    assertEquals(o.publicChar, e.get("p_char"));
    e.eval("o.publicChar = 'S';");
    assertEquals('S', o.publicChar);
    e.eval("o.publicChar = 10;");
    assertEquals(10, o.publicChar);
    e.eval("try {"
            + "    o.publicChar = 'Big string';" +
            "} catch(e) {" +
            "    var isThrown = true;" +
            "}");
    assertEquals("Exception thrown", true, e.get("isThrown"));
    assertEquals(10, o.publicChar);
}
 
Example 2
@Test
public void classFilterTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(new ClassFilter() {
        @Override
        public boolean exposeToScripts(final String fullName) {
            // don't allow anything that is not "java."
            return fullName.startsWith("java.");
        }
    });

    assertEquals(e.eval("typeof javax.script.ScriptEngine"), "object");
    assertEquals(e.eval("typeof java.util.Vector"), "function");

    try {
        e.eval("Java.type('javax.script.ScriptContext')");
        fail("should not reach here");
    } catch (final ScriptException | RuntimeException se) {
        if (! (se.getCause() instanceof ClassNotFoundException)) {
            fail("ClassNotFoundException expected");
        }
    }
}
 
Example 3
Source Project: hottub   Source File: LexicalBindingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test access to global lexically declared variables for shared script classes with single global.
 */
@Test
public static void megamorphicInheritedGlobalLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final String sharedGetterScript = "foo";
    final String sharedSetterScript = "foo = 1";

    for (int i = 0; i < MEGAMORPHIC_LOOP_COUNT; i++) {
        assertEquals(e.eval(sharedSetterScript), 1);
        assertEquals(e.eval(sharedGetterScript), 1);
        assertEquals(e.eval("delete foo; a" + i + " = 1; Object.prototype.foo = " + i + ";"), i);
        assertEquals(e.eval(sharedGetterScript), i);
    }

    assertEquals(e.eval("let foo = 'foo';"), null);
    assertEquals(e.eval(sharedGetterScript), "foo");
    assertEquals(e.eval(sharedSetterScript), 1);
    assertEquals(e.eval(sharedGetterScript), 1);
    assertEquals(e.eval("this.foo"), MEGAMORPHIC_LOOP_COUNT - 1);
}
 
Example 4
@Test
public void shouldContinueToEvalScriptsEvenWithTimedInterrupt() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine(
            new TimedInterruptGroovyCustomizer(1000));

    for (int ix = 0; ix < 5; ix++) {
        try {
            // this script takes 1000 ms longer than the interruptionTimeout
            engine.eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 2000) {}");
            fail("This should have timed out");
        } catch (ScriptException se) {
            assertEquals(org.apache.tinkerpop.gremlin.groovy.jsr223.TimedInterruptTimeoutException.class, se.getCause().getCause().getClass());
        }

        // this script takes 500 ms less than the interruptionTimeout
        assertEquals("test", engine.eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 500) {};'test'"));
    }

    assertEquals(2, engine.eval("1+1"));
}
 
Example 5
private AttributedString getPromptFromScript(SqlLine sqlLine,
    String promptScript) {
  try {
    final ScriptEngine engine = SCRIPT_ENGINE_SUPPLIER.get();
    final Bindings bindings = new SimpleBindings();
    final ConnectionMetadata meta = sqlLine.getConnectionMetadata();
    bindings.put("connectionIndex", meta.getIndex());
    bindings.put("databaseProductName", meta.getDatabaseProductName());
    bindings.put("userName", meta.getUserName());
    bindings.put("url", meta.getUrl());
    bindings.put("currentSchema", meta.getCurrentSchema());
    final Object o = engine.eval(promptScript, bindings);
    return new AttributedString(String.valueOf(o));
  } catch (ScriptException e) {
    e.printStackTrace();
    return new AttributedString(">");
  }
}
 
Example 6
@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));
}
 
Example 7
/**
 * Test access to global lexically declared variables for shared script classes with single global.
 */
@Test
public static void megamorphicSingleGlobalLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final String sharedGetterScript = "foo";
    final String sharedSetterScript = "foo = 1";

    for (int i = 0; i < MEGAMORPHIC_LOOP_COUNT; i++) {
        assertEquals(e.eval(sharedSetterScript), 1);
        assertEquals(e.eval(sharedGetterScript), 1);
        assertEquals(e.eval("delete foo; a" + i + " = 1; foo = " + i + ";"), i);
        assertEquals(e.eval(sharedGetterScript), i);
    }

    assertEquals(e.eval("let foo = 'foo';"), null);
    assertEquals(e.eval(sharedGetterScript), "foo");
    assertEquals(e.eval(sharedSetterScript), 1);
    assertEquals(e.eval(sharedGetterScript), 1);
    assertEquals(e.eval("this.foo"), MEGAMORPHIC_LOOP_COUNT - 1);
}
 
Example 8
Source Project: incubator-atlas   Source File: Titan1Graph.java    License: Apache License 2.0 6 votes vote down vote up
private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException {
    GremlinGroovyScriptEngine scriptEngine = getGremlinScriptEngine();

    try {
        Bindings bindings = scriptEngine.createBindings();

        bindings.put("graph", getGraph());
        bindings.put("g", getGraph().traversal());

        Object result = scriptEngine.eval(gremlinQuery, bindings);

        return result;
    } catch (ScriptException e) {
        throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery);
    } finally {
        releaseGremlinScriptEngine(scriptEngine);
    }
}
 
Example 9
Source Project: groovy   Source File: GroovyScriptEngineImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Object eval(String script, ScriptContext ctx)
        throws ScriptException {
    try {
        String val = (String) ctx.getAttribute("#jsr223.groovy.engine.keep.globals", ScriptContext.ENGINE_SCOPE);
        ReferenceBundle bundle = ReferenceBundle.getHardBundle();
        if (val != null && val.length() > 0) {
            if (val.equalsIgnoreCase("soft")) {
                bundle = ReferenceBundle.getSoftBundle();
            } else if (val.equalsIgnoreCase("weak")) {
                bundle = ReferenceBundle.getWeakBundle();
            } else if (val.equalsIgnoreCase("phantom")) {
                bundle = ReferenceBundle.getPhantomBundle();
            }
        }
        globalClosures.setBundle(bundle);
    } catch (ClassCastException cce) { /*ignore.*/ }

    try {
        Class<?> clazz = getScriptClass(script, ctx);
        if (clazz == null) throw new ScriptException("Script class is null");
        return eval(clazz, ctx);
    } catch (Exception e) {
        if (debug) e.printStackTrace();
        throw new ScriptException(e);
    }
}
 
Example 10
Source Project: qpid-broker-j   Source File: JavaScriptConfigEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
public String evaluateJavaScript(Reader fileReader)
{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    try
    {
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("json2.js")));
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test-utils.js")));
        engine.eval(fileReader);
        engine.eval("jsonString = JSON.stringify(" + TEST_CONFIG_VARIABLE_NAME + ")");
    }
    catch (ScriptException e)
    {
        throw new DistributedTestException("Exception while evaluating test config", e);
    }
    String result = (String) engine.get("jsonString");

    return result;
}
 
Example 11
Source Project: rice   Source File: BSFRuleExpression.java    License: Educational Community License v2.0 6 votes vote down vote up
public RuleExpressionResult evaluate(Rule rule, RouteContext context) {
    org.kuali.rice.kew.api.rule.RuleContract ruleDefinition = rule.getDefinition();
    String name = "" + ruleDefinition.getName();
    String type = ruleDefinition.getRuleExpressionDef().getType();
    String lang = parseLang(type, "groovy");
    String expression = ruleDefinition.getRuleExpressionDef().getExpression();
    RuleExpressionResult result;
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName(lang);
    try {
        declareBeans(engine, rule, context);
        result = (RuleExpressionResult) engine.eval(expression);
    } catch (ScriptException e) {
        String details =  ( e.getLineNumber() >= 0 ?  " line: " + e.getLineNumber() + " column: " + e.getColumnNumber() : "" );
        LOG.debug("Error evaluating rule '" + name + "' " + type +  " expression" + details + ": '" + expression + "'" + details, e);
        throw new RiceIllegalStateException("Error evaluating rule '" + name + "' " + type + " expression" + details, e);
    }
    if (result == null) {
        return new RuleExpressionResult(rule, false);
    } else {
        return result;
    }
}
 
Example 12
@Test
public void checkProxyAccess() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final boolean[] reached = new boolean[1];
    final Runnable r = (Runnable)Proxy.newProxyInstance(
        ScriptEngineTest.class.getClassLoader(),
        new Class[] { Runnable.class },
        new InvocationHandler() {
            @Override
            public Object invoke(final Object p, final Method mtd, final Object[] a) {
                reached[0] = true;
                return null;
            }
        });

    e.put("r", r);
    e.eval("r.run()");

    assertTrue(reached[0]);
}
 
Example 13
@Test
public void accessFieldFloatBoxing() throws ScriptException {
    e.eval("var p_float = o.publicFloatBox;");
    assertEqualsDouble(o.publicFloatBox, "p_float");
    o.publicFloatBox = 0.0f / 0.0f;
    assertEquals(true, e.eval("isNaN(o.publicFloatBox)"));
    o.publicFloatBox = 1.0f / 0.0f;
    assertEquals(true, e.eval("Number.POSITIVE_INFINITY === o.publicFloatBox"));
    o.publicFloatBox = -1.0f / 0.0f;
    assertEquals(true, e.eval("Number.NEGATIVE_INFINITY === o.publicFloatBox"));
    e.eval("o.publicFloatBox = 20;");
    assertEquals(20, o.publicFloatBox, 1e-10);
    e.eval("o.publicFloatBox = 0.0/0.0;");
    assertTrue(Float.isNaN(o.publicFloatBox));
    e.eval("o.publicFloatBox = 1.0/0.0;");
    assertEquals(Float.floatToIntBits(Float.POSITIVE_INFINITY), Float.floatToIntBits(o.publicFloatBox));
    e.eval("o.publicFloatBox = -1.0/0.0;");
    assertEquals(Float.NEGATIVE_INFINITY, o.publicFloatBox, 1e-10);
}
 
Example 14
@Test
public void accessFieldObjectArray() throws ScriptException {
    e.eval("var p_object_array = o.publicObjectArray;");
    assertEquals(o.publicObjectArray[0], e.eval("o.publicObjectArray[0]"));
    assertArrayEquals(o.publicObjectArray, (Object[])e.get("p_object_array"));
    e.eval("var t_object_arr = new (Java.type(\"jdk.nashorn.api.javaaccess.test.Person[]\"))(3);" +
            "t_object_arr[0] = new Person(100);" +
            "t_object_arr[1] = new Person(120);" +
            "t_object_arr[2] = new Person(140);" +
            "o.publicObjectArray = t_object_arr;");
    assertArrayEquals(new Person[] { new Person(100), new Person(120), new Person(140) }, o.publicObjectArray);
    e.eval("o.publicObjectArray[0] = new Person(10);");
    assertEquals(new Person(10), o.publicObjectArray[0]);
}
 
Example 15
/**
 * eval expressions using javascript engine
 *
 * @param script expression/script to eval.
 * @return result
 */
public static String evaljs(String script) {
    try {
        return JS.eval("JSON.stringify(" + script + ")").toString();
    } catch (ScriptException ex) {
       LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return "undefined";
}
 
Example 16
public void act(MapleClient c, MapleReactor reactor) {
    try {
        NashornScriptEngine iv = getScriptEngine("reactor/" + reactor.getId() + ".js", c);
        if (iv == null) return;
        
        ReactorActionManager rm = new ReactorActionManager(c, reactor, iv);
        iv.put("rm", rm);
        iv.invokeFunction("act");
    } catch (final ScriptException | NoSuchMethodException | NullPointerException e) {
        FilePrinter.printError(FilePrinter.REACTOR + reactor.getId() + ".txt", e);
    }
}
 
Example 17
Source Project: wandora   Source File: ScriptModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init(ModuleManager manager, HashMap<String, Object> settings) throws ModuleException {
    Object o;
    o=settings.get("scriptEngine");
    if(o!=null) engine=o.toString();
    
    o=settings.get("startScript");
    if(o!=null) startScript=o.toString();
    
    o=settings.get("stopScript");
    if(o!=null) stopScript=o.toString();

    o=settings.get("initScript");
    if(o!=null) initScript=o.toString();
    
    persistentObjects=new HashMap<String,Object>();
    
    if(initScript!=null){
        try{
            ScriptEngine scriptEngine=getScriptEngine();
            scriptEngine.put("settings",settings);
            scriptManager.executeScript(initScript, scriptEngine);
        }catch(ScriptException se){
            throw new ModuleException(se);
        }            
    }
    
    super.init(manager, settings);
}
 
Example 18
Source Project: constellation   Source File: GraphAnalysisUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public int graph_count_transactions(final PyFunction condition, final int distance) throws ScriptException {
    int count = 0;
    for (int i = 0; i < context.graph.getTransactionCount(); i++) {
        final int elementId = context.graph.getTransaction(i);
        context.enter(elementId, GraphElementType.TRANSACTION);
        boolean conditionMatches = isTrueValue(condition.__call__());
        context.exit();
        if (conditionMatches) {
            count++;
        }
    }
    return count;
}
 
Example 19
Source Project: timbuctoo   Source File: Gremlin.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String evaluateQuery(String query) throws ScriptException {
  GraphTraversal traversalResult = (GraphTraversal) engine.eval(query, bindings);
  StringBuilder result = new StringBuilder();
  while (traversalResult.hasNext()) {

    dumpItem(traversalResult.next(), result);
  }
  if (result.length() > 0) {
    return result.toString();
  } else {
    return "No results...";
  }
}
 
Example 20
@Test
public void accessStaticFinalFieldObjectArray() throws ScriptException {
    e.eval("var psf_object_array = SharedObject.publicStaticFinalObjectArray;");
    assertEquals(SharedObject.publicStaticFinalObjectArray[0], e.eval("SharedObject.publicStaticFinalObjectArray[0]"));
    assertArrayEquals(SharedObject.publicStaticFinalObjectArray, (Object[])e.get("psf_object_array"));
    e.eval("var tsf_object_arr = new (Java.type(\"jdk.nashorn.api.javaaccess.test.Person[]\"))(3);" +
            "tsf_object_arr[0] = new Person(100);" +
            "tsf_object_arr[1] = new Person(120);" +
            "tsf_object_arr[2] = new Person(140);" +
            "SharedObject.publicStaticFinalObjectArray = tsf_object_arr;");
    assertArrayEquals(new Person[] { new Person(-9), new Person(110), new Person(Integer.MAX_VALUE) }, SharedObject.publicStaticFinalObjectArray);
    e.eval("SharedObject.publicStaticFinalObjectArray[0] = new Person(90);");
    assertEquals(new Person(90), SharedObject.publicStaticFinalObjectArray[0]);
}
 
Example 21
Source Project: hottub   Source File: NumberBoxingTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessFinalFieldShortBoxing() throws ScriptException {
    e.eval("var pf_short = o.publicFinalShortBox;");
    assertEqualsDouble(o.publicFinalShortBox, "pf_short");
    e.eval("o.publicFinalShortBox = 180;");
    assertEquals(Short.valueOf((short)-26777), o.publicFinalShortBox);
}
 
Example 22
Source Project: hottub   Source File: ScopeTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean lookupVar(final ScriptEngine engine, final String varName) {
    try {
        engine.eval(varName);
        return true;
    } catch (final ScriptException se) {
        return false;
    }
}
 
Example 23
Source Project: hottub   Source File: BooleanAccessTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessStaticFieldBoolean() throws ScriptException {
    e.eval("var ps_boolean = SharedObject.publicStaticBoolean;");
    assertEquals(SharedObject.publicStaticBoolean, e.get("ps_boolean"));
    assertEquals("boolean", e.eval("typeof ps_boolean;"));
    e.eval("SharedObject.publicStaticBoolean = false;");
    assertEquals(false, SharedObject.publicStaticBoolean);
}
 
Example 24
Source Project: dfactor   Source File: DFActorManagerJs.java    License: MIT License 5 votes vote down vote up
private boolean _checkScriptFileValid(File f){
	boolean bRet = false;
	do {
		ScriptEngine engineTmp = _engineMgr.getEngineByName("JavaScript");
		try {
			engineTmp.eval(new FileReader(f));
			Set<String> setCur = _jsEngine.getBindings(ScriptContext.ENGINE_SCOPE).keySet();
			Bindings bindTmp = engineTmp.getBindings(ScriptContext.ENGINE_SCOPE);
			Iterator<String> it = bindTmp.keySet().iterator();
			while(it.hasNext()){
				String key = it.next();
				if(setCur.contains(key)){
					printError("global var duplicated: "+key+" in '"+f.getAbsolutePath()+"' & '"+_mapScriptKeyFile.get(key)+"'");
					return false;
				}else{
					_mapScriptKeyFile.put(key, f.getAbsolutePath());
				}
			}
		} catch (FileNotFoundException | ScriptException e) {
			e.printStackTrace();
			break;
		}finally{
			engineTmp = null;
		}
		bRet = true;
	} while (false);
	return bRet;
}
 
Example 25
@Test
public void accessStaticFieldIntBoxing() throws ScriptException {
    e.eval("var ps_int = SharedObject.publicStaticInt;");
    assertEquals(SharedObject.publicStaticInt, e.get("ps_int"));
    e.eval("SharedObject.publicStaticInt = 140;");
    assertEquals(140, SharedObject.publicStaticInt);
}
 
Example 26
Source Project: jdk8u60   Source File: NumberAccessTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessFieldInt() throws ScriptException {
    e.eval("var p_int = o.publicInt;");
    assertEquals(o.publicInt, e.get("p_int"));
    e.eval("o.publicInt = 14;");
    assertEquals(14, o.publicInt);
}
 
Example 27
/**
 * Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
 */
@Test
public static void getterSetterTest() 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 = "accessor1";

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
    assertEquals(e.eval("accessor1 = 1;"), 1);
    assertEquals(e.eval(sharedScript), 1);

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
    assertEquals(e.eval("accessor1 = 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("v"), 1);
    assertEquals(e.eval("v", newCtxt), 2);
}
 
Example 28
@Test
public void checkPropertyReadPermissions() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (final String name : propNames) {
        checkProperty(e, name);
    }
}
 
Example 29
@Test
public void accessStaticFieldByte() throws ScriptException {
    e.eval("var ps_byte = SharedObject.publicStaticByte;");
    assertEquals((double)SharedObject.publicStaticByte, ((Number)e.get("ps_byte")).doubleValue());
    e.eval("SharedObject.publicStaticByte = 16;");
    assertEquals(16, SharedObject.publicStaticByte);
}
 
Example 30
Source Project: smockin   Source File: JavaScriptResponseHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeJS_string_func_Test() throws ScriptException {

    final String helloFunction = "function helloMrSmith(name) {"
            + "return 'Hello Mr ' + name + ' Smith' "
            + "}";

    final Object response = javaScriptResponseHandler.executeJS(
            helloFunction
            + " helloMrSmith('James')");

    Assert.assertNotNull(response);
    Assert.assertTrue(response instanceof String);
    Assert.assertEquals("Hello Mr James Smith", response);
}