List of usage examples for org.apache.commons.io.input ReaderInputStream ReaderInputStream
public ReaderInputStream(Reader reader)
From source file:com.act.lcms.MzMLParser.java
public Iterator<S> getIterator(String inputFile) throws ParserConfigurationException, IOException, XMLStreamException { DocumentBuilderFactory docFactory = mkDocBuilderFactory(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); return new Iterator<S>() { boolean inEntry = false; XMLEventReader xr = xmlInputFactory.createXMLEventReader(new FileInputStream(inputFile), "utf-8"); // TODO: is the use of the XML version/encoding tag definitely necessary? StringWriter w = new StringWriter().append(XML_PREAMBLE).append("\n"); XMLEventWriter xw = xmlOutputFactory.createXMLEventWriter(w); S next = null;/*from w w w . ja v a 2 s . c o m*/ /* Because we're handling the XML as a stream, we can only determine whether we have another Spectrum to return * by attempting to parse the next one. `this.next()` reads */ private S getNextSpectrum() { S spectrum = null; if (xr == null || !xr.hasNext()) { return null; } try { while (xr.hasNext()) { XMLEvent e = xr.nextEvent(); if (!inEntry && e.isStartElement() && e.asStartElement().getName().getLocalPart().equals((SPECTRUM_OBJECT_TAG))) { xw.add(e); inEntry = true; } else if (e.isEndElement() && e.asEndElement().getName().getLocalPart().equals(SPECTRUM_OBJECT_TAG)) { xw.add(e); xw.flush(); /* TODO: the XMLOutputFactory docs don't make it clear if/how events can be written directly into a new * document structure, so we incur the cost of extracting each spectrum entry, serializing it, and * re-reading it into its own document so it can be handled by XPath. Master this strange corner of the * Java ecosystem and get rid of <></>his doc -> string -> doc conversion. */ Document doc = docBuilder.parse(new ReaderInputStream(new StringReader(w.toString()))); spectrum = handleSpectrumEntry(doc); xw.close(); /* Note: this can also be accomplished with `w.getBuffer().setLength(0);`, but using a new event writer * seems safer. */ w = new StringWriter(); w.append(XML_PREAMBLE).append("\n"); xw = xmlOutputFactory.createXMLEventWriter(w); inEntry = false; // Don't stop parsing if handleSpectrumEntry didn't like this spectrum document. if (spectrum != null) { break; } } else if (inEntry) { // Add this element if we're in an entry xw.add(e); } } // We've reached the end of the document; close the reader to show that we're done. if (!xr.hasNext()) { xr.close(); xr = null; } } catch (Exception e) { // TODO: do better. We seem to run into this sort of thing with Iterators a lot... throw new RuntimeException(e); } return spectrum; } private S tryParseNext() { // Fail the attempt if the reader is closed. if (xr == null || !xr.hasNext()) { return null; } // No checks on whether we already have a spectrum stored: we expect the callers to do that. return getNextSpectrum(); } @Override public boolean hasNext() { // Prime the pump if the iterator doesn't have a value stored yet. if (this.next == null) { this.next = tryParseNext(); } // If we have an entry waiting, return true; otherwise read the next entry and return true if successful. return this.next != null; } @Override public S next() { // Prime the pump like we do in hasNext(). if (this.next == null) { this.next = tryParseNext(); } // Take available spectrum and return it. S res = this.next; /* Advance to the next element immediately, making next() do the heavy lifting most of the time. Otherwise, * the parsing will resume on hasNext(), which seems like it ought to be a light-weight operation. */ this.next = tryParseNext(); return res; } }; }
From source file:com.seleritycorp.common.base.coreservices.RawCoreServicesClientTest.java
@Test public void testCallWriterWithNestedObject() throws Exception { JsonObject jsonResponse = new JsonObject(); JsonObject resultObject = new JsonObject(); JsonObject fooObject = new JsonObject(); JsonObject barObject = new JsonObject(); barObject.addProperty("test", 123); fooObject.add("bar", barObject); resultObject.add("foo", fooObject); jsonResponse.add("result", resultObject); HttpResponseStream response = createMock(HttpResponseStream.class); String fakeInput = jsonResponse.toString(); StringReader stringReader = new StringReader(fakeInput); ReaderInputStream fakeInputStream = new ReaderInputStream(stringReader); expect(response.getBodyAsStream()).andReturn(fakeInputStream); HttpRequest request = createMock(HttpRequest.class); expect(request.setReadTimeoutMillis(5)).andReturn(request); expect(request.executeAndStream()).andReturn(response); expect(metaDataFormatter.getUserAgent()).andReturn("quux"); Capture<JsonObject> jsonCapture = newCapture(); expect(requestFactory.createPostJson(eq("bar"), capture(jsonCapture))).andReturn(request); replayAll();/*from ww w .j av a 2 s . co m*/ RawCoreServiceClient client = createRawCoreServicesClient(); JsonObject params = new JsonObject(); params.addProperty("bar", 4711); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); client.call("baz", params, null, 5, writer); verifyAll(); assertThat(stringWriter.toString()).isEqualTo("{\"foo\":{\"bar\":{\"test\":123}}}"); JsonObject json = jsonCapture.getValue(); assertThat(json.get("id").getAsString()).isEqualTo("00000000-0000-0000-0000-000000000001"); assertThat(json.get("method").getAsString()).isEqualTo("baz"); assertThat(json.getAsJsonObject("params").get("bar").getAsInt()).isEqualTo(4711); assertThat(json.getAsJsonObject("header").get("user").getAsString()).isEqualTo("foo"); assertThat(json.getAsJsonObject("header").get("client").getAsString()).isEqualTo("quux"); assertThat(json.getAsJsonObject("header").get("token")).isNull(); }
From source file:com.marklogic.semantics.sesame.client.MarkLogicClient.java
/** * add triples from Reader/* ww w .jav a 2s.c o m*/ * * @param in * @param baseURI * @param dataFormat * @param contexts */ public void sendAdd(Reader in, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException, MarkLogicSesameException { //TBD- must deal with char encoding getClient().performAdd(new ReaderInputStream(in), baseURI, dataFormat, this.tx, contexts); }
From source file:adams.data.io.input.AbstractSpreadSheetReader.java
/** * Reads the spreadsheet from the given reader. The caller must ensure to * close the reader.//from w w w . java 2s . c om * * @param r the reader to read from * @return the spreadsheet or null in case of an error */ public SpreadSheet read(Reader r) { SpreadSheet result; check(); m_Stopped = false; m_LastError = null; try { switch (getInputType()) { case FILE: throw new IllegalStateException("Only supports reading from files, not input streams!"); case STREAM: result = doRead(new ReaderInputStream(r)); break; case READER: result = doRead(r); break; default: throw new IllegalStateException("Unhandled input type: " + getInputType()); } } catch (Exception e) { result = null; m_LastError = "Failed to read from reader!\n" + Utils.throwableToString(e); getLogger().severe(m_LastError); } if (m_Stopped) result = null; return result; }
From source file:com.seleritycorp.common.base.coreservices.RawCoreServicesClientTest.java
@Test public void testCallWriterWithArray() throws Exception { JsonObject jsonResponse = new JsonObject(); JsonObject resultObject = new JsonObject(); JsonArray fooArray = new JsonArray(); fooArray.add(123);/*from w w w. j a v a 2 s .com*/ fooArray.add(456); fooArray.add(789); resultObject.add("foo", fooArray); jsonResponse.add("result", resultObject); HttpResponseStream response = createMock(HttpResponseStream.class); String fakeInput = jsonResponse.toString(); StringReader stringReader = new StringReader(fakeInput); ReaderInputStream fakeInputStream = new ReaderInputStream(stringReader); expect(response.getBodyAsStream()).andReturn(fakeInputStream); HttpRequest request = createMock(HttpRequest.class); expect(request.setReadTimeoutMillis(5)).andReturn(request); expect(request.executeAndStream()).andReturn(response); expect(metaDataFormatter.getUserAgent()).andReturn("quux"); Capture<JsonObject> jsonCapture = newCapture(); expect(requestFactory.createPostJson(eq("bar"), capture(jsonCapture))).andReturn(request); replayAll(); RawCoreServiceClient client = createRawCoreServicesClient(); JsonObject params = new JsonObject(); params.addProperty("bar", 4711); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); client.call("baz", params, null, 5, writer); verifyAll(); assertThat(stringWriter.toString()).isEqualTo("{\"foo\":[123,456,789]}"); JsonObject json = jsonCapture.getValue(); assertThat(json.get("id").getAsString()).isEqualTo("00000000-0000-0000-0000-000000000001"); assertThat(json.get("method").getAsString()).isEqualTo("baz"); assertThat(json.getAsJsonObject("params").get("bar").getAsInt()).isEqualTo(4711); assertThat(json.getAsJsonObject("header").get("user").getAsString()).isEqualTo("foo"); assertThat(json.getAsJsonObject("header").get("client").getAsString()).isEqualTo("quux"); assertThat(json.getAsJsonObject("header").get("token")).isNull(); }
From source file:com.twentyn.patentExtractor.PatentDocument.java
/** * Converts a string of XML into a patent document object, extracting relevant fields from the patent XML. * * @param text The XML string to parse and extract. * @return A patent object if the XML can be read, or null otherwise. * @throws IOException/*from w w w . j a va2 s . c o m*/ * @throws ParserConfigurationException * @throws SAXException * @throws TransformerConfigurationException * @throws TransformerException * @throws XPathExpressionException */ public static PatentDocument patentDocumentFromXMLString(String text) throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException, TransformerException, XPathExpressionException { StringReader stringReader = new StringReader(text); return patentDocumentFromXMLStream(new ReaderInputStream(stringReader)); }
From source file:com.seleritycorp.common.base.coreservices.RawCoreServicesClientTest.java
@Test public void testCallWriterWithNestedObjectAndArray() throws Exception { JsonObject jsonResponse = new JsonObject(); JsonObject resultObject = new JsonObject(); JsonObject barObject = new JsonObject(); JsonArray fooArray = new JsonArray(); JsonObject objectOne = new JsonObject(); objectOne.addProperty("one", 1); JsonObject objectTwo = new JsonObject(); objectTwo.addProperty("two", 2); JsonObject objectThree = new JsonObject(); objectThree.addProperty("three", 3); fooArray.add(objectOne);//from w w w . j a va 2s . c o m fooArray.add(objectTwo); fooArray.add(objectThree); barObject.add("foo", fooArray); resultObject.add("bar", barObject); jsonResponse.add("result", resultObject); HttpResponseStream response = createMock(HttpResponseStream.class); String fakeInput = jsonResponse.toString(); StringReader stringReader = new StringReader(fakeInput); ReaderInputStream fakeInputStream = new ReaderInputStream(stringReader); expect(response.getBodyAsStream()).andReturn(fakeInputStream); HttpRequest request = createMock(HttpRequest.class); expect(request.setReadTimeoutMillis(5)).andReturn(request); expect(request.executeAndStream()).andReturn(response); expect(metaDataFormatter.getUserAgent()).andReturn("quux"); Capture<JsonObject> jsonCapture = newCapture(); expect(requestFactory.createPostJson(eq("bar"), capture(jsonCapture))).andReturn(request); replayAll(); RawCoreServiceClient client = createRawCoreServicesClient(); JsonObject params = new JsonObject(); params.addProperty("bar", 4711); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); client.call("baz", params, null, 5, writer); verifyAll(); assertThat(stringWriter.toString()) .isEqualTo("{\"bar\":{\"foo\":[{\"one\":1},{\"two\":2},{\"three\":3}]}}"); JsonObject json = jsonCapture.getValue(); assertThat(json.get("id").getAsString()).isEqualTo("00000000-0000-0000-0000-000000000001"); assertThat(json.get("method").getAsString()).isEqualTo("baz"); assertThat(json.getAsJsonObject("params").get("bar").getAsInt()).isEqualTo(4711); assertThat(json.getAsJsonObject("header").get("user").getAsString()).isEqualTo("foo"); assertThat(json.getAsJsonObject("header").get("client").getAsString()).isEqualTo("quux"); assertThat(json.getAsJsonObject("header").get("token")).isNull(); }
From source file:com.seleritycorp.common.base.http.client.HttpRequestTest.java
@Test public void testExecuteAndStreamOk() throws Exception { reset(responseFactory);/*from w w w . j a va2 s .com*/ StringReader stringReader = new StringReader("response"); ReaderInputStream readerInputStream = new ReaderInputStream(stringReader); expect(responseStreamFactory.create(backendResponse)).andReturn(httpResponseStream); expect(httpResponseStream.getBodyAsStream()).andReturn(readerInputStream); replayAll(); HttpRequest request = createHttpRequest("foo"); HttpResponseStream response = request.executeAndStream(); String result = IOUtils.toString(response.getBodyAsStream()); verifyAll(); assertThat(result).isEqualTo("response"); HttpUriRequest backendRequest = backendRequestCapture.getValue(); assertThat(backendRequest.getMethod()).isEqualTo("GET"); assertThat(backendRequest.getURI().toString()).isEqualTo("foo"); }
From source file:net.sourceforge.pmd.util.datasource.ReaderDataSource.java
/** * Convert the Reader into an InputStream. * <p>//from w ww . j av a 2 s .c o m * <strong>Note:</strong> This uses the default encoding. * </p> * * @return Derived InputStream * @throws IOException */ @Override public InputStream getInputStream() throws IOException { return new ReaderInputStream(reader); }
From source file:org.ambraproject.wombat.config.theme.StubTheme.java
@Override protected InputStream fetchStaticResource(String path) throws IOException { if (path.equals("config/journal.json")) { Map<String, Object> journalConfigMap = getJournalConfigMap(); return new ReaderInputStream(new StringReader(new Gson().toJson(journalConfigMap))); }// w w w . j av a 2 s . c om return null; }