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

The following examples show how to use java.io.InputStream#markSupported() . These examples are extracted from open source projects. 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
/**
 * Reset the input stream of the request before a retry.
 *
 * @param request Request containing input stream to reset
 * @param retriedException
 * @throws ResetException If Input Stream can't be reset which means the request can't be
 *                        retried
 */
private void resetRequestInputStream(final Request<?> request, SdkBaseException retriedException)
        throws ResetException {
    InputStream requestInputStream = request.getContent();
    if (requestInputStream != null) {
        if (requestInputStream.markSupported()) {
            try {
                requestInputStream.reset();
            } catch (IOException ex) {
                ResetException resetException = new ResetException(
                        "The request to the service failed with a retryable reason, but resetting the request input " +
                        "stream has failed. See exception.getExtraInfo or debug-level logging for the original failure " +
                        "that caused this retry.",
                        ex);
                resetException.setExtraInfo(retriedException.getMessage());
                throw resetException;
            }
        }
    }
}
 
Example 2
public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
	this.headers = inputMessage.getHeaders();
	InputStream inputStream = inputMessage.getBody();
	if (inputStream.markSupported()) {
		inputStream.mark(1);
		this.body = (inputStream.read() != -1 ? inputStream : null);
		inputStream.reset();
	}
	else {
		PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
		int b = pushbackInputStream.read();
		if (b == -1) {
			this.body = null;
		}
		else {
			this.body = pushbackInputStream;
			pushbackInputStream.unread(b);
		}
	}
}
 
Example 3
/**
 * Reads up to MAX_HEADER_LENGTH 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
 * MAX_HEADER_LENGTH bytes.
 * @param is
 * @param imageHeaderBytes
 * @return number of bytes read from is
 * @throws IOException
 */
private static int readHeaderFromStream(
    final InputStream is,
    final byte[] imageHeaderBytes)
    throws IOException {
  Preconditions.checkNotNull(is);
  Preconditions.checkNotNull(imageHeaderBytes);
  Preconditions.checkArgument(imageHeaderBytes.length >= MAX_HEADER_LENGTH);

  // 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(MAX_HEADER_LENGTH);
      return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
    } finally {
      is.reset();
    }
  } else {
    return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
  }
}
 
Example 4
Source Project: fresco   File: ImageFormatChecker.java    License: MIT License 6 votes vote down vote up
/**
 * 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 5
/**
 * 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.
 */
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);
        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 6
Source Project: base-imageloader   File: ImageDecorder.java    License: Apache License 2.0 5 votes vote down vote up
protected InputStream resetStream(InputStream imageStream, String url) throws IOException
{
    if (imageStream.markSupported())
    {
        try
        {
            imageStream.reset();
            return imageStream;
        } catch (IOException ignored)
        {
        }
    }
    IoUtils.closeSilently(imageStream);
    return getImageStream(url);
}
 
Example 7
private void parseWatchfaceFile(InputStream fwFileStream) throws Exception {
    if (d)
        UserError.Log.d(TAG, "Reading header");
    BufferedInputStream stream = new BufferedInputStream(fwFileStream);
    header = Header.readFrom(stream);
    if (d) {
        UserError.Log.d(TAG, "Header was read:");
        UserError.Log.d(TAG, String.format("Signature: %s, Unknown param: %d, ParametersSize: %d isValid: %s", header.getSignature(), header.getUnknown(), header.getParametersSize(), header.isValid()));
    }
    if (!header.isValid())
        throw new Exception("Wrong watchface format");
    if (d)
        UserError.Log.d(TAG, "Reading parameter offsets...");
    byte[] bytes = new byte[header.getParametersSize()];
    stream.read(bytes, 0, bytes.length);
    InputStream parameterStream = new ByteArrayInputStream(bytes);
    mainParam = Parameter.readFrom(parameterStream, 0);
    if (d)
        UserError.Log.d(TAG, "Parameters descriptor was read");
    parametersTableLength = (int) mainParam.getChildren().get(0).getValue();
    int imagesCount = (int) mainParam.getChildren().get(1).getValue();
    if (d)
        UserError.Log.d(TAG, "parametersTableLength: " + parametersTableLength + ", imagesCount: " + imagesCount);
    bytes = new byte[parametersTableLength];
    stream.read(bytes, 0, bytes.length);
    if (d)
        UserError.Log.d(TAG, "Reading images offsets...");
    bytes = new byte[imagesCount * 4];
    stream.read(bytes, 0, bytes.length);
    ByteBuffer b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
    imageOffsets = new ArrayList<>();
    while (b.hasRemaining()) {
        imageOffsets.add(b.getInt());
    }
    if (d)
        UserError.Log.d(TAG, "Image offsets were read");
    if (fwFileStream.markSupported())
        fwFileStream.reset();
}
 
Example 8
Source Project: netbeans   File: XDMAccessProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Document loadSwingDocument(InputStream in) throws IOException, BadLocationException {
    BaseDocument sd = new BaseDocument(true, "text/xml"); //NOI18N
    String encoding = in.markSupported() ? EncodingUtil.detectEncoding(in) : null;
    Reader r = encoding == null ? new InputStreamReader(in) : new InputStreamReader(in, encoding);
    sd.read(r, 0);
    return sd;
}
 
Example 9
Source Project: HeyGirl   File: DexBackedOdexFile.java    License: 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 10
Source Project: bazel-buildfarm   File: HttpBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
private boolean reset(InputStream in) throws IOException {
  if (in.markSupported()) {
    in.reset();
    return true;
  }
  if (in instanceof FileInputStream) {
    // FileInputStream does not support reset().
    ((FileInputStream) in).getChannel().position(0);
    return true;
  }
  return false;
}
 
Example 11
protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(BasicGalaxyRequest basicgalaxyrequest)
{
    InputStream inputstream;
    try
    {
        inputstream = basicgalaxyrequest.getContent();
    }
    catch (Exception exception)
    {
        throw new GalaxyClientException(ReturnCode.SIGNATURE_FAILED, (new StringBuilder()).append("Unable to read request payload to sign request: ").append(exception.getMessage()).toString(), exception);
    }
    if (inputstream != null)
    {
        break MISSING_BLOCK_LABEL_20;
    }
    return new ByteArrayInputStream(new byte[0]);
    if (inputstream instanceof StringInputStream)
    {
        break MISSING_BLOCK_LABEL_91;
    }
    if (!inputstream.markSupported())
    {
        throw new GalaxyClientException(ReturnCode.SIGNATURE_FAILED, "Unable to read request payload to sign request.");
    }
    InputStream inputstream1 = basicgalaxyrequest.getContent();
    inputstream = inputstream1;
    return inputstream;
}
 
Example 12
/**
 * 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 13
Source Project: pulsar   File: SecurityUtility.java    License: Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKeyFromPemStream(InputStream inStream) throws KeyManagementException {
    PrivateKey privateKey = null;

    if (inStream == null) {
        return privateKey;
    }

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream))) {
        if (inStream.markSupported()) {
            inStream.reset();
        }
        StringBuilder sb = new StringBuilder();
        String currentLine = null;

        // Jump to the first line after -----BEGIN [RSA] PRIVATE KEY-----
        while (!reader.readLine().startsWith("-----BEGIN")) {
            reader.readLine();
        }

        // Stop (and skip) at the last line that has, say, -----END [RSA] PRIVATE KEY-----
        while ((currentLine = reader.readLine()) != null && !currentLine.startsWith("-----END")) {
            sb.append(currentLine);
        }

        KeyFactory kf = KeyFactory.getInstance("RSA");
        KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(sb.toString()));
        privateKey = kf.generatePrivate(keySpec);
    } catch (GeneralSecurityException | IOException e) {
        throw new KeyManagementException("Private key loading error", e);
    }

    return privateKey;
}
 
Example 14
/**
 * Creates drawable from InputStream.
 * InputStream must support marking, IllegalArgumentException will be thrown otherwise.
 *
 * @param stream stream to read from
 * @throws IOException              when opening failed
 * @throws IllegalArgumentException if stream does not support marking
 * @throws NullPointerException     if stream is null
 */
public GifDrawable(InputStream stream) throws IOException {
    if (stream == null)
        throw new NullPointerException("Source is null");
    if (!stream.markSupported())
        throw new IllegalArgumentException("InputStream does not support marking");
    mGifInfoPtr = openStream(mMetaData, stream, false);
    mColors = new int[mMetaData[0] * mMetaData[1]];
    mInputSourceLength = -1L;
}
 
Example 15
Source Project: ZjDroid   File: DexBackedOdexFile.java    License: 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 16
Source Project: rtspTortmp   File: AmfObject.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(InputStream in) throws IOException {
    // Skip data type byte (we assume it's already read)       
    size = 1;
    InputStream markInputStream = in.markSupported() ? in : new BufferedInputStream(in);

    while (true) {
        // Look for the 3-byte object end marker [0x00 0x00 0x09]
        markInputStream.mark(3);
        byte[] endMarker = new byte[3];
        markInputStream.read(endMarker);

        if (endMarker[0] == OBJECT_END_MARKER[0] && endMarker[1] == OBJECT_END_MARKER[1] && endMarker[2] == OBJECT_END_MARKER[2]) {
            L.d("readFrom(): End marker found");
            size += 3;
            return;
        } else {
            // End marker not found; reset the stream to the marked position and read an AMF property
            markInputStream.reset();
            // Read the property key...
            String key = AmfString.readStringFrom(in, true);
            size += AmfString.sizeOf(key, true);
            // ...and the property value
            AmfData value = AmfDecoder.readFrom(markInputStream);
            size += value.getSize();
            properties.put(key, value);
        }
    }
}
 
Example 17
Source Project: org.hl7.fhir.core   File: XmlParser.java    License: Apache License 2.0 4 votes vote down vote up
public Element parse(InputStream stream) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
Document doc = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// xxe protection
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setXIncludeAware(false);
		factory.setExpandEntityReferences(false);
			
		factory.setNamespaceAware(true);
		if (policy == ValidationPolicy.EVERYTHING) {
		  // The SAX interface appears to not work when reporting the correct version/encoding.
		  // if we can, we'll inspect the header/encoding ourselves 
		  if (stream.markSupported()) {
		    stream.mark(1024);
		    version = checkHeader(stream);
		    stream.reset();
		  }
			// use a slower parser that keeps location data
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer nullTransformer = transformerFactory.newTransformer();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			doc = docBuilder.newDocument();
			DOMResult domResult = new DOMResult(doc);
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			spf.setValidating(false);
  		// xxe protection
		  spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
      spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			SAXParser saxParser = spf.newSAXParser();
			XMLReader xmlReader = saxParser.getXMLReader();
  		// xxe protection
		  xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
		  xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
	   			
			XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
			InputSource inputSource = new InputSource(stream);
			SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
			nullTransformer.transform(saxSource, domResult);
		} else {
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(stream);
		}
	} catch (Exception e) {
    logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
    doc = null;
	}
	if (doc == null)
		return null;
	else
    return parse(doc);
}
 
Example 18
/**
 * {@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 19
Source Project: sailfish-core   File: CSVMatrixReader.java    License: Apache License 2.0 4 votes vote down vote up
private static InputStream wrappedStream(InputStream in) {
    return in.markSupported() ? in : new BufferedInputStream(in);
}
 
Example 20
static GifInfoHandle openMarkableInputStream(InputStream stream, boolean justDecodeMetaData) throws GifIOException {
    if (!stream.markSupported()) {
        throw new IllegalArgumentException("InputStream does not support marking");
    }
    return openStream(stream, justDecodeMetaData);
}