Example usage for javax.script ScriptEngineManager getEngineByExtension

List of usage examples for javax.script ScriptEngineManager getEngineByExtension

Introduction

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

Prototype

public ScriptEngine getEngineByExtension(String extension) 

Source Link

Document

Look up and create a ScriptEngine for a given extension.

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.ingrid.interfaces.csw.index.impl.ScriptedIDFRecordLuceneMapper.java

/**
 * Load mapping script from filesystem and compile it if needed. This is
 * only done once when data is being indexed.
 *///w w w  .  j av a2 s. co m
@Override
public void init() {
    // read mapping file from disk
    if (configurationProvider != null) {
        this.mappingScript = configurationProvider.getMappingScript();
    }

    // also compile it again (just once per index generation)
    String scriptName = this.mappingScript.getName();
    String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1, scriptName.length());
    ScriptEngineManager mgr = new ScriptEngineManager();
    this.engine = mgr.getEngineByExtension(extension);
    if (this.engine instanceof Compilable) {
        Compilable compilable = (Compilable) this.engine;
        try {
            this.compiledScript = compilable
                    .compile(new InputStreamReader(new FileInputStream(this.mappingScript)));
        } catch (FileNotFoundException ex) {
            log.error("Mapping script was not found!", ex);
        } catch (ScriptException ex) {
            log.error("Error compiling mapping script!", ex);
        }
    }
}

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

@Override
public ElasticDocument map(SourceRecord record, ElasticDocument doc) throws Exception {
    if (mappingScript == null) {
        log.error("Mapping script is not set!");
        throw new IllegalArgumentException("Mapping script is not set!");
    }/*from  w w w.j  a v  a 2s.co  m*/
    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()));
                }
            }
        }

        // create utils for script

        CapabilitiesUtils capabilitiesUtils = new CapabilitiesUtils();
        capabilitiesUtils.setUrlStr((String) record.get(SourceRecord.ID));

        if (log.isDebugEnabled()) {
            log.debug("Requesting " + capabilitiesUtils.getUrlStr());
        }
        org.w3c.dom.Document wmsDoc = capabilitiesUtils.requestCaps();
        // we check for null and return -> NO Exception, so oncoming URLs are processed
        if (wmsDoc == null) {
            log.warn("!!! Problems requesting " + capabilitiesUtils.getUrlStr()
                    + " !!! We return null Document so will not be indexed !");
            return null;
        }
        //we put the xmlDoc(WMS doc) into the record and thereby pass it to the idf-mapper 
        record.put("WmsDoc", wmsDoc);

        IndexUtils idxUtils = new IndexUtils(doc);
        XPathUtils xPathUtils = new XPathUtils(new IDFNamespaceContext());

        Bindings bindings = engine.createBindings();
        bindings.put("wmsDoc", wmsDoc);
        bindings.put("log", log);
        bindings.put("CAP", capabilitiesUtils);
        bindings.put("IDX", idxUtils);
        bindings.put("XPATH", xPathUtils);
        bindings.put("javaVersion", System.getProperty("java.version"));

        if (compiledScript != null) {
            compiledScript.eval(bindings);
        } else {
            engine.eval(new InputStreamReader(mappingScript.getInputStream()), bindings);
        }

        return doc;

    } catch (Exception e) {
        log.error("Error mapping source record to lucene document.", e);
        e.printStackTrace();
        throw e;
    }

}

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  w  w .j ava  2 s.co 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.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./*from w w w  .  ja v  a  2 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:io.github.microcks.web.SoapController.java

private String getDispatchCriteriaFromScriptEval(Operation operation, String body) {
    ScriptEngineManager sem = new ScriptEngineManager();
    try {/*from w  w  w . j a  v  a2s  . co m*/
        // Evaluating request with script coming from operation dispatcher rules.
        ScriptEngine se = sem.getEngineByExtension("groovy");
        SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body);
        return (String) se.eval(operation.getDispatcherRules());
    } catch (Exception e) {
        log.error("Error during Script evaluation", e);
    }
    return null;
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;// w  ww  .  j  a v a  2  s.com

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

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.// ww w . j a v  a2  s .  c  om
 * @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.apache.synapse.mediators.bsf.ScriptMediator.java

protected void initScriptEngine() {
    if (log.isDebugEnabled()) {
        log.debug("Initializing script mediator for language : " + language);
    }/*  w  w  w.j  av  a 2s  .  c  om*/

    ScriptEngineManager manager = new ScriptEngineManager();
    manager.registerEngineExtension("js", new RhinoScriptEngineFactory());
    manager.registerEngineExtension("groovy", new GroovyScriptEngineFactory());
    manager.registerEngineExtension("rb", new JRubyScriptEngineFactory());
    manager.registerEngineExtension("jsEngine", new RhinoScriptEngineFactory());
    manager.registerEngineExtension("py", new JythonScriptEngineFactory());
    this.scriptEngine = manager.getEngineByExtension(language);
    this.jsEngine = manager.getEngineByExtension("jsEngine");
    if (scriptEngine == null) {
        handleException("No script engine found for language: " + language);
    }
    xmlHelper = XMLHelper.getArgHelper(scriptEngine);

    this.multiThreadedEngine = scriptEngine.getFactory().getParameter("THREADING") != null;
    log.debug("Script mediator for language : " + language + " supports multithreading? : "
            + multiThreadedEngine);
}

From source file:org.freeplane.plugin.script.GenericScript.java

private static ScriptEngine findScriptEngine(File scriptFile) {
    final ScriptEngineManager manager = getScriptEngineManager();
    final String extension = FilenameUtils.getExtension(scriptFile.getName());
    return checkNotNull(manager.getEngineByExtension(extension), "extension", extension);
}