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:com.smartsheet.api.internal.util.StreamUtil.java

/**
 * used when you want to clone a InputStream's content and still have it appear "rewound" to the stream beginning
 * @param source       the stream around the contents we want to clone
 * @param readbackSize the farthest we should read a resetable stream before giving up
 * @param target       an output stream into which we place a copy of the content read from source
 * @return the source if it was resetable; a new stream rewound around the source data otherwise
 * @throws IOException if any issues occur with the reading of bytes from the source stream
 *///from www  .  ja  va2  s. c  om
public static InputStream cloneContent(InputStream source, int readbackSize, ByteArrayOutputStream target)
        throws IOException {
    if (source == null) {
        return null;
    }
    // if the source supports mark/reset then we read and then reset up to the read-back size
    if (source.markSupported()) {
        readbackSize = Math.max(TEN_KB, readbackSize); // at least 10 KB (minimal waste, handles those -1 ContentLength cases)
        source.mark(readbackSize);
        copyContentIntoOutputStream(source, target, readbackSize, false);
        source.reset();
        return source;
    } else {
        copyContentIntoOutputStream(source, target, ONE_MB, true);
        byte[] fullContentBytes = target.toByteArray();
        // if we can't reset the source we need to create a replacement stream so others can read the content
        return new ByteArrayInputStream(fullContentBytes);
    }
}

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Indicates whether an InputStream is GZIP compressed. The InputStream must support
 * mark()/reset().//from w w  w.jav  a 2s  .c om
 * @param in the InputStream (must return true on markSupported())
 * @return true if the InputStream is GZIP compressed
 * @throws IOException in case of an I/O error
 */
public static boolean isGZIPCompressed(InputStream in) throws IOException {
    if (!in.markSupported()) {
        throw new IllegalArgumentException("InputStream must support mark()!");
    }
    byte[] data = new byte[2];
    in.mark(2);
    in.read(data);
    in.reset();
    return ((data[0] == GZIP_MAGIC[0]) && (data[1] == GZIP_MAGIC[1]));
}

From source file:com.predic8.membrane.core.util.HttpUtil.java

public static String readLine(InputStream in) throws IOException, EndOfStreamException {

    StringBuilder line = new StringBuilder(128);

    int b;/*w ww .jav a 2  s  .com*/
    while ((b = in.read()) != -1) {
        if (b == 13) {
            in.read();
            return line.toString();
        }
        if (b == 10) {
            in.mark(2);
            if (in.read() != 13)
                in.reset();
            return line.toString();
        }

        line.append((char) b);
    }

    throw new EOFWhileReadingLineException(line.toString());
}

From source file:com.amazonaws.services.s3.internal.AWSS3V4Signer.java

/**
 * Read the content of the request to get the length of the stream.
 * This method will wrap the stream by RepeatableInputStream if it is 
 * not mark-supported./*from  w w  w .  ja v a  2  s.c  o m*/
 */
private static long getContentLength(Request<?> request) throws IOException {
    InputStream content = request.getContent();
    if (!content.markSupported()) {
        int streamBufferSize = Constants.getStreamBufferSize();
        content = new RepeatableInputStream(content, streamBufferSize);
        request.setContent(content);
    }

    long contentLength = 0;
    byte[] tmp = new byte[4096];
    int read;
    try {
        content.mark(-1);
        while ((read = content.read(tmp)) != -1) {
            contentLength += read;
        }
        content.reset();
    } finally {
        content.close();
    }

    return contentLength;
}

From source file:de.innovationgate.wga.common.beans.csconfig.v1.CSConfig.java

public static CSConfig load(InputStream in, boolean forceClose)
        throws IOException, InvalidCSConfigVersionException {
    boolean marked = false;
    try {// ww  w . j av  a  2s  .c o m
        if (in.markSupported()) {
            in.mark(1024 * 64);
            marked = true;
        }
        CSConfig csConfig = (CSConfig) XStreamUtils.loadUtf8FromInputStream(XSTREAM, in, forceClose);
        csConfig.init();
        return csConfig;
    } catch (CannotResolveClassException e) {
        if (marked) {
            try {
                in.reset();
                throw new InvalidCSConfigVersionException(in);
            } catch (IOException ee) {
            }

        }

        throw new InvalidCSConfigVersionException();

    }
}

From source file:org.ut.biolab.medsavant.shared.util.IOUtils.java

/**
 * Checks if an input stream is gzipped.
 *
 * @param in/*from  w  w w .  ja  v  a 2s .com*/
 * @return
 */
public static boolean isGZipped(InputStream in) {
    if (!in.markSupported()) {
        in = new BufferedInputStream(in);
    }
    in.mark(2);
    int magic = 0;
    try {
        magic = in.read() & 0xff | ((in.read() << 8) & 0xff00);
        in.reset();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        return false;
    }
    return magic == GZIPInputStream.GZIP_MAGIC;
}

From source file:org.apache.nifi.processors.standard.util.crypto.CipherUtility.java

public static byte[] readBytesFromInputStream(InputStream in, String label, int limit, byte[] delimiter)
        throws IOException, ProcessException {
    if (in == null) {
        throw new IllegalArgumentException("Cannot read " + label + " from null InputStream");
    }/*w w  w. j a  v  a 2 s.c  om*/

    // If the value is not detected within the first n bytes, throw an exception
    in.mark(limit);

    // The first n bytes of the input stream contain the value up to the custom delimiter
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    byte[] stoppedBy = StreamUtils.copyExclusive(in, bytesOut, limit + delimiter.length, delimiter);

    if (stoppedBy != null) {
        byte[] bytes = bytesOut.toByteArray();
        return bytes;
    }

    // If no delimiter was found, reset the cursor
    in.reset();
    return null;
}

From source file:org.syphr.prom.PropertiesManagerTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    Assert.assertTrue("Unable to create \"" + TEST_DATA_DIR.getAbsolutePath() + "\"",
            TEST_DATA_DIR.isDirectory() || TEST_DATA_DIR.mkdirs());

    InputStream baseIn1 = PropertiesManagerTest.class.getResourceAsStream(BASE_PROPS_1_RESOURCE_PATH);
    Assert.assertNotNull("Base properties 1 is missing", baseIn1);

    OutputStream baseOut1 = new FileOutputStream(TEST_PROPS_1);
    IOUtils.copy(baseIn1, baseOut1);/* ww w .  ja v a 2 s  .c om*/

    baseIn1.close();
    baseOut1.close();

    InputStream baseIn2 = PropertiesManagerTest.class.getResourceAsStream(BASE_PROPS_2_RESOURCE_PATH);
    Assert.assertNotNull("Base properties 2 is missing", baseIn2);

    OutputStream baseOut2 = new FileOutputStream(TEST_PROPS_2);
    IOUtils.copy(baseIn2, baseOut2);

    baseIn2.close();
    baseOut2.close();

    InputStream baseIn2Default = PropertiesManagerTest.class
            .getResourceAsStream(BASE_PROPS_2_DEFAULT_RESOURCE_PATH);
    Assert.assertNotNull("Base properties 2 default is missing", baseIn2Default);

    baseIn2Default.mark(Integer.MAX_VALUE);

    OutputStream baseOut2Default = new FileOutputStream(TEST_PROPS_2_DEFAULT);
    IOUtils.copy(baseIn2Default, baseOut2Default);

    baseIn2Default.reset();
    test2DefaultProperties = new Properties();
    test2DefaultProperties.load(baseIn2Default);

    baseIn2Default.close();
    baseOut2Default.close();

    TRANSLATOR1 = new Translator<Key1>() {
        @Override
        public String getPropertyName(Key1 propertyKey) {
            return propertyKey.name().toLowerCase().replace('_', '-');
        }

        @Override
        public Key1 getPropertyKey(String propertyName) {
            String enumName = propertyName.toUpperCase().replace('-', '_');
            return Key1.valueOf(enumName);
        }
    };

    EXECUTOR = Executors.newCachedThreadPool();
}

From source file:org.lockss.util.CharsetUtil.java

/**
 * This will guess the charset of an inputstream.  If the inpust
 * @param in an input stream which we will be checking
 * @return the charset or null if nothing could be determined with greater
 * than 50% accuracy//  w  w  w  . j a  v  a  2 s.  c  o  m
 * @throws IOException if mark() not supported or read fails
 */
public static String guessCharsetName(InputStream in) throws IOException {
    if (!in.markSupported())
        throw new IllegalArgumentException("InputStream must support mark.");
    ByteArrayOutputStream buffered = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    in.mark(2048);
    int len = in.read(buf);
    if (len <= 0) {
        return UTF8; // this is just a default for 0 len stream
    }
    // If the charset is specified in the document, use that.
    String charset = findCharsetInText(buf, len);
    if (charset == null) { // we didn't find it check BOM
        if (hasUtf8BOM(buf, len)) {
            charset = UTF8;
            // Check UTF32 before UTF16 since a little endian UTF16 BOM is a prefix of
            // a little endian UTF32 BOM.
        } else if (hasUtf32BEBOM(buf, len)) {
            charset = UTF32BE;
        } else if (hasUtf32LEBOM(buf, len)) {
            charset = UTF32LE;
        } else if (hasUtf16BEBOM(buf, len)) {
            charset = UTF16BE;
        } else if (hasUtf16LEBOM(buf, len)) {
            charset = UTF16LE;
        } else if (hasUtf7BOM(buf, len)) {
            charset = UTF7;
        } else if (hasUtf1BOM(buf, len)) {
            charset = UTF1;
        } else {
            // Use icu4j to guess an encoding.
            charset = guessCharsetFromBytes(buf);
        }
    }
    if (charset != null) {
        charset = supportedCharsetName(charset);
    }
    if (charset == null) {
        charset = UTF8;
    }
    in.reset();
    return charset;
}

From source file:org.apache.jmeter.save.SaveService.java

/**
 * //  w  w w.j  a va  2  s.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 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);
        }
    }

}