Search in sources :

Example 86 with SimpleBindings

use of javax.script.SimpleBindings in project jvarkit by lindenb.

the class UniprotFilterJS method doWork.

@Override
public int doWork(final List<String> args) {
    Unmarshaller unmarshaller;
    Marshaller marshaller;
    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        if (engine == null) {
            LOG.error("not available: javascript. Use the SUN/Oracle JDK ?");
            return -1;
        }
        CompiledScript compiledScript = super.compileJavascript(scriptExpr, scriptFile);
        JAXBContext jc = JAXBContext.newInstance("org.uniprot");
        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://uniprot.org/uniprot http://www.uniprot.org/support/docs/uniprot.xsd");
        PrintWriter pw = new PrintWriter(System.out);
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);
        StreamSource src = null;
        if (args.isEmpty()) {
            src = new StreamSource(stdin());
        } else if (args.size() == 1) {
            src = new StreamSource(new File(args.get(0)));
        } else {
            LOG.error("illegal.number.of.arguments");
            return -1;
        }
        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);
        XMLEventFactory eventFactory = XMLEventFactory.newFactory();
        SimpleBindings bindings = new SimpleBindings();
        long nArticles = 0L;
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch(evt.getEventType()) {
                case XMLEvent.START_ELEMENT:
                    {
                        StartElement sE = evt.asStartElement();
                        Entry entry = null;
                        JAXBElement<Entry> jaxbElement = null;
                        if (sE.getName().getLocalPart().equals("entry")) {
                            jaxbElement = unmarshaller.unmarshal(r, Entry.class);
                            entry = jaxbElement.getValue();
                        } else {
                            w.add(r.nextEvent());
                            break;
                        }
                        if (entry != null) {
                            bindings.put("entry", entry);
                            bindings.put("index", nArticles++);
                            Object result = compiledScript.eval(bindings);
                            String entryName = "undefined";
                            if (!entry.getAccession().isEmpty())
                                entryName = entry.getAccession().get(0);
                            if (result == null)
                                break;
                            if (result instanceof Boolean) {
                                if (Boolean.FALSE.equals(result)) {
                                    w.add(eventFactory.createComment(" " + entryName + " "));
                                    w.add(eventFactory.createCharacters("\n"));
                                    break;
                                }
                            } else if (result instanceof Number) {
                                if (((Number) result).intValue() != 1) {
                                    w.add(eventFactory.createComment(" " + entryName + " "));
                                    w.add(eventFactory.createCharacters("\n"));
                                    break;
                                }
                            } else {
                                LOG.warning("Script returned something that is not a boolean or a number:" + result.getClass());
                                break;
                            }
                            marshaller.marshal(jaxbElement, w);
                            w.add(eventFactory.createCharacters("\n"));
                        }
                        break;
                    }
                case XMLEvent.SPACE:
                    break;
                default:
                    {
                        w.add(r.nextEvent());
                        break;
                    }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return 0;
    } catch (Exception err) {
        LOG.error(err);
        return -1;
    } finally {
    }
}
Also used : CompiledScript(javax.script.CompiledScript) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) XMLEventFactory(javax.xml.stream.XMLEventFactory) ScriptEngineManager(javax.script.ScriptEngineManager) JAXBContext(javax.xml.bind.JAXBContext) XMLEventWriter(javax.xml.stream.XMLEventWriter) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) PrintWriter(java.io.PrintWriter) Marshaller(javax.xml.bind.Marshaller) StreamSource(javax.xml.transform.stream.StreamSource) JAXBElement(javax.xml.bind.JAXBElement) ScriptEngine(javax.script.ScriptEngine) StartElement(javax.xml.stream.events.StartElement) SimpleBindings(javax.script.SimpleBindings) XMLEvent(javax.xml.stream.events.XMLEvent) File(java.io.File) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 87 with SimpleBindings

use of javax.script.SimpleBindings in project jvarkit by lindenb.

the class BlastFilterJS method doWork.

@Override
public int doWork(List<String> args) {
    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript(scriptExpr, scriptFile);
        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");
        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        PrintWriter pw = openFileOrStdoutAsPrintWriter(outputFile);
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);
        final String inputName = oneFileOrNull(args);
        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }
        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);
        XMLEventFactory eventFactory = XMLEventFactory.newFactory();
        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch(evt.getEventType()) {
                case XMLEvent.START_ELEMENT:
                    {
                        StartElement sE = evt.asStartElement();
                        Hit hit = null;
                        JAXBElement<Hit> jaxbElement = null;
                        if (sE.getName().getLocalPart().equals("Hit")) {
                            jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                            hit = jaxbElement.getValue();
                        } else {
                            w.add(r.nextEvent());
                            break;
                        }
                        if (hit != null) {
                            bindings.put("hit", hit);
                            boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);
                            if (accept) {
                                marshaller.marshal(jaxbElement, w);
                                w.add(eventFactory.createCharacters("\n"));
                            }
                        }
                        break;
                    }
                case XMLEvent.SPACE:
                    break;
                default:
                    {
                        w.add(r.nextEvent());
                        break;
                    }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        LOG.error(err);
        return -1;
    } finally {
    }
}
Also used : CompiledScript(javax.script.CompiledScript) Marshaller(javax.xml.bind.Marshaller) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) XMLEventFactory(javax.xml.stream.XMLEventFactory) StreamSource(javax.xml.transform.stream.StreamSource) JAXBContext(javax.xml.bind.JAXBContext) JAXBElement(javax.xml.bind.JAXBElement) StartElement(javax.xml.stream.events.StartElement) Hit(gov.nih.nlm.ncbi.blast.Hit) XMLEventWriter(javax.xml.stream.XMLEventWriter) SimpleBindings(javax.script.SimpleBindings) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) File(java.io.File) XMLInputFactory(javax.xml.stream.XMLInputFactory) PrintWriter(java.io.PrintWriter)

Example 88 with SimpleBindings

use of javax.script.SimpleBindings in project spring-framework by spring-projects.

the class ScriptTemplateView method renderInternal.

@Override
protected Mono<Void> renderInternal(Map<String, Object> model, @Nullable MediaType contentType, ServerWebExchange exchange) {
    return exchange.getResponse().writeWith(Mono.fromCallable(() -> {
        try {
            ScriptEngine engine = getEngine();
            String url = getUrl();
            Assert.state(url != null, "'url' not set");
            String template = getTemplate(url);
            Function<String, String> templateLoader = path -> {
                try {
                    return getTemplate(path);
                } catch (IOException ex) {
                    throw new IllegalStateException(ex);
                }
            };
            Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
            RenderingContext context = new RenderingContext(obtainApplicationContext(), locale, templateLoader, url);
            Object html;
            if (this.renderFunction == null) {
                SimpleBindings bindings = new SimpleBindings();
                bindings.putAll(model);
                model.put("renderingContext", context);
                html = engine.eval(template, bindings);
            } else if (this.renderObject != null) {
                Object thiz = engine.eval(this.renderObject);
                html = ((Invocable) engine).invokeMethod(thiz, this.renderFunction, template, model, context);
            } else {
                html = ((Invocable) engine).invokeFunction(this.renderFunction, template, model, context);
            }
            byte[] bytes = String.valueOf(html).getBytes(StandardCharsets.UTF_8);
            // just wrapping, no allocation
            return exchange.getResponse().bufferFactory().wrap(bytes);
        } catch (ScriptException ex) {
            throw new IllegalStateException("Failed to render script template", new StandardScriptEvalException(ex));
        } catch (Exception ex) {
            throw new IllegalStateException("Failed to render script template", ex);
        }
    }));
}
Also used : Locale(java.util.Locale) Function(java.util.function.Function) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine) ApplicationContextException(org.springframework.context.ApplicationContextException) ScriptException(javax.script.ScriptException) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException)

Example 89 with SimpleBindings

use of javax.script.SimpleBindings in project serverless by bluenimble.

the class MacroSourceCommand method execute.

@Override
public CommandResult execute(final Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    InputStream input = null;
    SimpleBindings bindings = new SimpleBindings();
    String command = (String) tool.currentContext().get(ToolContext.CommandLine);
    if (!Lang.isNullOrEmpty(command)) {
        bindings.put("Command", command);
    }
    bindings.put("Home", BlueNimble.Work);
    bindings.put("Config", BlueNimble.Config);
    bindings.put("Tool", new JsTool(tool));
    bindings.put(JavaClass, new Function<String, Class<?>>() {

        @Override
        public Class<?> apply(String type) {
            try {
                return MacroSourceCommand.class.getClassLoader().loadClass(type);
            } catch (ClassNotFoundException cnfe) {
                throw new RuntimeException(cnfe);
            }
        }
    });
    bindings.put("Vars", tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS));
    Keys keys = BlueNimble.keys();
    if (keys != null) {
        bindings.put("Keys", keys.json());
    }
    try {
        input = new FileInputStream(script);
        List<InputStream> blocks = new ArrayList<InputStream>();
        blocks.add(new ByteArrayInputStream(Native.getBytes()));
        blocks.add(input);
        Engine.eval(new InputStreamReader(new SequenceInputStream(Collections.enumeration(blocks))), bindings);
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(input);
    }
    return null;
}
Also used : JsTool(com.bluenimble.platform.icli.mgm.utils.JsTool) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SimpleBindings(javax.script.SimpleBindings) Keys(com.bluenimble.platform.icli.mgm.Keys) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException)

Example 90 with SimpleBindings

use of javax.script.SimpleBindings in project java8-tutorial by winterbe.

the class Nashorn11 method test6.

private static void test6() throws ScriptException {
    NashornScriptEngine engine = createEngine();
    ScriptContext defaultContext = engine.getContext();
    defaultContext.getBindings(ScriptContext.GLOBAL_SCOPE).put("foo", "hello");
    ScriptContext customContext = new SimpleScriptContext();
    customContext.setBindings(defaultContext.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.ENGINE_SCOPE);
    Bindings bindings = new SimpleBindings();
    bindings.put("foo", "world");
    customContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
    // engine.eval("foo = 23;");                 // overrides foo in all contexts, why???
    // hello
    engine.eval("print(foo)");
    // world
    engine.eval("print(foo)", customContext);
    // hello
    engine.eval("print(foo)", defaultContext);
}
Also used : SimpleScriptContext(javax.script.SimpleScriptContext) SimpleBindings(javax.script.SimpleBindings) NashornScriptEngine(jdk.nashorn.api.scripting.NashornScriptEngine) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings)

Aggregations

SimpleBindings (javax.script.SimpleBindings)102 Bindings (javax.script.Bindings)65 ScriptEngine (javax.script.ScriptEngine)23 Test (org.junit.Test)22 ScriptContext (javax.script.ScriptContext)17 ScriptException (javax.script.ScriptException)17 ScriptEngineManager (javax.script.ScriptEngineManager)16 SimpleScriptContext (javax.script.SimpleScriptContext)15 Test (org.testng.annotations.Test)11 CompiledScript (javax.script.CompiledScript)10 PrintWriter (java.io.PrintWriter)9 HashMap (java.util.HashMap)8 Map (java.util.Map)8 SlingBindings (org.apache.sling.api.scripting.SlingBindings)7 File (java.io.File)6 StringWriter (java.io.StringWriter)5 ArrayList (java.util.ArrayList)4 XMLEventReader (javax.xml.stream.XMLEventReader)4 XMLEventWriter (javax.xml.stream.XMLEventWriter)4 XMLInputFactory (javax.xml.stream.XMLInputFactory)4