java.io.InputStream#markSupported ( )源码实例Demo

下面列出了java.io.InputStream#markSupported ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ibm-cos-sdk-java   文件: AmazonHttpClient.java
/**
 * 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;
            }
        }
    }
}
 
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);
		}
	}
}
 
源代码3 项目: FanXin-based-HuanXin   文件: ImageFormatChecker.java
/**
 * 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);
  }
}
 
源代码4 项目: fresco   文件: ImageFormatChecker.java
/**
 * 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);
  }
}
 
源代码5 项目: VideoOS-Android-SDK   文件: Globals.java
/**
 * 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;
}
 
源代码6 项目: base-imageloader   文件: ImageDecorder.java
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);
}
 
源代码7 项目: xDrip   文件: WatchFaceGenerator.java
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();
}
 
源代码8 项目: netbeans   文件: XDMAccessProvider.java
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;
}
 
源代码9 项目: HeyGirl   文件: DexBackedOdexFile.java
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);
}
 
源代码10 项目: bazel-buildfarm   文件: HttpBlobStore.java
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;
}
 
源代码11 项目: MiBandDecompiled   文件: AbstractGalaxySigner.java
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;
}
 
源代码12 项目: ibm-cos-sdk-java   文件: AmazonHttpClient.java
/**
 * 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;
}
 
源代码13 项目: pulsar   文件: SecurityUtility.java
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;
}
 
源代码14 项目: Overchan-Android   文件: GifDrawable.java
/**
 * 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;
}
 
源代码15 项目: ZjDroid   文件: DexBackedOdexFile.java
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);
}
 
源代码16 项目: rtspTortmp   文件: AmfObject.java
@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);
        }
    }
}
 
源代码17 项目: org.hl7.fhir.core   文件: XmlParser.java
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);
}
 
源代码18 项目: alfresco-core   文件: AbstractCharactersetFinder.java
/**
 * {@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) {}
    }
}
 
源代码19 项目: sailfish-core   文件: CSVMatrixReader.java
private static InputStream wrappedStream(InputStream in) {
    return in.markSupported() ? in : new BufferedInputStream(in);
}
 
static GifInfoHandle openMarkableInputStream(InputStream stream, boolean justDecodeMetaData) throws GifIOException {
    if (!stream.markSupported()) {
        throw new IllegalArgumentException("InputStream does not support marking");
    }
    return openStream(stream, justDecodeMetaData);
}