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:it.geosolutions.geobatch.action.scripting.ScriptingTest.java

@Test
public void testGetEngineByExt() throws ScriptException {

    String engineExt = "js";

    ScriptEngineManager mgr = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = mgr.getEngineByExtension(engineExt);
    assertNotNull("Can't find engine '" + engineExt + "'", engine);

    ScriptEngineFactory sef = engine.getFactory();
    System.out.println("FACTORY for " + engineExt + ": " + "'" + sef.getEngineName() + "' " + "'"
            + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' ");

    // evaluate JavaScript code from String
    engine.eval("print('Hello, World')");

}

From source file:de.hasait.genesis.scriptgen.ScriptGenProcessor.java

private ScriptEngine determineScriptEngine(final String pScriptFileExtension, final ClassLoader pClassLoader) {
    final ScriptEngine engine;
    final NashornScriptEngineFactory nashornScriptEngineFactory = new NashornScriptEngineFactory();
    if (nashornScriptEngineFactory.getExtensions().contains(pScriptFileExtension)) {
        engine = nashornScriptEngineFactory.getScriptEngine(pClassLoader);
    } else {// w w w  . j a  va2s  .co  m
        final ScriptEngineManager factory = new ScriptEngineManager();
        engine = factory.getEngineByExtension(pScriptFileExtension);
    }
    return engine;
}

From source file:net.mindengine.galen.suite.actions.GalenPageActionRunJavascript.java

@Override
public List<ValidationError> execute(Browser browser, GalenPageTest pageTest,
        ValidationListener validationListener) throws Exception {

    File file = GalenUtils.findFile(javascriptPath);
    Reader scriptFileReader = new FileReader(file);
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    ScriptContext context = engine.getContext();
    context.setAttribute("name", "JavaScript", ScriptContext.ENGINE_SCOPE);

    engine.put("global", new ScriptExecutor(engine, file.getParent()));
    engine.put("browser", browser);

    provideWrappedWebDriver(engine, browser);

    importAllMajorClasses(engine);//from w  w  w.j av  a 2 s  . c o m
    engine.eval("var arg = " + jsonArguments);
    engine.eval(scriptFileReader);
    return NO_ERRORS;
}

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

@Override
public void activate(ComponentContext context) throws Exception {
    RuntimeService runtime = Framework.getRuntime();
    String scrPath = Framework.getRuntime().getProperty("org.nuxeo.scripts.dir");
    if (scrPath == null) {
        //Bundle bundle = context.getRuntimeContext().getBundle();
        //new File(bundle.getLocation());
        scriptDir = new File(runtime.getHome(), "scripts");
    } else {/*from  w  ww  . j a  v a  2 s  .  c  om*/
        scriptDir = new File(scrPath);
    }
    scripts = new Hashtable<String, ScriptDescriptor>();
    scriptMgr = new ScriptEngineManager();

    // start remote scripting service
    Boolean isServer = (Boolean) context.getPropertyValue("isServer", Boolean.TRUE);
    //TODO: server functionality should be removed
    //        if (isServer) {
    //            server = new ScriptingServerImpl(this);
    //            RemotingService remoting = (RemotingService) Framework.getRuntime().getComponent(RemotingService.NAME);
    //            TransporterServer transporterServer = remoting.getTransporterServer();
    //            transporterServer.addHandler(server, ScriptingServer.class.getName());
    //        }
}

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.
 * /*  w  ww.  j  a  va2s.  com*/
 * @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:com.qwazr.scripts.ScriptManager.java

private ScriptManager(ExecutorService executorService, File rootDirectory)
        throws IOException, URISyntaxException {

    // Load Nashorn
    ScriptEngineManager manager = new ScriptEngineManager();
    scriptEngine = manager.getEngineByName("nashorn");
    runsMap = new HashMap<String, RunThreadAbstract>();
    this.executorService = executorService;
}

From source file:org.jumpmind.metl.core.runtime.component.ContentRouter.java

@Override
protected void start() {
    ScriptEngineManager factory = new ScriptEngineManager();
    scriptEngine = factory.getEngineByName("groovy");
    TypedProperties properties = getTypedProperties();
    rowsPerMessage = properties.getLong(ROWS_PER_MESSAGE);
    String json = getComponent().get(SETTING_CONFIG);
    onlyRouteFirstMatch = getComponent().getBoolean(ONLY_ROUTE_FIRST_MATCH, false);
    if (isNotBlank(json)) {
        try {//from   w  w  w . jav a2  s.  com
            routes = new ObjectMapper().readValue(json, new TypeReference<List<Route>>() {
            });
            // Verify all routes are valid
            for (Route route : routes) {
                FlowStepLink link = getFlow().findLinkBetweenSourceAndTarget(this.getFlowStepId(),
                        route.getTargetStepId());
                if (link == null) {
                    throw new MisconfiguredException("A route target step is not linked.");
                }
            }
        } catch (Exception e) {
            throw new IoException(e);
        }
    }
}

From source file:com.thoughtworks.gauge.refactor.RefactoringMethodVisitor.java

public void visit(MethodDeclaration methodDeclaration, Object arg) {
    try {// ww w  . j  a va  2  s .co  m
        List<AnnotationExpr> annotations = methodDeclaration.getAnnotations();
        if (annotations == null)
            return;
        for (AnnotationExpr annotationExpr : annotations) {
            if (!(annotationExpr instanceof SingleMemberAnnotationExpr))
                continue;

            SingleMemberAnnotationExpr annotation = (SingleMemberAnnotationExpr) annotationExpr;
            if (annotation.getMemberValue() instanceof BinaryExpr) {
                ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                try {
                    Object result = engine.eval(annotation.getMemberValue().toString());
                    refactor(methodDeclaration, new StringLiteralExpr(result.toString()), annotation);
                } catch (ScriptException e) {
                    continue;
                }
            }
            if (annotation.getMemberValue() instanceof StringLiteralExpr) {
                StringLiteralExpr memberValue = (StringLiteralExpr) annotation.getMemberValue();
                refactor(methodDeclaration, memberValue, annotation);
            }
        }
    } catch (Exception ignored) {
    }
}

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  w w  w  .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.siphon.db2js.DbjsUnitManager.java

@Override
protected JsEngineHandlerContext createEngineContext(String srcFile, String aliasPath, DataSource dataSource,
        final Map<String, Object> otherArgs) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

    JsEngineUtil.initEngine(engine, (Object[]) otherArgs.get("jslib"));

    File path = new File(srcFolder);

    engine.put("logger", logger);
    engine.put("dataSource", dataSource);
    engine.put("application", otherArgs.get("application"));
    //  js ??? java 
    if (otherArgs.get("preloadJs") != null) {
        String[] preloadJs = (String[]) otherArgs.get("preloadJs"); // [abs path, alias]
        logger.info("evaluate preload js: " + preloadJs[0]);
        JsEngineUtil.eval(engine, preloadJs[0], preloadJs[1],
                FileUtils.readFileToString(new File(preloadJs[0]), "utf-8"), true, false);
    }/*  w w w  .  j  ava  2 s.  c  om*/

    File src = new File(srcFile);
    String code = FileUtils.readFileToString(src, "utf-8");
    String covertedCode = this.convertCode(code, src);
    File tmp = new File(srcFile + ".converted.js");
    FileUtils.write(tmp, covertedCode, "utf-8");
    if (logger.isDebugEnabled())
        logger.debug(srcFile + " converted as " + tmp.getAbsolutePath());

    JsEngineUtil.eval(engine, srcFile, aliasPath, covertedCode, false, true);

    JsEngineHandlerContext ctxt = new JsEngineHandlerContext();
    ctxt.setScriptEngine(engine);
    ctxt.setHandler((ScriptObjectMirror) engine.eval("dbjs"));
    ctxt.setJson(new JSON(engine)); // jdk has a NativeJSON class inside but
    // it's sealed
    ctxt.setJsTypeUtil(new JsTypeUtil(engine));

    return ctxt;
}