Java Code Examples for java.io.InputStream#markSupported()
The following examples show how to use
java.io.InputStream#markSupported() .
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: AmazonHttpClient.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
/** * 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
Source File: Globals.java From VideoOS-Android-SDK with GNU General Public License v3.0 | 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. */ 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 3
Source File: ImageFormatChecker.java From fresco with MIT License | 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 4
Source File: ImageFormatChecker.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
/** * 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 5
Source File: AbstractMessageConverterMethodArgumentResolver.java From java-technology-stack with MIT License | 6 votes |
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 6
Source File: DexBackedOdexFile.java From HeyGirl with Apache License 2.0 | 5 votes |
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 7
Source File: XDMAccessProvider.java From netbeans with Apache License 2.0 | 5 votes |
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 8
Source File: HttpBlobStore.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
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 9
Source File: AbstractGalaxySigner.java From MiBandDecompiled with Apache License 2.0 | 5 votes |
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 10
Source File: AmazonHttpClient.java From ibm-cos-sdk-java with Apache License 2.0 | 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 11
Source File: WatchFaceGenerator.java From xDrip with GNU General Public License v3.0 | 5 votes |
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 12
Source File: ImageDecorder.java From base-imageloader with Apache License 2.0 | 5 votes |
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 13
Source File: SecurityUtility.java From pulsar with Apache License 2.0 | 5 votes |
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
Source File: GifDrawable.java From Overchan-Android with GNU General Public License v3.0 | 5 votes |
/** * 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 File: DexBackedOdexFile.java From ZjDroid with Apache License 2.0 | 5 votes |
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 File: AmfObject.java From rtspTortmp with Apache License 2.0 | 5 votes |
@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 File: XmlParser.java From org.hl7.fhir.core with Apache License 2.0 | 4 votes |
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
Source File: AbstractCharactersetFinder.java From alfresco-core with GNU Lesser General Public License v3.0 | 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 19
Source File: CSVMatrixReader.java From sailfish-core with Apache License 2.0 | 4 votes |
private static InputStream wrappedStream(InputStream in) { return in.markSupported() ? in : new BufferedInputStream(in); }
Example 20
Source File: GifInfoHandle.java From android-gif-drawable-eclipse-sample with MIT License | 4 votes |
static GifInfoHandle openMarkableInputStream(InputStream stream, boolean justDecodeMetaData) throws GifIOException { if (!stream.markSupported()) { throw new IllegalArgumentException("InputStream does not support marking"); } return openStream(stream, justDecodeMetaData); }