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:org.archive.modules.deciderules.ScriptedDecideRule.java

public void afterPropertiesSet() throws Exception {
    // fail at build-time if script engine not available
    if (null == new ScriptEngineManager().getEngineByName(engineName)) {
        throw new BeanInitializationException("named ScriptEngine not available");
    }/*from   ww  w.j  a v a2s .co  m*/
}

From source file:org.openmrs.module.appframework.service.AppFrameworkServiceImpl.java

public AppFrameworkServiceImpl(AllAppTemplates allAppTemplates, AllAppDescriptors allAppDescriptors,
        AllFreeStandingExtensions allFreeStandingExtensions, AllComponentsState allComponentsState,
        LocationService locationService, FeatureToggleProperties featureToggles,
        AppFrameworkConfig appFrameworkConfig, AllUserApps allUserApps) {
    this.allAppTemplates = allAppTemplates;
    this.allAppDescriptors = allAppDescriptors;
    this.allFreeStandingExtensions = allFreeStandingExtensions;
    this.allComponentsState = allComponentsState;
    this.locationService = locationService;
    this.featureToggles = featureToggles;
    this.appFrameworkConfig = appFrameworkConfig;
    this.javascriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    this.allUserApps = allUserApps;
}

From source file:JrubyTest.java

/**
 * /*from w  w  w.  j  a  v  a  2  s . c  om*/
 * @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:com.yahoo.validatar.execution.rest.JSON.java

@Override
public boolean setup(String[] arguments) {
    evaluator = new ScriptEngineManager().getEngineByName(JAVASCRIPT_ENGINE);
    OptionSet options = parser.parse(arguments);
    defaultTimeout = (Integer) options.valueOf(TIMEOUT_KEY);
    defaultRetries = (Integer) options.valueOf(RETRY_KEY);
    defaultFunction = (String) options.valueOf(FUNCTION_NAME_KEY);
    return true;/*from www.j a  va2 s  .co m*/
}

From source file:com.funambol.rhinounit.maven.plugin.RhinoUnitMojo.java

/**
 * Returns the ScripEngine for the given script extension. Engines are
 * stored and reused so that only one engine per extension will be returned.
 * If the engine for a given extension does not exist, EngineNotFoundException
 * is thrown./*w w  w.j  a  v a2  s  .c o m*/
 *
 * @return the engine
 *
 * @throws EngineNotFoundException if no engine is found for the given extension
 */
public ScriptEngine getEngine(String extension) throws EngineNotFoundException {
    //
    // Let's initialize engines if necessary...
    //
    if (engines == null) {
        engines = new HashMap<String, ScriptEngine>();
    }

    ScriptEngine engine = engines.get(extension);

    if (engine == null) {
        ScriptEngineManager engineManager = new ScriptEngineManager();

        if ((engine = engineManager.getEngineByExtension(extension)) == null) {
            throw new EngineNotFoundException(extension);
        }

        if (passProjectAsProperty) {
            if (nameOfProjectProperty == null) {
                nameOfProjectProperty = DEFAULT_NAME_OF_PROJECT_PROPERTY;
            }
            engine.put(nameOfProjectProperty, project);
        }
        engines.put(extension, engine);
    }
    return engine;
}

From source file:unUtils.ActionEval.java

public ActionEval(ApplicationConfig appConfig) {
    this.appConfig = appConfig;

    scriptEnginManager = new ScriptEngineManager();
}

From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> grouping_fields) {
    // This is currently fixed:
    java_api.set(true);//from   w  w w .j  a v  a2  s  .  com

    final JsScriptEngineBean config_bean = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()),
                    JsScriptEngineBean.class)
            .get();
    _config.trySet(config_bean);
    _context.trySet(context);
    _control.trySet(control);

    // Initialize script engine:
    ScriptEngineManager manager = new ScriptEngineManager();
    _engine.trySet(manager.getEngineByName("JavaScript"));
    _script_context.trySet(_engine.get().getContext()); // (actually not needed since we're compiling things)

    _bucket_logger.set(context.getLogger(Optional.of(bucket)));

    // Load globals:
    _engine.get().put("_a2_global_context", _context.get());
    _engine.get().put("_a2_global_grouping_fields", grouping_fields.orElse(Collections.emptyList()));
    _engine.get().put("_a2_global_previous_stage", previous_next._1().toString());
    _engine.get().put("_a2_global_next_stage", previous_next._2().toString());
    _engine.get().put("_a2_global_bucket", bucket);
    _engine.get().put("_a2_global_config", BeanTemplateUtils.configureMapper(Optional.empty())
            .convertValue(config_bean.config(), JsonNode.class));
    _engine.get().put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
    _engine.get().put("_a2_bucket_logger", _bucket_logger.optional().orElse(null));
    _engine.get().put("_a2_enrichment_name", Optional.ofNullable(control.name()).orElse("no_name"));

    // Load the resources:
    Stream.concat(config_bean.imports().stream(),
            Stream.of("aleph2_js_globals_before.js", "", "aleph2_js_globals_after.js"))
            .flatMap(Lambdas.flatWrap_i(import_path -> {
                try {
                    if (import_path.equals("")) { // also import the user script just before here
                        return config_bean.script();
                    } else
                        return IOUtils.toString(
                                JsScriptEngineService.class.getClassLoader().getResourceAsStream(import_path),
                                "UTF-8");
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (script {1}): {2}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), import_path,
                                    e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            })).forEach(Lambdas.wrap_consumer_i(script -> {
                try {
                    _engine.get().eval(script);
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (main script): {1}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            }));
    ;
}

From source file:de.ingrid.iplug.dscmapclient.index.mapper.ScriptedIdfDocumentMapper.java

/**
 * map in this case means, map the sourcerecord to 
 * an idf document and store it as xml-string
 *///from  w ww  .j a  va2s  . c o m
public ElasticDocument map(SourceRecord record, ElasticDocument luceneDoc) throws Exception {

    if (luceneDoc.get("id") == null || luceneDoc.get("serviceUnavailable") != null) {
        log.warn("!!! No 'id' set in index document (id=" + luceneDoc.get("id")
                + ") or 'serviceUnavailable' set (serviceUnavailable=" + luceneDoc.get("serviceUnavailable")
                + ") !!! No IDF possible, we return null Document so will not be indexed !");
        return null;
    }

    if (mappingScript == null) {
        log.error("Mapping script is not set!");
        throw new IllegalArgumentException("Mapping script is not set!");
    }

    org.w3c.dom.Document w3cDoc = docBuilder.newDocument();
    try {
        if (engine == null) {
            String scriptName = mappingScript.getFilename();
            String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length());
            ScriptEngineManager mgr = new ScriptEngineManager();
            engine = mgr.getEngineByExtension(extension);
            if (compile) {
                if (engine instanceof Compilable) {
                    Compilable compilable = (Compilable) engine;
                    compiledScript = compilable.compile(new InputStreamReader(mappingScript.getInputStream()));
                }
            }
        }

        IndexUtils idxUtils = new IndexUtils(luceneDoc);
        CapabilitiesUtils capUtils = new CapabilitiesUtils();
        XPathUtils xPathUtils = new XPathUtils(new IDFNamespaceContext());
        DOMUtils domUtils = new DOMUtils(w3cDoc, xPathUtils);
        XMLUtils xmlUtils = new XMLUtils();
        org.w3c.dom.Document wmsDoc = (org.w3c.dom.Document) record.get("WmsDoc");
        Bindings bindings = engine.createBindings();
        bindings.put("wmsDoc", wmsDoc);
        bindings.put("CAP", capUtils);
        bindings.put("XML", xmlUtils);
        bindings.put("sourceRecord", record);
        bindings.put("luceneDoc", luceneDoc);
        bindings.put("w3cDoc", w3cDoc);
        bindings.put("log", log);
        bindings.put("IDX", idxUtils);
        bindings.put("XPATH", xPathUtils);
        bindings.put("DOM", domUtils);
        bindings.put("javaVersion", System.getProperty("java.version"));

        if (compiledScript != null) {
            compiledScript.eval(bindings);
        } else {
            engine.eval(new InputStreamReader(mappingScript.getInputStream()), bindings);
        }
    } catch (Exception e) {
        log.error("Error mapping source record to lucene document.");
        //e.printStackTrace();
        throw e;
    }

    return luceneDoc;
}

From source file:com.t_oster.visicut.misc.Helper.java

public static Double evaluateExpression(String expr) {
    expr = expr.replace(",", ".");
    try {/*from  ww w  .  j a  va2s .  com*/
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        expr = engine.eval(expr).toString();
    } catch (Exception e) {
        //e.printStackTrace();
    }
    return Double.parseDouble(expr);
}

From source file:wordnice.api.Nice.java

public static ScriptEngine createJavascript() {
    try {/*from w  w w. j  av  a2 s . c  o  m*/
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
        if (engine != null)
            return engine;
    } catch (RuntimeException re) {
    }
    throw new RuntimeException("No Javascript engine found!");
}