Example usage for javax.script ScriptEngineManager getEngineByName

List of usage examples for javax.script ScriptEngineManager getEngineByName

Introduction

In this page you can find the example usage for javax.script ScriptEngineManager getEngineByName.

Prototype

public ScriptEngine getEngineByName(String shortName) 

Source Link

Document

Looks up and creates a ScriptEngine for a given name.

Usage

From source file:org.jdto.mergers.ScriptMerger.java

private ScriptEngine initializeScriptEngine(String[] extraParam) {
    String engineName = DEFAULT_SCRIPT_ENGINE;

    //the script engine may be configured as the second parameter.
    if (extraParam.length > 1 && !StringUtils.isEmpty(extraParam[1])) {
        engineName = extraParam[1];//from w ww . ja  v  a  2  s  .c o  m
    }

    //TODO - REVIEW IF THIS IS SAFE TO INSTANTIATE ALL THE TIME
    ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();

    //TODO - REVIEW IF THIS IS SAFE TO INSTANTIATE ALL THE TIME
    ScriptEngine engine = scriptEngineMgr.getEngineByName(engineName);

    if (engine == null) {
        logger.error("Engine " + engineName + " not found!.");
        throw new IllegalArgumentException("No scripting engine " + "could be found with name: " + engineName);
    }

    return engine;
}

From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java

@Test
public void serviceShouldBeDeclared() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);//from ww  w .  j  a va2  s  .  co m

    InputStream stream = this.getClass().getResourceAsStream("/checkWrapper.js");
    assertNotNull(stream);
    engine.eval(scriptingService.getJSWrapper());
    engine.eval(IOUtils.toString(stream));
    assertEquals("Hello" + System.lineSeparator(), outContent.toString());
}

From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> grouping_fields) {
    // This is currently fixed:
    java_api.set(true);//from   w ww.  j av  a2s .co  m

    final JsScriptEngineBean config_bean = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()),
                    JsScriptEngineBean.class)
            .get();
    _config.trySet(config_bean);
    _context.trySet(context);
    _control.trySet(control);

    // Initialize script engine:
    ScriptEngineManager manager = new ScriptEngineManager();
    _engine.trySet(manager.getEngineByName("JavaScript"));
    _script_context.trySet(_engine.get().getContext()); // (actually not needed since we're compiling things)

    _bucket_logger.set(context.getLogger(Optional.of(bucket)));

    // Load globals:
    _engine.get().put("_a2_global_context", _context.get());
    _engine.get().put("_a2_global_grouping_fields", grouping_fields.orElse(Collections.emptyList()));
    _engine.get().put("_a2_global_previous_stage", previous_next._1().toString());
    _engine.get().put("_a2_global_next_stage", previous_next._2().toString());
    _engine.get().put("_a2_global_bucket", bucket);
    _engine.get().put("_a2_global_config", BeanTemplateUtils.configureMapper(Optional.empty())
            .convertValue(config_bean.config(), JsonNode.class));
    _engine.get().put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
    _engine.get().put("_a2_bucket_logger", _bucket_logger.optional().orElse(null));
    _engine.get().put("_a2_enrichment_name", Optional.ofNullable(control.name()).orElse("no_name"));

    // Load the resources:
    Stream.concat(config_bean.imports().stream(),
            Stream.of("aleph2_js_globals_before.js", "", "aleph2_js_globals_after.js"))
            .flatMap(Lambdas.flatWrap_i(import_path -> {
                try {
                    if (import_path.equals("")) { // also import the user script just before here
                        return config_bean.script();
                    } else
                        return IOUtils.toString(
                                JsScriptEngineService.class.getClassLoader().getResourceAsStream(import_path),
                                "UTF-8");
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (script {1}): {2}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), import_path,
                                    e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            })).forEach(Lambdas.wrap_consumer_i(script -> {
                try {
                    _engine.get().eval(script);
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (main script): {1}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            }));
    ;
}

From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java

@Test
public void testNashornWithCompile() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);//from   w w  w  .ja v  a 2  s  .com

    Compilable compiler = (Compilable) engine;
    assertNotNull(compiler);

    InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js");
    assertNotNull(stream);
    String js = IOUtils.toString(stream);

    CompiledScript compiled = compiler.compile(new StringReader(js));

    engine.put("mapper", new Mapper());

    compiled.eval(engine.getContext());
    assertEquals("1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]"
            + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string"
            + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2"
            + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}"
            + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString());
}

From source file:uk.co.edgeorgedev.notifj.notification.growl.OSXGrowlNotification.java

/**
 * Creates new ApppleScript Engine which is used to create notifications
 * @throws NotificationOperatingSystemException if the system operating system is <i>not</i> Mac OSX
 * @since   1.0//from   w  w w.ja v a 2s. c  om
 */
@Override
public void open() throws NotificationException {
    if (!SystemUtils.IS_OS_MAC_OSX)
        throw new NotificationOperatingSystemException("Operating System is not Mac OSX");

    ScriptEngineManager engineManager = new ScriptEngineManager();
    mScriptEngine = engineManager.getEngineByName("AppleScript");
}

From source file:org.xwiki.rendering.macro.script.AbstractJSR223ScriptMacro.java

/**
 * @param engineName the script engine name (eg "groovy", etc)
 * @return the Script engine to use to evaluate the script
 * @throws MacroExecutionException in case of an error in parsing the jars parameter
 *//*  w w w .j  a  v a2s  .com*/
private ScriptEngine getScriptEngine(String engineName) throws MacroExecutionException {
    // Look for a script engine in the Execution Context since we want the same engine to be used
    // for all evals during the same execution lifetime.
    // We must use the same engine because that engine may create an internal ClassLoader in which
    // it loads new classes defined in the script and if we create a new engine then defined classes
    // will be lost.
    // However we also need to be able to execute several script Macros during a single execution request
    // and for example the second macro could have jar parameters. In order to support this use case
    // we ensure in AbstractScriptMacro to reuse the same thread context ClassLoader during the whole
    // request execution.
    ExecutionContext executionContext = this.execution.getContext();
    Map<String, ScriptEngine> scriptEngines = (Map<String, ScriptEngine>) executionContext
            .getProperty(EXECUTION_CONTEXT_ENGINE_KEY);
    if (scriptEngines == null) {
        scriptEngines = new HashMap<String, ScriptEngine>();
        executionContext.setProperty(EXECUTION_CONTEXT_ENGINE_KEY, scriptEngines);
    }
    ScriptEngine engine = scriptEngines.get(engineName);

    if (engine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        engine = sem.getEngineByName(engineName);
        scriptEngines.put(engineName, engine);
    }

    return engine;
}

From source file:org.jgentleframework.integration.scripting.ScriptingInstantiationInterceptor.java

@Override
public Object instantiate(ObjectInstantiation oi) throws Throwable {

    Object result = null;//  www  . j a v a  2s.com
    Class<?> target = oi.getTargetClass();
    Definition definition = this.definitionManager.getDefinition(target);
    if (definition.isAnnotationPresent(ScriptingInject.class)) {
        if (!target.isInterface()) {
            if (log.isFatalEnabled()) {
                log.fatal("Could not binding to Scripting service",
                        new ScriptException("Target class must be a interface!"));
            }
        }
        final ScriptingInject scriptingInject = definition.getAnnotation(ScriptingInject.class);
        Object previous = oi.getPreviousResult();
        if (previous == null) {
            ScriptEngineManager engineManager = new ScriptEngineManager();
            ScriptEngine engine = engineManager.getEngineByName(scriptingInject.lang().getType());
            if (engine == null) {
                if (log.isFatalEnabled()) {
                    log.fatal(
                            "Script engine with name : " + scriptingInject.lang().getType() + " is not found!",
                            new ScriptException("Script engine with name : " + scriptingInject.lang().getType()
                                    + " is not found!"));
                }
                throw new ScriptException(
                        "Script engine with name : " + scriptingInject.lang().getType() + " is not found!");
            }
            File parentFile = null;
            if (!(PathType.CLASSPATH.equals(scriptingInject.pathType())
                    || PathType.CLASSPATH.equals(scriptingInject.pathType()))) {
                parentFile = new File(scriptingInject.pathType().getType());
            }
            File sourceFile = null;
            if (parentFile != null) {
                sourceFile = new File(parentFile, scriptingInject.scriptFile());
            } else {
                if (PathType.CLASSPATH.equals(scriptingInject.pathType())) {
                    sourceFile = new File(ScriptingInstantiationInterceptor.class
                            .getResource(scriptingInject.scriptFile()).toURI());
                } else {
                    sourceFile = new File(scriptingInject.scriptFile());
                }
            }
            engine.eval(new FileReader(sourceFile));
            Invocable inv = (Invocable) engine;
            final Object scriptObject = inv.getInterface(target);
            result = scriptObject;
            final Enhancer enhancer = new Enhancer();
            enhancer.setInterfaces(new Class<?>[] { target });
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                        throws Throwable {

                    if (method.getName().equals("hashCode")) {
                        final int prime = 31;
                        int result = 1;
                        result = prime * result + super.hashCode();
                        result = prime * result + enhancer.hashCode();
                        return result;
                    } else {
                        MethodInvocation invocation = new BasicMethodInvocation(obj, method, args);
                        return invoke(invocation, scriptObject);
                    }
                }

                protected Object invoke(MethodInvocation invocation, Object stub) throws NoSuchMethodException,
                        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

                    Object result = null;
                    Method method = null;
                    Method methodType = invocation.getMethod();
                    Class<?> clazz = stub.getClass();
                    Class<?>[] classType = ReflectUtils.getClassTypeOf(invocation.getArguments());
                    method = ReflectUtils.getSupportedMethod(clazz, methodType.getName(), classType);
                    result = method.invoke(stub, invocation.getArguments());
                    return result;
                }
            });
            if (oi.args() != null && oi.argTypes() != null)
                result = enhancer.create(oi.argTypes(), oi.args());
            else
                result = enhancer.create();
            oi.setPreviousResult(result);
        } else {
            if (log.isFatalEnabled()) {
                log.fatal(
                        "Does not support multible Instantiation Interceptor "
                                + "conjointly with Scripting Instantiation",
                        new ScriptException("Does not support multible Instantiation Interceptor!"));
            }
        }
        return oi.proceed();
    } else {
        if (log.isWarnEnabled()) {
            log.warn("The target interface is not annotated with [" + ScriptingInject.class + "]");
        }
    }
    return result;
}

From source file:de.ingrid.mdek.mapping.ScriptImportDataMapper.java

/**
 * Get the script engine (JavaScript). It returns always the same instance once initialized.
 * //from  ww  w . j a v  a  2 s .com
 * @return script engine.
 */
protected ScriptEngine getScriptEngine() {
    if (engine == null) {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript");
    }
    return engine;
}

From source file:org.nyu.edu.dlts.CodeViewerDialog.java

/**
 * Method to evaluate the syntax of the script.
 * Basically try running and see if any syntax errors occur
 *//*from   w ww .j  a v a2 s. c  o m*/
private void evaluateButtonActionPerformed() {
    try {
        if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_JAVA)) {
            Interpreter bsi = new Interpreter();
            bsi.set("record", new String("Test"));
            bsi.set("recordType", "test");
            bsi.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_RUBY)) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jri = manager.getEngineByName("jruby");
            jri.put("recordType", "test");
            jri.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_PYTHON)) {
            PythonInterpreter pyi = new PythonInterpreter();
            pyi.set("record", new String("Test"));
            pyi.set("recordType", "test");
            pyi.exec(getCurrentScript());
        } else {
            // must be java script
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jsi = manager.getEngineByName("javascript");
            jsi.put("record", new String("Test"));
            jsi.put("recordType", "test");
            jsi.eval(getCurrentScript());
        }

        messageTextArea.setText("No Syntax Errors Found ...");
    } catch (Exception e) {
        messageTextArea.setText("Error Occurred:\n" + dbCopyFrame.getStackTrace(e));
    }
}

From source file:net.sf.keystore_explorer.utilities.net.PacProxySelector.java

private Invocable compilePacScript(String pacScript) throws PacProxyException {
    try {/*from w w  w  .  j a  va 2s  .c o  m*/
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");

        Invocable invocale = (Invocable) jsEngine;

        jsEngine.eval(pacScript);
        jsEngine.eval(new InputStreamReader(PacProxySelector.class.getResourceAsStream("pacUtils.js")));

        return invocale;
    } catch (ScriptException ex) {
        throw new PacProxyException(res.getString("NoCompilePacScript.exception.message"), ex);
    }
}