java.io.SequenceInputStream Java Examples

The following examples show how to use java.io.SequenceInputStream. 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: ByteArrayOutputStream.java    From android-common with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #2
Source File: ByteArrayOutputStream.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since Commons IO 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #3
Source File: ByteArrayOutputStream.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #4
Source File: XmlSource.java    From beam with Apache License 2.0 6 votes vote down vote up
private void setUpXMLParser(ReadableByteChannel channel, byte[] lookAhead) throws IOException {
  try {
    // We use Woodstox because the StAX implementation provided by OpenJDK reports
    // character locations incorrectly. Note that Woodstox still currently reports *byte*
    // locations incorrectly when parsing documents that contain multi-byte characters.
    XMLInputFactory2 xmlInputFactory = (XMLInputFactory2) XMLInputFactory.newInstance();
    this.parser =
        xmlInputFactory.createXMLStreamReader(
            new SequenceInputStream(
                new ByteArrayInputStream(lookAhead), Channels.newInputStream(channel)),
            getCurrentSource().configuration.getCharset());

    // Current offset should be the offset before reading the record element.
    while (true) {
      int event = parser.next();
      if (event == XMLStreamConstants.START_ELEMENT) {
        String localName = parser.getLocalName();
        if (localName.equals(getCurrentSource().configuration.getRecordElement())) {
          break;
        }
      }
    }
  } catch (FactoryConfigurationError | XMLStreamException e) {
    throw new IOException(e);
  }
}
 
Example #5
Source File: SequenceResource.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream asStream() {
    return new SequenceInputStream(new Enumeration<InputStream>() {

        /**
         * Iterator over all resources associated with this
         * SequenceResource.
         */
        private final Iterator<Resource> resourceIterator = resources.iterator();

        @Override
        public boolean hasMoreElements() {
            return resourceIterator.hasNext();
        }

        @Override
        public InputStream nextElement() {
            return resourceIterator.next().asStream();
        }

    });
}
 
Example #6
Source File: SequenceInputStreamDemo.java    From Java with Artistic License 2.0 6 votes vote down vote up
private static void mergeTwo() throws IOException {
	// SequenceInputStream(InputStream s1, InputStream s2)
	InputStream s1 = new FileInputStream("MyBufferedReader.java");
	InputStream s2 = new FileInputStream("MyBufferedReaderDemo.java");
	SequenceInputStream sis = new SequenceInputStream(s1, s2);

	BufferedOutputStream bos = new BufferedOutputStream(
			new FileOutputStream("Copy.java"));

	byte[] bys = new byte[1024];
	int len = 0;
	while ((len = sis.read(bys)) != -1) {
		bos.write(bys, 0, len);
	}

	bos.close();
	sis.close();
}
 
Example #7
Source File: DicomStreamUtil.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
public static InputStream dicomStreamWithFileMetaHeader(
    String sopInstanceUID,
    String sopClassUID,
    String transferSyntax,
    InputStream inDicomStream) // PDVInputStream
    throws IOException {
  // File meta header (group 0002 tags), always in Explicit VR Little Endian.
  // http://dicom.nema.org/dicom/2013/output/chtml/part10/chapter_7.html
  ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
  DicomOutputStream fmiStream = new DicomOutputStream(outBuffer, UID.ExplicitVRLittleEndian);
  Attributes fmi =
      Attributes.createFileMetaInformation(sopInstanceUID, sopClassUID, transferSyntax);
  fmiStream.writeFileMetaInformation(fmi);

  // Add the file meta header + DICOM dataset (other groups) as a sequence of input streams.
  return new SequenceInputStream(
      new ByteArrayInputStream(outBuffer.toByteArray()), inDicomStream);
}
 
Example #8
Source File: ByteArrayOutputStream.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #9
Source File: ByteArrayOutputStream.java    From ToolsFinal with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #10
Source File: ByteArrayOutputStream.java    From FimiX8-RE with MIT License 6 votes vote down vote up
private InputStream toBufferedInputStream() {
    int remaining = this.count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList(this.buffers.size());
    for (byte[] buf : this.buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #11
Source File: RegisterPrecompiledJSPInitializer.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
private static WebApp parseXmlFragment() {
    InputStream precompiledJspWebXml = RegisterPrecompiledJSPInitializer.class.getResourceAsStream("/precompiled-jsp-web.xml");
    InputStream webXmlIS = new SequenceInputStream(
            new SequenceInputStream(
                    IOUtils.toInputStream("<web-app>", Charset.defaultCharset()),
                    precompiledJspWebXml),
            IOUtils.toInputStream("</web-app>", Charset.defaultCharset()));

    try {
        JAXBContext jaxbContext = new JAXBDataBinding(WebApp.class).getContext();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        WebApp webapp = (WebApp) unmarshaller.unmarshal(webXmlIS);
        try {
            webXmlIS.close();
        } catch (java.io.IOException ignored) {}
        return webapp;
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse precompiled-jsp-web.xml", e);
    }
}
 
Example #12
Source File: ByteArrayOutputStream.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #13
Source File: CompositeBufferViewTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link CompositeBufferView#slice(int, int)} and {@link CompositeBufferView#getReader(int, int)}.
 */
@Test
public void testSlice() throws IOException {
    val components = createComponents();
    val cb = BufferView.wrap(components);
    val expectedSize = components.stream().mapToInt(BufferView::getLength).sum();
    val expected = StreamHelpers.readAll(
            new SequenceInputStream(Iterators.asEnumeration(components.stream().map(BufferView::getReader).iterator())),
            expectedSize);
    for (int i = 0; i < expectedSize / 2; i++) {
        int sliceLength = expectedSize - i;
        val slice = cb.slice(i, sliceLength);
        val sliceData = slice.getCopy();
        AssertExtensions.assertArrayEquals("slice(offset, length)", expected, i, sliceData, 0, sliceLength);

        val sliceReader = cb.getReader(i, sliceLength);
        val sliceReaderData = StreamHelpers.readAll(sliceReader, sliceLength);
        AssertExtensions.assertArrayEquals("getReader(offset, length)", expected, i, sliceReaderData, 0, sliceLength);
    }
}
 
Example #14
Source File: CompositeBufferViewTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link BufferView#wrap(List)}.
 */
@Test
public void testWrap() throws IOException {
    val empty = BufferView.wrap(Collections.emptyList());
    Assert.assertSame(BufferView.empty(), empty);

    val b1 = new ByteArraySegment(new byte[]{1});
    val b2 = new ByteArraySegment(new byte[]{2});
    val single = BufferView.wrap(Collections.singletonList(b1));
    Assert.assertSame(b1, single);

    val composite = BufferView.wrap(Arrays.asList(b1, b2));
    Assert.assertEquals(b1.getLength() + b2.getLength(), composite.getLength());
    AssertExtensions.assertStreamEquals("",
            new SequenceInputStream(b1.getReader(), b2.getReader()), composite.getReader(), composite.getLength());

    val contentBufs = composite.getContents();
    val expectedContentBufs = Stream.of(b1, b2).flatMap(b -> b.getContents().stream()).collect(Collectors.toList());
    AssertExtensions.assertListEquals("", expectedContentBufs, contentBufs, ByteBuffer::equals);
}
 
Example #15
Source File: RegisterPrecompiledJSPInitializer.java    From airsonic with GNU General Public License v3.0 6 votes vote down vote up
private static WebApp parseXmlFragment() {
    InputStream precompiledJspWebXml = RegisterPrecompiledJSPInitializer.class.getResourceAsStream("/precompiled-jsp-web.xml");
    InputStream webXmlIS = new SequenceInputStream(
            new SequenceInputStream(
                    IOUtils.toInputStream("<web-app>", Charset.defaultCharset()),
                    precompiledJspWebXml),
            IOUtils.toInputStream("</web-app>", Charset.defaultCharset()));

    try {
        JAXBContext jaxbContext = new JAXBDataBinding(WebApp.class).getContext();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        WebApp webapp = (WebApp) unmarshaller.unmarshal(webXmlIS);
        try {
            webXmlIS.close();
        } catch (java.io.IOException ignored) {}
        return webapp;
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse precompiled-jsp-web.xml", e);
    }
}
 
Example #16
Source File: ByteArrayOutputStream.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 *
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.5
 */
public synchronized InputStream toInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    final List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (final byte[] buf : buffers) {
        final int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    reuseBuffers = false;
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #17
Source File: MultistreamXMLDumpParser.java    From dkpro-jwktl with Apache License 2.0 6 votes vote down vote up
private InputStream getInputStreamAtOffset(final RandomAccessFile file, long offset) throws IOException {
	if (offset + 2 >= file.length()) {
		throw new IOException("read past EOF");
	}
	file.seek(offset + 2); // skip past 'BZ' header
	InputStream is = new CBZip2InputStream(new FileInputStream(file.getFD()) {
		@Override
		public void close() throws IOException {
		}
	});
	if (offset == 0) {
		return new SequenceInputStream(is, new ByteArrayInputStream(MEDIAWIKI_CLOSING.getBytes()));
	} else {
		return new SequenceInputStream(
				new ByteArrayInputStream(MEDIAWIKI_OPENING.getBytes()),
				new SequenceInputStream(is,
						new ByteArrayInputStream(MEDIAWIKI_CLOSING.getBytes())));
	}
}
 
Example #18
Source File: NoOpStorageUserDataWriteOnlyTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
@Test
public void testWrite() throws Exception {
    String segmentName = "foo_write";
    int appendCount = 10;

    try (Storage s = createStorage()) {
        s.initialize(DEFAULT_EPOCH);
        createSegment(segmentName, s);

        val writeHandle = s.openWrite(segmentName).join();
        long offset = 0;
        for (int j = 0; j < appendCount; j++) {
            byte[] writeData = String.format(APPEND_FORMAT, segmentName, j).getBytes();

            val dataStream = new SequenceInputStream(new ByteArrayInputStream(writeData), new ByteArrayInputStream(new byte[100]));
            s.write(writeHandle, offset, dataStream, writeData.length, TIMEOUT).join();
            offset += writeData.length;
        }

    }
}
 
Example #19
Source File: StreamDecoder.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Automatically detects charset of the input stream, reads it, decodes it, and returns the
 * resulting string with a newline appended if the original stream is non-empty. Does not close
 * the provided input stream.
 *
 * @throws IOException if there is an error
 */
@SuppressWarnings("PMD.CloseResource") // PMD does not understand Closer.
static @Nonnull String decodeStreamAndAppendNewline(@Nonnull InputStream inputStream)
    throws IOException {
  byte[] rawBytes = IOUtils.toByteArray(inputStream);
  Charset cs = Charset.forName(new CharsetDetector().setText(rawBytes).detect().getName());
  try (Closer closer = Closer.create()) {
    InputStream inputByteStream =
        closer.register(bomInputStream(new ByteArrayInputStream(rawBytes)));
    InputStream finalInputStream =
        closer.register(
            rawBytes.length > 0
                ? new SequenceInputStream(
                    inputByteStream,
                    closer.register(bomInputStream(new ByteArrayInputStream("\n".getBytes(cs)))))
                : inputByteStream);
    return new String(IOUtils.toByteArray(finalInputStream), cs);
  }
}
 
Example #20
Source File: ProxyServlet.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * retryEnabled の時だけだよ
 * @return
 */
private ContentProvider createRetryContentProvider() {
    final HttpServletRequest request = this.request;

    return new InputStreamContentProvider(
            new SequenceInputStream(new ByteArrayInputStream(this.contentBuffer.toByteArray()),
                    this.contentInputStream)) {
        @Override
        public long getLength() {
            return request.getContentLength();
        }

        @Override
        protected ByteBuffer onRead(byte[] buffer, int offset, int length) {
            if (ProxyServlet.this._isDebugEnabled) {
                ProxyServlet.this._log
                        .debug("{} proxying content to upstream: {} bytes", getRequestId(request), length);
            }
            return super.onRead(buffer, offset, length);
        }
    };
}
 
Example #21
Source File: ByteArrayOutputStream.java    From AndroidBase with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #22
Source File: ByteArrayOutputStream.java    From rexxar-android with MIT License 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #23
Source File: ParquetFileReader.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
protected PageHeader readPageHeader() throws IOException {
  PageHeader pageHeader;
  stream.mark(8192); // headers should not be larger than 8k
  try {
    pageHeader = Util.readPageHeader(stream);
  } catch (IOException e) {
    // this is to workaround a bug where the compressedLength
    // of the chunk is missing the size of the header of the dictionary
    // to allow reading older files (using dictionary) we need this.
    // usually 13 to 19 bytes are missing
    // if the last page is smaller than this, the page header itself is truncated in the buffer.
    stream.reset(); // resetting the buffer to the position before we got the error
    LOG.info("completing the column chunk to read the page header");
    pageHeader = Util.readPageHeader(new SequenceInputStream(stream, f)); // trying again from the buffer + remainder of the stream.
  }
  return pageHeader;
}
 
Example #24
Source File: JSONProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected InputStream getInputStream(Class<T> cls, Type type, InputStream is) throws Exception {
    if (unwrapped) {
        String rootName = getRootName(cls, type);
        InputStream isBefore = new ByteArrayInputStream(rootName.getBytes());
        String after = "}";
        InputStream isAfter = new ByteArrayInputStream(after.getBytes());
        final InputStream[] streams = new InputStream[]{isBefore, is, isAfter};

        Enumeration<InputStream> list = new Enumeration<InputStream>() {
            private int index;
            public boolean hasMoreElements() {
                return index < streams.length;
            }

            public InputStream nextElement() {
                return streams[index++];
            }

        };
        return new SequenceInputStream(list);
    }
    return is;

}
 
Example #25
Source File: MainModuleResource.java    From onos with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(SCRIPT)
public Response getMainModule() throws IOException {
    UiExtensionService service = get(UiExtensionService.class);
    InputStream jsTemplate = getClass().getClassLoader().getResourceAsStream(MAIN_JS);
    String js = new String(toByteArray(jsTemplate));

    int p1s = split(js, 0, INJECT_VIEW_IDS_START) - INJECT_VIEW_IDS_START.length();
    int p1e = split(js, 0, INJECT_VIEW_IDS_END);
    int p2s = split(js, p1e, null);

    StreamEnumeration streams =
            new StreamEnumeration(of(stream(js, 0, p1s),
                                     includeViewIds(service),
                                     stream(js, p1e, p2s)));

    return Response.ok(new SequenceInputStream(streams)).build();
}
 
Example #26
Source File: ByteArrayOutputStream.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example #27
Source File: CompositeBufferViewTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link BufferView#wrap(List)}.
 */
@Test
public void testWrapRecursive() throws IOException {
    val b1 = new ByteArraySegment(new byte[]{1});
    val b2 = new ByteArraySegment(new byte[]{2});
    val b3 = new ByteArraySegment(new byte[]{3});

    val c1 = BufferView.wrap(Arrays.asList(b1, b2));
    val c2 = BufferView.wrap(Arrays.asList(c1, b3));
    Assert.assertEquals(b1.getLength() + b2.getLength() + b3.getLength(), c2.getLength());
    AssertExtensions.assertStreamEquals("",
            new SequenceInputStream(Iterators.asEnumeration(Arrays.asList(b1.getReader(), b2.getReader(), b3.getReader()).iterator())),
            c2.getReader(), c2.getLength());

    val contentBufs = c2.getContents();
    val expectedContentBufs = Stream.of(b1, b2, b3).flatMap(b -> b.getContents().stream()).collect(Collectors.toList());
    AssertExtensions.assertListEquals("", expectedContentBufs, contentBufs, ByteBuffer::equals);
}
 
Example #28
Source File: DOM4JProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private org.dom4j.Document readXMLBom() throws Exception {
    byte[] bom = new byte[]{(byte)239, (byte)187, (byte)191};
    assertEquals("efbbbf", StringUtils.toHexString(bom));
    byte[] strBytes = "<a/>".getBytes(StandardCharsets.UTF_8);
    InputStream is = new SequenceInputStream(new ByteArrayInputStream(bom),
                                             new ByteArrayInputStream(strBytes));
    DOM4JProvider p = new DOM4JProvider();
    p.setProviders(new ProvidersImpl(createMessage(false)));
    return p.readFrom(org.dom4j.Document.class, org.dom4j.Document.class,
        new Annotation[] {}, MediaType.valueOf("text/xml;a=b"),
        new MetadataMap<String, String>(),
        is);
}
 
Example #29
Source File: CompositeBufferViewTests.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link CompositeBufferView#getCopy()}.
 */
@Test
public void testGetCopy() throws IOException {
    val components = createComponents();
    val cb = BufferView.wrap(components);
    val expectedSize = components.stream().mapToInt(BufferView::getLength).sum();
    val expected = StreamHelpers.readAll(
            new SequenceInputStream(Iterators.asEnumeration(components.stream().map(BufferView::getReader).iterator())),
            expectedSize);
    val actual = cb.getCopy();
    Assert.assertArrayEquals("", expected, actual);
}
 
Example #30
Source File: CompositeBufferViewTests.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link CompositeBufferView#copyTo(OutputStream)}.
 */
@Test
public void testCopyToOutputStream() throws IOException {
    val components = createComponents();
    val cb = BufferView.wrap(components);
    val expectedSize = components.stream().mapToInt(BufferView::getLength).sum();
    val expected = StreamHelpers.readAll(
            new SequenceInputStream(Iterators.asEnumeration(components.stream().map(BufferView::getReader).iterator())),
            expectedSize);
    val actual = new ByteArrayOutputStream();
    cb.copyTo(actual);
    Assert.assertEquals(expectedSize, actual.size());
    Assert.assertArrayEquals("", expected, actual.toByteArray());
}