Example usage for java.io BufferedInputStream reset

List of usage examples for java.io BufferedInputStream reset

Introduction

In this page you can find the example usage for java.io BufferedInputStream reset.

Prototype

public synchronized void reset() throws IOException 

Source Link

Document

See the general contract of the reset method of InputStream.

Usage

From source file:org.apache.storm.daemon.logviewer.handler.LogviewerLogSearchHandler.java

/**
 * Tries once to read ahead in the stream to fill the context and
 * resets the stream to its position before the call.
 *///from w ww  .  j  ava2  s  .  co m
private byte[] tryReadAhead(BufferedInputStream stream, ByteBuffer haystack, int offset, int fileLength,
        int bytesRead) throws IOException {
    int numExpected = Math.min(fileLength - bytesRead, GREP_CONTEXT_SIZE);
    byte[] afterBytes = new byte[numExpected];
    stream.mark(numExpected);
    // Only try reading once.
    stream.read(afterBytes, 0, numExpected);
    stream.reset();
    return afterBytes;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReaderSpi.java

@Override
public boolean canDecodeInput(Object source) throws IOException {
    if (!(source instanceof BufferedInputStream)) {
        return false;
    }//from w ww.j  a v a  2 s  . c om
    if (source == null) {
        throw new IllegalArgumentException("source == null!");
    }
    BufferedInputStream stream = (BufferedInputStream) source;
    dbgLog.fine("applying the por test\n");

    byte[] b = new byte[POR_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }

    int nbytes = stream.read(b, 0, POR_HEADER_SIZE);

    //printHexDump(b, "hex dump of the byte-array");

    if (nbytes == 0) {
        throw new IOException();
    } else if (nbytes < 491) {
        // size test
        dbgLog.fine("this file is NOT spss-por type");
        return false;
    }

    if (stream.markSupported()) {
        stream.reset();
    }

    boolean DEBUG = false;

    //windows [0D0A]=>   [1310] = [CR/LF]
    //unix    [0A]  =>   [10]
    //mac     [0D]  =>   [13]
    // 3char  [0D0D0A]=> [131310] spss for windows rel 15
    // expected results
    // unix    case: [0A]   : [80], [161], [242], [323], [404], [485]
    // windows case: [0D0A] : [81], [163], [245], [327], [409], [491]
    //  : [0D0D0A] : [82], [165], [248], [331], [414], [495]

    // convert b into a ByteBuffer

    ByteBuffer buff = ByteBuffer.wrap(b);
    byte[] nlch = new byte[36];
    int pos1;
    int pos2;
    int pos3;
    int ucase = 0;
    int wcase = 0;
    int mcase = 0;
    int three = 0;
    int nolines = 6;
    int nocols = 80;
    for (int i = 0; i < nolines; ++i) {
        int baseBias = nocols * (i + 1);
        // 1-char case
        pos1 = baseBias + i;
        buff.position(pos1);
        dbgLog.finer("\tposition(1)=" + buff.position());
        int j = 6 * i;
        nlch[j] = buff.get();

        if (nlch[j] == 10) {
            ucase++;
        } else if (nlch[j] == 13) {
            mcase++;
        }

        // 2-char case
        pos2 = baseBias + 2 * i;
        buff.position(pos2);
        dbgLog.finer("\tposition(2)=" + buff.position());

        nlch[j + 1] = buff.get();
        nlch[j + 2] = buff.get();

        // 3-char case
        pos3 = baseBias + 3 * i;
        buff.position(pos3);
        dbgLog.finer("\tposition(3)=" + buff.position());

        nlch[j + 3] = buff.get();
        nlch[j + 4] = buff.get();
        nlch[j + 5] = buff.get();

        dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]);
        dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]);

        if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) {
            three++;
        } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) {
            wcase++;
        }

        buff.rewind();
    }
    if (three == nolines) {
        dbgLog.fine("0D0D0A case");
        windowsNewLine = false;
    } else if ((ucase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0A case");
        windowsNewLine = false;
    } else if ((ucase < nolines) && (wcase == nolines)) {
        dbgLog.fine("0D0A case");
    } else if ((mcase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0D case");
        windowsNewLine = false;
    }

    buff.rewind();
    int PORmarkPosition = POR_MARK_POSITION_DEFAULT;
    if (windowsNewLine) {
        PORmarkPosition = PORmarkPosition + 5;
    } else if (three == nolines) {
        PORmarkPosition = PORmarkPosition + 10;
    }

    byte[] pormark = new byte[8];
    buff.position(PORmarkPosition);
    buff.get(pormark, 0, 8);
    String pormarks = new String(pormark);

    dbgLog.fine(
            "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-");

    if (pormarks.equals(POR_MARK)) {
        dbgLog.fine("this file is spss-por type");
        return true;
    } else {
        dbgLog.fine("this file is NOT spss-por type");
    }
    return false;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReaderSpi.java

@Override
public boolean canDecodeInput(BufferedInputStream stream) throws IOException {
    if (stream == null) {
        throw new IllegalArgumentException("file == null!");
    }/*w  w w .  j av a2  s  .  c o m*/

    dbgLog.fine("applying the por test\n");

    byte[] b = new byte[POR_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }

    int nbytes = stream.read(b, 0, POR_HEADER_SIZE);

    //printHexDump(b, "hex dump of the byte-array");

    if (nbytes == 0) {
        throw new IOException();
    } else if (nbytes < 491) {
        // size test
        dbgLog.fine("this file is NOT spss-por type");
        return false;
    }

    if (stream.markSupported()) {
        stream.reset();
    }

    boolean DEBUG = false;

    //windows [0D0A]=>   [1310] = [CR/LF]
    //unix    [0A]  =>   [10]
    //mac     [0D]  =>   [13]
    // 3char  [0D0D0A]=> [131310] spss for windows rel 15
    // expected results
    // unix    case: [0A]   : [80], [161], [242], [323], [404], [485]
    // windows case: [0D0A] : [81], [163], [245], [327], [409], [491]
    //  : [0D0D0A] : [82], [165], [248], [331], [414], [495]

    // convert b into a ByteBuffer

    ByteBuffer buff = ByteBuffer.wrap(b);
    byte[] nlch = new byte[36];
    int pos1;
    int pos2;
    int pos3;
    int ucase = 0;
    int wcase = 0;
    int mcase = 0;
    int three = 0;
    int nolines = 6;
    int nocols = 80;
    for (int i = 0; i < nolines; ++i) {
        int baseBias = nocols * (i + 1);
        // 1-char case
        pos1 = baseBias + i;
        buff.position(pos1);
        dbgLog.finer("\tposition(1)=" + buff.position());
        int j = 6 * i;
        nlch[j] = buff.get();

        if (nlch[j] == 10) {
            ucase++;
        } else if (nlch[j] == 13) {
            mcase++;
        }

        // 2-char case
        pos2 = baseBias + 2 * i;
        buff.position(pos2);
        dbgLog.finer("\tposition(2)=" + buff.position());

        nlch[j + 1] = buff.get();
        nlch[j + 2] = buff.get();

        // 3-char case
        pos3 = baseBias + 3 * i;
        buff.position(pos3);
        dbgLog.finer("\tposition(3)=" + buff.position());

        nlch[j + 3] = buff.get();
        nlch[j + 4] = buff.get();
        nlch[j + 5] = buff.get();

        dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]);
        dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]);

        if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) {
            three++;
        } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) {
            wcase++;
        }

        buff.rewind();
    }
    if (three == nolines) {
        dbgLog.fine("0D0D0A case");
        windowsNewLine = false;
    } else if ((ucase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0A case");
        windowsNewLine = false;
    } else if ((ucase < nolines) && (wcase == nolines)) {
        dbgLog.fine("0D0A case");
    } else if ((mcase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0D case");
        windowsNewLine = false;
    }

    buff.rewind();
    int PORmarkPosition = POR_MARK_POSITION_DEFAULT;
    if (windowsNewLine) {
        PORmarkPosition = PORmarkPosition + 5;
    } else if (three == nolines) {
        PORmarkPosition = PORmarkPosition + 10;
    }

    byte[] pormark = new byte[8];
    buff.position(PORmarkPosition);
    buff.get(pormark, 0, 8);
    String pormarks = new String(pormark);

    //dbgLog.fine("pormark =>" + pormarks + "<-");
    dbgLog.fine(
            "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-");

    if (pormarks.equals(POR_MARK)) {
        dbgLog.fine("this file is spss-por type");
        return true;
    } else {
        dbgLog.fine("this file is NOT spss-por type");
    }
    return false;
}

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

/**
 * Return the contents of the given input stream, limited to Anki2Importer.MEDIAPICKLIMIT bytes
 * This is only used for comparison of media files with the limited resources of mobile devices
 *///from   w  w  w  .  ja v  a 2s .  c o m
byte[] _mediaPick(BufferedInputStream is) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(MEDIAPICKLIMIT * 2);
        byte[] buf = new byte[MEDIAPICKLIMIT];
        int readLen;
        int readSoFar = 0;
        is.mark(MEDIAPICKLIMIT * 2);
        while (true) {
            readLen = is.read(buf);
            baos.write(buf);
            if (readLen == -1) {
                break;
            }
            readSoFar += readLen;
            if (readSoFar > MEDIAPICKLIMIT) {
                break;
            }
        }
        is.reset();
        byte[] result = new byte[MEDIAPICKLIMIT];
        System.arraycopy(baos.toByteArray(), 0, result, 0, Math.min(baos.size(), MEDIAPICKLIMIT));
        return result;
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

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

public byte[] process(String aContentType, String startDateStr, String endDateStr, InputStream responseStream)
        throws IOException {

    String charset = null;/*from ww  w .  j  a  v a  2s. c  om*/
    String contentType = null;
    if (aContentType != null) {
        String[] str = aContentType.split("=");
        if (str != null)
            contentType = str[0];
        if (str.length > 1) {
            charset = str[1];
        }
    }

    BufferedInputStream bis = new BufferedInputStream(responseStream);

    //Processing of skipping to the first character
    int temp = 0;
    boolean noContent = false;
    bis.mark(1);
    while (true) {
        try {
            temp = bis.read();
            if (temp == -1 || (temp >= 0x20 && temp <= 0x7e)) {
                if (temp == -1) {
                    noContent = true;
                }
                break;
            } else {
                bis.mark(1);
            }
        } catch (IOException e) {
            log.error("", e);
            break;
        }
    }

    // if 200 and empty
    if (noContent) {
        bis.close();
        return process("[]", 0);
    }

    try {
        bis.reset();
    } catch (IOException e2) {
    }
    //Processing of skipping to the first character up to here

    Reader reader = null;
    boolean isXML = false;
    try {
        if (contentType != null && (contentType.startsWith("text/xml")
                || contentType.startsWith("application/xml") || contentType.startsWith("application/rss+xml")
                || contentType.startsWith("application/rdf+xml"))) {
            isXML = true;
        } else {
            char firstChar = (char) bis.read();
            if (firstChar == '<') {
                isXML = true;
            }
            bis.reset();
        }
    } catch (IOException e) {
        log.error("", e);
    }

    if (isXML) {
        if (isCalDAV(bis)) {
            StringBuffer buf = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(bis, charset));
            String s = null;
            boolean append = false;
            boolean inVALARM = false;
            buf.append("BEGIN:VCALENDAR").append("\r\n");
            String davHref = null;
            while ((s = br.readLine()) != null) {
                String _davHref = getDAVHref(s, br);
                if (_davHref != null)
                    davHref = _davHref;

                if (s.indexOf("BEGIN:VEVENT") >= 0) {
                    append = true;
                }
                if (s.indexOf("BEGIN:VALARM") >= 0) {
                    inVALARM = true;
                }
                if (append && !inVALARM) {
                    if (s.indexOf("END:VEVENT") >= 0 && davHref != null) {
                        buf.append(davHref).append("\r\n");
                        davHref = null;
                    }
                    buf.append(s).append("\r\n");
                }
                if (s.indexOf("END:VEVENT") >= 0) {
                    append = false;
                }
                if (s.indexOf("END:VALARM") >= 0) {
                    inVALARM = false;
                }
            }
            buf.append("END:VCALENDAR");

            if (log.isDebugEnabled())
                log.debug(buf.toString());
            reader = new StringReader(buf.toString());
        } else {
            try {
                reader = ICalendarUtil.convertRdf2Ics(bis);
            } catch (SAXException e) {
                log.error("", e);
                if (log.isInfoEnabled())
                    log.info("Unanalyzable RSS information is recieved.[" + e.getLocalizedMessage() + "]");
                return process("Unanalyzable RSS information is recieved. : " + e.getLocalizedMessage(), 1);
            } catch (IOException e) {
                log.error("", e);
                if (log.isInfoEnabled())
                    log.info("Unanalyzable RSS information is recieved.[" + e.getLocalizedMessage() + "]");
                return process("Unanalyzable RSS information is recieved.: " + e.getLocalizedMessage(), 1);
            }
        }
    } else {
        try {
            if (charset != null)
                reader = new InputStreamReader(bis, charset);
            else
                reader = new InputStreamReader(bis, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            try {
                reader = new InputStreamReader(bis, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                log.error("", e1);
            }
        }
    }

    String result = null;
    try {
        //PrereqRDF and removal of line break ICS and Reader#reset done.
        result = parseICalendar(reader, startDateStr, endDateStr);
    } catch (IOException e) {
        log.error("", e);
        if (log.isInfoEnabled())
            log.info("Unanalyzable ics information is recieved.[" + e.getLocalizedMessage() + "]");
        return process("Unanalyzable ics information is recieved. : " + e.getLocalizedMessage(), 1);
    } catch (ParserException e) {
        log.error("", e);
        if (log.isInfoEnabled())
            log.info("Unanalyzable ics information is recieved.[" + e.getLocalizedMessage() + "]");
        return process("Unanalyzable ics information is recieved. : " + e.getLocalizedMessage(), 1);
    }

    return process("[" + result + "]", 0);

}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

public String getLabel(URI link, IProgressMonitor monitor) throws ConnectionException {
    String title = ""; //$NON-NLS-1$

    /* Define Properties for Connection */
    Map<Object, Object> properties = new HashMap<Object, Object>();
    properties.put(IConnectionPropertyConstants.PROGRESS_MONITOR, monitor);
    properties.put(IConnectionPropertyConstants.CON_TIMEOUT, FEED_LABEL_CON_TIMEOUT);

    /* Open Stream */
    InputStream inS = openStream(link, properties);
    try {/*from   ww  w  .jav  a 2  s .  c om*/

        /* Return on Cancelation or Shutdown */
        if (monitor.isCanceled())
            return null;

        /* Buffered Stream to support mark and reset */
        BufferedInputStream bufIns = new BufferedInputStream(inS);
        bufIns.mark(8192);

        /* Try to read Encoding out of XML Document */
        String encoding = getEncodingFromXML(new InputStreamReader(bufIns), monitor);

        /* Avoid lowercase UTF-8 notation */
        if ("utf-8".equalsIgnoreCase(encoding)) //$NON-NLS-1$
            encoding = "UTF-8"; //$NON-NLS-1$

        /* Reset the Stream to its beginning */
        bufIns.reset();

        /* Grab Title using supplied Encoding */
        if (StringUtils.isSet(encoding) && Charset.isSupported(encoding))
            title = getTitleFromFeed(new BufferedReader(new InputStreamReader(bufIns, encoding)), monitor);

        /* Grab Title using Default Encoding */
        else
            title = getTitleFromFeed(new BufferedReader(new InputStreamReader(bufIns)), monitor);

        /* Remove the title tags (also delete attributes in title tag) */
        title = title.replaceAll("<title[^>]*>", ""); //$NON-NLS-1$ //$NON-NLS-2$
        title = title.replaceAll("</title>", ""); //$NON-NLS-1$ //$NON-NLS-2$

        /* Remove potential CDATA Tags */
        title = title.replaceAll(Pattern.quote("<![CDATA["), ""); //$NON-NLS-1$ //$NON-NLS-2$
        title = title.replaceAll(Pattern.quote("]]>"), ""); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (IOException e) {
        if (!(e instanceof MonitorCanceledException))
            Activator.safeLogError(e.getMessage(), e);
    }

    /* Finally close the Stream */
    finally {
        closeStream(inS, true); //Abort the stream to avoid downloading the full content
    }

    // Have an upper maximum of title length to protect against issues
    String result = StringUtils.stripTags(title.trim(), true);
    if (result.length() > MAX_DETECTED_TITLE_LENGTH)
        result = result.substring(0, MAX_DETECTED_TITLE_LENGTH);

    return result;
}

From source file:org.parosproxy.paros.core.proxy.ProxyThread.java

@Override
public void run() {
    proxyThreadList.add(thread);/*from   www. ja v  a 2  s  .com*/
    boolean isSecure = this instanceof ProxyThreadSSL;
    HttpRequestHeader firstHeader = null;

    try {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inSocket.getInputStream(), 2048);
        inSocket = new CustomStreamsSocket(inSocket, bufferedInputStream, inSocket.getOutputStream());

        httpIn = new HttpInputStream(inSocket);
        httpOut = new HttpOutputStream(inSocket.getOutputStream());

        firstHeader = httpIn.readRequestHeader(isSecure);

        if (firstHeader.getMethod().equalsIgnoreCase(HttpRequestHeader.CONNECT)) {

            // ZAP: added host name variable
            String hostName = firstHeader.getHostName();
            try {
                httpOut.write(CONNECT_HTTP_200);
                httpOut.flush();

                byte[] bytes = new byte[3];
                bufferedInputStream.mark(3);
                bufferedInputStream.read(bytes);
                bufferedInputStream.reset();

                if (isSslTlsHandshake(bytes)) {
                    isSecure = true;
                    beginSSL(hostName);
                }

                firstHeader = httpIn.readRequestHeader(isSecure);
                processHttp(firstHeader, isSecure);
            } catch (MissingRootCertificateException e) {
                // Unluckily Firefox and Internet Explorer will not show this message.
                // We should find a way to let the browsers display this error message.
                // May we can redirect to some kind of ZAP custom error page.

                final HttpMessage errmsg = new HttpMessage(firstHeader);
                setErrorResponse(errmsg, BAD_GATEWAY_RESPONSE_STATUS, e, "ZAP SSL Error");

                writeHttpResponse(errmsg, httpOut);

                throw new IOException(e);
            }
        } else {
            processHttp(firstHeader, isSecure);
        }
    } catch (SocketTimeoutException e) {
        // ZAP: Log the exception
        if (firstHeader != null) {
            log.warn("Timeout accessing " + firstHeader.getURI());
        } else {
            log.warn("Timeout", e);
        }
    } catch (HttpMalformedHeaderException e) {
        log.warn("Malformed Header: ", e);
    } catch (HttpException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.debug("IOException: ", e);
    } finally {
        proxyThreadList.remove(thread);

        // ZAP: do only close if flag is false
        if (!keepSocketOpen) {
            disconnect();
        }
    }
}

From source file:org.sipfoundry.sipxconfig.phonebook.PhonebookManagerImpl.java

/**
 * Trying to determine if the file is vCard file
 *//*from   w  w w.  j  a v  a2  s .c o  m*/
boolean isVcard(BufferedInputStream is, String encoding) {
    final String vcardSignature = "BEGIN:VCARD";
    try {
        // keep buffer smaller than the readlimit: trying to ensure that we can reset the
        // stream
        BufferedReader isr = new BufferedReader(new InputStreamReader(is, encoding),
                vcardSignature.length() * 2);
        is.mark(vcardSignature.length() * 10);
        String line;
        do {
            line = isr.readLine();
        } while (StringUtils.isBlank(line));
        boolean isVcard = vcardSignature.equalsIgnoreCase(line);
        is.reset();
        return isVcard;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.sonatype.nexus.proxy.storage.local.fs.DefaultFSLocalRepositoryStorage.java

public void storeItem(Repository repository, StorageItem item)
        throws UnsupportedStorageOperationException, LocalStorageException {
    final File target;
    final ContentLocator originalContentLocator;
    if (item instanceof StorageFileItem) {
        originalContentLocator = ((StorageFileItem) item).getContentLocator();
    } else {/*  ww w .j a v a2s . c  o m*/
        originalContentLocator = null;
    }
    try {
        // set some sanity stuff
        item.setStoredLocally(System.currentTimeMillis());
        item.setRemoteChecked(item.getStoredLocally());
        item.setExpired(false);

        ContentLocator cl = null;

        if (item instanceof StorageFileItem) {
            StorageFileItem fItem = (StorageFileItem) item;

            prepareStorageFileItemForStore(fItem);

            cl = fItem.getContentLocator();

            try {
                final BufferedInputStream bufferedInputStream;
                if (!cl.isReusable()) {
                    // link persister will close the stream, so prevent it doing so
                    bufferedInputStream = new BufferedInputStream(cl.getContent()) {
                        @Override
                        public void close() {
                            // nop
                        }
                    };
                    bufferedInputStream.mark(1024);
                    cl = new PreparedContentLocator(bufferedInputStream, cl.getMimeType(), cl.getLength());
                } else {
                    bufferedInputStream = null;
                }
                if (getLinkPersister().isLinkContent(cl)) {
                    // we are about to store a file that has link content, ban this store attempt
                    throw new UnsupportedStorageOperationException(
                            "Illegal Link API use on path " + item.getPath());
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.reset();
                }
            } catch (IOException e) {
                // meh, need to wrap it
                throw new LocalStorageException("Link-check failed ", e);
            }
        } else if (item instanceof StorageLinkItem) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            try {
                getLinkPersister().writeLinkContent((StorageLinkItem) item, bos);
            } catch (IOException e) {
                // should not happen, look at implementation
                // we will handle here two byte array backed streams!
                throw new LocalStorageException("Problem ", e);
            }

            cl = new ByteArrayContentLocator(bos.toByteArray(), "text/xml");
        }

        target = getFileFromBase(repository, item.getResourceStoreRequest());

        getFSPeer().storeItem(repository, getBaseDir(repository, item.getResourceStoreRequest()), item, target,
                cl);
    } finally {
        // NEXUS-5468: Ensure that in case of file item with prepared content
        // (typically those coming from RRS, as the content is actually wrapped HTTP response body, hence not reusable)
        // get closed irrelevant of the actual outcome. If all went right, stream was already closed,
        // and we will be "punished" by one extra (redundant) call to Closeable#close().
        if (originalContentLocator instanceof Closeable) {
            IOUtils.closeQuietly((Closeable) originalContentLocator);
        }
    }

    if (item instanceof StorageFileItem) {
        // replace content locator transparently, if we just consumed a non-reusable one
        // Hint: in general, those items coming from user uploads or remote proxy caching requests are non
        // reusable ones
        ((StorageFileItem) item)
                .setContentLocator(new FileContentLocator(target, ((StorageFileItem) item).getMimeType()));
    }

    final ContentLocator mdis = item instanceof StorageFileItem ? ((StorageFileItem) item).getContentLocator()
            : null;

    try {
        repository.getAttributesHandler().storeAttributes(item, mdis);
    } catch (IOException e) {
        throw new LocalStorageException("Cannot store attributes!", e);
    }
}

From source file:flex.messaging.services.http.proxy.ResponseFilter.java

protected void writeResponseAsString(InputStream inStream, int length, ProxyContext context)
        throws IOException {
    char[] tmp = new char[RESPONSE_CHUNK];
    //int i = 0;//from  w  w  w .j  a  v  a 2 s  . c o m
    StringBuffer sb = new StringBuffer(length < 0 ? 16 : length);
    BufferedInputStream bufferedIn = new BufferedInputStream(inStream);
    String charset = context.getHttpMethod().getResponseCharSet();

    bufferedIn.mark(4);

    // Check for BOM as InputStreamReader does not strip BOM in all cases.
    boolean hasBOM = false;
    int read = bufferedIn.read();
    if (read > 0) {
        // UTF-8 BOM is EF BB BF
        if (0xEF == (read & 0xFF)) {
            read = bufferedIn.read();
            if (0xBB == (read & 0xFF)) {
                read = bufferedIn.read();
                if (0xBF == (read & 0xFF)) {
                    hasBOM = true;
                    charset = "UTF-8";
                }
            }
        }
        // UTF-16 Little Endian BOM is FF FE
        // UTF-32 Little Endian BOM is FF FE 00 00
        else if (0xFF == (read & 0xFF)) {
            read = bufferedIn.read();
            if (0xFE == (read & 0xFF)) {
                hasBOM = true;
                charset = "UTF16-LE";

                // Check two more bytes incase we have UTF-32
                bufferedIn.mark(2);
                read = bufferedIn.read();
                if (0x00 == (read & 0xFF)) {
                    read = bufferedIn.read();
                    if (0x00 == (read & 0xFF)) {
                        charset = "UTF32-LE";
                    } else {
                        bufferedIn.reset();
                    }
                } else {
                    bufferedIn.reset();
                }
            }
        }
        // UTF-16 Big Endian BOM is FE FF
        else if (0xFE == (read & 0xFF)) {
            read = bufferedIn.read();
            if (0xFF == (read & 0xFF)) {
                hasBOM = true;
                charset = "UTF16-BE";
            }
        }
        // UTF-32 Big Endian BOM is 00 00 FE FF
        else if (0x00 == (read & 0xFF)) {
            read = bufferedIn.read();
            if (0x00 == (read & 0xFF)) {
                read = bufferedIn.read();
                if (0xFE == (read & 0xFF)) {
                    read = bufferedIn.read();
                    if (0xFF == (read & 0xFF)) {
                        hasBOM = true;
                        charset = "UTF32-BE";
                    }
                }
            }
        }

        // If we didn't find a BOM, all bytes should contribute to the content
        if (!hasBOM)
            bufferedIn.reset();
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(bufferedIn, charset));
    int charactersRead = -1;
    while ((charactersRead = reader.read(tmp, 0, tmp.length)) >= 0) {
        sb.append(new String(tmp, 0, charactersRead));
    }

    context.setResponse(sb.toString());
}