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:com.github.safrain.remotegsh.server.RgshFilter.java

private ScriptEngine createGroovyEngine() {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
    if (engine == null) {
        log.log(Level.SEVERE, "Groovy engine not found.");
        throw new UnsupportedOperationException("Groovy engine not found.");
    }/*from  www.j  a v a  2s .c  o  m*/
    return engine;
}

From source file:com.ikanow.infinit.e.api.knowledge.federated.SimpleFederatedQueryEngine.java

@Override
public void preQueryActivities(ObjectId queryId, AdvancedQueryPojo query, String[] communityIdStrs) {

    _scoreStats = null;/*from  w  ww.j  av  a 2 s  .c om*/
    _asyncRequestsPerQuery = null;

    // 1] Check whether this makes sense to query, get the (sole) entity if so
    String entityType = null;
    String entityValue = null;
    String entityIndex = null;
    String textToTest = null;
    if ((null != query.qt) && (query.qt.size() > 0) && (query.qt.size() < 4)) {

        String logic = query.logic;
        if (null != logic) {
            logic = logic.toLowerCase();
        }
        if ((null != logic) && (logic.contains("or") || logic.contains("not"))) {
            //DEBUG
            if (_DEBUG)
                _logger.debug("DEB: preQA1: Logic too complex: " + query.logic);
            if (_testMode) {
                throw new RuntimeException("Bad testQueryJson: Logic too complex: " + query.logic);
            }

            return; // logic too complex
        } //TESTED (1.3)
        for (AdvancedQueryPojo.QueryTermPojo qt : query.qt) {
            if ((null != qt.entity) || ((null != qt.entityType) && (null != qt.entityValue))) {
                if (null == entityType) { // we now have == 1 entity 
                    if (null != qt.entityValue) {
                        entityValue = qt.entityValue;
                        entityType = qt.entityType;
                        entityIndex = entityValue.toLowerCase() + "/" + entityType.toLowerCase();
                    } //TESTED (1.5)
                    else {
                        entityIndex = qt.entity.toLowerCase();
                        int index = qt.entity.lastIndexOf('/');
                        if (index > 0) {
                            entityValue = qt.entity.substring(0, index);
                            entityType = qt.entity.substring(index + 1).toLowerCase();
                        }
                    } //TESTED (1.6)
                } else { // >1 entity, not supported
                    //DEBUG
                    if (_DEBUG)
                        _logger.debug("DEB: preQA2a: >1 entity: " + qt.entity + " / " + entityType + " / "
                                + query.toApi());
                    if (_testMode) {
                        throw new RuntimeException("Bad testQueryJson: >1 entity: " + qt.entity + " / "
                                + entityType + " / " + query.toApi());
                    }

                    return;
                } //TESTED (1.4)
            } //TESTED
            else if ((null != qt.etext) && (qt.etext.equals("*"))) {
                //this is fine provided it's only ANDed together (eg above logic case)
            } else if (null != qt.etext) { // Only work if it matches one of the regexes
                if (null == entityType) {
                    textToTest = qt.etext;
                    entityType = "etext";
                } else { // >1 entity, not supported
                    //DEBUG
                    if (_DEBUG)
                        _logger.debug("DEB: preQA2b: >1 entity: " + qt.entity + " / " + entityType + " / "
                                + query.toApi());
                    if (_testMode) {
                        throw new RuntimeException("Bad testQueryJson: >1 entity: " + qt.entity + " / "
                                + entityType + " / " + query.toApi());
                    }

                    return;
                } //TESTED (1.4)               
            } else if (null == qt.time) { // temporal 
                //DEBUG
                if (_DEBUG)
                    _logger.debug("DEB: preQA3: non-entity/date " + query.toApi());
                if (_testMode) {
                    throw new RuntimeException("Bad testQueryJson: non-entity/date " + query.toApi());
                }
                return;
            } //TESTED (1.1)
        } //(end loop over query terms)

    } //TESTED (1.*)
    if (null == entityType) { // Query too complex
        //DEBUG
        if (_DEBUG)
            _logger.debug("DEB: preQA4: query missing entity " + query.toApi());
        if (_testMode) {
            throw new RuntimeException("Bad testQueryJson: query missing entity " + query.toApi());
        }

        return;
    } //TESTED (1.2)
    entityType = entityType.toLowerCase();

    // 2] If so, query across all the end

    for (SourceFederatedQueryConfigPojo endpoint : _endpoints) {

        // Endpoint validation:
        if (null == endpoint.entityTypes) {
            if (_testMode) {
                throw new RuntimeException("No entity types specified");
            } else {
                continue;
            }
        }
        if (null != textToTest) { // This is text, see if you can convert to an entity
            entityValue = null; //(reset for different endpoints - used in the check to decide whether to continue)

            for (String entityTypeRegex : endpoint.entityTypes) {
                if (entityTypeRegex.startsWith("/")) {
                    int regexIndex = entityTypeRegex.lastIndexOf('/'); // (guaranteed to be >= 0)
                    try {
                        Pattern regex = Pattern.compile(entityTypeRegex.substring(1, regexIndex));
                        if (regex.matcher(textToTest).matches()) {
                            entityType = entityTypeRegex.substring(1 + regexIndex);
                            if (entityType.length() > 0) {
                                entityValue = textToTest;
                                entityIndex = entityValue.toLowerCase() + "/" + entityType.toLowerCase();
                            }
                        }
                    } catch (Exception e) { // if not in test mode, carry on
                        if (_testMode) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            } //(end loop over entity regexes)
        } //TESTED 
        if (null == entityValue) { // None of the regexes matched
            if (_testMode) {
                throw new RuntimeException("Text specified, does not match any of the regexes: "
                        + Arrays.toString(endpoint.entityTypes.toArray()) + " ... text = " + textToTest);
            }
            continue;
        }

        //DEBUG
        if (_DEBUG)
            _logger.debug("DEB: preQA5: ENDPOINT: " + Arrays.toString(endpoint.entityTypes.toArray()) + " / "
                    + entityType);

        if ((null != endpoint.importScript) && !endpoint.importScript.isEmpty()) {
            if (null == endpoint.scriptlang) {
                endpoint.scriptlang = "python"; // python ==default
            }
            if (endpoint.scriptlang.equalsIgnoreCase("python")) {
                _pyEngine = new ScriptEngineManager().getEngineByName("python");
                if (null == _pyEngine) {
                    _logger.error(
                            "Python not installed - copy jython 2.5+ into /opt/infinite-home/lib/unbundled");
                    if (_testMode) {
                        throw new RuntimeException(
                                "Python not installed - copy jython 2.5+ into /opt/infinite-home/lib/unbundled");
                    }
                } //TESTED (by hand, importScript != null and scriptlang: "python", jython not on classpath)
            } else if (endpoint.scriptlang.equalsIgnoreCase("external")) {
                //nothing to do here, just carry on, will handle the external bit later on
            } else {
                _logger.error("Python/External is currently the only supported scriptlang");
                if (_testMode) {
                    throw new RuntimeException("Python is currently the only supported scriptlang");
                }
            } //TESTED (by hand, importScript != null and scriptlang: "none")
        } //TESTED

        if ((null != endpoint.bypassSimpleQueryParsing) && endpoint.bypassSimpleQueryParsing) {
            throw new RuntimeException("Currently only simple query parsing is supported");
        }
        if ((null != endpoint.entityTypes) && endpoint.entityTypes.contains(entityType)) {

            // If not using the full source pipeline processing capability (ie always generating 0/1
            BasicDBObject cachedDoc = null;
            String cachedDocUrl = buildScriptUrl(endpoint.parentSource.getKey(), entityIndex);
            BasicDBObject cachedDoc_expired = null;
            if (!isComplexSource(endpoint.parentSource)) {
                // Check if the *doc* (not *API response*) generated from this endpoint/entity has been cached, check expiry if so
                if (_cacheMode && ((null == endpoint.cacheTime_days) || (endpoint.cacheTime_days >= 0))) {

                    if (_DEBUG)
                        _logger.debug("DEB: preQA6ya: Search Doc Cache: " + cachedDocUrl + " , "
                                + endpoint.cacheTime_days);

                    BasicDBObject cachedDocQuery = new BasicDBObject(DocumentPojo.url_, cachedDocUrl);
                    cachedDocQuery.put(DocumentPojo.sourceKey_, endpoint.parentSource.getKey());
                    cachedDoc = (BasicDBObject) DbManager.getDocument().getMetadata().findOne(cachedDocQuery);
                    if (null != cachedDoc) {
                        // (quick check if we have a complex source in here)
                        String sourceUrl = cachedDoc.getString(DocumentPojo.sourceUrl_);
                        if (null != sourceUrl) { // switching from complex to simple source - delete the cached docs

                            if (_DEBUG)
                                _logger.debug("DEB: preQA6yb: Clear Search Doc Cache: " + cachedDocUrl + " , "
                                        + sourceUrl);

                            cachedDocQuery.remove(DocumentPojo.url_);
                            cachedDocQuery.put(DocumentPojo.sourceUrl_, sourceUrl);
                            DbManager.getDocument().getMetadata().remove(cachedDocQuery);
                            cachedDoc = null;
                        } //TESTED (by hand)
                        else if (checkDocCache_isExpired(cachedDoc, endpoint)) {
                            cachedDoc_expired = cachedDoc;
                            cachedDoc = null;
                        }
                    }
                } //TESTED (by hand)
            }

            if (null == _asyncRequestsPerQuery) {
                // If we've got this far create a list to store the async requests
                _asyncRequestsPerQuery = new LinkedList<FederatedRequest>();
            }

            if (null != cachedDoc) { // (simple sources only, by construction)
                // Common params:
                FederatedRequest requestOverview = new FederatedRequest();
                requestOverview.endpointInfo = endpoint;
                requestOverview.communityIdStrs = communityIdStrs;
                requestOverview.requestParameter = entityValue;
                requestOverview.queryIndex = entityIndex;
                requestOverview.mergeKey = endpoint.parentSource.getKey();

                if (_DEBUG)
                    _logger.debug("DEB: preQA6z: Doc Cache: " + cachedDocUrl + " , " + cachedDoc);

                requestOverview.cachedDoc = cachedDoc;
                _asyncRequestsPerQuery.add(requestOverview);
            } //TESTED (by hand)
            else if (null != endpoint.importScript) {

                BasicDBObject cachedVal = null;
                if (_cacheMode) { // (source key not static, plus not sure it's desirable, so for simplicity just don't cache requests in test mode) 
                    cachedVal = this.getCache(cachedDocUrl, endpoint);
                }

                // Common params:
                FederatedRequest requestOverview = new FederatedRequest();
                requestOverview.endpointInfo = endpoint;
                requestOverview.communityIdStrs = communityIdStrs;
                requestOverview.requestParameter = entityValue;
                requestOverview.queryIndex = entityIndex;
                requestOverview.mergeKey = endpoint.parentSource.getKey();
                requestOverview.cachedDoc_expired = cachedDoc_expired;

                if (null != cachedVal) {
                    if (checkIfNeedToClearCache(cachedVal, endpoint.parentSource)) {
                        if (_DEBUG)
                            _logger.debug("DEB: preQA6aa: Clear cache: " + cachedDocUrl + " , " + cachedVal);
                        cachedVal = null;
                    }
                }
                requestOverview.cachedResult = cachedVal; // will often be null                  

                if ((null == cachedVal) || isComplexSource(endpoint.parentSource)) {
                    if (null != cachedVal) {
                        if (_DEBUG)
                            _logger.debug(
                                    "DEB: preQA6ab: Complex Src Cache: " + cachedDocUrl + " , " + cachedVal);
                    }
                    if (endpoint.scriptlang.equalsIgnoreCase("external")) {
                        requestOverview.importThread = new FederatedScriptHarvest();
                    } else {
                        requestOverview.importThread = new FederatedJythonHarvest();
                    }
                    requestOverview.importThread.queryEngine = this;
                    requestOverview.importThread.request = requestOverview;
                    requestOverview.importThread.start();
                } else {
                    if (_DEBUG)
                        _logger.debug("DEB: preQA6a: Cache: " + cachedDocUrl + " , " + cachedVal);
                }
                // Launch thread
                _asyncRequestsPerQuery.add(requestOverview);
            } //TESTED (by hand)
            else {

                if (isComplexSource(endpoint.parentSource)) {

                    //DEBUG
                    if (_DEBUG)
                        _logger.debug("DEB: preQA6ba: Build complex source, num requests = "
                                + endpoint.requests.size());

                    FederatedRequest requestOverview = new FederatedRequest();
                    requestOverview.endpointInfo = endpoint;
                    requestOverview.communityIdStrs = communityIdStrs;
                    requestOverview.requestParameter = entityValue;
                    requestOverview.queryIndex = entityIndex;
                    requestOverview.mergeKey = endpoint.parentSource.getKey();
                    requestOverview.cachedDoc_expired = cachedDoc_expired;

                    requestOverview.importThread = new FederatedSimpleHarvest();
                    requestOverview.importThread.queryEngine = this;
                    requestOverview.importThread.request = requestOverview;
                    requestOverview.importThread.start();

                    // Launch thread
                    _asyncRequestsPerQuery.add(requestOverview);
                } else { // simple source               
                    try {
                        for (SourceFederatedQueryConfigPojo.FederatedQueryEndpointUrl request : endpoint.requests) {
                            FederatedRequest requestOverview = createSimpleHttpEndpoint_includingCache(
                                    entityValue, entityIndex, communityIdStrs, endpoint, request,
                                    cachedDoc_expired);

                            //DEBUG
                            if (_DEBUG)
                                _logger.debug("DEB: preQA6bb: Build request: " + request.endPointUrl);

                            _asyncRequestsPerQuery.add(requestOverview);
                        } //(end loop over multiple requests
                    } catch (Exception e) {
                        _logger.error("Unknown error creating federated query for " + endpoint.titlePrefix
                                + ": " + e.getMessage());
                        if (_testMode) {
                            throw new RuntimeException("Unknown error creating federated query for "
                                    + endpoint.titlePrefix + ": " + e.getMessage(), e);
                        }
                    }
                } //(end if simple not complex)
            } //(end cached doc vs script vs request mode for queries)

        } //(end if this request is for this entity type)
        else { // no entity matches - if in test mode then bomb out with useful error
            if (_testMode) {
                throw new RuntimeException("Specified entity: " + entityIndex + " not in set: "
                        + Arrays.toString(endpoint.entityTypes.toArray()));
            }
        }
    } //(end loop over endpoints)
}

From source file:tools.httpserver.custom.ScriptList.java

/**
 * Create a new empty SpoonScript file using provided parameters
 * @param params_values parameters to use for file creation (table containing "param=value" strings)
 * @param type Set if script concerns REQMOD or RESPMOD
 * @param user User who generates the request
 * @return Action to do after: edit the new file if all is ok, return error otherwise
 *//*  www  .  j  av  a  2 s .  com*/
public static String create(String[] params_values, Icap.TYPE type, User user) {
    String name = null;
    String language = null;

    for (String s : params_values) {
        String[] values = s.split("=");
        if (values.length != 2)
            continue;
        if (values[0].equals("script.name"))
            name = values[1].replace("+", " ").trim();
        if (values[0].equals("script.language"))
            language = TextTools.hexToUTF8(values[1]).trim();
    }
    if (name == null || language == null) {
        error = "Invalid script name or language";
        return "";
    }
    SpoonScript[] scripts = type == Icap.TYPE.REQMOD ? icap.services.GreasySpoon.reqSpoonScripts
            : icap.services.GreasySpoon.respSpoonScripts;
    for (SpoonScript script : scripts) {
        if (script.getScriptName().equalsIgnoreCase(name)) {
            error = "A script with this name already exists.";
            return "";
        }
    }

    ScriptEngineFactory factory = null;
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    for (ScriptEngineFactory factories : scriptEngineManager.getEngineFactories()) {
        if (factories.getEngineName().equalsIgnoreCase(language)) {
            factory = factories;
            break;
        }
    }
    String factorylanguage;
    String extension;
    if (factory == null) {
        if (language.equals("java")) {
            factorylanguage = "java";
            extension = "java";
        } else {
            error = "Provided language cannot be founded.";
            return "";
        }
    } else {
        factorylanguage = factory.getLanguageName();
        extension = factory.getExtensions().get(0);
    }

    String scriptdirectory = icap.services.GreasySpoon.scriptsDirectory;
    String commentstring = icap.services.GreasySpoon.languageComments.getProperty(factorylanguage, "//").trim();
    String tag;
    if (type == Icap.TYPE.REQMOD) {
        tag = icap.services.GreasySpoon.greasySpoonReqTag;
    } else {
        tag = icap.services.GreasySpoon.greasySpoonRespTag;
    }
    String filecomment = SpoonScript.getScriptSkeleton(type, extension, commentstring);

    String filename = scriptdirectory + File.separator + name.replace(" ", "_").replace("%20", "_") + tag
            + extension;

    SpoonScript.save(filename, filecomment.replace("%name%", name), user.getRights());
    icap.services.GreasySpoon.forceReload();
    return "edit=" + filename;
}

From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java

private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript)
        throws IOException, ScriptException, NoSuchMethodException, ParseException {
    moduleInfo = new ModuleInfo(moduleName, moduleVersion);

    Pattern pat = Pattern.compile("webjars!(.*).js");
    Matcher m = pat.matcher(jsScript);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group(1));
    }/*w  w w .  j  a  va  2s . c  om*/
    m.appendTail(sb);

    jsScript = sb.toString();

    sb = new StringBuffer();

    pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)");
    m = pat.matcher(jsScript);
    while (m.find()) {
        m.appendReplacement(sb, m.group(2));
    }
    m.appendTail(sb);

    jsScript = sb.toString();

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String script = IOUtils.toString(
            getClass().getResourceAsStream("/org/pentaho/osgi/platform/webjars/require-js-aggregator.js"));
    script = script.replace("{{EXTERNAL_CONFIG}}", jsScript);

    engine.eval(script);

    requireConfig = (Map<String, Object>) parser
            .parse(((Invocable) engine).invokeFunction("processConfig", "").toString());
}

From source file:org.apache.camel.builder.script.ScriptBuilder.java

protected ScriptEngine createScriptEngine() {
    ScriptEngineManager manager = new ScriptEngineManager();
    try {/*from   w  w w  . j ava  2s  . c  om*/
        engine = manager.getEngineByName(scriptEngineName);
    } catch (NoClassDefFoundError ex) {
        LOG.error("Cannot load the scriptEngine for " + scriptEngineName + ", the exception is " + ex
                + ", please ensure correct JARs is provided on classpath.");
    }
    if (engine == null) {
        throw new IllegalArgumentException("No script engine could be created for: " + getScriptEngineName());
    }
    if (isPython()) {
        ScriptContext context = engine.getContext();
        context.setAttribute("com.sun.script.jython.comp.mode", "eval", ScriptContext.ENGINE_SCOPE);
    }
    return engine;
}

From source file:org.tinymediamanager.scraper.util.YoutubeLinkExtractor.java

private String decryptSignature(String encryptedSignature) throws Exception {
    // first extract the player url and download the js player
    Matcher matcher = playerUrlPattern.matcher(jsonConfiguration);
    if (matcher.find()) {
        // only download the player javascript the first time
        if (StringUtils.isBlank(playerJavascript)) {
            Url jsPlayer = new Url("https:" + matcher.group(1).replaceAll("\\\\", ""));
            StringWriter writer = new StringWriter();
            IOUtils.copy(jsPlayer.getInputStream(), writer, "UTF-8");
            playerJavascript = writer.toString();
        }//from  w  w  w .  ja  va  2s .c  om
        if (StringUtils.isBlank(playerJavascript)) {
            return "";
        }

        // here comes the magic: extract the decrypt JS functions and translate them to Java :)
        matcher = patternDecryptFunction.matcher(playerJavascript);
        if (matcher.find()) {
            String decryptFunction = matcher.group(1);

            // extract relevant JS code
            String javaScript = extractJavascriptCode(playerJavascript, decryptFunction);

            // create a script engine manager
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("JavaScript");
            engine.eval(javaScript);
            Invocable inv = (Invocable) engine;

            // invoke the function to decrypt the signature
            String result = (String) inv.invokeFunction(decryptFunction, encryptedSignature);

            return result;
        }
    }
    return "";
}

From source file:tools.httpserver.custom.ScriptList.java

/**
 * @return a vector containing Scriptengines names and associated languages
 *//*from   w ww.  j av a2s.c  o m*/
public static Vector<String[]> getScriptEngines() {
    Vector<String[]> vector = new Vector<String[]>();
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    for (ScriptEngineFactory factories : scriptEngineManager.getEngineFactories()) {
        boolean inserted = false;
        for (int i = 0; i < vector.size(); i++) {
            String[] s = vector.elementAt(i);
            if (s[0].compareToIgnoreCase(factories.getEngineName()) > 0) {
                vector.insertElementAt(new String[] { factories.getEngineName(), factories.getLanguageName() },
                        i);
                inserted = true;
                break;
            }
        }
        if (!inserted)
            vector.add(new String[] { factories.getEngineName(), factories.getLanguageName() });
    }
    if (javax.tools.ToolProvider.getSystemJavaCompiler() != null) {
        vector.add(new String[] { "java", "java" });
    }
    return vector;
}

From source file:org.openadaptor.auxil.processor.script.ScriptProcessor.java

/**
 * Locates a ScriptEngine for the current language.
 * <br>/*from   w ww.  j a  v a 2  s.c o m*/
 * Complicated slightly by differences between implementations 
 * in java 1.5 and earlier versus 1.6 and later.
 * See Issue [SC52]
 * <br>
 * 
 * @return ScriptEngine instance for the current language
 */
protected ScriptEngine createScriptEngine() {
    ScriptEngine engine = null;
    ScriptEngineManager mgr = new ScriptEngineManager();
    List factories = getEngineFactories(mgr);
    Iterator it = factories.iterator();
    while (it.hasNext() && (engine == null)) { //More factories to try, and no match yet.
        ScriptEngineFactory factory = (ScriptEngineFactory) it.next();
        if (log.isDebugEnabled()) { //Debug code to identify origins of factories etc.
            Object origin = ClasspathUtils.getClassOrigin(mgr);
            if (origin == null) {
                origin = "<JRE>";
            }
            log.debug("ScriptEngineManager loaded from: " + origin);
            origin = ClasspathUtils.getClassOrigin(factory);
            if (origin == null) {
                origin = "<JRE>";
            }
            String name = factory.getEngineName();
            String version = factory.getEngineVersion();
            log.debug("ScriptEngineFactory " + name + " (" + version + "): " + origin);
        }
        try {
            List aliases = getFactoryNames(factory);
            if (aliases != null) { //If null couldn't get any for factory.
                Iterator aliasIterator = aliases.iterator();
                while (aliasIterator.hasNext()) {
                    if (language.equals(aliasIterator.next())) {
                        log.debug("Found matching script engine for " + language);
                        engine = factory.getScriptEngine();
                        break;
                    }
                }
            } else {
                log.debug("Failed to get names for factory " + factory.getEngineName());
            }
        } catch (AbstractMethodError ame) {
            log.debug("Failed to interrogate Factory - " + factory.getEngineName());
        }
    }
    if (engine == null) {
        log.error("Failed to find engine for language " + language);
        throw new RuntimeException("Failed to find engine for language " + language);
    }
    return engine;
}

From source file:org.apache.synapse.mediators.bsf.ScriptMediator.java

protected void initScriptEngine() {
    if (log.isDebugEnabled()) {
        log.debug("Initializing script mediator for language : " + language);
    }//from  w w  w . j av  a  2s . c  o m

    ScriptEngineManager manager = new ScriptEngineManager();
    manager.registerEngineExtension("js", new RhinoScriptEngineFactory());
    manager.registerEngineExtension("groovy", new GroovyScriptEngineFactory());
    manager.registerEngineExtension("rb", new JRubyScriptEngineFactory());
    manager.registerEngineExtension("jsEngine", new RhinoScriptEngineFactory());
    manager.registerEngineExtension("py", new JythonScriptEngineFactory());
    this.scriptEngine = manager.getEngineByExtension(language);
    this.jsEngine = manager.getEngineByExtension("jsEngine");
    if (scriptEngine == null) {
        handleException("No script engine found for language: " + language);
    }
    xmlHelper = XMLHelper.getArgHelper(scriptEngine);

    this.multiThreadedEngine = scriptEngine.getFactory().getParameter("THREADING") != null;
    log.debug("Script mediator for language : " + language + " supports multithreading? : "
            + multiThreadedEngine);
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.DataFactoryScriptingSupport.java

public void initialize(final DataFactory dataFactory, final DataFactoryContext dataFactoryContext)
        throws ReportDataFactoryException {
    if (globalScriptContext != null) {
        return;//from   ww  w. j  av a  2  s .c  o  m
    }

    this.dataFactory = dataFactory;
    this.resourceManager = dataFactoryContext.getResourceManager();
    this.contextKey = dataFactoryContext.getContextKey();
    this.configuration = dataFactoryContext.getConfiguration();
    this.resourceBundleFactory = dataFactoryContext.getResourceBundleFactory();
    this.dataFactoryContext = dataFactoryContext;

    globalScriptContext = new SimpleScriptContext();
    globalScriptContext.setAttribute("dataFactory", dataFactory, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("configuration", configuration, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("resourceManager", resourceManager, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("contextKey", contextKey, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("resourceBundleFactory", resourceBundleFactory,
            ScriptContext.ENGINE_SCOPE);

    if (StringUtils.isEmpty(globalScriptLanguage)) {
        return;
    }

    globalScriptContext.setAttribute("scriptHelper",
            new ScriptHelper(globalScriptContext, globalScriptLanguage, resourceManager, contextKey),
            ScriptContext.ENGINE_SCOPE);

    final ScriptEngine maybeInvocableEngine = new ScriptEngineManager().getEngineByName(globalScriptLanguage);
    if (maybeInvocableEngine == null) {
        throw new ReportDataFactoryException(String.format(
                "DataFactoryScriptingSupport: Failed to locate scripting engine for language '%s'.",
                globalScriptLanguage));
    }
    if (maybeInvocableEngine instanceof Invocable == false) {
        return;
    }
    this.globalScriptEngine = (Invocable) maybeInvocableEngine;

    maybeInvocableEngine.setContext(globalScriptContext);
    try {
        maybeInvocableEngine.eval(globalScript);
    } catch (ScriptException e) {
        throw new ReportDataFactoryException(
                "DataFactoryScriptingSupport: Failed to execute datafactory init script.", e);
    }
}