Example usage for java.io InputStream markSupported

List of usage examples for java.io InputStream markSupported

Introduction

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

Prototype

public boolean markSupported() 

Source Link

Document

Tests if this input stream supports the mark and reset methods.

Usage

From source file:com.sun.jersey.client.apache.ApacheHttpClientHandler.java

private static InputStream getInputStream(HttpMethod method) throws IOException {
    InputStream i = method.getResponseBodyAsStream();

    if (i == null) {
        return new ByteArrayInputStream(new byte[0]);
    } else if (i.markSupported()) {
        return i;
    } else {/*from w ww . j av  a 2 s.  c o m*/
        return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
    }
}

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   w w  w.  ja v  a  2 s .  co m
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:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java

private static InputStream getInputStream(final HttpResponse response) throws IOException {

    if (response.getEntity() == null) {
        return new ByteArrayInputStream(new byte[0]);
    } else {//from   w  w  w.j  a  v a2 s  .c  o m
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported())
            return i;
        return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
    }
}

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

/**
 * Indicates whether an InputStream is GZIP compressed. The InputStream must support
 * mark()/reset().//w  w w.  j av a2 s.  c o m
 * @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:org.sipfoundry.sipxconfig.site.common.AssetSelector.java

public static boolean isAcceptedAudioFormat(InputStream stream) {
    try {/*  w ww .jav a 2  s  . co  m*/
        InputStream testedStream = stream;
        // HACK: looks like in openjdk InputStream does not support mark/reset
        if (!stream.markSupported()) {
            // getAudioInputStream depends on mark reset do we wrap buffered input stream
            // around passed stream
            testedStream = new BufferedInputStream(stream);
        }
        AudioInputStream audio = AudioSystem.getAudioInputStream(new BufferedInputStream(testedStream));
        AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, // sample
                // rate
                16, // bits per sample
                1, // channels
                2, // frame rate
                8000, // frame size
                false); // isBigEndian)
        return format.matches(audio.getFormat());
    } catch (IOException e) {
        LOG.warn("Uploaded file problems.", e);
    } catch (UnsupportedAudioFileException e) {
        LOG.info("Unsupported format", e);
    }
    return false;
}

From source file:org.talend.dataprep.schema.xls.XlsUtils.java

/**
 *
 * @param inputStream xls sheet inputStream
 * @return the column number from reading sheet metadata or -1 if unknown
 * @throws XMLStreamException//  w  w  w  .  j  a va2s  .com
 * @throws IOException
 */
public static int getColumnsNumber(InputStream inputStream) throws XMLStreamException, IOException {
    // If doesn't support mark, wrap up
    if (!inputStream.markSupported()) {
        inputStream = new PushbackInputStream(inputStream, 8);
    }

    int colNumber = 0;

    // TDP-1781 xlsx files may not containing dimension so we fallback to col element number

    XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream);
    try {
        while (streamReader.hasNext()) {
            switch (streamReader.next()) {
            case START_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "dimension")) {
                    Map<String, String> attributesValues = getAttributesNameValue(streamReader);
                    if (!attributesValues.isEmpty()) {
                        return getColumnsNumberFromDimension(attributesValues.get("ref"));
                    }
                }
                if (StringUtils.equals(streamReader.getLocalName(), "col")) {
                    colNumber++;
                }
                break;
            case END_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "cols")) {
                    return colNumber;
                }
            default:
                // no op
            }
        }
    } finally {
        if (streamReader != null) {
            streamReader.close();
        }
    }
    return -1;
}

From source file:org.talend.dataprep.schema.xls.XlsUtils.java

/**
 * read workbook xml spec to get non hidden sheets
 *
 * @param inputStream/*from   ww w . ja  v  a 2  s .c  o m*/
 * @return
 */
public static List<String> getActiveSheetsFromWorkbookSpec(InputStream inputStream) throws XMLStreamException {
    // If doesn't support mark, wrap up
    if (!inputStream.markSupported()) {
        inputStream = new PushbackInputStream(inputStream, 8);
    }
    XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream);
    try {
        /*
         *
         * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook
         * xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
         * xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <fileVersion appName="xl"
         * lastEdited="5" lowestEdited="5" rupBuild="9303" codeName="{8C4F1C90-05EB-6A55-5F09-09C24B55AC0B}"/>
         * <workbookPr codeName="ThisWorkbook" defaultThemeVersion="124226"/> <bookViews> <workbookView xWindow="0"
         * yWindow="732" windowWidth="22980" windowHeight="8868" firstSheet="1" activeTab="8"/> </bookViews>
         * <sheets> <sheet name="formdata" sheetId="4" state="hidden" r:id="rId1"/> <sheet name="MONDAY" sheetId="1"
         * r:id="rId2"/> <sheet name="TUESDAY" sheetId="8" r:id="rId3"/> <sheet name="WEDNESDAY" sheetId="10"
         * r:id="rId4"/> <sheet name="THURSDAY" sheetId="11" r:id="rId5"/> <sheet name="FRIDAY" sheetId="12"
         * r:id="rId6"/> <sheet name="SATURDAY" sheetId="13" r:id="rId7"/> <sheet name="SUNDAY" sheetId="14"
         * r:id="rId8"/> <sheet name="WEEK SUMMARY" sheetId="15" r:id="rId9"/> </sheets>
         *
         */
        // we only want sheets not with state=hidden

        List<String> names = new ArrayList<>();

        while (streamReader.hasNext()) {
            switch (streamReader.next()) {
            case START_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheet")) {
                    Map<String, String> attributesValues = getAttributesNameValue(streamReader);
                    if (!attributesValues.isEmpty()) {
                        String sheetState = attributesValues.get("state");
                        if (!StringUtils.equals(sheetState, "hidden")) {
                            String sheetName = attributesValues.get("name");
                            names.add(sheetName);
                        }
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheets")) {
                    // shortcut to stop parsing
                    return names;
                }
                break;
            default:
                // no op
            }
        }
        return names;
    } finally {
        if (streamReader != null) {
            streamReader.close();
        }
    }
}

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 av a2s  .  c  om*/
 * @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.ut.biolab.medsavant.shared.util.IOUtils.java

/**
 * Checks if an input stream is gzipped.
 *
 * @param in//from ww w .j  a  v a2 s  . c  o m
 * @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:de.innovationgate.wga.common.beans.csconfig.v1.CSConfig.java

public static CSConfig load(InputStream in, boolean forceClose)
        throws IOException, InvalidCSConfigVersionException {
    boolean marked = false;
    try {/*w  w  w  .j  a v a 2s .  com*/
        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();

    }
}