Java Code Examples for java.io.InputStream#reset()

The following examples show how to use java.io.InputStream#reset() . 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: HttpUnitUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * parse the given inputSource with a new Parser
 * @param inputSource
 * @return the document parsed from the input Source
 */
public static Document parse(InputSource inputSource) throws SAXException,IOException {
	DocumentBuilder db=newParser();
	try {
		Document doc=db.parse(inputSource);
	return doc;  			
	} catch (java.net.MalformedURLException mue) {
		if (EXCEPTION_DEBUG) {
			String msg=mue.getMessage();
			if (msg!=null) {
				System.err.println(msg);
			}	
			InputStream is=inputSource.getByteStream();
			is.reset();
			String content=parseISToString(is);
			System.err.println(content);
		}	
		throw mue;
	}
}
 
Example 2
Source File: ReaderToUTF8StreamTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tests that shifting of existing bytes works.
 *
 * @throws IOException if something goes wrong
 */
public void testMarkResetShiftBytesFew_Internal()
        throws IOException {
    InputStream is = getStream(128*1024);
    byte[] buf = new byte[DEFAULT_INTERNAL_BUFFER_SIZE - 2*1024];
    fillArray(is, buf);
    // The following mark fits within the existing default buffer, but the
    // bytes after the mark have to be shifted to the left.
    is.mark(4*1024);
    byte[] readBeforeReset = new byte[3*1024];
    byte[] readAfterReset = new byte[3*1024];
    fillArray(is, readBeforeReset);
    // Obtain something to compare with.
    InputStream src = getStream(128*1024);
    InputStreamUtil.skipFully(src, DEFAULT_INTERNAL_BUFFER_SIZE - 2*1024);
    byte[] comparisonRead = new byte[3*1024];
    fillArray(src, comparisonRead);
    // Compare
    assertEquals(new ByteArrayInputStream(comparisonRead),
                 new ByteArrayInputStream(readBeforeReset));
    // Reset the stream.
    is.reset();
    fillArray(is, readAfterReset);
    assertEquals(new ByteArrayInputStream(readBeforeReset),
                 new ByteArrayInputStream(readAfterReset));
}
 
Example 3
Source File: LiteralByteStringTest.java    From travelguide with Apache License 2.0 6 votes vote down vote up
public void testNewInput_skip() throws IOException {
  InputStream input = stringUnderTest.newInput();
  int stringSize = stringUnderTest.size();
  int nearEndIndex = stringSize * 2 / 3;
  long skipped1 = input.skip(nearEndIndex);
  assertEquals("InputStream.skip()", skipped1, nearEndIndex);
  assertEquals("InputStream.available()",
      stringSize - skipped1, input.available());
  assertTrue("InputStream.mark() is available", input.markSupported());
  input.mark(0);
  assertEquals("InputStream.skip(), read()",
      stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
  assertEquals("InputStream.available()",
               stringSize - skipped1 - 1, input.available());
  long skipped2 = input.skip(stringSize);
  assertEquals("InputStream.skip() incomplete",
      skipped2, stringSize - skipped1 - 1);
  assertEquals("InputStream.skip(), no more input", 0, input.available());
  assertEquals("InputStream.skip(), no more input", -1, input.read());
  input.reset();
  assertEquals("InputStream.reset() succeded",
               stringSize - skipped1, input.available());
  assertEquals("InputStream.reset(), read()",
      stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
 
Example 4
Source File: OldAndroidByteArrayInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public static String markRead(InputStream a, int x, int y) throws IOException {
    int m = 0;
    int r;
    StringBuilder builder = new StringBuilder();
    do {
        m++;
        r = a.read();
        if (m == x)
            a.mark((x + y));
        if (m == (x + y))
            a.reset();

        if (r != -1)
            builder.append((char) r);
    } while (r != -1);
    return builder.toString();
}
 
Example 5
Source File: WebEmbedded.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void setSource(String fileName, final InputStream src) {
    if (src != null) {
        resource = new StreamResource((StreamResource.StreamSource) () -> {
            try {
                src.reset();
            } catch (IOException e) {
                Logger log = LoggerFactory.getLogger(WebEmbedded.this.getClass());
                log.debug("Ignored IOException on stream reset", e);
            }
            return src;
        }, fileName);
        component.setSource(resource);
    } else {
        resetSource();
    }
}
 
Example 6
Source File: PersistentStoreTransaction.java    From xodus with Apache License 2.0 6 votes vote down vote up
long getBlobSize(final long blobHandle) throws IOException {
    final LongHashMap<InputStream> blobStreams = this.blobStreams;
    if (blobStreams != null) {
        final InputStream stream = blobStreams.get(blobHandle);
        if (stream != null) {
            stream.reset();
            return stream.skip(Long.MAX_VALUE); // warning, this may return inaccurate results
        }
    }
    final LongHashMap<File> blobFiles = this.blobFiles;
    if (blobFiles != null) {
        final File file = blobFiles.get(blobHandle);
        if (file != null) {
            return file.length();
        }
    }
    return -1;
}
 
Example 7
Source File: ReaderToUTF8StreamTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tests that the reset-call will fail we exceed the mark ahead limit and
 * the internal buffer has to be refilled.
 *
 * @throws IOException if something goes wrong
 */
public void testMarkResetExceedReadAheadLimitFail_Internal()
        throws IOException {
    InputStream is = getStream(64*1024+17);
    is.mark(10);
    // The internal buffer is 32 KB (implementation detail).
    int toRead = 38*1024+7;
    int read = 0;
    byte[] buf = new byte[toRead];
    while (read < toRead) {
        read += is.read(buf, read, toRead - read);
    }
    // Note the following is implementation dependent.
    try {
        is.reset();
        fail("reset-call was expected to throw IOException");
    } catch (IOException ioe) {
        // As expected, do nothing
    }
}
 
Example 8
Source File: DexBackedOdexFile.java    From ZjDroid with Apache License 2.0 5 votes vote down vote up
public static DexBackedOdexFile fromInputStream(@Nonnull Opcodes opcodes,
		@Nonnull InputStream is) throws IOException {
	if (!is.markSupported()) {
		throw new IllegalArgumentException("InputStream must support mark");
	}
	is.mark(8);
	byte[] partialHeader = new byte[8];
	try {
		ByteStreams.readFully(is, partialHeader);
	} catch (EOFException ex) {
		throw new NotADexFile("File is too short");
	} finally {
		is.reset();
	}

	verifyMagic(partialHeader);

	is.reset();
	byte[] odexBuf = new byte[OdexHeaderItem.ITEM_SIZE];
	ByteStreams.readFully(is, odexBuf);
	int dexOffset = OdexHeaderItem.getDexOffset(odexBuf);
	if (dexOffset > OdexHeaderItem.ITEM_SIZE) {
		ByteStreams.skipFully(is, dexOffset - OdexHeaderItem.ITEM_SIZE);
	}

	byte[] dexBuf = ByteStreams.toByteArray(is);

	return new DexBackedOdexFile(opcodes, odexBuf, dexBuf);
}
 
Example 9
Source File: WaveFloatFileReader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(InputStream stream)
        throws UnsupportedAudioFileException, IOException {

    stream.mark(200);
    AudioFileFormat format;
    try {
        format = internal_getAudioFileFormat(stream);
    } finally {
        stream.reset();
    }
    return format;
}
 
Example 10
Source File: DLSSoundbankReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public Soundbank getSoundbank(InputStream stream)
        throws InvalidMidiDataException, IOException {
    try {
        stream.mark(512);
        return new DLSSoundbank(stream);
    } catch (RIFFInvalidFormatException e) {
        stream.reset();
        return null;
    }
}
 
Example 11
Source File: JdCloudSigner.java    From jdcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * 方法描述:对请求内容进行hash并转为16进制
 * @param request
 * @return 
 * @author lixuenan3
 * @date 2018年3月22日 下午5:43:31
 */
protected String calculateContentHash(SdkHttpFullRequest.Builder request) {
    InputStream payloadStream = getBinaryRequestPayloadStream(request.getContent());
    String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
    try {
        payloadStream.reset();
    } catch (IOException e) {
        throw new SdkClientException("Unable to reset stream after calculating signature", e);
    }
    return contentSha256;
}
 
Example 12
Source File: WaveExtensibleFileReader.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(InputStream stream)
        throws UnsupportedAudioFileException, IOException {

    stream.mark(200);
    AudioFileFormat format;
    try {
        format = internal_getAudioFileFormat(stream);
    } finally {
        stream.reset();
    }
    return format;
}
 
Example 13
Source File: ID3v1Info.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isID3v1StartPosition(InputStream input) throws IOException {
    input.mark(3);
    try {
        return input.read() == 'T' && input.read() == 'A' && input.read() == 'G';
    } finally {
        input.reset();
    }
}
 
Example 14
Source File: ID3v1Info.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isID3v1StartPosition(InputStream input) throws IOException {
    input.mark(3);
    try {
        return input.read() == 'T' && input.read() == 'A' && input.read() == 'G';
    } finally {
        input.reset();
    }
}
 
Example 15
Source File: WaveExtensibleFileReader.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(InputStream stream)
        throws UnsupportedAudioFileException, IOException {

    stream.mark(200);
    AudioFileFormat format;
    try {
        format = internal_getAudioFileFormat(stream);
    } finally {
        stream.reset();
    }
    return format;
}
 
Example 16
Source File: MessageBodyClientHttpResponseWrapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Indicates whether the response has an empty message body.
 * <p>Implementation tries to read the first bytes of the response stream:
 * <ul>
 * <li>if no bytes are available, the message body is empty</li>
 * <li>otherwise it is not empty and the stream is reset to its start for further reading</li>
 * </ul>
 * @return {@code true} if the response has a zero-length message body, {@code false} otherwise
 * @throws IOException in case of I/O errors
 */
@SuppressWarnings("ConstantConditions")
public boolean hasEmptyMessageBody() throws IOException {
	InputStream body = this.response.getBody();
	// Per contract body shouldn't be null, but check anyway..
	if (body == null) {
		return true;
	}
	if (body.markSupported()) {
		body.mark(1);
		if (body.read() == -1) {
			return true;
		}
		else {
			body.reset();
			return false;
		}
	}
	else {
		this.pushbackInputStream = new PushbackInputStream(body);
		int b = this.pushbackInputStream.read();
		if (b == -1) {
			return true;
		}
		else {
			this.pushbackInputStream.unread(b);
			return false;
		}
	}
}
 
Example 17
Source File: MarkReset.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    try
    {
        setUp();

        for (int i = 0; i < 8; i++) {
            ModelByteBuffer buff;
            if(i % 2 == 0)
                buff = new ModelByteBuffer(test_file);
            else
                buff = new ModelByteBuffer(test_byte_array);
            if((i / 2) == 1)
                buff.subbuffer(5);
            if((i / 2) == 2)
                buff.subbuffer(5,500);
            if((i / 2) == 3)
                buff.subbuffer(5,600,true);

            long capacity = buff.capacity();
            InputStream is = buff.getInputStream();
            try
            {
                is.mark(1000);
                int ret = is.available();
                int a = is.read();
                is.skip(75);
                is.reset();
                if(is.available() != ret)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret)+") !");
                int b = is.read();
                if(a != b)
                    throw new RuntimeException(
                            "is doesn't return same value after reset ("
                            + a + "!="+b+") !");

                is.skip(15);
                ret = is.available();
                is.mark(1000);
                is.reset();
                if(is.available() != ret)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret)+") !");


            }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 18
Source File: AbstractPreparedQuery.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected final byte[] streamToBytes(InputStream in, boolean escape, int streamLength, boolean useLength) {
    in.mark(Integer.MAX_VALUE); // we may need to read this same stream several times, so we need to reset it at the end.
    try {
        if (this.streamConvertBuf == null) {
            this.streamConvertBuf = new byte[4096];
        }
        if (streamLength == -1) {
            useLength = false;
        }

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();

        int bc = useLength ? readblock(in, this.streamConvertBuf, streamLength) : readblock(in, this.streamConvertBuf);

        int lengthLeftToRead = streamLength - bc;

        if (escape) {
            bytesOut.write('_');
            bytesOut.write('b');
            bytesOut.write('i');
            bytesOut.write('n');
            bytesOut.write('a');
            bytesOut.write('r');
            bytesOut.write('y');
            bytesOut.write('\'');
        }

        while (bc > 0) {
            if (escape) {
                StringUtils.escapeblockFast(this.streamConvertBuf, bytesOut, bc, this.usingAnsiMode);
            } else {
                bytesOut.write(this.streamConvertBuf, 0, bc);
            }

            if (useLength) {
                bc = readblock(in, this.streamConvertBuf, lengthLeftToRead);

                if (bc > 0) {
                    lengthLeftToRead -= bc;
                }
            } else {
                bc = readblock(in, this.streamConvertBuf);
            }
        }

        if (escape) {
            bytesOut.write('\'');
        }

        return bytesOut.toByteArray();
    } finally {
        try {
            in.reset();
        } catch (IOException e) {
        }
        if (this.autoClosePStmtStreams.getValue()) {
            try {
                in.close();
            } catch (IOException ioEx) {
            }

            in = null;
        }
    }
}
 
Example 19
Source File: WaveFileReader.java    From openjdk-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains the audio file format of the input stream provided.  The stream must
 * point to valid audio file data.  In general, audio file providers may
 * need to read some data from the stream before determining whether they
 * support it.  These parsers must
 * be able to mark the stream, read enough data to determine whether they
 * support the stream, and, if not, reset the stream's read pointer to its original
 * position.  If the input stream does not support this, this method may fail
 * with an IOException.
 * @param stream the input stream from which file format information should be
 * extracted
 * @return an <code>AudioFileFormat</code> object describing the audio file format
 * @throws UnsupportedAudioFileException if the stream does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 * @see InputStream#markSupported
 * @see InputStream#mark
 */
public AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException {
    // fix for 4489272: AudioSystem.getAudioFileFormat() fails for InputStream, but works for URL
    AudioFileFormat aff = getFMT(stream, true);
    // the following is not strictly necessary - but was implemented like that in 1.3.0 - 1.4.1
    // so I leave it as it was. May remove this for 1.5.0
    stream.reset();
    return aff;
}
 
Example 20
Source File: WaveFileReader.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains the audio file format of the input stream provided.  The stream must
 * point to valid audio file data.  In general, audio file providers may
 * need to read some data from the stream before determining whether they
 * support it.  These parsers must
 * be able to mark the stream, read enough data to determine whether they
 * support the stream, and, if not, reset the stream's read pointer to its original
 * position.  If the input stream does not support this, this method may fail
 * with an IOException.
 * @param stream the input stream from which file format information should be
 * extracted
 * @return an <code>AudioFileFormat</code> object describing the audio file format
 * @throws UnsupportedAudioFileException if the stream does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 * @see InputStream#markSupported
 * @see InputStream#mark
 */
public AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException {
    // fix for 4489272: AudioSystem.getAudioFileFormat() fails for InputStream, but works for URL
    AudioFileFormat aff = getFMT(stream, true);
    // the following is not strictly necessary - but was implemented like that in 1.3.0 - 1.4.1
    // so I leave it as it was. May remove this for 1.5.0
    stream.reset();
    return aff;
}