Example usage for javax.script ScriptEngineManager getEngineByName

List of usage examples for javax.script ScriptEngineManager getEngineByName

Introduction

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

Prototype

public ScriptEngine getEngineByName(String shortName) 

Source Link

Document

Looks up and creates a ScriptEngine for a given name.

Usage

From source file:org.eclipse.smarthome.transform.javascript.internal.JavaScriptTransformationService.java

/**
 * Transforms the input <code>source</code> by Java Script. It expects the
 * transformation rule to be read from a file which is stored under the
 * 'configurations/transform' folder. To organize the various
 * transformations one should use subfolders.
 * /*from  w  ww .j a va  2  s.co m*/
 * @param filename
 *            the name of the file which contains the Java script
 *            transformation rule. Transformation service inject input
 *            (source) to 'input' variable.
 * @param source
 *            the input to transform
 */
@Override
public String transform(String filename, String source) throws TransformationException {
    Logger logger = LoggerFactory.getLogger(JavaScriptTransformationService.class);
    if (filename == null || source == null) {
        throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
    }

    logger.debug("about to transform '{}' by the Java Script '{}'", source, filename);

    Reader reader;

    try {
        String path = ConfigConstants.getConfigFolder() + File.separator
                + TransformationService.TRANSFORM_FOLDER_NAME + File.separator + filename;
        reader = new InputStreamReader(new FileInputStream(path));
    } catch (FileNotFoundException e) {
        throw new TransformationException("An error occurred while loading script.", e);
    }

    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("input", source);

    Object result = null;

    long startTime = System.currentTimeMillis();

    try {
        result = engine.eval(reader);
    } catch (ScriptException e) {
        throw new TransformationException("An error occurred while executing script.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime);

    return String.valueOf(result);
}

From source file:org.eclipse.smarthome.core.transform.internal.service.JavaScriptTransformationService.java

/**
 * Transforms the input <code>source</code> by Java Script. It expects the
 * transformation rule to be read from a file which is stored under the
 * 'configurations/transform' folder. To organize the various
 * transformations one should use subfolders.
 * /*from  www .  j a  va 2  s  .co  m*/
 * @param filename
 *            the name of the file which contains the Java script
 *            transformation rule. Transformation service inject input
 *            (source) to 'input' variable.
 * @param source
 *            the input to transform
 */
public String transform(String filename, String source) throws TransformationException {

    if (filename == null || source == null) {
        throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
    }

    logger.debug("about to transform '{}' by the Java Script '{}'", source, filename);

    Reader reader;

    try {
        String path = ConfigDispatcher.getConfigFolder() + File.separator
                + TransformationActivator.TRANSFORM_FOLDER_NAME + File.separator + filename;
        reader = new InputStreamReader(new FileInputStream(path));
    } catch (FileNotFoundException e) {
        throw new TransformationException("An error occured while loading script.", e);
    }

    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("input", source);

    Object result = null;

    long startTime = System.currentTimeMillis();

    try {
        result = engine.eval(reader);
    } catch (ScriptException e) {
        throw new TransformationException("An error occured while executing script.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime);

    return String.valueOf(result);
}

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);// ww w. j  a v a 2s .  c  o m
    this.engine = (Invocable) engine;
    this.delegate = new HttpMessageWriter();
}

From source file:com.asual.lesscss.compiler.NashornCompiler.java

public NashornCompiler(LessOptions options, ResourceLoader loader, URL less, URL env, URL engine, URL cssmin,
        URL sourceMap) throws IOException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine scriptEngine = factory.getEngineByName("nashorn");
    try {//from   w  w  w .j  a v  a  2  s . c  o  m
        scriptEngine.eval(new InputStreamReader(sourceMap.openConnection().getInputStream()));
        scriptEngine.eval(new InputStreamReader(env.openConnection().getInputStream()));
        ScriptObjectMirror lessenv = (ScriptObjectMirror) scriptEngine.get("lessenv");
        lessenv.put("charset", options.getCharset());
        lessenv.put("css", options.isCss());
        lessenv.put("lineNumbers", options.getLineNumbers());
        lessenv.put("optimization", options.getOptimization());
        lessenv.put("sourceMap", options.isSourceMap());
        lessenv.put("sourceMapRootpath", options.getSourceMapRootpath());
        lessenv.put("sourceMapBasepath", options.getSourceMapBasepath());
        lessenv.put("sourceMapURL", options.getSourceMapUrl());
        lessenv.put("loader", loader);
        lessenv.put("paths", options.getPaths());
        scriptEngine.eval(new InputStreamReader(less.openConnection().getInputStream()));
        scriptEngine.eval(new InputStreamReader(cssmin.openConnection().getInputStream()));
        scriptEngine.eval(new InputStreamReader(engine.openConnection().getInputStream()));
        compile = (ScriptObjectMirror) scriptEngine.get("compile");
    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:JrubyTest.java

/**
 * //from w  w w .  jav a2s.co  m
 * @throws Exception
 */
@Test
public void poi() throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;
    InputStream in = null;
    try {
        in = getClass().getClassLoader().getResourceAsStream("sample1.xls");
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        scriptReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test.rb"));
        if (engine instanceof Compilable) {
            CompiledScript script = ((Compilable) engine).compile(scriptReader);
            SimpleBindings bindings = new SimpleBindings();
            bindings.put("@book", book);
            script.eval(bindings);
        }
    } finally {
        IOUtils.closeQuietly(scriptReader);
        IOUtils.closeQuietly(in);
    }
}

From source file:JrubyTest.java

/**
 * // w w  w . jav a  2s. com
 */
@Test
public void repeatedTitle() throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;
    InputStream in = null;
    try {
        in = getClass().getClassLoader().getResourceAsStream("test-specifications.xls");
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        scriptReader = new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream("test-specification-repeated-title.rb"));
        if (engine instanceof Compilable) {
            CompiledScript script = ((Compilable) engine).compile(scriptReader);
            SimpleBindings bindings = new SimpleBindings();
            bindings.put("@book", book);
            script.eval(bindings);
        }
    } finally {
        IOUtils.closeQuietly(scriptReader);
        IOUtils.closeQuietly(in);
    }
}

From source file:JrubyTest.java

/**
 * ?Excel????//from  w  w  w . jav a  2s  .  c o m
 *
 * @throws Exception
 */
@Test
public void parseTestSpecification() throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;
    InputStream in = null;
    try {
        in = getClass().getClassLoader().getResourceAsStream("test-specifications.xls");
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        scriptReader = new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream("test-specification-parser.rb"));
        if (engine instanceof Compilable) {
            CompiledScript script = ((Compilable) engine).compile(scriptReader);
            SimpleBindings bindings = new SimpleBindings();
            bindings.put("@book", book);
            script.eval(bindings);
        }
    } finally {
        IOUtils.closeQuietly(scriptReader);
        IOUtils.closeQuietly(in);
    }

}

From source file:com.qwazr.webapps.transaction.ControllerManager.java

private ControllerManager(File dataDir) {
    this.dataDir = dataDir;
    ScriptEngineManager manager = new ScriptEngineManager();
    scriptEngine = manager.getEngineByName("nashorn");
    servletMap = new AccessTimeCacheMap<>(3600);
}

From source file:org.hbird.business.scripting.bean.ScriptExecutor.java

public ScriptExecutor(ScriptComponent component) {
    this.component = component;

    ScriptEngineManager factory = new ScriptEngineManager();
    engine = factory.getEngineByName(component.format);

    engine.put("output", component.output);

    /** *///ww w  .ja  v  a2 s .co m
    if (component.script == null || component.script.equals("") == true) {

        /** Default root is the the resource folder of the current project. */
        String root = "src/main/resources/library/";
        if (System.getProperty("hbird.scriptlibrary") != null) {
            root = System.getProperty("hbird.scriptlibrary");
            if (root.endsWith("/") == false) {
                root += "/";
            }
        }

        File file = new File(root + component.getScriptName() + ".js");
        if (file.exists() == false) {
            LOG.error("Failed to find script file '" + file.getAbsolutePath() + "'.");
            LOG.error(
                    "Use the runtime system property '-Dhbird.scriptlibrary=[path]' to point to the script library. Script will not be evaluated.");
        } else {
            try {
                component.script = FileUtils.readFileToString(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.zols.datastore.validator.TV4.java

public TV4() {
    mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("JavaScript");
    try {//w w  w . j  av  a2  s. c o m
        json = engine.eval("JSON");
        loadJavaScriptFile("/tv4.js");
        loadJavaScriptFile("/tv4Wrapper.js");
    } catch (Exception e) {
        e.printStackTrace();
    }
}