Example usage for javax.script ScriptEngine getFactory

List of usage examples for javax.script ScriptEngine getFactory

Introduction

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

Prototype

public ScriptEngineFactory getFactory();

Source Link

Document

Returns a ScriptEngineFactory for the class to which this ScriptEngine belongs.

Usage

From source file:org.apache.nifi.scripting.ScriptEngineFactory.java

ScriptEngine getNewEngine(File scriptFile, String extension) throws ScriptException {
    ScriptEngine engine = scriptEngMgr.getEngineByExtension(extension);
    if (null == engine) {
        throw new IllegalArgumentException("No ScriptEngine exists for extension " + extension);
    }//  w w  w.j  a  v  a 2 s  . co  m
    // Initialize some paths
    StringBuilder sb = new StringBuilder();
    switch (extension) {
    case "rb":
        String parent = scriptFile.getParent();
        parent = StringUtils.replace(parent, "\\", "/");
        sb.append("$:.unshift '").append(parent).append("'\n").append("$:.unshift File.join '").append(parent)
                .append("', 'lib'\n");
        engine.eval(sb.toString());

        break;
    case "py":
        parent = scriptFile.getParent();
        parent = StringUtils.replace(parent, "\\", "/");
        String lib = parent + "/lib";
        sb.append("import sys\n").append("sys.path.append('").append(parent).append("')\n")
                .append("sys.path.append('").append(lib).append("')\n").append("__file__ = '")
                .append(scriptFile.getAbsolutePath()).append("'\n");
        engine.eval(sb.toString());
        break;
    default:
        break;
    }

    Object threading = engine.getFactory().getParameter(THREADING);
    // the MULTITHREADED status means that the scripts need to be careful about sharing state
    if (THREAD_ISOLATED.equals(threading) || STATELESS.equals(threading) || MULTITHREADED.equals(threading)) {
        // replace prior instance if any
        threadSafeEngines.put(extension, engine);
    }
    return engine;
}

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  w w .  ja v a2s  .com*/
 * @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.geoserver.script.ScriptManager.java

ScriptEngine initEngine(ScriptEngine engine) {
    if (engine == null) {
        return null;
    }//from   ww w. j ava  2 s.  c  om

    for (ScriptPlugin plugin : plugins()) {
        if (plugin.getScriptEngineFactoryClass().isInstance(engine.getFactory())) {
            plugin.initScriptEngine(engine);
            break;
        }
    }

    return engine;
}

From source file:org.jahia.utils.ScriptEngineUtils.java

private void initEngine(ScriptEngine engine) {
    if (engine.getFactory().getNames().contains("velocity")) {
        final Properties velocityProperties = new Properties();
        final String key = "runtime.log.logsystem.log4j.logger";
        final String log4jLoggerProp = System.getProperty(key);
        if (log4jLoggerProp != null) {
            velocityProperties.setProperty(key, log4jLoggerProp);
        } else {//from   w  w  w .  ja  va 2 s .co m
            velocityProperties.setProperty(key, "root");
        }
        engine.getContext().setAttribute("com.sun.script.velocity.properties", velocityProperties,
                ScriptContext.GLOBAL_SCOPE);
    }
}

From source file:org.nuxeo.runtime.scripting.ScriptingComponent.java

@Override
public CompiledScript getScript(String name) throws ScriptException, IOException {
    ScriptDescriptor sd = scripts.get(name);
    if (sd != null) {
        if (sd.script != null) {
            return sd.script;
        }/*  w  ww  .  j a v  a 2  s. c  o  m*/
        ScriptEngine engine = getEngineByFileName(sd.src);
        if (engine == null) {
            log.warn("Script engine not found for: " + sd.src);
        } else if (engine instanceof Compilable) {
            try {
                Reader reader = getReader(sd);
                try {
                    sd.script = ((Compilable) engine).compile(reader);
                    return sd.script;
                } finally {
                    reader.close();
                }
            } catch (ScriptException e) {
                throw new ScriptException(
                        "Script file was not found: " + sd.src + " when trying to load " + name);
            }
        } else {
            throw new ScriptException(
                    "Not a compilable scripting engine: " + engine.getFactory().getEngineName());
        }
    }
    return null;
}

From source file:org.nuxeo.runtime.scripting.ScriptingComponent.java

@Override
public CompiledScript compile(String path) throws ScriptException {
    ScriptEngine engine = getEngineByFileName(path);
    if (engine != null) {
        if (engine instanceof Compilable) {
            try {
                Reader reader = new FileReader(getScriptFile(path));
                try {
                    return ((Compilable) engine).compile(reader);
                } finally {
                    reader.close();//from  w w w .j  ava2s.  c  o m
                }
            } catch (IOException e) {
                throw new ScriptException(e);
            }
        } else {
            throw new ScriptException(
                    "Script Engine " + engine.getFactory().getEngineName() + " is not compilable");
        }
    } else {
        throw new ScriptException("No suitable script engine found for the file " + path);
    }
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * Goes through the methods of the object found in the <code>scriptEngine</code>'s ENGINE_SCOPE
 * and for each of them generates a top-level function that is called the same name and accepts the same
 * parameters.//from  w  w  w .ja v a2  s  .  c om
 * 
 * @param scriptEngine the script engine to generate the top-level functions in
 * @param bindingName the name of the object in the script engine to generate the functions from
 * 
 * @see ScriptEngineInitializer#generateIndirectionMethod(String, Method)
 * @see NoTopLevelIndirection
 */
public static void bindIndirectionMethods(ScriptEngine scriptEngine, String bindingName) {
    Object object = scriptEngine.get(bindingName);
    if (object == null) {
        LOG.debug("The script engine doesn't contain a binding called '" + bindingName
                + "'. No indirection functions will be generated.");
        return;
    }

    ScriptEngineInitializer initializer = getInitializer(scriptEngine.getFactory().getLanguageName());
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), Object.class);
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();

        Map<String, Set<Method>> overloadsPerMethodName = new HashMap<String, Set<Method>>();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {
            Method method = methodDescriptor.getMethod();
            if (shouldIndirect(method)) {
                Set<Method> overloads = overloadsPerMethodName.get(method.getName());
                if (overloads == null) {
                    overloads = new HashSet<Method>();
                    overloadsPerMethodName.put(method.getName(), overloads);
                }
                overloads.add(method);
            }
        }

        for (Set<Method> overloads : overloadsPerMethodName.values()) {
            Set<String> methodDefs = initializer.generateIndirectionMethods(bindingName, overloads);
            for (String methodDef : methodDefs) {
                try {
                    scriptEngine.eval(methodDef);
                } catch (ScriptException e) {
                    LOG.warn("Unable to define global function declared as:\n" + methodDef, e);
                }
            }
        }
    } catch (IntrospectionException e) {
        LOG.debug("Could not inspect class " + object.getClass().getName()
                + ". No indirection methods for variable '" + bindingName + "' will be generated.", e);
    }
}

From source file:org.springframework.data.hadoop.scripting.Jsr223ScriptEvaluator.java

protected ScriptEngine discoverEngine(ScriptSource script, Map<String, Object> arguments) {
    ScriptEngineManager engineManager = new ScriptEngineManager(classLoader);
    ScriptEngine engine = null;

    if (StringUtils.hasText(language)) {
        engine = engineManager.getEngineByName(language);
    } else {/*ww  w . ja v  a 2  s  .c  om*/
        // make use the extension (enhanced ScriptSource interface)
        Assert.hasText(extension, "no language or extension specified");
        engine = engineManager.getEngineByExtension(extension);
    }

    Assert.notNull(engine, "No suitable engine found for "
            + (StringUtils.hasText(language) ? "language " + language : "extension " + extension));

    if (log.isDebugEnabled()) {
        ScriptEngineFactory factory = engine.getFactory();
        log.debug(String.format("Using ScriptEngine %s (%s), language %s (%s)", factory.getEngineName(),
                factory.getEngineVersion(), factory.getLanguageName(), factory.getLanguageVersion()));
    }

    return engine;
}

From source file:org.unitime.timetable.server.script.ScriptExecution.java

@Override
protected void execute() throws Exception {
    org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession();

    Transaction tx = hibSession.beginTransaction();
    try {/*from   w ww . j av a  2  s . c o m*/
        setStatus("Starting up...", 3);

        Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession);

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(script.getEngine());
        engine.put("hibSession", hibSession);
        engine.put("session", SessionDAO.getInstance().get(getSessionId()));
        engine.put("log", this);

        incProgress();

        engine.getContext().setWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    info(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });
        engine.getContext().setErrorWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    warn(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });

        incProgress();

        debug("Engine: " + engine.getFactory().getEngineName() + " (ver. "
                + engine.getFactory().getEngineVersion() + ")");
        debug("Language: " + engine.getFactory().getLanguageName() + " (ver. "
                + engine.getFactory().getLanguageVersion() + ")");

        for (ScriptParameter parameter : script.getParameters()) {
            String value = iRequest.getParameters().get(parameter.getName());

            if ("file".equals(parameter.getType()) && iFile != null) {
                debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)");
                engine.put(parameter.getName(), iFile);
                continue;
            }

            if (value == null)
                value = parameter.getDefaultValue();
            if (value == null) {
                engine.put(parameter.getName(), null);
                continue;
            }
            debug(parameter.getName() + ": " + value);

            if (parameter.getType().equalsIgnoreCase("boolean")) {
                engine.put(parameter.getName(), "true".equalsIgnoreCase(value));
            } else if (parameter.getType().equalsIgnoreCase("long")) {
                engine.put(parameter.getName(), Long.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("int")
                    || parameter.getType().equalsIgnoreCase("integer")) {
                engine.put(parameter.getName(), Integer.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("double")) {
                engine.put(parameter.getName(), Double.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("float")) {
                engine.put(parameter.getName(), Float.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("short")) {
                engine.put(parameter.getName(), Short.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("byte")) {
                engine.put(parameter.getName(), Byte.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("department")) {
                engine.put(parameter.getName(),
                        DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("departments")) {
                List<Department> departments = new ArrayList<Department>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), departments);
            } else if (parameter.getType().equalsIgnoreCase("subject")) {
                engine.put(parameter.getName(),
                        SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("subjects")) {
                List<SubjectArea> subjects = new ArrayList<SubjectArea>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), subjects);
            } else if (parameter.getType().equalsIgnoreCase("building")) {
                engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("buildings")) {
                List<Building> buildings = new ArrayList<Building>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), buildings);
            } else if (parameter.getType().equalsIgnoreCase("room")) {
                engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("rooms")) {
                List<Room> rooms = new ArrayList<Room>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), rooms);
            } else if (parameter.getType().equalsIgnoreCase("location")) {
                engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("locations")) {
                List<Location> locations = new ArrayList<Location>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), locations);
            } else {
                engine.put(parameter.getName(), value);
            }
        }

        incProgress();

        if (engine instanceof Compilable) {
            setStatus("Compiling script...", 1);
            CompiledScript compiled = ((Compilable) engine).compile(script.getScript());
            incProgress();
            setStatus("Running script...", 100);
            compiled.eval();
        } else {
            setStatus("Running script...", 100);
            engine.eval(script.getScript());
        }

        hibSession.flush();
        tx.commit();

        setStatus("All done.", 1);
        incProgress();
    } catch (Exception e) {
        tx.rollback();
        error("Execution failed: " + e.getMessage(), e);
    } finally {
        hibSession.close();
    }
}

From source file:org.zaproxy.zap.extension.zest.ExtensionZest.java

@Override
public void hook(ExtensionHook extensionHook) {
    super.hook(extensionHook);

    extensionHook.addOptionsParamSet(getParam());

    if (getView() != null) {
        extensionHook.addProxyListener(this);
        extensionHook.addSessionListener(new ViewSessionChangedListener());

        extensionHook.getHookView().addStatusPanel(this.getZestResultsPanel());
        extensionHook.getHookView().addOptionPanel(getOptionsPanel());

        this.dialogManager = new ZestDialogManager(this, this.getExtScript().getScriptUI());
        new ZestMenuManager(this, extensionHook);

        View.getSingleton().addMainToolbarButton(getRecordButton());
        View.getSingleton().addMainToolbarSeparator(getToolbarSeparator());

        if (getExtScript().getScriptUI() != null) {
            ZestTreeTransferHandler th = new ZestTreeTransferHandler(this);
            getExtScript().getScriptUI().addScriptTreeTransferHandler(ZestElementWrapper.class, th);
        }//w ww  . j  av a 2s  .co m
    }

    List<Path> defaultTemplates = getDefaultTemplates();

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine se = mgr.getEngineByName(ZestScriptEngineFactory.NAME);
    if (se != null) {
        // Looks like this only works if the Zest lib is in the top level
        // lib directory
        this.zestEngineFactory = (ZestScriptEngineFactory) se.getFactory();
    } else {
        // Needed for when the Zest lib is in an add-on (usual case)
        this.zestEngineFactory = new ZestScriptEngineFactory();
        se = zestEngineFactory.getScriptEngine();
    }
    zestEngineWrapper = new ZestEngineWrapper(se, defaultTemplates);
    this.getExtScript().registerScriptEngineWrapper(zestEngineWrapper);

    this.getExtScript().addListener(this);

    if (this.getExtScript().getScriptUI() != null) {
        ZestTreeCellRenderer renderer = new ZestTreeCellRenderer();
        this.getExtScript().getScriptUI().addRenderer(ZestElementWrapper.class, renderer);
        this.getExtScript().getScriptUI().addRenderer(ZestScriptWrapper.class, renderer);
        this.getExtScript().getScriptUI().disableScriptDialog(ZestScriptWrapper.class);
    }
}