List of usage examples for java.io InputStream markSupported
public boolean markSupported()
mark
and reset
methods. From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
/** * Opens a URL. It can be a simple URL or one which requires basic * authentication.// w ww . j a v a 2s . c o m * <p/> * Tries to access the given URL. If http response is either * {@code HttpStatus.SC_UNAUTHORIZED} or * {@code HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED}, asks for * login/password and tries to authenticate into proxy server and/or URL. * <p/> * This implementation relies on the Apache Http Client due to its * capabilities of proxy/http authentication. <br/> * Proxy configuration is determined by {@link ProxySelectorRoutePlanner} using the JVM proxy * settings by default. * <p/> * For more information see: <br/> * - {@code http://hc.apache.org/httpcomponents-client-ga/} <br/> * - {@code http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/ProxySelectorRoutePlanner.html} * <p/> * There's a very simple realm cache implementation. * Login/Password for each realm are stored in a static {@link Map}. * Before asking the user the method verifies if the information is already * available in the memory cache. * * @param url the URL string to be opened. * @param needsMarkResetSupport Indicates the caller <em>must</em> have an input stream that * supports the mark/reset operations (as indicated by {@link InputStream#markSupported()}. * Implementation detail: If the original stream does not, it will be fetched and wrapped * into a {@link ByteArrayInputStream}. This can only work sanely if the resource is a * small file that can fit in memory. It also means the caller has no chance of showing * a meaningful download progress. If unsure, callers should set this to false. * @param monitor {@link ITaskMonitor} to output status. * @param headers An optional array of HTTP headers to use in the GET request. * @return Returns a {@link Pair} with {@code first} holding an {@link InputStream} * and {@code second} holding an {@link HttpResponse}. * The returned pair is never null and contains * at least a code; for http requests that provide them the response * also contains locale, headers and an status line. * The input stream can be null, especially in case of error. * The caller must only accept the stream if the response code is 200 or similar. * @throws IOException Exception thrown when there are problems retrieving * the URL or its content. * @throws CanceledByUserException Exception thrown if the user cancels the * authentication dialog. */ @NonNull static Pair<InputStream, HttpResponse> openUrl(@NonNull String url, boolean needsMarkResetSupport, @NonNull ITaskMonitor monitor, @Nullable Header[] headers) throws IOException, CanceledByUserException { Exception fallbackOnJavaUrlConnect = null; Pair<InputStream, HttpResponse> result = null; try { result = openWithHttpClient(url, monitor, headers); } catch (UnknownHostException e) { // Host in unknown. No need to even retry with the Url object, // if it's broken, it's broken. It's already an IOException but // it could use a better message. throw new IOException("Unknown Host " + e.getMessage(), e); } catch (ClientProtocolException e) { // We get this when HttpClient fails to accept the current protocol, // e.g. when processing file:// URLs. fallbackOnJavaUrlConnect = e; } catch (IOException e) { throw e; } catch (CanceledByUserException e) { // HTTP Basic Auth or NTLM login was canceled by user. throw e; } catch (Exception e) { if (DEBUG) { System.out.printf("[HttpClient Error] %s : %s\n", url, e.toString()); } fallbackOnJavaUrlConnect = e; } if (fallbackOnJavaUrlConnect != null) { // If the protocol is not supported by HttpClient (e.g. file:///), // revert to the standard java.net.Url.open. try { result = openWithUrl(url, headers); } catch (IOException e) { throw e; } catch (Exception e) { if (DEBUG && !fallbackOnJavaUrlConnect.equals(e)) { System.out.printf("[Url Error] %s : %s\n", url, e.toString()); } } } // If the caller requires an InputStream that supports mark/reset, let's // make sure we have such a stream. if (result != null && needsMarkResetSupport) { InputStream is = result.getFirst(); if (is != null) { if (!is.markSupported()) { try { // Consume the whole input stream and offer a byte array stream instead. // This can only work sanely if the resource is a small file that can // fit in memory. It also means the caller has no chance of showing // a meaningful download progress. InputStream is2 = toByteArrayInputStream(is); if (is2 != null) { result = Pair.of(is2, result.getSecond()); try { is.close(); } catch (Exception ignore) { } } } catch (Exception e3) { // Ignore. If this can't work, caller will fail later. } } } } if (result == null) { // Make up an error code if we don't have one already. HttpResponse outResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), //$NON-NLS-1$ HttpStatus.SC_METHOD_FAILURE, ""); //$NON-NLS-1$; // 420=Method Failure result = Pair.of(null, outResponse); } return result; }
From source file:edu.vt.middleware.crypt.util.CryptReader.java
/** * Reads a certificate chain of the default certificate type from an input * stream containing data in any of the following formats: * * <ul>// w w w .j av a 2 s .c o m * <li>Sequence of DER-encoded certificates</li> * <li>Concatenation of PEM-encoded certificates</li> * <li>PKCS#7 certificate chain</li> * </ul> * * @param chainStream Stream containing certificate chain data. * @param type Type of certificate to read, e.g. X.509. * * @return Array of certificates in the order in which they appear in the * stream. * * @throws CryptException On certificate read or format errors. */ public static Certificate[] readCertificateChain(final InputStream chainStream, final String type) throws CryptException { final CertificateFactory cf = CryptProvider.getCertificateFactory(type); InputStream in = chainStream; if (!chainStream.markSupported()) { in = new BufferedInputStream(chainStream); } final List<Certificate> certList = new ArrayList<Certificate>(); try { while (in.available() > 0) { final Certificate cert = cf.generateCertificate(in); if (cert != null) { certList.add(cert); } } } catch (CertificateException e) { throw new CryptException("Certificate read/format error.", e); } catch (IOException e) { throw new CryptException("Stream I/O error."); } return certList.toArray(new Certificate[certList.size()]); }
From source file:org.apache.jmeter.save.SaveService.java
/** * // www.j a v a2 s. com * @param reader {@link InputStream} * @param file the JMX file used only for debug, can be null * @return the loaded tree * @throws IOException if there is a problem reading the file or processing it */ private static HashTree readTree(InputStream reader, File file) throws IOException { if (!reader.markSupported()) { reader = new BufferedInputStream(reader); } reader.mark(Integer.MAX_VALUE); ScriptWrapper wrapper = null; try { // Get the InputReader to use InputStreamReader inputStreamReader = getInputStreamReader(reader); wrapper = (ScriptWrapper) JMXSAVER.fromXML(inputStreamReader); inputStreamReader.close(); if (wrapper == null) { log.error("Problem loading XML: see above."); return null; } return wrapper.testPlan; } catch (CannotResolveClassException e) { if (file != null) { throw new IllegalArgumentException("Problem loading XML from:'" + file.getAbsolutePath() + "', cannot determine class for element: " + e, e); } else { throw new IllegalArgumentException("Problem loading XML, cannot determine class for element: " + e, e); } } catch (ConversionException | NoClassDefFoundError e) { if (file != null) { throw new IllegalArgumentException( "Problem loading XML from:'" + file.getAbsolutePath() + "', missing class " + e, e); } else { throw new IllegalArgumentException("Problem loading XML, missing class " + e, e); } } }
From source file:byps.BWire.java
/** * Reads a ByteBuffer from an InputStream * Closes the InputStream.//from ww w.j a v a 2s . co m * @param is * @return * @throws IOException */ public static ByteBuffer bufferFromStream(InputStream is, Boolean gzip) throws IOException { if (is == null) return null; try { ByteBuffer ibuf = ByteBuffer.allocate(10 * 1000); if (gzip != null) { if (gzip) { is = new GZIPInputStream(is); } } else { if (!is.markSupported()) is = new BufferedInputStream(is, 2); is.mark(2); int magic = is.read() | (is.read() << 8); is.reset(); if (magic == GZIPInputStream.GZIP_MAGIC) { is = new GZIPInputStream(is); } } ReadableByteChannel rch = Channels.newChannel(is); while (rch.read(ibuf) != -1) { if (ibuf.remaining() == 0) { ByteBuffer nbuf = ByteBuffer.allocate(ibuf.capacity() * 2); ibuf.flip(); nbuf.put(ibuf); ibuf = nbuf; } } ibuf.flip(); return ibuf; } finally { is.close(); } }
From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java
private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { if (response.getEntity() == null) { return new ByteArrayInputStream(new byte[0]); } else {/* ww w. ja v a 2 s . c om*/ final InputStream i = response.getEntity().getContent(); if (i.markSupported()) { return i; } return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); } }
From source file:com.netsteadfast.greenstep.util.SimpleUtils.java
/** * http://stackoverflow.com/questions/12593752/why-do-i-failed-to-read-excel-2007-using-poi * //from www .ja v a2 s. co m * @param inp * @return * @throws IOException * @throws InvalidFormatException */ public static Workbook createPOIWorkbook(InputStream inp) throws IOException, InvalidFormatException { // If clearly doesn't do mark/reset, wrap up if (!inp.markSupported()) { inp = new PushbackInputStream(inp, 8); } if (POIFSFileSystem.hasPOIFSHeader(inp)) { return new HSSFWorkbook(inp); } if (DocumentFactoryHelper.hasOOXMLHeader(inp)) { return new XSSFWorkbook(OPCPackage.open(inp)); } throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { final InputStream inputStream; if (response.getEntity() == null) { inputStream = new ByteArrayInputStream(new byte[0]); } else {/* w ww . ja va 2 s . co m*/ final InputStream i = response.getEntity().getContent(); if (i.markSupported()) { inputStream = i; } else { inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); } } return new FilterInputStream(inputStream) { @Override public void close() throws IOException { response.close(); super.close(); } }; }
From source file:org.apache.tika.parser.pkg.TikaCompressorStreamFactory.java
/** * Try to detect the type of compressor stream. * * @param in input stream// w w w . j a va 2s .com * @return type of compressor stream detected * @throws CompressorException if no compressor stream type was detected * or if something else went wrong * @throws IllegalArgumentException if stream is null or does not support mark * * @since 1.14 */ public static String detect(final InputStream in) throws CompressorException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); int signatureLength = -1; try { signatureLength = IOUtils.readFully(in, signature); in.reset(); } catch (IOException e) { throw new CompressorException("IOException while reading signature.", e); } if (BZip2CompressorInputStream.matches(signature, signatureLength)) { return BZIP2; } if (GzipCompressorInputStream.matches(signature, signatureLength)) { return GZIP; } if (Pack200CompressorInputStream.matches(signature, signatureLength)) { return PACK200; } if (FramedSnappyCompressorInputStream.matches(signature, signatureLength)) { return SNAPPY_FRAMED; } if (ZCompressorInputStream.matches(signature, signatureLength)) { return Z; } if (DeflateCompressorInputStream.matches(signature, signatureLength)) { return DEFLATE; } if (XZUtils.matches(signature, signatureLength)) { return XZ; } if (LZMAUtils.matches(signature, signatureLength)) { return LZMA; } /* if (FramedLZ4CompressorInputStream.matches(signature, signatureLength)) { return LZ4_FRAMED; }*/ throw new CompressorException("No Compressor found for the stream signature."); }
From source file:org.phoenix.jmeter.core.SaveService.java
/** * // ww w . j a v a 2 s.c om * @param reader {@link InputStream} * @param file the JMX file used only for debug, can be null * @return the loaded tree * @throws IOException if there is a problem reading the file or processing it */ private static final HashTree readTree(InputStream reader, File file) throws IOException { if (!reader.markSupported()) { reader = new BufferedInputStream(reader); } reader.mark(Integer.MAX_VALUE); ScriptWrapper wrapper = null; try { // Get the InputReader to use InputStreamReader inputStreamReader = getInputStreamReader(reader); wrapper = (ScriptWrapper) JMXSAVER.fromXML(inputStreamReader); inputStreamReader.close(); if (wrapper == null) { log.error("Problem loading XML: see above."); return null; } return wrapper.testPlan; } catch (CannotResolveClassException e) { // FIXME We switching to JAVA7, use Multi-Catch Exceptions if (e.getMessage().startsWith("node")) { log.info("Problem loading XML, trying Avalon format"); reader.reset(); return OldSaveService.loadSubTree(reader); } if (file != null) { throw new IllegalArgumentException("Problem loading XML from:'" + file.getAbsolutePath() + "', cannot determine class for element: " + e, e); } else { throw new IllegalArgumentException("Problem loading XML, cannot determine class for element: " + e, e); } } catch (NoClassDefFoundError e) { if (file != null) { throw new IllegalArgumentException( "Problem loading XML from:'" + file.getAbsolutePath() + "', missing class " + e, e); } else { throw new IllegalArgumentException("Problem loading XML, missing class " + e, e); } } catch (ConversionException e) { if (file != null) { throw new IllegalArgumentException( "Problem loading XML from:'" + file.getAbsolutePath() + "', conversion error " + e, e); } else { throw new IllegalArgumentException("Problem loading XML, conversion error " + e, e); } } }
From source file:org.apache.tika.parser.pkg.TikaArchiveStreamFactory.java
/** * Try to determine the type of Archiver * @param in input stream//from w ww. j a v a 2s. c om * @return type of archiver if found * @throws ArchiveException if an archiver cannot be detected in the stream * @since 1.14 */ public static String detect(InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[SIGNATURE_SIZE]; in.mark(signature.length); int signatureLength = -1; try { signatureLength = IOUtils.readFully(in, signature); in.reset(); } catch (IOException e) { throw new ArchiveException("IOException while reading signature."); } if (ZipArchiveInputStream.matches(signature, signatureLength)) { return ZIP; } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return JAR; } if (ArArchiveInputStream.matches(signature, signatureLength)) { return AR; } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return CPIO; } else if (ArjArchiveInputStream.matches(signature, signatureLength)) { return ARJ; } else if (SevenZFile.matches(signature, signatureLength)) { return SEVEN_Z; } // Dump needs a bigger buffer to check the signature; final byte[] dumpsig = new byte[DUMP_SIGNATURE_SIZE]; in.mark(dumpsig.length); try { signatureLength = IOUtils.readFully(in, dumpsig); in.reset(); } catch (IOException e) { throw new ArchiveException("IOException while reading dump signature"); } if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return DUMP; } // Tar needs an even bigger buffer to check the signature; read the first block final byte[] tarHeader = new byte[TAR_HEADER_SIZE]; in.mark(tarHeader.length); try { signatureLength = IOUtils.readFully(in, tarHeader); in.reset(); } catch (IOException e) { throw new ArchiveException("IOException while reading tar signature"); } if (TarArchiveInputStream.matches(tarHeader, signatureLength)) { return TAR; } // COMPRESS-117 - improve auto-recognition if (signatureLength >= TAR_HEADER_SIZE) { TarArchiveInputStream tais = null; try { tais = new TarArchiveInputStream(new ByteArrayInputStream(tarHeader)); // COMPRESS-191 - verify the header checksum if (tais.getNextTarEntry().isCheckSumOK()) { return TAR; } } catch (final Exception e) { // NOPMD // can generate IllegalArgumentException as well // as IOException // autodetection, simply not a TAR // ignored } finally { IOUtils.closeQuietly(tais); } } throw new ArchiveException("No Archiver found for the stream signature"); }