Example usage for javax.script ScriptEngine getClass

List of usage examples for javax.script ScriptEngine getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.danann.cernunnos.script.ScriptEvaluator.java

public ScriptEvaluator(ScriptEngine engine, String script) {
    this.scriptEngine = engine;
    this.script = script;

    //Running under JDK5, don't do compilation
    if (compilableClass == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Running under JDK5, not using compilable script features for script:\n" + script);
        }/*from  www  . j  a  va  2s .c om*/

        this.compiledScript = null;
    }
    //ScriptEngine doesn't implement Compilable
    else if (!ClassUtils.isAssignable(compilableClass, engine.getClass())) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("ScriptEngine '" + engine + "' does not implement '" + compilableClass
                    + "', not using compilable script features for script:\n" + script);
        }

        this.compiledScript = null;
    }
    //Find the Compilable.eval method to compile the script with
    else {
        Object compiledScript;
        try {
            compiledScript = compileCompilableMethod.invoke(this.scriptEngine, this.script);
        } catch (IllegalArgumentException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Failed to compile script using ScriptEngine '" + engine
                        + "', not using compilable script features for script:\n" + script, e);
            }

            compiledScript = null;
        } catch (IllegalAccessException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Failed to compile script using ScriptEngine '" + engine
                        + "', not using compilable script features for script:\n" + script, e);
            }

            compiledScript = null;
        } catch (InvocationTargetException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Failed to compile script using ScriptEngine '" + engine
                        + "', not using compilable script features for script:\n" + script, e);
            }

            compiledScript = null;
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Compiled script using ScriptEngine '" + engine
                    + "', using compilable script features for script:\n" + script);
        }

        this.compiledScript = compiledScript;
    }
}

From source file:org.apache.jmeter.util.JSR223TestElement.java

/**
 * This method will run inline script or file script with special behaviour for file script:
 * - If ScriptEngine implements Compilable script will be compiled and cached
 * - If not if will be run/*from  w  w w .  j  av a2 s . c o  m*/
 * @param scriptEngine ScriptEngine
 * @param bindings {@link Bindings} might be null
 * @return Object returned by script
 * @throws IOException when reading the script fails
 * @throws ScriptException when compiling or evaluation of the script fails
 */
protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings)
        throws IOException, ScriptException {
    if (bindings == null) {
        bindings = scriptEngine.createBindings();
    }
    populateBindings(bindings);
    File scriptFile = new File(getFilename());
    // Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws "java.lang.Error: unimplemented"
    boolean supportsCompilable = scriptEngine instanceof Compilable
            && !(scriptEngine.getClass().getName().equals("bsh.engine.BshScriptEngine")); // $NON-NLS-1$
    if (!StringUtils.isEmpty(getFilename())) {
        if (scriptFile.exists() && scriptFile.canRead()) {
            BufferedReader fileReader = null;
            try {
                if (supportsCompilable) {
                    String cacheKey = getScriptLanguage() + "#" + // $NON-NLS-1$
                            scriptFile.getAbsolutePath() + "#" + // $NON-NLS-1$
                            scriptFile.lastModified();
                    CompiledScript compiledScript = compiledScriptsCache.get(cacheKey);
                    if (compiledScript == null) {
                        synchronized (compiledScriptsCache) {
                            compiledScript = compiledScriptsCache.get(cacheKey);
                            if (compiledScript == null) {
                                // TODO Charset ?
                                fileReader = new BufferedReader(new FileReader(scriptFile),
                                        (int) scriptFile.length());
                                compiledScript = ((Compilable) scriptEngine).compile(fileReader);
                                compiledScriptsCache.put(cacheKey, compiledScript);
                            }
                        }
                    }
                    return compiledScript.eval(bindings);
                } else {
                    // TODO Charset ?
                    fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length());
                    return scriptEngine.eval(fileReader, bindings);
                }
            } finally {
                IOUtils.closeQuietly(fileReader);
            }
        } else {
            throw new ScriptException("Script file '" + scriptFile.getAbsolutePath()
                    + "' does not exist or is unreadable for element:" + getName());
        }
    } else if (!StringUtils.isEmpty(getScript())) {
        if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) {
            computeScriptMD5();
            CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5);
            if (compiledScript == null) {
                synchronized (compiledScriptsCache) {
                    compiledScript = compiledScriptsCache.get(this.scriptMd5);
                    if (compiledScript == null) {
                        compiledScript = ((Compilable) scriptEngine).compile(getScript());
                        compiledScriptsCache.put(this.scriptMd5, compiledScript);
                    }
                }
            }

            return compiledScript.eval(bindings);
        } else {
            return scriptEngine.eval(getScript(), bindings);
        }
    } else {
        throw new ScriptException("Both script file and script text are empty for element:" + getName());
    }
}

From source file:org.apache.solr.update.processor.StatelessScriptUpdateProcessorFactory.java

/**
 * Initializes a list of script engines - an engine per script file.
 *
 * @param req The solr request./*  w ww .j  ava 2  s  .  co  m*/
 * @param rsp The solr response
 * @return The list of initialized script engines.
 */
private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp) throws SolrException {

    List<EngineInfo> scriptEngines = new ArrayList<>();

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager(resourceLoader.getClassLoader());

    scriptEngineManager.put("logger", log);
    scriptEngineManager.put("req", req);
    scriptEngineManager.put("rsp", rsp);
    if (params != null) {
        scriptEngineManager.put("params", params);
    }

    for (ScriptFile scriptFile : scriptFiles) {
        ScriptEngine engine = null;
        if (null != engineName) {
            engine = scriptEngineManager.getEngineByName(engineName);
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, false);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by name: "
                        + engineName + (null != details ? " -- supported names: " + details : ""));
            }
        } else {
            engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension());
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, true);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "No ScriptEngine found by file extension: " + scriptFile.getFileName()
                                + (null != details ? " -- supported extensions: " + details : ""));

            }
        }

        if (!(engine instanceof Invocable)) {
            String msg = "Engine "
                    + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName()))
                    + " does not support function invocation (via Invocable): " + engine.getClass().toString()
                    + " (" + engine.getFactory().getEngineName() + ")";
            log.error(msg);
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);
        }

        if (scriptEngineCustomizer != null) {
            scriptEngineCustomizer.customize(engine);
        }

        scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile));
        try {
            Reader scriptSrc = scriptFile.openReader(resourceLoader);

            try {
                engine.eval(scriptSrc);
            } catch (ScriptException e) {
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "Unable to evaluate script: " + scriptFile.getFileName(), e);
            } finally {
                IOUtils.closeQuietly(scriptSrc);
            }
        } catch (IOException ioe) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unable to evaluate script: " + scriptFile.getFileName(), ioe);
        }
    }
    return scriptEngines;
}

From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java

@Override
public boolean checkPermission(DocumentModel doc, String xpath, Blob blob, String reason,
        Map<String, Serializable> extendedInfos) {
    List<DownloadPermissionDescriptor> descriptors = registry.getDownloadPermissionDescriptors();
    if (descriptors.isEmpty()) {
        return true;
    }/*from   ww w . j  a  v  a 2s .co  m*/
    xpath = fixXPath(xpath);
    Map<String, Object> context = new HashMap<>();
    Map<String, Serializable> ei = extendedInfos == null ? Collections.emptyMap() : extendedInfos;
    NuxeoPrincipal currentUser = ClientLoginModule.getCurrentPrincipal();
    context.put("Document", doc);
    context.put("XPath", xpath);
    context.put("Blob", blob);
    context.put("Reason", reason);
    context.put("Infos", ei);
    context.put("Rendition", ei.get("rendition"));
    context.put("CurrentUser", currentUser);
    for (DownloadPermissionDescriptor descriptor : descriptors) {
        ScriptEngine engine = scriptEngineManager.getEngineByName(descriptor.getScriptLanguage());
        if (engine == null) {
            throw new NuxeoException("Engine not found for language: " + descriptor.getScriptLanguage()
                    + " in permission: " + descriptor.getName());
        }
        if (!(engine instanceof Invocable)) {
            throw new NuxeoException("Engine " + engine.getClass().getName() + " not Invocable for language: "
                    + descriptor.getScriptLanguage() + " in permission: " + descriptor.getName());
        }
        Object result;
        try {
            engine.eval(descriptor.getScript());
            engine.getBindings(ScriptContext.ENGINE_SCOPE).putAll(context);
            result = ((Invocable) engine).invokeFunction(RUN_FUNCTION);
        } catch (NoSuchMethodException e) {
            throw new NuxeoException("Script does not contain function: " + RUN_FUNCTION + "() in permission: "
                    + descriptor.getName(), e);
        } catch (ScriptException e) {
            log.error("Failed to evaluate script: " + descriptor.getName(), e);
            continue;
        }
        if (!(result instanceof Boolean)) {
            log.error("Failed to get boolean result from permission: " + descriptor.getName() + " (" + result
                    + ")");
            continue;
        }
        boolean allow = ((Boolean) result).booleanValue();
        if (!allow) {
            return false;
        }
    }
    return true;
}