下面列出了怎么用java.io.SequenceInputStream的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
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));
}
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);
}
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();
}
/**
* 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));
}
/**
* 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));
}
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);
}
}
/**
* 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));
}
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())));
}
}
/**
* 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);
}
};
}
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;
}
@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();
}
/**
* 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));
}
/**
* 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));
}
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;
}
/**
* 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));
}
/**
* 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));
}
/**
* 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);
}
}
@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;
}
}
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
}
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);
}
}
@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();
}
});
}
/**
* 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));
}
/**
* 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));
}
/**
* 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));
}
public static ImageInputStream prependDHTSeg(ImageInputStream iisWithoutDHT) throws IOException {
Vector<InputStream> v = new Vector<InputStream>();
v.add(new ByteArrayInputStream(JFIFSOISeg));
v.add(new ByteArrayInputStream(MJPGDHTSeg));
iisWithoutDHT.seek(2);// skip JFIF SOI
v.add(new ImageInputStreamAdapter(iisWithoutDHT));
return new MemoryCacheImageInputStream(new SequenceInputStream(v.elements()));
}
public InputStream getInputStream() {
InputStream in = new ByteArrayInputStream(append.toByteArray());
if (prepend.isEmpty()) return in;
List<InputStream> isa = new ArrayList<>(prepend.size()+1);
for (byte[] bytes : prepend) {
isa.add(new ByteArrayInputStream(bytes));
}
isa.add(in);
return new SequenceInputStream(Collections.enumeration(isa));
}
public static void main(String[] argv) throws Exception {
try (InputStream stream =
new SequenceInputStream(new LOSEnumeration())) {
stream.read();
}
try (InputStream stream =
new SequenceInputStream(new LOSEnumeration())) {
byte[] b = new byte[1];
stream.read(b, 0, 1);
}
}