Java Code Examples for javax.script.ScriptEngineFactory

The following are top voted examples for showing how to use javax.script.ScriptEngineFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: JFXActionProvider.java   View source code 6 votes vote down vote up
private boolean isJavaScriptAvailable() {
    if(isJSAvailableChecked) {
        return isJSAvailable;
    }
    ScriptEngineManager mgr = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = mgr.getEngineFactories();
    for (ScriptEngineFactory factory: factories) {
        List<String> engNames = factory.getNames();
        for(String name: engNames) {
            if(name.equalsIgnoreCase("js") || name.equalsIgnoreCase("javascript")) { //NOI18N
                isJSAvailableChecked = true;
                isJSAvailable = true;
                return isJSAvailable;
            }
        }
    }
    isJSAvailableChecked = true;
    isJSAvailable = false;
    return isJSAvailable;
}
 
Example 2
Project: incubator-netbeans   File: J2SEDeployActionProvider.java   View source code 6 votes vote down vote up
private boolean isJavaScriptAvailable() {
    if(isJSAvailableChecked) {
        return isJSAvailable;
    }
    ScriptEngineManager mgr = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = mgr.getEngineFactories();
    for (ScriptEngineFactory factory: factories) {
        List<String> engNames = factory.getNames();
        for(String name: engNames) {
            if(name.equalsIgnoreCase("js") || name.equalsIgnoreCase("javascript")) { //NOI18N
                isJSAvailableChecked = true;
                isJSAvailable = true;
                return isJSAvailable;
            }
        }
    }
    isJSAvailableChecked = true;
    isJSAvailable = false;
    return isJSAvailable;
}
 
Example 3
Project: incubator-netbeans   File: NbPacScriptEvaluator.java   View source code 6 votes vote down vote up
private String getEngineInfo(ScriptEngine engine) {
    StringBuilder sb = new StringBuilder();
    ScriptEngineFactory f = engine.getFactory();
    sb.append("LanguageName=");
    sb.append("\"").append(f.getLanguageName()).append("\"");
    sb.append(" ");
    sb.append("LanguageVersion=");
    sb.append("\"").append(f.getLanguageVersion()).append("\"");
    sb.append(" ");
    sb.append("EngineName=");
    sb.append("\"").append(f.getEngineName()).append("\"");
    sb.append(" ");
    sb.append("EngineNameAliases=");
    sb.append(Arrays.toString(f.getNames().toArray(new String[f.getNames().size()])));
    sb.append(" ");
    sb.append("EngineVersion=");
    sb.append("\"").append(f.getEngineVersion()).append("\"");
    return sb.toString();
}
 
Example 4
Project: unitimes   File: ScriptOptionsBackend.java   View source code 6 votes vote down vote up
@Override
@PreAuthorize("checkPermission('Scripts')")
public ScriptOptionsInterface execute(GetScriptOptionsRpcRequest request, SessionContext context) {
	ScriptOptionsInterface options = new ScriptOptionsInterface();
	
	for (ScriptEngineFactory factory: new ScriptEngineManager().getEngineFactories())
		options.addEngine(factory.getLanguageName());
	
	for (Right right: Right.values()) {
		if (!right.hasType() || right.type().equals(Session.class) || right.type().equals(Department.class) || right.type().equals(SubjectArea.class))
			options.addPermission(right.toString());
	}
	
	options.setCanAdd(context.hasPermission(Right.ScriptEdit));
	
	return options;
}
 
Example 5
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test of iterator() to test iteration order. Providers deployed
 * as named modules should be found before providers deployed on the class
 * path.
 */
@Test
public void testIteratorOrder() {
    ServiceLoader<ScriptEngineFactory> loader
        = ServiceLoader.load(ScriptEngineFactory.class);
    boolean foundUnnamed = false;
    for (ScriptEngineFactory factory : collectAll(loader)) {
        if (factory.getClass().getModule().isNamed()) {
            if (foundUnnamed) {
                assertTrue(false, "Named module element after unnamed");
            }
        } else {
            foundUnnamed = true;
        }
    }
}
 
Example 6
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test of the public static provider method. BananaScriptEngine
 * defines a provider method that returns the same instance.
 */
@Test
public void testSingleton() {
    Optional<Provider<ScriptEngineFactory>> oprovider
        = ServiceLoader.load(ScriptEngineFactory.class)
            .stream()
            .filter(p -> p.type().getName().equals("org.banana.BananaScriptEngineFactory"))
            .findFirst();
    assertTrue(oprovider.isPresent());
    Provider<ScriptEngineFactory> provider = oprovider.get();

    // invoke Provider::get twice
    ScriptEngineFactory factory1 = provider.get();
    ScriptEngineFactory factory2 = provider.get();
    assertTrue(factory1 == factory2);
}
 
Example 7
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test of stream() to ensure that elements for providers in named
 * modules come before elements for providers in unnamed modules.
 */
@Test
public void testStreamOrder() {
    List<Class<?>> types = ServiceLoader.load(ScriptEngineFactory.class)
            .stream()
            .map(Provider::type)
            .collect(Collectors.toList());

    boolean foundUnnamed = false;
    for (Class<?> factoryClass : types) {
        if (factoryClass.getModule().isNamed()) {
            if (foundUnnamed) {
                assertTrue(false, "Named module element after unnamed");
            }
        } else {
            foundUnnamed = true;
        }
    }
}
 
Example 8
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test ServiceLoader.load specifying the platform class loader.
 * The providers on the module path and class path should not be located.
 */
@Test
public void testWithPlatformClassLoader() {
    ClassLoader pcl = ClassLoader.getPlatformClassLoader();

    // iterator
    ServiceLoader<ScriptEngineFactory> loader
        = ServiceLoader.load(ScriptEngineFactory.class, pcl);
    Set<String> names = collectAll(loader)
            .stream()
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertFalse(names.contains("BananaScriptEngine"));
    assertFalse(names.contains("PearScriptEngine"));

    // stream
    names = ServiceLoader.load(ScriptEngineFactory.class, pcl)
            .stream()
            .map(Provider::get)
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertFalse(names.contains("BananaScriptEngine"));
    assertFalse(names.contains("PearScriptEngine"));
}
 
Example 9
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test of ServiceLoader.load, using the class loader for
 * a module in a custom layer as the context.
 */
@Test
public void testWithCustomLayer1() {
    ModuleLayer layer = createCustomLayer("bananascript");

    ClassLoader loader = layer.findLoader("bananascript");
    List<ScriptEngineFactory> providers
        = collectAll(ServiceLoader.load(ScriptEngineFactory.class, loader));

    // should have at least 2 x bananascript + pearscript
    assertTrue(providers.size() >= 3);

    // first element should be the provider in the custom layer
    ScriptEngineFactory factory = providers.get(0);
    assertTrue(factory.getClass().getClassLoader() == loader);
    assertTrue(factory.getClass().getModule().getLayer() == layer);
    assertTrue(factory.getEngineName().equals("BananaScriptEngine"));

    // remainder should be the boot layer
    providers.remove(0);
    Set<String> names = providers.stream()
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertTrue(names.contains("BananaScriptEngine"));
    assertTrue(names.contains("PearScriptEngine"));
}
 
Example 10
Project: openjdk-jdk10   File: ModulesTest.java   View source code 6 votes vote down vote up
/**
 * Basic test of ServiceLoader.load using a custom Layer as the context.
 */
@Test
public void testWithCustomLayer2() {
    ModuleLayer layer = createCustomLayer("bananascript");

    List<ScriptEngineFactory> factories
        = collectAll(ServiceLoader.load(layer, ScriptEngineFactory.class));

    // should have at least 2 x bananascript
    assertTrue(factories.size() >= 2);

    // first element should be the provider in the custom layer
    ScriptEngineFactory factory = factories.get(0);
    assertTrue(factory.getClass().getModule().getLayer() == layer);
    assertTrue(factory.getEngineName().equals("BananaScriptEngine"));

    // remainder should be the boot layer
    factories.remove(0);
    Set<String> names = factories.stream()
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertTrue(names.contains("BananaScriptEngine"));
    assertFalse(names.contains("PearScriptEngine"));
}
 
Example 11
Project: openjdk-jdk10   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 12
Project: openjdk-jdk10   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 13
Project: openjdk-jdk10   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 14
Project: openjdk-jdk10   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 15
Project: openjdk9   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 16
Project: openjdk9   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 17
Project: openjdk9   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 18
Project: openjdk9   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 19
Project: openbravo-brazil   File: EvaluationTest.java   View source code 6 votes vote down vote up
/**
 * Tests the evaluation of a simple java script expression executed on a set of objects.
 */
@Test
public void testEvaluation() {
  setSystemAdministratorContext();

  // as a test print scripting language names
  final ScriptEngineManager manager = new ScriptEngineManager();
  for (final ScriptEngineFactory sef : manager.getEngineFactories()) {
    log.debug(sef.getEngineName());
  }

  final List<Table> tables = OBDal.getInstance().createCriteria(Table.class).list();
  boolean found = false;
  for (final Table t : tables) {
    final String script = Table.PROPERTY_CLIENT + "." + Client.PROPERTY_ID + " == '0' && "
        + Table.PROPERTY_DBTABLENAME + "== 'AD_Client' && " + Table.PROPERTY_DATAACCESSLEVEL
        + " > 5";
    final Boolean result = Evaluator.getInstance().evaluateBoolean(t, script);
    log.debug(t.getName() + " : " + result);
    found = found || result;
    if (found) {
      break;
    }
  }
  assertTrue(found);
}
 
Example 20
Project: kaziranga   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 21
Project: kaziranga   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 22
Project: kaziranga   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 23
Project: kaziranga   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 24
Project: lookaside_java-1.8.0-openjdk   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 25
Project: lookaside_java-1.8.0-openjdk   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 26
Project: lookaside_java-1.8.0-openjdk   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 27
Project: lookaside_java-1.8.0-openjdk   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 28
Project: jdk8u_nashorn   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 29
Project: jdk8u_nashorn   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 30
Project: jdk8u_nashorn   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 31
Project: jdk8u_nashorn   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 32
Project: Camel   File: ScriptBuilder.java   View source code 6 votes vote down vote up
protected static ScriptEngineFactory lookupScriptEngineFactory(String language) {
    ScriptEngineManager manager = new ScriptEngineManager();
    for (ScriptEngineFactory factory : manager.getEngineFactories()) {
        // some script names has alias
        String[] names = getScriptNames(language);
        for (String name : names) {
            if (factory.getLanguageName().equals(name)) {
                return factory;
            }
        }
    }

    // fallback to get engine by name
    ScriptEngine engine = createScriptEngine(language, true);
    if (engine != null) {
        return engine.getFactory();
    }
    return null;
}
 
Example 33
Project: binnavi   File: LanguageBox.java   View source code 6 votes vote down vote up
private void fillLanguageBox(final ScriptEngineManager manager) {
  final List<ScriptEngineFactory> factories = manager.getEngineFactories();

  final List<ScriptingLanguage> languages = new ArrayList<ScriptingLanguage>();

  for (final ScriptEngineFactory factory : factories) {
    // Disable Rhino scripting engine for JavaScript / ECMAScript.
    if (factory.getLanguageName().equals("python")) {
      languages
          .add(new ScriptingLanguage(factory.getLanguageName(), factory.getLanguageVersion()));
    }
  }

  Collections.sort(languages);

  for (final ScriptingLanguage language : languages) {
    addItem(language);
  }
}
 
Example 34
Project: JythonExample   File: JythonExample.java   View source code 6 votes vote down vote up
/**
 * Display all script engines.
 */
public static void listEngines() {
  final ScriptEngineManager mgr = new ScriptEngineManager();
  final List<ScriptEngineFactory> factories =
      mgr.getEngineFactories();
  for (final ScriptEngineFactory factory: factories) {
    System.out.println("ScriptEngineFactory Info");

    final String engName = factory.getEngineName();
    final String engVersion = factory.getEngineVersion();
    final String langName = factory.getLanguageName();
    final String langVersion = factory.getLanguageVersion();

    System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);

    final List<String> engNames = factory.getNames();
    for (final String name: engNames) {
      System.out.printf("\tEngine Alias: %s\n", name);
    }
    System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
  }
}
 
Example 35
Project: jjsb4a   File: JSR223Demo.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine engine = m.getEngineByMimeType("application/javascript");
    if (engine != null) {

        // workaround until we find a way to get a headless WebView object
        WebView wv = new WebView(getBaseContext());
        ((JJSBridge4AndroidEngine) engine).setView(wv);

        Log.d(TAG, ScriptEngine.NAME + " " + engine.get(ScriptEngine.NAME));
        Log.d(TAG, ScriptEngine.ENGINE + " " + engine.get(ScriptEngine.ENGINE));

        ScriptEngineFactory f = engine.getFactory();
        String program = f.getOutputStatement("\"Hello world\"");
        try {
            engine.eval(program);
        } catch (ScriptException ex) {
            Log.e(TAG, "eval()", ex);
        }
    }
}
 
Example 36
Project: scripturian   File: Jsr223LanguageAdapter.java   View source code 6 votes vote down vote up
/**
 * Constructor. Uses the JSR-223 script engine factory to gather the
 * language adapter attributes. Sub-classes must be annotated with
 * {@link ScriptEngines}.
 * 
 * @throws LanguageAdapterException
 */
public Jsr223LanguageAdapter() throws LanguageAdapterException
{
	ScriptEngines scriptEngineNames = getClass().getAnnotation( ScriptEngines.class );
	if( scriptEngineNames == null )
		throw new LanguageAdapterException( getClass(), getClass().getCanonicalName() + " does not have a ScriptEngines annotation" );

	String scriptEngineName = scriptEngineNames.value()[0];
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
	scriptEngine = scriptEngineManager.getEngineByName( scriptEngineName );
	if( scriptEngine == null )
		throw new LanguageAdapterException( getClass(), getClass().getCanonicalName() + " could not load ScriptEngine " + scriptEngineName );

	ScriptEngineFactory factory = scriptEngine.getFactory();

	attributes.put( NAME, "JSR-223/" + factory.getEngineName() );
	attributes.put( VERSION, factory.getEngineVersion() );
	attributes.put( LANGUAGE_NAME, factory.getLanguageName() );
	attributes.put( LANGUAGE_VERSION, factory.getLanguageVersion() );
	attributes.put( EXTENSIONS, new ArrayList<String>( factory.getExtensions() ) );
	attributes.put( DEFAULT_EXTENSION, factory.getExtensions().get( 0 ) );
	attributes.put( TAGS, Arrays.asList( scriptEngineNames.value() ) );
	attributes.put( DEFAULT_TAG, factory.getNames().get( 0 ) );

	attributes.put( JSR223_SCRIPT_ENGINE_NAME, scriptEngineName );
}
 
Example 37
Project: scheduling   File: Script.java   View source code 6 votes vote down vote up
private Map<ScriptEngine, Integer> findScriptEngineCandidates(boolean findByName) {
    Map<ScriptEngine, Integer> matchPositionPerScriptEngineCandidate = new HashMap<>();
    int matchPosition;
    List<String> lookupCriteria;

    for (ScriptEngineFactory factory : new ScriptEngineManager().getEngineFactories()) {
        matchPosition = 0;
        if (findByName) {
            lookupCriteria = factory.getNames();
        } else {
            lookupCriteria = factory.getExtensions();
        }

        for (String criteria : lookupCriteria) {
            if (criteria.equalsIgnoreCase(scriptEngineLookupName)) {
                matchPositionPerScriptEngineCandidate.put(factory.getScriptEngine(), matchPosition);
            }
            matchPosition++;
        }
    }

    return matchPositionPerScriptEngineCandidate;
}
 
Example 38
Project: openhab-hdl   File: ScriptManager.java   View source code 6 votes vote down vote up
public ScriptManager(RuleTriggerManager triggerManager, ItemRegistry itemRegistry) {
	this.triggerManager = triggerManager;
	instance = this;
	logger.info("Available engines:");
	for (ScriptEngineFactory f : new ScriptEngineManager().getEngineFactories()) {
		logger.info(f.getEngineName());
	}

	this.setItemRegistry(itemRegistry);

	File folder = getFolder("scripts");

	if (folder.exists() && folder.isDirectory()) {
		loadScripts(folder);

		scriptUpdateWatcher = new Thread(new ScriptUpdateWatcher(this, folder));
		scriptUpdateWatcher.start();
	} else {
		logger.warn("Script directory: jsr_scripts missing, no scripts will be added!");
	}
}
 
Example 39
Project: search   File: StatelessScriptUpdateProcessorFactory.java   View source code 6 votes vote down vote up
/**
 * For error messages - returns null if there are any exceptions of any 
 * kind building the string (or of the list is empty for some unknown reason).
 * @param ext - if true, list of extensions, otherwise a list of engine names
 */
private static String getSupportedEngines(ScriptEngineManager mgr,
                                          boolean ext) {
  String result = null;
  try {
    List<ScriptEngineFactory> factories = mgr.getEngineFactories();
    if (null == factories) return result;

    Set<String> engines = new LinkedHashSet<>(factories.size());
    for (ScriptEngineFactory f : factories) {
      if (ext) {
        engines.addAll(f.getExtensions());
      } else {
        engines.addAll(f.getNames());
      }
    }
    result = StringUtils.join(engines, ", ");
  } catch (RuntimeException e) {
    /* :NOOP: */
  }
  return result;
}
 
Example 40
Project: infobip-open-jdk-8   File: TrustedScriptEngineTest.java   View source code 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}