Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

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

Prototype

public ScriptEngineManager() 

Source Link

Document

The effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

Usage

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 www  .  j  a va2s . c  o  m
 */
@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.mule.module.scripting.component.Scriptable.java

public void initialise() throws InitialisationException {
    scriptEngineManager = new ScriptEngineManager();

    // Create scripting engine
    if (scriptEngineName != null) {
        scriptEngine = createScriptEngineByName(scriptEngineName);
        if (scriptEngine == null) {
            throw new InitialisationException(MessageFactory.createStaticMessage("Scripting engine '"
                    + scriptEngineName + "' not found.  Available engines are: " + listAvailableEngines()),
                    this);
        }//from www  . j a va  2 s  . c  om
    }
    // Determine scripting engine to use by file extension
    else if (scriptFile != null) {
        int i = scriptFile.lastIndexOf(".");
        if (i > -1) {
            logger.info("Script Engine name not set. Guessing by file extension.");
            String ext = scriptFile.substring(i + 1);
            scriptEngine = createScriptEngineByExtension(ext);
            if (scriptEngine == null) {
                throw new InitialisationException(MessageFactory.createStaticMessage("File extension '" + ext
                        + "' does not map to a scripting engine.  Available engines are: "
                        + listAvailableEngines()), this);
            } else {
                setScriptEngineName(scriptEngine.getFactory().getEngineName());
            }
        }
    }

    Reader script;
    // Load script from variable
    if (StringUtils.isNotBlank(scriptText)) {
        script = new StringReader(scriptText);
    }
    // Load script from file
    else if (scriptFile != null) {
        InputStream is;
        try {
            is = IOUtils.getResourceAsStream(scriptFile, getClass());
        } catch (IOException e) {
            throw new InitialisationException(CoreMessages.cannotLoadFromClasspath(scriptFile), e, this);
        }
        if (is == null) {
            throw new InitialisationException(CoreMessages.cannotLoadFromClasspath(scriptFile), this);
        }
        script = new InputStreamReader(is);
    } else {
        throw new InitialisationException(CoreMessages.propertiesNotSet("scriptText, scriptFile"), this);
    }

    // Pre-compile script if scripting engine supports compilation.
    if (scriptEngine instanceof Compilable) {
        try {
            compiledScript = ((Compilable) scriptEngine).compile(script);
        } catch (ScriptException e) {
            throw new InitialisationException(e, this);
        }
    }
}

From source file:com.xafero.vee.cmd.MainApp.java

private static void printLanguages() {
    ScriptEngineManager mgr = new ScriptEngineManager();
    for (ScriptEngineFactory factory : mgr.getEngineFactories())
        System.out.println(MoreObjects.toStringHelper("").add("name", factory.getEngineName())
                .add("version", factory.getEngineVersion())
                .add("extensions", "[ " + Strings.join(" | ", factory.getExtensions()) + " ]")
                .add("mimeTypes", "[ " + Strings.join(" | ", factory.getMimeTypes()) + " ]")
                .add("aliases", "[ " + Strings.join(" | ", factory.getNames()) + " ]")
                .add("language", factory.getLanguageName() + " " + factory.getLanguageVersion())
                .omitNullValues().toString().replace(", ", String.format(", %n ")));
}

From source file:org.craftercms.engine.scripting.impl.Jsr233CompiledScriptFactory.java

@PostConstruct
public void init() {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    scriptEngine = (Compilable) scriptEngineManager.getEngineByName(scriptEngineName);
}

From source file:org.pentaho.platform.plugin.condition.scriptable.ScriptableCondition.java

public boolean shouldExecute(final Map currentInputs, final Log logger) throws Exception {
    boolean shouldExecute = this.getDefaultResult();
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName(this.getScriptLanguage());
    if (engine == null) {
        throw new IllegalArgumentException(Messages.getInstance().getErrorString(
                "ScriptableCondition.ERROR_0001_ENGINE_NOT_AVAILABLE", this.getScriptLanguage())); //$NON-NLS-1$
    }//w w w  . jav a  2s  .  co  m
    Object inputValue;
    IActionParameter inputParameter;
    String inputName = null;
    Iterator inputs = currentInputs.entrySet().iterator();
    Map.Entry mapEntry;
    while (inputs.hasNext()) {
        mapEntry = (Map.Entry) inputs.next();
        inputName = (String) mapEntry.getKey();
        if (this.getIgnoreInputNamesWithMinus() && inputName.indexOf('-') >= 0) {
            logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_IGNORED_INPUT", inputName)); //$NON-NLS-1$
            continue;
        }
        inputParameter = (IActionParameter) mapEntry.getValue();
        inputValue = inputParameter.getValue();
        engine.put(inputName, inputValue); // What happens to resultset objects I wonder...
    }
    engine.put("out", System.out);
    engine.put("rule", this);
    Object resultObject = engine.eval(this.getScript());
    if (resultObject instanceof Boolean) {
        return ((Boolean) resultObject).booleanValue();
    } else if (resultObject instanceof String) {
        return ("true".equalsIgnoreCase(resultObject.toString()))
                || ("yes".equalsIgnoreCase(resultObject.toString())); //$NON-NLS-1$ //$NON-NLS-2$
    } else if (resultObject instanceof Number) {
        return ((Number) resultObject).intValue() > 0;
    } else if (resultObject instanceof IPentahoResultSet) {
        return ((IPentahoResultSet) resultObject).getRowCount() > 0;
    }
    logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_DEFAULT_RESULT_RETURNED")); //$NON-NLS-1$
    return shouldExecute;
}

From source file:de.ingrid.iplug.dscmapclient.index.mapper.ScriptedWmsDocumentMapper.java

@Override
public ElasticDocument map(SourceRecord record, ElasticDocument doc) throws Exception {
    if (mappingScript == null) {
        log.error("Mapping script is not set!");
        throw new IllegalArgumentException("Mapping script is not set!");
    }//from  w  w w .j av a2s . com
    try {
        if (engine == null) {
            String scriptName = mappingScript.getFilename();
            String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length());
            ScriptEngineManager mgr = new ScriptEngineManager();
            engine = mgr.getEngineByExtension(extension);
            if (compile) {
                if (engine instanceof Compilable) {
                    Compilable compilable = (Compilable) engine;
                    compiledScript = compilable.compile(new InputStreamReader(mappingScript.getInputStream()));
                }
            }
        }

        // create utils for script

        CapabilitiesUtils capabilitiesUtils = new CapabilitiesUtils();
        capabilitiesUtils.setUrlStr((String) record.get(SourceRecord.ID));

        if (log.isDebugEnabled()) {
            log.debug("Requesting " + capabilitiesUtils.getUrlStr());
        }
        org.w3c.dom.Document wmsDoc = capabilitiesUtils.requestCaps();
        // we check for null and return -> NO Exception, so oncoming URLs are processed
        if (wmsDoc == null) {
            log.warn("!!! Problems requesting " + capabilitiesUtils.getUrlStr()
                    + " !!! We return null Document so will not be indexed !");
            return null;
        }
        //we put the xmlDoc(WMS doc) into the record and thereby pass it to the idf-mapper 
        record.put("WmsDoc", wmsDoc);

        IndexUtils idxUtils = new IndexUtils(doc);
        XPathUtils xPathUtils = new XPathUtils(new IDFNamespaceContext());

        Bindings bindings = engine.createBindings();
        bindings.put("wmsDoc", wmsDoc);
        bindings.put("log", log);
        bindings.put("CAP", capabilitiesUtils);
        bindings.put("IDX", idxUtils);
        bindings.put("XPATH", xPathUtils);
        bindings.put("javaVersion", System.getProperty("java.version"));

        if (compiledScript != null) {
            compiledScript.eval(bindings);
        } else {
            engine.eval(new InputStreamReader(mappingScript.getInputStream()), bindings);
        }

        return doc;

    } catch (Exception e) {
        log.error("Error mapping source record to lucene document.", e);
        e.printStackTrace();
        throw e;
    }

}

From source file:org.ngrinder.operation.cotroller.ScriptConsoleController.java

/**
 * Run the given script. The run result is stored in "result" of the given model.
 *
 * @param script script//  w w  w.j a  va2s. c  o m
 * @param model  model
 * @return operation/script_console
 */
@RequestMapping("")
public String run(@RequestParam(value = "script", defaultValue = "") String script, Model model) {
    if (StringUtils.isNotBlank(script)) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
        engine.put("applicationContext", this.applicationContext);
        engine.put("agentManager", this.agentManager);
        engine.put("agentManagerService", this.agentManagerService);
        engine.put("regionService", this.regionService);
        engine.put("consoleManager", this.consoleManager);
        engine.put("userService", this.userService);
        engine.put("perfTestService", this.perfTestService);
        engine.put("tagService", this.tagService);
        engine.put("fileEntryService", this.fileEntryService);
        engine.put("config", getConfig());
        engine.put("pluginManager", this.pluginManager);
        engine.put("cacheManager", this.cacheManager);
        engine.put("user", getCurrentUser());
        final StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        engine.getContext().setWriter(writer);
        engine.getContext().setErrorWriter(writer);
        try {
            Object result = engine.eval(script);
            result = out.toString() + "\n" + ObjectUtils.defaultIfNull(result, "");
            model.addAttribute("result", result);
        } catch (ScriptException e) {
            model.addAttribute("result", out.toString() + "\n" + e.getMessage());
        }
    }
    model.addAttribute("script", script);
    return "operation/script_console";
}

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

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

    Object result = null;/*from   w w w . j  a v  a  2s.c o  m*/
    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:cc.arduino.net.CustomProxySelector.java

private Proxy pacProxy(String pac, URI uri) throws IOException, ScriptException, NoSuchMethodException {
    setAuthenticator(preferences.get(Constants.PREF_PROXY_AUTO_USERNAME),
            preferences.get(Constants.PREF_PROXY_AUTO_PASSWORD));

    URLConnection urlConnection = new URL(pac).openConnection();
    urlConnection.connect();/*  w w  w. ja  v  a  2  s.co m*/
    if (urlConnection instanceof HttpURLConnection) {
        int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
        if (responseCode != 200) {
            throw new IOException("Unable to fetch PAC file at " + pac + ". Response code is " + responseCode);
        }
    }
    String pacScript = new String(IOUtils.toByteArray(urlConnection.getInputStream()),
            Charset.forName("ASCII"));

    ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
    nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("pac", new PACSupportMethods());
    Stream.of("isPlainHostName(host)", "dnsDomainIs(host, domain)", "localHostOrDomainIs(host, hostdom)",
            "isResolvable(host)", "isInNet(host, pattern, mask)", "dnsResolve(host)", "myIpAddress()",
            "dnsDomainLevels(host)", "shExpMatch(str, shexp)").forEach((fn) -> {
                try {
                    nashorn.eval("function " + fn + " { return pac." + fn + "; }");
                } catch (ScriptException e) {
                    throw new RuntimeException(e);
                }
            });
    nashorn.eval(pacScript);
    String proxyConfigs = callFindProxyForURL(uri, nashorn);
    return makeProxyFrom(proxyConfigs);
}

From source file:org.callimachusproject.fluid.consumers.HttpJavaScriptResponseWriter.java

public HttpJavaScriptResponseWriter() throws ScriptException {
    String systemId = getSystemId("SCRIPT");
    ScriptEngineManager man = new ScriptEngineManager();
    ScriptEngine engine = man.getEngineByName("rhino");
    engine.put(ScriptEngine.FILENAME, systemId);
    engine.eval(SCRIPT);/*  w  w w  .j av a 2  s  .c om*/
    this.engine = (Invocable) engine;
    this.delegate = new HttpMessageWriter();
}