List of usage examples for javax.script SimpleBindings put
public Object put(String name, Object value)
From source file:JrubyTest.java
/** * //from w w w . j a va2 s . c o m * @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:JrubyTest.java
/** * //from www. j a va 2 s .c o m */ @Test public void repeatedTitle() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("jruby"); Reader scriptReader = null; InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream("test-specifications.xls"); Workbook workbook = load(in); Book book = new Book(workbook); scriptReader = new InputStreamReader( getClass().getClassLoader().getResourceAsStream("test-specification-repeated-title.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:JrubyTest.java
/** * ?Excel????/*from ww w . j a va2s . c o m*/ * * @throws Exception */ @Test public void parseTestSpecification() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("jruby"); Reader scriptReader = null; InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream("test-specifications.xls"); Workbook workbook = load(in); Book book = new Book(workbook); scriptReader = new InputStreamReader( getClass().getClassLoader().getResourceAsStream("test-specification-parser.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.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java
@Override protected Collection<Throwable> call(String inputName) throws Exception { final CompiledScript compiledScript; Unmarshaller unmarshaller;//from w w w .j a v a 2s. c o m Marshaller marshaller; try { compiledScript = super.compileJavascript(); 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(); XMLOutputFactory xof = XMLOutputFactory.newFactory(); xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); XMLEventWriter w = xof.createXMLEventWriter(pw); 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) { return wrapException(err); } finally { } }
From source file:net.unit8.longadeseo.plugin.impl.JRubyExcelPlugin.java
@Override public void afterService(DavResource resource, InputStream in) { try {//from w ww .j ava2 s . c o m Workbook workbook = load(in); Book book = new Book(workbook); SimpleBindings bindings = new SimpleBindings(); bindings.put("@book", book); script.eval(bindings); } catch (Exception e) { throw new PluginExecutionException(e); } }
From source file:org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor.java
private void iterateBytecodeTraversal(final Context context) throws Exception { final RequestMessage msg = context.getRequestMessage(); logger.debug("Traversal request {} for in thread {}", msg.getRequestId(), Thread.currentThread().getName()); // right now the TraversalOpProcessor can take a direct GraphSON representation of Bytecode or directly take // deserialized Bytecode object. final Object bytecodeObj = msg.getArgs().get(Tokens.ARGS_GREMLIN); final Bytecode bytecode = bytecodeObj instanceof Bytecode ? (Bytecode) bytecodeObj : mapper.readValue(bytecodeObj.toString(), Bytecode.class); // earlier validation in selection of this op method should free us to cast this without worry final Map<String, String> aliases = (Map<String, String>) msg.optionalArgs(Tokens.ARGS_ALIASES).get(); final GraphManager graphManager = context.getGraphManager(); final String traversalSourceName = aliases.entrySet().iterator().next().getValue(); final TraversalSource g = graphManager.getTraversalSource(traversalSourceName); final Traversal.Admin<?, ?> traversal; try {/*from ww w .j ava 2 s . com*/ final Optional<String> lambdaLanguage = BytecodeHelper.getLambdaLanguage(bytecode); if (!lambdaLanguage.isPresent()) traversal = JavaTranslator.of(g).translate(bytecode); else { final SimpleBindings b = new SimpleBindings(); b.put(Tokens.VAL_TRAVERSAL_SOURCE_ALIAS, g); traversal = context.getGremlinExecutor().eval(bytecode, b, lambdaLanguage.get()); } } catch (Exception ex) { logger.error("Could not deserialize the Traversal instance", context); throw new OpProcessorException("Could not deserialize the Traversal instance", ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); } final Timer.Context timerContext = traversalOpTimer.time(); try { final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final Graph graph = g.getGraph(); context.getGremlinExecutor().getExecutorService().submit(() -> { try { beforeProcessing(graph, context); try { // compile the traversal - without it getEndStep() has nothing in it traversal.applyStrategies(); handleIterator(context, new TraverserIterator(traversal), graph); } catch (TimeoutException ex) { final String errorMessage = String.format( "Response iteration exceeded the configured threshold for request [%s] - %s", msg.getRequestId(), ex.getMessage()); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).statusAttributeException(ex).create()); onError(graph, context); return; } catch (Exception ex) { logger.warn(String.format("Exception processing a Traversal on iteration for request [%s].", msg.getRequestId()), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); onError(graph, context); return; } } catch (Exception ex) { logger.warn( String.format("Exception processing a Traversal on request [%s].", msg.getRequestId()), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); onError(graph, context); } finally { timerContext.stop(); } }); } catch (Exception ex) { timerContext.stop(); throw new OpProcessorException("Could not iterate the Traversal instance", ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR).statusMessage(ex.getMessage()) .statusAttributeException(ex).create()); } }
From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java
private SimpleBindings createBindings(GraphMLEdge edge) { SimpleBindings bindings = new SimpleBindings(); bindings.put("edge", edge); bindings.put("sourceNode", getNodeForEdgeVertexConnector(edge.getSource())); bindings.put("targetNode", getNodeForEdgeVertexConnector(edge.getTarget())); bindings.put("measurements", new MeasurementsWrapper(serviceAccessor.getMeasurementsService())); bindings.put("nodeDao", serviceAccessor.getNodeDao()); bindings.put("snmpInterfaceDao", serviceAccessor.getSnmpInterfaceDao()); return bindings; }
From source file:utybo.branchingstorytree.swing.impl.XSFClient.java
@Override public Object invokeScript(String resourceName, String function, XSFBridge bst, BranchingStory story, int line) throws BSTException { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript"); SimpleBindings binds = new SimpleBindings(); binds.putAll(story.getRegistry().getAllInt()); binds.putAll(story.getRegistry().getAllString()); binds.put("bst", bst); scriptEngine.setBindings(binds, ScriptContext.ENGINE_SCOPE); try {// w w w . j a v a 2 s. c om scriptEngine.eval(scripts.get(resourceName)); return scriptEngine.eval(function + "()"); } catch (ScriptException e) { throw new BSTException(line, "Script exception : " + e.getMessage(), story); } }