Java Code Examples for java.io.InputStream.markSupported()

The following are Jave code examples for showing how to use markSupported() of the java.io.InputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CacheWebView   File: BytesEncodingDetect.java   View Source Code Vote up 7 votes
public String detectEncodingStr(InputStream inputStream){
    String strEnc ="UTF-8";
    inputStream.mark(0);
    int enc = detectEncoding(inputStream);
    try {
        if (inputStream.markSupported()){
            inputStream.reset();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (enc!=-1){
        return Encoding.htmlname[enc];
    }

    return strEnc;
}
 
Example 2
Project: GitHub   File: ImageFormatChecker.java   View Source Code Vote up 6 votes
/**
 * Reads up to maxHeaderLength bytes from is InputStream. If mark is supported by is, it is
 * used to restore content of the stream after appropriate amount of data is read.
 * Read bytes are stored in imageHeaderBytes, which should be capable of storing
 * maxHeaderLength bytes.
 * @param maxHeaderLength the maximum header length
 * @param is
 * @param imageHeaderBytes
 * @return number of bytes read from is
 * @throws IOException
 */
private static int readHeaderFromStream(
    int maxHeaderLength,
    final InputStream is,
    final byte[] imageHeaderBytes)
    throws IOException {
  Preconditions.checkNotNull(is);
  Preconditions.checkNotNull(imageHeaderBytes);
  Preconditions.checkArgument(imageHeaderBytes.length >= maxHeaderLength);

  // If mark is supported by the stream, use it to let the owner of the stream re-read the same
  // data. Otherwise, just consume some data.
  if (is.markSupported()) {
    try {
      is.mark(maxHeaderLength);
      return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
    } finally {
      is.reset();
    }
  } else {
    return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
  }
}
 
Example 3
Project: andbg   File: DexBackedDexFile.java   View Source Code Vote up 6 votes
public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is)
        throws IOException {
    if (!is.markSupported()) {
        throw new IllegalArgumentException("InputStream must support mark");
    }
    is.mark(44);
    byte[] partialHeader = new byte[44];
    try {
        ByteStreams.readFully(is, partialHeader);
    } catch (EOFException ex) {
        throw new NotADexFile("File is too short");
    } finally {
        is.reset();
    }

    verifyMagicAndByteOrder(partialHeader, 0);

    byte[] buf = ByteStreams.toByteArray(is);
    return new DexBackedDexFile(opcodes, buf, 0, false);
}
 
Example 4
Project: Hubs   File: Globals.java   View Source Code Vote up 6 votes
/** Load lua source or lua binary from an input stream into a Prototype. 
 * The InputStream is either a binary lua chunk starting with the lua binary chunk signature, 
 * or a text input file.  If it is a text input file, it is interpreted as a UTF-8 byte sequence.  
 * @param is Input stream containing a lua script or compiled lua"
 * @param chunkname Name that will be used within the chunk as the source.
 * @param mode String containing 'b' or 't' or both to control loading as binary or text or either.
 */
public Prototype loadPrototype(InputStream is, String chunkname, String mode) throws IOException {
	if (mode.indexOf('b') >= 0) {
		if (undumper == null)
			error("No undumper.");
		if (!is.markSupported())
			is = new BufferedStream(is);
		is.mark(4);
		final Prototype p = undumper.undump(is, chunkname);
		if (p != null)
			return p;
		is.reset();
	}
	if (mode.indexOf('t') >= 0) {
		return compilePrototype(is, chunkname);
	}
	error("Failed to load prototype "+chunkname+" using mode '"+mode+"'");
	return null;
}
 
Example 5
Project: validator-web   File: HttpServletRequestWrapper.java   View Source Code Vote up 6 votes
public boolean hasEmptyMessageBody() throws IOException {
    InputStream body = super.getInputStream();
    if (body == null) {
        return true;
    } else if (body.markSupported()) {
        body.mark(1);
        if (body.read() == -1) {
            return true;
        } else {
            body.reset();
            return false;
        }
    } else {
        this.pushbackInputStream = new PushbackServletInputStream(body);
        int b = this.pushbackInputStream.read();
        if (b == -1) {
            return true;
        } else {
            this.pushbackInputStream.unread(b);
            return false;
        }
    }
}
 
Example 6
Project: GitHub   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo) throws IOException {
	if (imageStream.markSupported()) {
		try {
			imageStream.reset();
			return imageStream;
		} catch (IOException ignored) {
		}
	}
	IoUtils.closeSilently(imageStream);
	return getImageStream(decodingInfo);
}
 
Example 7
Project: openaudible   File: ChunkContainerReader.java   View Source Code Vote up 5 votes
/**
 * Checks for the constraints of this class.
 *
 * @param stream stream to test.
 * @throws IllegalArgumentException If stream does not meet the requirements.
 */
protected void checkStream(final InputStream stream)
        throws IllegalArgumentException {
    if (this.hasFailingReaders && !stream.markSupported()) {
        throw new IllegalArgumentException(
                "Stream has to support mark/reset.");
    }
}
 
Example 8
Project: GifImageLoader   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo) throws IOException {
	if (imageStream.markSupported()) {
		try {
			imageStream.reset();
			return imageStream;
		} catch (IOException ignored) {
		}
	}
	IoUtils.closeSilently(imageStream);
	return getImageStream(decodingInfo);
}
 
Example 9
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View Source Code Vote up 5 votes
/**
 * Reset the input stream of the request before a retry.
 *
 * @param request Request containing input stream to reset
 * @throws ResetException If Input Stream can't be reset which means the request can't be
 *                        retried
 */
private void resetRequestInputStream(final Request<?> request) throws ResetException {
    InputStream requestInputStream = request.getContent();
    if (requestInputStream != null) {
        if (requestInputStream.markSupported()) {
            try {
                requestInputStream.reset();
            } catch (IOException ex) {
                throw new ResetException("Failed to reset the request input stream", ex);
            }
        }
    }
}
 
Example 10
Project: NioSmtpClient   File: InputStreamMessageContent.java   View Source Code Vote up 5 votes
@Override
public float get8bitCharacterProportion() {
  if (eightBitCharProportion != UNCOUNTED) {
    return eightBitCharProportion;
  }

  int eightBitCharCount = 0;

  InputStream inputStream = getStream();

  if (!inputStream.markSupported()) {
    // if we can't examine the stream non-destructively,
    // assume it has some 8 bit characters, but not enough
    // to require encoding the body as base64
    eightBitCharProportion = DEFAULT_8BIT_PROPORTION;
    return eightBitCharProportion;
  }

  inputStream.mark(READ_LIMIT);

  try {
    int c, bytesRead = 0;

    while (bytesRead < READ_LIMIT && (c = inputStream.read()) != -1) {
      if (0 != (c & 0x80)) {
        eightBitCharCount++;
      }

      bytesRead++;
    }

    inputStream.reset();
    eightBitCharProportion = 1.0F * eightBitCharCount / bytesRead;

  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return eightBitCharProportion;
}
 
Example 11
Project: jdk8u-jdk   File: MarkSupported.java   View Source Code Vote up 5 votes
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
            {
                if(!is.markSupported())
                    throw new RuntimeException("InputStream doesn't support mark/reset!");
            }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 12
Project: aws-sdk-java-v2   File: RetryableStage.java   View Source Code Vote up 5 votes
/**
 * Reset the input stream of the request before a retry.
 *
 * @throws ResetException If Input Stream can't be reset which means the request can't be retried.
 */
private static void resetRequestInputStream(InputStream inputStream) throws ResetException {
    if (inputStream.markSupported()) {
        try {
            inputStream.reset();
        } catch (IOException ex) {
            throw new ResetException("Failed to reset the request input stream", ex);
        }
    }
}
 
Example 13
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View Source Code Vote up 5 votes
/**
 * Buffer input stream if possible.
 *
 * @param content Input stream to buffer
 * @return SdkBufferedInputStream if possible, otherwise original input stream.
 */
private InputStream buffer(InputStream content) {
    if (!content.markSupported()) {
        content = new SdkBufferedInputStream(content);
    }
    return content;
}
 
Example 14
Project: Sendroid   File: ImageDecorder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, String url) throws IOException {
    if (imageStream.markSupported()) {
        try {
            imageStream.reset();
            return imageStream;
        } catch (IOException ignored) {
        }
    }
    closeSilently(imageStream);
    return getImageStream(url);
}
 
Example 15
Project: ImageLoaderSupportGif   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo) throws IOException {
	if (imageStream.markSupported()) {
		try {
			imageStream.reset();
			return imageStream;
		} catch (IOException ignored) {
		}
	}
	IoUtils.closeSilently(imageStream);
	return getImageStream(decodingInfo);
}
 
Example 16
Project: fitnotifications   File: Trie2.java   View Source Code Vote up 5 votes
/**
 * Get the UTrie version from an InputStream containing the serialized form
 * of either a Trie (version 1) or a Trie2 (version 2).
 *
 * @param is   an InputStream containing the serialized form
 *             of a UTrie, version 1 or 2.  The stream must support mark() and reset().
 *             The position of the input stream will be left unchanged.
 * @param littleEndianOk If FALSE, only big-endian (Java native) serialized forms are recognized.
 *                    If TRUE, little-endian serialized forms are recognized as well.
 * @return     the Trie version of the serialized form, or 0 if it is not
 *             recognized as a serialized UTrie
 * @throws     IOException on errors in reading from the input stream.
 */
public static int getVersion(InputStream is, boolean littleEndianOk) throws IOException {
    if (! is.markSupported()) {
        throw new IllegalArgumentException("Input stream must support mark().");
        }
    is.mark(4);
    byte sig[] = new byte[4];
    int read = is.read(sig);
    is.reset();

    if (read != sig.length) {
        return 0;
    }

    if (sig[0]=='T' && sig[1]=='r' && sig[2]=='i' && sig[3]=='e') {
        return 1;
    }
    if (sig[0]=='T' && sig[1]=='r' && sig[2]=='i' && sig[3]=='2') {
        return 2;
    }
    if (littleEndianOk) {
        if (sig[0]=='e' && sig[1]=='i' && sig[2]=='r' && sig[3]=='T') {
            return 1;
        }
        if (sig[0]=='2' && sig[1]=='i' && sig[2]=='r' && sig[3]=='T') {
            return 2;
        }
    }
    return 0;
}
 
Example 17
Project: lams   File: MultipartIterator.java   View Source Code Vote up 5 votes
/**
 * Handles retrieving the boundary and setting the input stream
 */
protected void parseRequest() throws IOException
{
    //get the content-type header, which contains the boundary used for separating multipart elements
    getContentTypeOfRequest();
    //get the content-length header, used to prevent denial of service attacks and for detecting
    //whether a file size is over the limit before the client sends the file
    this.contentLength = this.request.getContentLength();
    //parse the boundary from the content-type header's value
    getBoundaryFromContentType();
    //don't let the stream read past the content length
    this.inputStream.setMaxLength(this.contentLength+1);
    //just stop now if the content length is bigger than the maximum allowed size
    if ((this.maxSize > -1) && (this.contentLength > this.maxSize))
    {
        this.maxLengthExceeded = true;
    }
    else
    {
        InputStream requestInputStream = this.request.getInputStream();
        //mark the input stream to allow multiple reads
        if (requestInputStream.markSupported())
        {
            requestInputStream.mark(contentLength+1);
        }
        this.inputStream.setBoundary(this.boundary);
        this.inputStream.setInputStream(requestInputStream);
    }
}
 
Example 18
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View Source Code Vote up 5 votes
/**
 * Used to perform a last reset on the content input stream (if mark-supported); this is so
 * that, for backward compatibility reason, any "blind" retry (ie without calling reset) by
 * user of this library with the same input stream (such as ByteArrayInputStream) could
 * still succeed.
 *
 * @param t the failure
 * @return the failure as given
 */
private <T extends Throwable> T lastReset(final T t) {
    try {
        InputStream content = request.getContent();
        if (content != null) {
            if (content.markSupported()) {
                content.reset();
            }
        }
    } catch (Exception ex) {
        log.debug("FYI: failed to reset content inputstream before throwing up", ex);
    }
    return t;
}
 
Example 19
Project: alfresco-core   File: AbstractCharactersetFinder.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 * <p>
 * The input stream is checked to ensure that it supports marks, after which
 * a buffer is extracted, leaving the stream in its original state.
 */
public final Charset detectCharset(InputStream is)
{
    // Only support marking streams
    if (!is.markSupported())
    {
        throw new IllegalArgumentException("The InputStream must support marks.  Wrap the stream in a BufferedInputStream.");
    }
    try
    {
        int bufferSize = getBufferSize();
        if (bufferSize < 0)
        {
            throw new RuntimeException("The required buffer size may not be negative: " + bufferSize);
        }
        // Mark the stream for just a few more than we actually will need
        is.mark(bufferSize);
        // Create a buffer to hold the data
        byte[] buffer = new byte[bufferSize];
        // Fill it
        int read = is.read(buffer);
        // Create an appropriately sized buffer
        if (read > -1 && read < buffer.length)
        {
            byte[] copyBuffer = new byte[read];
            System.arraycopy(buffer, 0, copyBuffer, 0, read);
            buffer = copyBuffer;
        }
        // Detect
        return detectCharset(buffer);
    }
    catch (IOException e)
    {
        // Attempt a reset
        throw new AlfrescoRuntimeException("IOException while attempting to detect charset encoding.", e);
    }
    finally
    {
        try { is.reset(); } catch (Throwable ee) {}
    }
}
 
Example 20
Project: HtmlNative   File: JseIoLib.java   View Source Code Vote up 4 votes
private FileImpl( RandomAccessFile file, InputStream is, OutputStream os ) {
	this.file = file;
	this.is = is!=null? is.markSupported()? is: new BufferedInputStream(is): null;
	this.os = os;
}