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:org.apache.hadoop.fs.tar.TarFSUtils.java

private static byte[] getFirstFewBytes(InputStream in, int n) throws IOException {
    byte[] b = new byte[n];

    if (in.markSupported()) {
        in.mark(n);
        int bytesRead = in.read(b);
        in.reset();/*from  w ww .  j  a v  a2s  .  c  o  m*/

        if (bytesRead < n)
            return null;
    } else
        throw new IOException("Mark must be supported");

    return b;
}

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.document.DocTypeIdentifier.java

/**
 * Guess the document format and return an appropriate document type string
 *
 * @param is An InputStream holding the document
 * @return "xml" if the document is an XML document or "pdf" if the document
 * is a PDF document, or else an error message.
 *//*from  www .j  a  v a2 s.c  o  m*/
public static DocType getDocType(InputStream is) {
    InputStream input = null;

    try {
        input = new BufferedInputStream(is);
        input.mark(5);
        byte[] preamble = new byte[5];
        int read = 0;
        try {
            read = input.read(preamble);
            input.reset();
        } catch (IOException ex) {
            return DocType.UNKNOWN;
        }
        if (read < 5) {
            return DocType.UNKNOWN;
        }
        String preambleString = new String(preamble);
        byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' };
        byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' };
        if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) {
            return DocType.XML;
        } else if (preambleString.equals("%PDF-")) {
            return DocType.PDF;
        } else if (preamble[0] == 'P' && preamble[1] == 'K') {
            ZipInputStream asics = new ZipInputStream(new BufferedInputStream(is));
            ByteArrayOutputStream datafile = null;
            ByteArrayOutputStream signatures = null;
            ZipEntry entry;
            try {
                while ((entry = asics.getNextEntry()) != null) {
                    if (entry.getName().equals("META-INF/signatures.p7s")) {
                        signatures = new ByteArrayOutputStream();
                        IOUtils.copy(asics, signatures);
                        signatures.close();
                    } else if (entry.getName().equalsIgnoreCase("META-INF/signatures.p7s")) {
                        /* Wrong case */
                        return DocType.ASICS_NON_ETSI;
                    } else if (entry.getName().indexOf("/") == -1) {
                        if (datafile == null) {
                            datafile = new ByteArrayOutputStream();
                            IOUtils.copy(asics, datafile);
                            datafile.close();
                        } else {
                            return DocType.ASICS_S;
                        }
                    }
                }
            } catch (Exception ex) {
                return DocType.UNKNOWN;
            }
            if (datafile == null || signatures == null) {
                return DocType.UNKNOWN;
            }
            return DocType.ASICS_CADES;

        } else if (preambleString.getBytes()[0] == 0x30) {
            return DocType.CADES;
        } else {
            return DocType.UNKNOWN;
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.apache.any23.extractor.csv.CSVReaderBuilder.java

/**
 * make sure the reader has correct delimiter and quotation set.
 * Check first lines and make sure they have the same amount of columns and at least 2
 *
 * @param is input stream to be checked/*from  ww w  .ja v  a 2s .c om*/
 * @param strategy strategy to be verified.
 * @return
 * @throws IOException
 * @param is
 */
private static boolean testStrategy(InputStream is, CSVStrategy strategy) throws IOException {
    final int MIN_COLUMNS = 2;

    is.mark(Integer.MAX_VALUE);
    try {
        final CSVParser parser = new CSVParser(new InputStreamReader(is), strategy);
        int linesToCheck = 5;
        int headerColumnCount = -1;
        while (linesToCheck > 0) {
            String[] row;
            row = parser.getLine();
            if (row == null) {
                break;
            }
            if (row.length < MIN_COLUMNS) {
                return false;
            }
            if (headerColumnCount == -1) { // first row
                headerColumnCount = row.length;
            } else { // make sure rows have the same number of columns or one more than the header
                if (row.length < headerColumnCount) {
                    return false;
                } else if (row.length - 1 > headerColumnCount) {
                    return false;
                }
            }
            linesToCheck--;
        }
        return true;
    } finally {
        is.reset();
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.ZipUtils.java

/**
 * check if the {@link InputStream} provided is a zip file
 * //from w w w.  j av  a  2s .  com
 * @param in the stream.
 * @return if it is a ZIP file.
 */
public static boolean isZipStream(InputStream in) {
    if (!in.markSupported()) {
        in = new BufferedInputStream(in);
    }
    boolean isZip = true;
    try {
        in.mark(MAGIC.length);
        for (byte element : MAGIC) {
            if (element != (byte) in.read()) {
                isZip = false;
                break;
            }
        }
        in.reset();
    } catch (IOException e) {
        isZip = false;
    }
    return isZip;
}

From source file:Main.java

/**
 * detectEncoding.java - Returns the character encoding of an input stream containin an XML file.<br/> 
 * Copyright (c) 2009 Alexander Hristov .
 *
 * Licensed under the LGPL License - http://www.gnu.org/licenses/lgpl.txt
 * Returns the character encoding of an input stream containin an XML file.<br/> 
 * /*from   w w  w.  java2s .c o m*/
 * The encoding is detected using the guidelines specified in the
 * <a href='http://www.w3.org/TR/xml/#sec-guessing'>XML W3C Specification</a>,
 * and the method was designed to be as fast as possible, without extensive
 * string operations or regular expressions<br/> <br/> 
 * 
 * <code>
 * A sample use would be<br/><br/>
 * InputStream in = ...; <br/>
 * String encoding = detectEncoding(in);<br/>
 * BufferedReader reader = new BufferedReader(new InputStreamReader(in,encoding)); <br/>
 * </code><br/> 
 * 
 * and from that point you can happily read text from the input stream.
 * 
 * @param in
 *          Stream containing the data to be read. The stream must support
 *          mark()/reset(), otherwise the caller should wrap that stream in a
 *          {@link BufferedInputStream} before invokin the method. After the
 *          call, the stream is positioned at the &lt; character (this means
 *          that if there were any byte-order-marks, they are skipped).
 * 
 * @return Detected encoding, using the canonical name in java.io (see <a
 *         href=
 *         'http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html'>Supported
 *         Encodings</a> ).
 * 
 * @author Alexander Hristov
 */
public static String detectEncoding(InputStream in) throws IOException {
    String encoding = null;
    in.mark(400);
    int ignoreBytes = 0;
    boolean readEncoding = false;
    byte[] buffer = new byte[400];
    int read = in.read(buffer, 0, 4);
    switch (buffer[0]) {
    case (byte) 0x00:
        if (buffer[1] == (byte) 0x00 && buffer[2] == (byte) 0xFE && buffer[3] == (byte) 0xFF) {
            ignoreBytes = 4;
            encoding = "UTF_32BE";
        } else if (buffer[1] == (byte) 0x00 && buffer[2] == (byte) 0x00 && buffer[3] == (byte) 0x3C) {
            encoding = "UTF_32BE";
            readEncoding = true;
        } else if (buffer[1] == (byte) 0x3C && buffer[2] == (byte) 0x00 && buffer[3] == (byte) 0x3F) {
            encoding = "UnicodeBigUnmarked";
            readEncoding = true;
        }
        break;
    case (byte) 0xFF:
        if (buffer[1] == (byte) 0xFE && buffer[2] == (byte) 0x00 && buffer[3] == (byte) 0x00) {
            ignoreBytes = 4;
            encoding = "UTF_32LE";
        } else if (buffer[1] == (byte) 0xFE) {
            ignoreBytes = 2;
            encoding = "UnicodeLittleUnmarked";
        }
        break;

    case (byte) 0x3C:
        readEncoding = true;
        if (buffer[1] == (byte) 0x00 && buffer[2] == (byte) 0x00 && buffer[3] == (byte) 0x00) {
            encoding = "UTF_32LE";
        } else if (buffer[1] == (byte) 0x00 && buffer[2] == (byte) 0x3F && buffer[3] == (byte) 0x00) {
            encoding = "UnicodeLittleUnmarked";
        } else if (buffer[1] == (byte) 0x3F && buffer[2] == (byte) 0x78 && buffer[3] == (byte) 0x6D) {
            encoding = "ASCII";
        }
        break;
    case (byte) 0xFE:
        if (buffer[1] == (byte) 0xFF) {
            encoding = "UnicodeBigUnmarked";
            ignoreBytes = 2;
        }
        break;
    case (byte) 0xEF:
        if (buffer[1] == (byte) 0xBB && buffer[2] == (byte) 0xBF) {
            encoding = "UTF8";
            ignoreBytes = 3;
        }
        break;
    case (byte) 0x4C:
        if (buffer[1] == (byte) 0x6F && buffer[2] == (byte) 0xA7 && buffer[3] == (byte) 0x94) {
            encoding = "CP037";
        }
        break;
    }
    if (encoding == null) {
        encoding = System.getProperty("file.encoding");
    }
    if (readEncoding) {
        read = in.read(buffer, 4, buffer.length - 4);
        Charset cs = Charset.forName(encoding);
        String s = new String(buffer, 4, read, cs);
        int pos = s.indexOf("encoding");
        if (pos == -1) {
            encoding = System.getProperty("file.encoding");
        } else {
            int limit = s.indexOf("?>");
            char delim;
            int start = s.indexOf(delim = '\'', pos);
            if (start == -1 || start >= limit)
                start = s.indexOf(delim = '"', pos);
            if (start == -1 || start >= limit)
                throw (new IOException("Encoding error " + buffer));
            int end = s.indexOf(delim, start + 1);
            if (end == -1 || end >= limit)
                throw (new IOException("Encoding error " + buffer));
            encoding = s.substring(start + 1, end);
        }
    }

    in.reset();
    while (ignoreBytes-- > 0)
        in.read();
    return encoding;
}

From source file:Main.java

public static Bitmap getImageBitmapFromAssetsFolderThroughImagePathName(Context context, String imagePathName,
        int reqWidth, int reqHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;//w w w  . jav  a 2  s .co  m
    Bitmap bitmap = null;
    AssetManager assetManager = context.getResources().getAssets();
    InputStream inputStream = null;

    try {
        inputStream = assetManager.open(imagePathName);
        inputStream.mark(Integer.MAX_VALUE);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    }

    try {
        if (inputStream != null) {
            BitmapFactory.decodeStream(inputStream, null, opts);
            inputStream.reset();
        } else {
            return null;
        }
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    opts.inSampleSize = calculateInSampleSiez(opts, reqWidth, reqHeight);
    //         Log.d(TAG,""+opts.inSampleSize);
    opts.inJustDecodeBounds = false;
    opts.inPreferredConfig = Bitmap.Config.RGB_565;
    opts.inPurgeable = true;
    opts.inInputShareable = true;
    opts.inDither = false;
    opts.inTempStorage = new byte[512 * 1024];
    try {
        if (inputStream != null) {
            bitmap = BitmapFactory.decodeStream(inputStream, null, opts);
        } else {
            return null;
        }
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    //Log.d(TAG,"w:"+bitmap.getWidth()+" h:"+bitmap.getHeight());
    if (bitmap != null) {
        try {
            bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true);
        } catch (OutOfMemoryError outOfMemoryError) {
            outOfMemoryError.printStackTrace();
            System.gc();
            return null;
        }
    }
    return bitmap;
}

From source file:org.infoscoop.request.filter.RssFilter.java

public static boolean isAtom(InputStream is) throws IOException {
    is.mark(1);
    byte[] xmldec = new byte[500];
    is.read(xmldec);/*  w  w w  .  ja  v a 2  s  .co m*/

    String xmlDecStr = new String(xmldec);
    boolean isAtom = false;
    if (xmlDecStr.indexOf("<feed") > 0) {
        isAtom = true;
    }
    is.reset();
    if (log.isDebugEnabled()) {
        log.debug(isAtom ? "Process atom." : "Process rss.");
    }

    return isAtom;
}

From source file:com.aaasec.sigserv.cscommon.DocTypeIdentifier.java

/**
 * Guess the document format and return an appropriate document type string
 *
 * @param is An InputStream holding the document
 * @return "xml" if the document is an XML document or "pdf" if the document
 * is a PDF document, or else an error message.
 */// w ww  . ja v a 2 s  .c  o m
public static SigDocumentType getDocType(InputStream is) {
    InputStream input = null;

    try {
        input = new BufferedInputStream(is);
        input.mark(5);
        byte[] preamble = new byte[5];
        int read = 0;
        try {
            read = input.read(preamble);
            input.reset();
        } catch (IOException ex) {
            return SigDocumentType.Unknown;
        }
        if (read < 5) {
            return SigDocumentType.Unknown;
        }
        String preambleString = new String(preamble);
        byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' };
        byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' };
        if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) {
            return SigDocumentType.XML;
        } else if (preambleString.equals("%PDF-")) {
            return SigDocumentType.PDF;
        } else if (preamble[0] == 'P' && preamble[1] == 'K') {
            ZipInputStream asics = new ZipInputStream(new BufferedInputStream(is));
            ByteArrayOutputStream datafile = null;
            ByteArrayOutputStream signatures = null;
            ZipEntry entry;
            try {
                while ((entry = asics.getNextEntry()) != null) {
                    if (entry.getName().equals("META-INF/signatures.p7s")) {
                        signatures = new ByteArrayOutputStream();
                        IOUtils.copy(asics, signatures);
                        signatures.close();
                    } else if (entry.getName().equalsIgnoreCase("META-INF/signatures.p7s")) {
                        /* Wrong case */
                        // asics;Non ETSI compliant
                        return SigDocumentType.Unknown;
                    } else if (entry.getName().indexOf("/") == -1) {
                        if (datafile == null) {
                            datafile = new ByteArrayOutputStream();
                            IOUtils.copy(asics, datafile);
                            datafile.close();
                        } else {
                            //                              // asics;ASiC-S profile support only one data file
                            return SigDocumentType.Unknown;
                        }
                    }
                }
            } catch (Exception ex) {
                // null;Invalid ASiC-S
                return SigDocumentType.Unknown;
            }
            if (datafile == null || signatures == null) {
                // asics;ASiC-S profile support only one data file with CAdES signature
                return SigDocumentType.Unknown;
            }
            // asics/cades
            return SigDocumentType.Unknown;

        } else if (preambleString.getBytes()[0] == 0x30) {
            // cades;
            return SigDocumentType.Unknown;
        } else {
            // null;Document format not recognized/handled
            return SigDocumentType.Unknown;
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.apache.sling.distribution.packaging.impl.SimpleDistributionPackage.java

public static SimpleDistributionPackage fromStream(InputStream stream, String type) {

    try {/* w  w  w  .ja va  2  s.  co  m*/
        int size = SimpleDistributionPackage.PACKAGE_START.getBytes("UTF-8").length;
        stream.mark(size);
        byte[] buffer = new byte[size];
        int bytesRead = stream.read(buffer, 0, size);
        stream.reset();
        String s = new String(buffer, "UTF-8");

        if (bytesRead > 0 && buffer[0] > 0 && s.startsWith(SimpleDistributionPackage.PACKAGE_START)) {
            String streamString = IOUtils.toString(stream, "UTF-8");

            return fromIdString(streamString, type);
        }
    } catch (IOException e) {
        log.error("cannot read stream", e);
    }

    return null;
}

From source file:org.dishevelled.compress.Compress.java

/**
 * Return true if the specified file is a gzip input stream.
 *
 * @since 1.3/* ww  w  .  j  a  v  a2  s. c  o m*/
 * @param inputStream input stream, must not be null
 * @return true if the specified file is a gzip input stream
 */
public static boolean isGzipInputStream(final InputStream inputStream) {
    checkNotNull(inputStream);
    InputStream in = inputStream.markSupported() ? inputStream : new BufferedInputStream(inputStream);
    try {
        in.mark(2);
        return in.read() == 31 && in.read() == 139;
    } catch (IOException e) {
        return false;
    } finally {
        try {
            in.reset();
        } catch (IOException e) {
            // ignore
        }
    }
}