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 {
}
}
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 {
}
}
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);
}
}));
}
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;
}
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);
}
Aggregations