Example usage for java.io InputStream mark

List of usage examples for java.io InputStream mark

Introduction

In this page you can find the example usage for java.io InputStream mark.

Prototype

public synchronized void mark(int readlimit) 

Source Link

Document

Marks the current position in this input stream.

Usage

From source file:byps.BWire.java

/**
 * Reads a ByteBuffer from an InputStream
 * Closes the InputStream./*from ww w . jav  a  2  s .  com*/
 * @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.stratuscom.harvester.codebase.ClassServer.java

/**
 * Read up to CRLF, return false if EOF/*from w ww.j  ava 2s  .c o  m*/
 */
private static boolean readLine(InputStream in, StringBuffer buf) throws IOException {
    while (true) {
        int c = in.read();
        if (c < 0) {
            return buf.length() > 0;
        }
        /*
         * The characters below are part of the http protocol and not
         * localizable, so we're OK with character literals.
         */
        if (c == '\r') {
            in.mark(1);
            c = in.read();
            if (c != '\n') {
                in.reset();
            }
            return true;
        }
        if (c == '\n') {
            return true;
        }
        buf.append((char) c);
    }
}

From source file:org.phoenix.jmeter.core.SaveService.java

/**
 * /*from  w  ww.  j av  a 2s. c  o m*/
 * @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.TikaCompressorStreamFactory.java

/**
 * Try to detect the type of compressor stream.
 *
 * @param in input stream/*from  w  w  w .  j a v  a2s.  co m*/
 * @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:util.epub.util.commons.io.XmlStreamReader.java

/**
 * Returns the encoding declared in the <?xml encoding=...?>, NULL if none.
 *
 * @param is InputStream to create the reader from.
 * @param guessedEnc guessed encoding/* w ww.j  a v  a 2  s  .co  m*/
 * @return the encoding declared in the <?xml encoding=...?>
 * @throws IOException thrown if there is a problem reading the stream.
 */
private static String getXmlProlog(InputStream is, String guessedEnc) throws IOException {
    String encoding = null;
    if (guessedEnc != null) {
        byte[] bytes = new byte[BUFFER_SIZE];
        is.mark(BUFFER_SIZE);
        int offset = 0;
        int max = BUFFER_SIZE;
        int c = is.read(bytes, offset, max);
        int firstGT = -1;
        String xmlProlog = null;
        while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
            offset += c;
            max -= c;
            c = is.read(bytes, offset, max);
            xmlProlog = new String(bytes, 0, offset, guessedEnc);
            firstGT = xmlProlog.indexOf('>');
        }
        if (firstGT == -1) {
            if (c == -1) {
                throw new IOException("Unexpected end of XML stream");
            } else {
                throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes");
            }
        }
        int bytesRead = offset;
        if (bytesRead > 0) {
            is.reset();
            BufferedReader bReader = new BufferedReader(new StringReader(xmlProlog.substring(0, firstGT + 1)));
            StringBuilder prolog = new StringBuilder();
            String line = bReader.readLine();
            while (line != null) {
                prolog.append(line);
                line = bReader.readLine();
            }
            Matcher m = ENCODING_PATTERN.matcher(prolog);
            if (m.find()) {
                encoding = m.group(1).toUpperCase();
                encoding = encoding.substring(1, encoding.length() - 1);
            }
        }
    }
    return encoding;
}

From source file:org.apache.tika.parser.pkg.TikaArchiveStreamFactory.java

/**
 * Try to determine the type of Archiver
 * @param in input stream/*from   w w  w.j a v  a 2 s .c o  m*/
 * @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");
}

From source file:org.craftercms.cstudio.alfresco.dm.util.DmUtils.java

public static String getMd5ForFile(InputStream input) {
    //PushbackInputStream helper = null;
    String result = null;//from ww w.j a  v a2s. c om
    MessageDigest md = null;
    try {
        //helper = new PushbackInputStream(input);
        //InputStreamReader reader = new InputStreamReader(input);
        md = MessageDigest.getInstance("MD5");

        md.reset();
        byte[] bytes = new byte[1024];
        int numBytes;
        //input.mark(input.available());
        input.mark(Integer.MAX_VALUE);
        while ((numBytes = input.read(bytes)) != -1) {
            md.update(bytes, 0, numBytes);
        }
        byte[] digest = md.digest();
        result = new String(Hex.encodeHex(digest));
        input.reset();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error while creating MD5 digest", e);
    } catch (IOException e) {
        logger.error("Error while reading input stream", e);
    } finally {

    }
    return result;
}

From source file:com.google.ratel.deps.io.input.XmlStreamReader.java

/**
 * Returns the encoding declared in the <?xml encoding=...?>, NULL if none.
 *
 * @param is InputStream to create the reader from.
 * @param guessedEnc guessed encoding//from   w w w  .  ja va2s.c  o  m
 * @return the encoding declared in the <?xml encoding=...?>
 * @throws IOException thrown if there is a problem reading the stream.
 */
private static String getXmlProlog(InputStream is, String guessedEnc) throws IOException {
    String encoding = null;
    if (guessedEnc != null) {
        byte[] bytes = new byte[BUFFER_SIZE];
        is.mark(BUFFER_SIZE);
        int offset = 0;
        int max = BUFFER_SIZE;
        int c = is.read(bytes, offset, max);
        int firstGT = -1;
        String xmlProlog = null;
        while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
            offset += c;
            max -= c;
            c = is.read(bytes, offset, max);
            xmlProlog = new String(bytes, 0, offset, guessedEnc);
            firstGT = xmlProlog.indexOf('>');
        }
        if (firstGT == -1) {
            if (c == -1) {
                throw new IOException("Unexpected end of XML stream");
            } else {
                throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes");
            }
        }
        int bytesRead = offset;
        if (bytesRead > 0) {
            is.reset();
            BufferedReader bReader = new BufferedReader(new StringReader(xmlProlog.substring(0, firstGT + 1)));
            StringBuffer prolog = new StringBuffer();
            String line = bReader.readLine();
            while (line != null) {
                prolog.append(line);
                line = bReader.readLine();
            }
            Matcher m = ENCODING_PATTERN.matcher(prolog);
            if (m.find()) {
                encoding = m.group(1).toUpperCase();
                encoding = encoding.substring(1, encoding.length() - 1);
            }
        }
    }
    return encoding;
}

From source file:com.zimbra.common.util.ByteUtil.java

/**
 * Determines if the data in the given stream is gzipped.
 * Requires that the <tt>InputStream</tt> supports mark/reset.
 *///from  w  w  w  .j a v a 2s.co  m
public static boolean isGzipped(InputStream in) throws IOException {
    in.mark(2);
    int header = in.read() | (in.read() << 8);
    in.reset();
    if (header == GZIPInputStream.GZIP_MAGIC) {
        return true;
    }
    return false;
}

From source file:de.fanero.uncompress.stream.StreamDetectorImpl.java

private byte[] readHeader(InputStream in, int headerSize) throws IOException {

    in.mark(headerSize);
    byte[] header = new byte[headerSize];
    try {/*from   ww w .j  a v a2  s .  c o m*/
        ByteStreams.readFully(in, header);
    } catch (IOException e) {
        // its ok
    }

    in.reset();
    return header;
}