org.apache.commons.io.input.ReaderInputStream Java Examples

The following examples show how to use org.apache.commons.io.input.ReaderInputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TarReader.java    From metafacture-core with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Reader reader) {
    try (
            InputStream stream = new ReaderInputStream(reader,
                    Charset.defaultCharset());
            ArchiveInputStream tarStream = new TarArchiveInputStream(stream);
    ) {
        ArchiveEntry entry;
        while ((entry = tarStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                processFileEntry(tarStream);
            }
        }
    } catch (IOException e) {
        throw new MetafactureException(e);
    }
}
 
Example #2
Source File: JsonPayloadIOTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnmarshall_Simple() throws Exception {
    String json = "{\r\n" +
            "  \"hello\" : \"world\",\r\n" +
            "  \"foo\" : \"bar\"\r\n" +
            "}";

    JsonPayloadIO io = new JsonPayloadIO();
    Map data = io.unmarshall(new ReaderInputStream(new StringReader(json)));
    Assert.assertNotNull(data);
    Assert.assertEquals("world", data.get("hello"));
    Assert.assertEquals("bar", data.get("foo"));
    Assert.assertNull(data.get("other"));

    data = io.unmarshall(json.getBytes("UTF-8"));
    Assert.assertNotNull(data);
    Assert.assertEquals("world", data.get("hello"));
    Assert.assertEquals("bar", data.get("foo"));
    Assert.assertNull(data.get("other"));
}
 
Example #3
Source File: DocumentIndexer.java    From act with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processPatentText(File patentFile, Reader patentTextReader, int patentTextLength)
    throws IOException, ParserConfigurationException,
    SAXException, TransformerConfigurationException,
    TransformerException, XPathExpressionException {
  PatentDocument patentDocument = PatentDocument.patentDocumentFromXMLStream(
      new ReaderInputStream(patentTextReader, Charset.forName("utf-8")));
  if (patentDocument == null) {
    LOGGER.info("Found non-patent type document, skipping.");
    return;
  }
  Document doc = patentDocToLuceneDoc(patentFile, patentDocument);
  LOGGER.debug("Adding document: " + doc.get("id"));
  this.indexWriter.addDocument(doc);
  this.indexWriter.commit();
}
 
Example #4
Source File: PatentScorer.java    From act with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processPatentText(File patentFile, Reader patentTextReader, int patentTextLength)
    throws IOException, ParserConfigurationException,
    SAXException, TransformerConfigurationException,
    TransformerException, XPathExpressionException {

  System.out.println("Patent text length: " + patentTextLength);
  CharBuffer buff = CharBuffer.allocate(patentTextLength);
  int read = patentTextReader.read(buff);
  System.out.println("Read bytes: " + read);
  patentTextReader.reset();
  String fullContent = new String(buff.array());

  PatentDocument patentDocument = PatentDocument.patentDocumentFromXMLStream(
      new ReaderInputStream(patentTextReader, Charset.forName("utf-8")));
  if (patentDocument == null) {
    LOGGER.info("Found non-patent type document, skipping.");
    return;
  }

  double pr = this.patentModel.ProbabilityOf(fullContent);
  this.outputWriter.write(objectMapper.writeValueAsString(new ClassificationResult(patentDocument.getFileId(), pr)));
  this.outputWriter.write(LINE_SEPARATOR);
  System.out.println("Doc " + patentDocument.getFileId() + " has score " + pr);
}
 
Example #5
Source File: JavaScriptUrlRewriteStreamFilter.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream filter(
    InputStream stream,
    String encoding,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {

  if ( config != null ) {
    return new ReaderInputStream(
        new JavaScriptUrlRewriteFilterReader(
            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
  } else {
    return stream;
  }
}
 
Example #6
Source File: XmlUrlRewriteStreamFilter.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream filter(
    InputStream stream,
    String encoding,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {
  try {
    return new ReaderInputStream(
        new XmlUrlRewriteFilterReader(
            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
  } catch( ParserConfigurationException | XMLStreamException e ) {
    throw new IOException( e );
  }
}
 
Example #7
Source File: HtmlUrlRewriteStreamFilter.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream filter(
    InputStream stream,
    String encoding,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {
  try {
    return new ReaderInputStream(
        new HtmlUrlRewriteFilterReader(
            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
  } catch( ParserConfigurationException e ) {
    throw new IOException( e );
  }
}
 
Example #8
Source File: UtilsTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaveImage() throws Exception {
  final DockerClient dockerClient = mock(DockerClient.class);
  final Log log = mock(Log.class);
  final Path path = Files.createTempFile(IMAGE, ".tgz");
  final String imageDataLine = "TestDataForDockerImage";

  Mockito.doAnswer(new Answer<InputStream>() {
      @Override
      public InputStream answer(InvocationOnMock invocation) throws Throwable {
          return new ReaderInputStream(new StringReader(imageDataLine));
      }
  }).when(dockerClient).save(IMAGE);

  try {
      Utils.saveImage(dockerClient, IMAGE, path, log);
      verify(dockerClient).save(eq(IMAGE));
  } finally {
      if (Files.exists(path)) {
          Files.delete(path);
      }
  }
}
 
Example #9
Source File: ClueWebSearcher.java    From SEAL with Apache License 2.0 6 votes vote down vote up
/** Utility method:
 * Formulate an HTTP POST request to upload the batch query file
 * @param queryBody
 * @return
 * @throws UnsupportedEncodingException
 */
private HttpPost makePost(String queryBody) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(ClueWebSearcher.BATCH_CATB_BASEURL);
    InputStreamBody qparams = 
        new InputStreamBody(
                new ReaderInputStream(new StringReader(queryBody)),
                "text/plain",
        "query.txt");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("viewstatus", new StringBody("1")); 
    entity.addPart("indextype",  new StringBody("catbparams"));
    entity.addPart("countmax",   new StringBody("100"));
    entity.addPart("formattype", new StringBody(format));
    entity.addPart("infile",     qparams);

    post.setEntity(entity);
    return post;
}
 
Example #10
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void readFrom(Reader in, Syntax syntax, String baseURI)
		throws IOException, ModelRuntimeException,
		SyntaxNotSupportedException {
	ReaderInputStream is = new ReaderInputStream(in, StandardCharsets.UTF_8);
	readFrom(is, syntax, baseURI);
}
 
Example #11
Source File: BartWorksCrossmod.java    From bartworks with MIT License 5 votes vote down vote up
@Mod.EventHandler
public void onFMLServerStart(FMLServerStartingEvent event) {
    if (LoaderReference.miscutils)
        for (Object s : RadioHatchCompat.TranslateSet){
            StringTranslate.inject(new ReaderInputStream(new StringReader((String) s)));
        }
}
 
Example #12
Source File: FormUrlRewriteStreamFilter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream filter(
    InputStream stream,
    String encoding,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {
  return new ReaderInputStream(
      new FormUrlRewriteFilterReader(
          new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
}
 
Example #13
Source File: JsonUrlRewriteStreamFilter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream filter(
    InputStream stream,
    String encoding,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {
  return new ReaderInputStream(
      new JsonUrlRewriteFilterReader(
          new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
}
 
Example #14
Source File: SwingBoxEditorKit.java    From SwingBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void read(Reader in, Document doc, int pos) throws IOException,
        BadLocationException
{

    if (doc instanceof org.fit.cssbox.swingbox.SwingBoxDocument)
    {
        InputStream is = new ReaderInputStream(in);
        readImpl(is, (org.fit.cssbox.swingbox.SwingBoxDocument) doc, pos);
    }
    else
    {
        super.read(in, doc, pos);
    }
}
 
Example #15
Source File: NetconfDeviceConfigSynchronizerProviderTest.java    From onos with Apache License 2.0 5 votes vote down vote up
protected CompositeStream toCompositeStream(String id, String inXml) {
    try {
        InputStream xml = new ReaderInputStream(
                     CharSource.wrap(inXml)
                         .openStream());

        return new DefaultCompositeStream(id, xml);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #16
Source File: ServerFileImplTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public void create() throws Exception {
  assertResourceNotExists(workspace, "project/file");

  StringReader reader = new StringReader("content");
  file.create(new ReaderInputStream(reader));

  assertResourceExists(workspace, "project/file");
  assertFileHasContent(workspace, "project/file", "content");
}
 
Example #17
Source File: ServerFileImplTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void createExistent() throws Exception {
  createFile(workspace, "project/file");

  StringReader reader = new StringReader("content");
  file.create(new ReaderInputStream(reader));
}
 
Example #18
Source File: ServerFileImplTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void setContents() throws Exception {
  createFile(workspace, "project/file", "old content");

  StringReader reader = new StringReader("new content");
  file.setContents(new ReaderInputStream(reader));

  assertFileHasContent(workspace, "project/file", "new content");
}
 
Example #19
Source File: ServerFileImplTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void setContentsOfNonExistent() throws Exception {
  assertResourceNotExists(workspace, "project/file");

  StringReader reader = new StringReader("new content");
  file.setContents(new ReaderInputStream(reader));

  assertFileHasContent(workspace, "project/file", "new content");
}
 
Example #20
Source File: Message.java    From iaf with Apache License 2.0 5 votes vote down vote up
public InputStream asInputStream(String defaultCharset) throws IOException {
	if (request == null) {
		return null;
	}
	if (request instanceof InputStream) {
		log.debug("returning InputStream as InputStream");
		return (InputStream) request;
	}
	if (request instanceof URL) {
		log.debug("returning URL as InputStream");
		return ((URL) request).openStream();
	}
	if (request instanceof File) {
		log.debug("returning File as InputStream");
		try {
			return new FileInputStream((File)request);
		} catch (IOException e) {
			throw new IOException("Cannot open file ["+((File)request).getPath()+"]");
		}
	}
	if (StringUtils.isEmpty(defaultCharset)) {
		defaultCharset=StreamUtil.DEFAULT_INPUT_STREAM_ENCODING;
	}
	if (request instanceof Reader) {
		log.debug("returning Reader as InputStream");
		return new ReaderInputStream((Reader) request, defaultCharset);
	}
	if (request instanceof byte[]) {
		log.debug("returning byte[] as InputStream");
		return new ByteArrayInputStream((byte[]) request);
	}
	log.debug("returning String as InputStream");
	return new ByteArrayInputStream(request.toString().getBytes(defaultCharset));
}
 
Example #21
Source File: JavaXToInputStreamUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
    final String initialString = "text";
    final InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream());

    IOUtils.closeQuietly(targetStream);
}
 
Example #22
Source File: IOUtilsTest.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    File f = new File(FILE_PATH);
    assertTrue(f.delete());
    String msg = "yuzhouwan";

    System.setIn(new ReaderInputStream(new StringReader(msg)));
    IOUtils.copyBytes(System.in, new FileOutputStream(f), DEFAULT_IO_LENGTH);

    byte[] buff = new byte[DEFAULT_IO_LENGTH];
    int len = new FileInputStream(f).read(buff, 0, msg.getBytes().length);

    assertEquals(msg, new String(buff, 0, len));
}
 
Example #23
Source File: DriverCompilationCustomizer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private String hash(SourceUnit source) {
   try(InputStream is = new ReaderInputStream(source.getSource().getReader())) {
      return Utils.shortHash(is);
   }
   catch(Exception e) {
      LOGGER.warn("Error hashing {}", source.getName(), e);
      return null;
   }
}
 
Example #24
Source File: TestApplicationMasterRestClient.java    From samza with Apache License 2.0 5 votes vote down vote up
private void setupMockClientResponse(int statusCode, String statusReason, String responseBody) throws IOException {
  StatusLine statusLine = mock(StatusLine.class);
  when(statusLine.getStatusCode()).thenReturn(statusCode);
  when(statusLine.getReasonPhrase()).thenReturn(statusReason);

  HttpEntity entity = mock(HttpEntity.class);
  when(entity.getContent()).thenReturn(new ReaderInputStream(new StringReader(responseBody)));

  CloseableHttpResponse response = mock(CloseableHttpResponse.class);
  when(response.getStatusLine()).thenReturn(statusLine);
  when(response.getEntity()).thenReturn(entity);

  when(mockClient.execute(any(HttpHost.class), any(HttpGet.class))).thenReturn(response);
}
 
Example #25
Source File: WordCountProcessor.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public void processPatentText(File patentFile, Reader patentTextReader, int patentTextLength)
    throws IOException, ParserConfigurationException, SAXException,
    TransformerConfigurationException, TransformerException, XPathExpressionException {

  PatentDocument doc = PatentDocument.patentDocumentFromXMLStream(new ReaderInputStream(patentTextReader));
  if (doc == null) {
    LOGGER.warn(String.format("Got null patent document object for patent at %s", patentFile.getAbsolutePath()));
    return;
  }
  // Put all the text back together into one big string.  Sigh.
  List<String> textFields = new ArrayList<String>(1 + doc.getClaimsText().size() + doc.getTextContent().size());
  textFields.add(doc.getTitle());
  textFields.addAll(doc.getClaimsText());
  textFields.addAll(doc.getTextContent());
  String joinedText = StringUtils.join(textFields, "\n");

  // TODO: parallelize this.  Because come on, it's the nineties and Map Reduce is almost a thousand years old.
  Map<String, Integer> wordCount = new HashMap<>();
  List<String> words = this.tokenizer.tokenize(joinedText);
  for (String word : words) {
    if (EXCLUDE_NUMBERS.matcher(word).matches()) {
      continue; // Ignore words that are just numbers (with decimals)
    }

    word = word.toLowerCase();
    if (stopWords.contains(word)) {
      continue; // Ignore stop words;
    }

    Integer count = wordCount.get(word);
    if (count == null) {
      count = 1;
    }
    wordCount.put(word, count + 1);
  }

  PatentDocumentWordCount pdwc = new PatentDocumentWordCount(patentFile.getAbsolutePath(), wordCount);
  System.out.println(objectMapper.writeValueAsString(pdwc));
}
 
Example #26
Source File: ConvertStringAndInputStreamTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void convertStringToOrFromInputStream() throws IOException {
    /*             1. Using Apache Utils */
    // convert String to InputStream
    InputStream inputStreamApache = IOUtils.toInputStream("test1", StandardCharsets.UTF_8);
    // convert InputStream to String
    String stringApache = IOUtils.toString(inputStreamApache, StandardCharsets.UTF_8);
    System.out.println(stringApache); // print test1

    /*             2. Using JDK */
    // convert String to InputStream
    InputStream inputStreamJDK = new ByteArrayInputStream("test2".getBytes(StandardCharsets.UTF_8));

    // convert InputStream to String
    BufferedReader str = new BufferedReader(new InputStreamReader(inputStreamJDK));
    String stringJDK = str.readLine();
    System.out.println(stringJDK); // print test2

    /*             3. Using guava */
    // convert String to InputStream
    InputStream targetStreamGuava = new ReaderInputStream(CharSource.wrap("test3").openStream());

    // convert InputStream to String
    String stringGuava = CharStreams.toString(new InputStreamReader(targetStreamGuava, Charsets.UTF_8));
    System.out.println(stringGuava); // print test3


    /*             4. Using JDK and Scanner*/
    InputStream inputStreamForScanner = new ReaderInputStream(CharSource.wrap("test4").openStream());
    // convert InputStream to String
    java.util.Scanner s = new java.util.Scanner(inputStreamForScanner).useDelimiter("\\A");
    String stringScanner = s.hasNext() ? s.next() : "";
    System.out.println(stringScanner);

    /*             5. Using Java 8 */
    InputStream inputStreamForJava8 = new ReaderInputStream(CharSource.wrap("test5").openStream());
    // convert InputStream to String
    String stringJava8 = new BufferedReader(new InputStreamReader(inputStreamForJava8)).lines().collect(Collectors.joining("\n"));
    System.out.println(stringJava8);
}
 
Example #27
Source File: ConvertStringAndInputStreamTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void convertStringToOrFromInputStream() throws IOException {
    /*             1. Using Apache Utils */
    // convert String to InputStream
    InputStream inputStreamApache = IOUtils.toInputStream("test1", StandardCharsets.UTF_8);
    // convert InputStream to String
    String stringApache = IOUtils.toString(inputStreamApache, StandardCharsets.UTF_8);
    System.out.println(stringApache); // print test1

    /*             2. Using JDK */
    // convert String to InputStream
    InputStream inputStreamJDK = new ByteArrayInputStream("test2".getBytes(StandardCharsets.UTF_8));

    // convert InputStream to String
    BufferedReader str = new BufferedReader(new InputStreamReader(inputStreamJDK));
    String stringJDK = str.readLine();
    System.out.println(stringJDK); // print test2

    /*             3. Using guava */
    // convert String to InputStream
    InputStream targetStreamGuava = new ReaderInputStream(CharSource.wrap("test3").openStream());

    // convert InputStream to String
    String stringGuava = CharStreams.toString(new InputStreamReader(targetStreamGuava, Charsets.UTF_8));
    System.out.println(stringGuava); // print test3


    /*             4. Using JDK and Scanner*/
    InputStream inputStreamForScanner = new ReaderInputStream(CharSource.wrap("test4").openStream());
    // convert InputStream to String
    java.util.Scanner s = new java.util.Scanner(inputStreamForScanner).useDelimiter("\\A");
    String stringScanner = s.hasNext() ? s.next() : "";
    System.out.println(stringScanner);

    /*             5. Using Java 8 */
    InputStream inputStreamForJava8 = new ReaderInputStream(CharSource.wrap("test5").openStream());
    // convert InputStream to String
    String stringJava8 = new BufferedReader(new InputStreamReader(inputStreamForJava8)).lines().collect(Collectors.joining("\n"));
    System.out.println(stringJava8);
}
 
Example #28
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
 * 
 * @author wayshall
 * @param object
 * @param contentType example: MediaType.APPLICATION_OCTET_STREAM_VALUE
 * @return
 */
public ObjectOperation storeAsJson(Object object, String contentType){
	String json = JsonMapper.DEFAULT_MAPPER.toJson(object);
	StringReader sr = new StringReader(json);
	ObjectMetadata meta = new ObjectMetadata();
	meta.setContentType(contentType);
	return store(new ReaderInputStream(sr), meta);
}
 
Example #29
Source File: ReConfigurableBeanTest.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    String config;
    try(StringWriter sw = new StringWriter();
        OutputStream osw = new WriterOutputStream(sw, StandardCharsets.UTF_8)) {
        service.write(MimeTypeUtils.APPLICATION_JSON_VALUE, osw);
        config = sw.toString();
    }
    System.out.println(config);
    try (StringReader sr = new StringReader(config);
         InputStream is = new ReaderInputStream(sr, StandardCharsets.UTF_8)) {
        service.read(MimeTypeUtils.APPLICATION_JSON_VALUE, is);
    }
    sampleBean.check();
}
 
Example #30
Source File: CosClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
 * 
 * @author wayshall
 * @param object
 * @param contentType example: MediaType.APPLICATION_OCTET_STREAM_VALUE
 * @return
 */
public ObjectOperation storeAsJson(Object object, String contentType){
	String json = JsonMapper.DEFAULT_MAPPER.toJson(object);
	StringReader sr = new StringReader(json);
	ObjectMetadata meta = new ObjectMetadata();
	meta.setContentType(contentType);
	return store(new ReaderInputStream(sr), meta);
}