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.xafero.vee.cmd.MainApp.java

private static void execute(String fileName) throws FileNotFoundException, ScriptException {
    File file = (new File(fileName)).getAbsoluteFile();
    if (!file.exists())
        throw new FileNotFoundException("There's no file named '" + file + "'!");
    String extension = Files.getExtension(file);
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByExtension(extension);
    Bindings env = engine.createBindings();
    inject(env, file);// w  ww. j  av a2s.  c om
    try {
        Object result = engine.eval(new FileReader(file), env);
        if (result != null)
            System.out.println(result.toString());
    } catch (ScriptException e) {
        throw e;
    }
}

From source file:co.mcme.barry.listeners.ChatListener.java

@EventHandler(priority = EventPriority.MONITOR)
public void onMathChat(AsyncPlayerChatEvent event) {
    if (event.getMessage().contains(".math")) {
        Player p = event.getPlayer();/*from   w  w  w.  j av  a 2 s.c om*/
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        String[] msg = event.getMessage().split(" ");
        if (msg.length > 1) {
            try {
                List<String> list = new ArrayList<>(Arrays.asList(msg));
                list.removeAll(Arrays.asList("", null, ".math"));
                String expression = StringUtils.join(list, " ");
                BarryPlugin.sendGlobalMessage("(" + ChatColor.DARK_AQUA + p.getName() + ChatColor.WHITE + ") "
                        + expression + " = " + engine.eval(expression));
            } catch (ScriptException ex) {
                b.sendTargetedMessage("I can't figure out that math problem.", p);
            }
        } else {
            b.sendTargetedMessage("I need to know what math to do", p);
        }
    }
}

From source file:com.blackbear.flatworm.config.ScriptletBO.java

/**
 * Constructor for ScriptIdentityImpl that attempts to load the Script Engine specified by name.
 *
 * @param scriptEngineName The name of the script engine to load. If {@code null} the {@code ScriptletBO.DEFAULT_SCRIPT_ENGINE} is
 *                         used./*from  www.j  a  v  a 2  s  .  c o m*/
 * @param functionName     The name of the function in the script that should be executed - the {@link
 *                         com.blackbear.flatworm.FileFormat} instance will be the only parameter sent to the function specified. If the
 *                         {@code functionName} is {@code null} then the {@code ScriptIdentityImp.DEFAULT_SCRIPT_IDENTITY_FUNCTION_NAME} value will be
 *                         used.
 * @throws FlatwormConfigurationException should the script be invalid or should the {@code scriptEngineName} not resolve to a valid
 *                                        script engine.
 */
public ScriptletBO(String scriptEngineName, String functionName) throws FlatwormConfigurationException {
    this.scriptEngineName = StringUtils.isBlank(scriptEngineName) ? DEFAULT_SCRIPT_ENGINE : scriptEngineName;
    this.functionName = StringUtils.isBlank(functionName)
            ? ScriptIdentityImpl.DEFAULT_SCRIPT_IDENTITY_FUNCTION_NAME
            : functionName;

    ScriptEngineManager engineManager = new ScriptEngineManager();
    scriptEngine = engineManager.getEngineByName(this.scriptEngineName);

    if (scriptEngine == null) {
        throw new FlatwormConfigurationException(String
                .format("The %s ScriptEngine could not be found by the given name.", this.scriptEngineName));
    } else {
        scriptInvocable = (Invocable) scriptEngine;
    }
}

From source file:com.google.cloud.genomics.dockerflow.util.StringUtils.java

/**
 * Evaluate a javascript expression, like "${= 2*3}".
 *
 * @param js//  w w w. j a  v a 2  s. c om
 * @return the results as a string.
 */
public static String evalJavaScript(String expression) throws ScriptException {
    FileUtils.LOG.debug("javascript: " + expression);

    // Remove new lines from arrays, etc
    String s = expression.trim().replace("\n", " ");
    StringBuilder sb = new StringBuilder();

    int start = s.indexOf("${=") + 3;

    // Keep text before the js
    if (start > 3) {
        sb.append(s.substring(0, start - 3));
    }
    int end = s.lastIndexOf("}");
    FileUtils.LOG.debug("start=" + start + ", end=" + end);

    String js = s.substring(start, end);
    FileUtils.LOG.info("Evaluate js: " + js);

    sb.append(String.valueOf(new ScriptEngineManager().getEngineByName("JavaScript").eval(js)).trim());

    // Keep text after the js
    if (end < s.length() - 1) {
        sb.append(s.substring(end + 1));
    }

    String retval = sb.toString();

    // If there's more js, evaluate it too
    if (StringUtils.isJavaScript(retval)) {
        retval = evalJavaScript(retval);
    }

    return retval;
}

From source file:edu.anu.spice.SpiceScorer.java

public void scoreBatch(SpiceArguments args) throws IOException, ScriptException {
    Stopwatch timer = Stopwatch.createStarted();
    SpiceParser parser = new SpiceParser(args.cache, args.numThreads, args.synsets);

    // Build filters for tuple categories
    Map<String, TupleFilter> filters = new HashMap<String, TupleFilter>();
    if (args.tupleSubsets) {
        filters.put("Object", TupleFilter.objectFilter);
        filters.put("Attribute", TupleFilter.attributeFilter);
        filters.put("Relation", TupleFilter.relationFilter);
        filters.put("Cardinality", TupleFilter.cardinalityFilter);
        filters.put("Color", TupleFilter.colorFilter);
        filters.put("Size", TupleFilter.sizeFilter);
    }/*from w w  w.jav  a  2  s  .c om*/

    // Parse test and refs from input file
    ArrayList<Object> image_ids = new ArrayList<Object>();
    ArrayList<String> testCaptions = new ArrayList<String>();
    ArrayList<String> refCaptions = new ArrayList<String>();
    ArrayList<Integer> refChunks = new ArrayList<Integer>();
    JSONParser json = new JSONParser();
    JSONArray input;
    try {
        input = (JSONArray) json.parse(new FileReader(args.inputPath));
        for (Object o : input) {
            JSONObject item = (JSONObject) o;
            image_ids.add(item.get("image_id"));
            testCaptions.add((String) item.get("test"));
            JSONArray refs = (JSONArray) item.get("refs");
            refChunks.add(refs.size());
            for (Object ref : refs) {
                refCaptions.add((String) ref);
            }
        }
    } catch (ParseException e) {
        System.err.println("Could not read input: " + args.inputPath);
        System.err.println(e.toString());
        e.printStackTrace();
    }

    System.err.println("Parsing reference captions");
    List<SceneGraph> refSgs = parser.parseCaptions(refCaptions, refChunks);
    System.err.println("Parsing test captions");
    List<SceneGraph> testSgs = parser.parseCaptions(testCaptions);

    this.stats = new SpiceStats(filters, args.detailed);
    for (int i = 0; i < testSgs.size(); ++i) {
        this.stats.score(image_ids.get(i), testSgs.get(i), refSgs.get(i), args.synsets);
    }
    if (!args.silent) {
        System.out.println(this.stats.toString());
    }

    if (args.outputPath != null) {
        BufferedWriter outputWriter = new BufferedWriter(new FileWriter(args.outputPath));

        // Pretty print output using javascript
        String jsonStringNoWhitespace = this.stats.toJSONString();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
        scriptEngine.put("jsonString", jsonStringNoWhitespace);
        scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
        String prettyPrintedJson = (String) scriptEngine.get("result");

        outputWriter.write(prettyPrintedJson);
        outputWriter.close();
    }
    System.out.println("SPICE evaluation took: " + timer.stop());
}

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  w w .ja va2 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.sonar.fortify.crawler.Main.java

private void executeJSCode(String pageSrc) throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.put("d", this);
    engine.eval(pageSrc);/*www . ja va 2s. c o m*/
}

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  .j  a v a2s  .co  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:com.seajas.search.profiler.validator.ModifierValidator.java

/**
 * Validate the given command object.//from  w  w  w.  j  a v a 2s  .  c  o m
 * 
 * @param command
 * @param errors
 */
@Override
public void validate(final Object command, final Errors errors) {
    ModifierCommand modifier = (ModifierCommand) command;

    if (modifier.getAction() != null
            && (modifier.getAction().equals("add") || modifier.getAction().equals("edit"))) {
        if (StringUtils.isEmpty(modifier.getUrlExpression()))
            errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.empty");
        else
            try {
                Pattern.compile(modifier.getUrlExpression());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.invalid");
            }

        if (StringUtils.isEmpty(modifier.getUrlType()))
            errors.rejectValue("urlType", "modifiers.validator.error.url.type.empty");
    } else if (modifier.getFilterAction() != null && (modifier.getFilterAction().equals("add-filter")
            || modifier.getFilterAction().equals("edit-filter"))) {
        if (StringUtils.isEmpty(modifier.getFilterStart()))
            errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.empty");
        else if (modifier.getFilterAsExpression())
            try {
                Pattern.compile(modifier.getFilterStart());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.invalid");
            }

        if (StringUtils.isEmpty(modifier.getFilterEnd()))
            errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.empty");
        else if (modifier.getFilterAsExpression())
            try {
                Pattern.compile(modifier.getFilterEnd());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.invalid");
            }
    } else if (modifier.getScriptAction() != null && (modifier.getScriptAction().equals("add-script")
            || modifier.getScriptAction().equals("edit-script"))) {
        if (StringUtils.isEmpty(modifier.getScriptLanguage()))
            errors.rejectValue("scriptLanguage", "modifiers.validator.error.script.language.invalid");

        if (StringUtils.isEmpty(modifier.getScriptContent()))
            errors.rejectValue("scriptContent", "modifiers.validator.error.script.content.empty");
        else {
            if (modifier.getScriptLanguage().equalsIgnoreCase("xslt")) {
                StreamSource source = new StreamSource(new StringReader(modifier.getScriptContent()));

                try {
                    TransformerFactory.newInstance().newTransformer(source);
                } catch (Exception e) {
                    errors.rejectValue("scriptContent",
                            "modifiers.validator.error.script.content.invalid.transformation");
                }
            } else {
                ScriptEngineManager engineManager = new ScriptEngineManager();
                ScriptEngine engine = engineManager.getEngineByName(modifier.getScriptLanguage().toLowerCase());

                engine.put("input", "");
                engine.put("inputUrl", "");
                engine.put("inputMaximumContentLength", 0L);

                try {
                    engine.eval(modifier.getScriptContent());
                } catch (ScriptException e) {
                    errors.rejectValue("scriptContent",
                            "modifiers.validator.error.script.content.syntax.error");

                    logger.warn("Script validation failed", e);
                }
            }
        }
    }
}