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.fcrepo.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*w ww .j a v a2  s. c  o m*/
 */
public static RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers)
        throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        logger.debug("processing multipart content...");
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Long.parseLong(contentLength);
                    }
                }

                break;
            } else {
                logger.trace("ignoring form field \"{}\" \"{}\"", item.getFieldName(), item.getName());
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            String contentLength = request.getHeader("Content-Length");
            long size = 0;
            if (contentLength != null) {
                size = Long.parseLong(contentLength);
            } else
                size = request.getContentLength();
            if (size > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = size;
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                } else {
                    logger.warn(
                            "Expected chunked data not found- " + "Transfer-Encoding : {}, Content-Length: {}",
                            transferEncoding, size);
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Long.parseLong(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java

private static String deserializeNonXMLErrorStream(BufferedInputStream errorStream, Exception e) {
    String errorString = null;//from   w w  w. j a  v  a  2 s  .c  o m
    try {
        errorStream.reset();
        errorString = e.getMessage() + "\n" + IOUtils.toString(errorStream);
    } catch (IOException e1) {
        errorString = "errorStream could not be reset/reread";
    }
    return errorString;
}

From source file:uk.ac.cam.arb33.multipartformdecoder.Main.java

private static byte[] getBoundary(BufferedInputStream in) throws IOException {

    //Assume boundary is within first 1024 bytes
    byte[] tmp = new byte[1024];
    in.mark(tmp.length + 2);// w ww .  j a  v  a  2s .co  m

    //boundary is sequence of ASCII characters with prefix "--" and terminated with CRLF
    if (in.read() != MultipartStream.DASH || in.read() != MultipartStream.DASH) {
        in.reset();
        throw new IOException("Invalid format for MultipathStream");
    }

    int bytesRead = 0;
    int emptyPosition = 0;
    while ((bytesRead = in.read(tmp, 0, tmp.length - emptyPosition)) != -1) {
        for (int i = 0; i < tmp.length - 1; i++) {
            if (tmp[i] == MultipartStream.CR && tmp[i + 1] == MultipartStream.LF) {
                byte[] boundary = new byte[i];
                System.arraycopy(tmp, 0, boundary, 0, i);
                in.reset();
                return boundary;
            }
        }
        emptyPosition += bytesRead;
    }

    in.reset();
    throw new IOException("Could not find any boundary definition in first " + tmp.length + " bytes");
}

From source file:org.bimserver.utils.ByteUtils.java

public static byte[] extractHead(BufferedInputStream bufferedInputStream, int maxSize) throws IOException {
    bufferedInputStream.mark(maxSize);//from   ww w . j  a  v  a  2 s  . c om
    byte[] initialBytes = new byte[maxSize];
    int read = IOUtils.read(bufferedInputStream, initialBytes);
    if (read != maxSize) {
        byte[] trimmed = new byte[read];
        System.arraycopy(initialBytes, 0, trimmed, 0, read);
        initialBytes = trimmed;
    }
    bufferedInputStream.reset();
    return initialBytes;
}

From source file:com.blork.anpod.util.BitmapUtils.java

private static Bitmap decodeStream(InputStream is, int desiredWidth, int desiredHeight) {
    Bitmap b = null;//from   w  w w.ja v a 2 s .  c o m
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BufferedInputStream bis = new BufferedInputStream(is);
        bis.mark(Integer.MAX_VALUE);

        BitmapFactory.decodeStream(bis, null, o);
        bis.reset();

        int scale = 1;
        if (o.outHeight > desiredHeight || o.outWidth > desiredWidth) {
            scale = (int) Math.pow(2,
                    (int) Math.round(Math.log(
                            Math.max(desiredHeight, desiredWidth) / (double) Math.max(o.outHeight, o.outWidth))
                            / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        o2.inDither = true;
        o2.inPurgeable = true;

        b = BitmapFactory.decodeStream(bis, null, o2);
        bis.close();
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return b;
}

From source file:org.apache.flex.compiler.filespecs.CombinedFile.java

/**
 * Get the BOM tag of a stream./* ww  w  .j  av  a  2 s  .c  o m*/
 * 
 * @param strm BufferedInputStream to be checked.
 * @return {@link BOM} type.
 * @throws IOException Error.
 */
public static BOM getBOM(BufferedInputStream strm) throws IOException {
    assert (strm.markSupported()) : "getBOM call on stream which does not support mark";

    // Peek the first 4 bytes.
    final byte[] peek = new byte[4];
    strm.mark(4);
    strm.read(peek);
    strm.reset();

    // Try matching 4-byte BOM tags.
    final byte[] quadruplet = Arrays.copyOf(peek, 4);
    if (Arrays.equals(BOM.UTF_32_BE.pattern, quadruplet))
        return BOM.UTF_32_BE;
    else if (Arrays.equals(BOM.UTF_32_LE.pattern, quadruplet))
        return BOM.UTF_32_LE;

    // Try matching 3-byte BOM tags.
    final byte[] triplet = Arrays.copyOf(peek, 3);
    if (Arrays.equals(BOM.UTF_8.pattern, triplet))
        return BOM.UTF_8;

    // Try matching 2-byte BOM tags.
    final byte[] twin = Arrays.copyOf(peek, 2);
    if (Arrays.equals(BOM.UTF_16_BE.pattern, twin))
        return BOM.UTF_16_BE;
    else if (Arrays.equals(BOM.UTF_16_LE.pattern, twin))
        return BOM.UTF_16_LE;

    // No BOM tag.
    return BOM.NONE;
}

From source file:org.apache.synapse.transport.passthru.util.RelayUtils.java

public static void builldMessage(MessageContext messageContext, boolean earlyBuild, InputStream in)
        throws IOException, AxisFault {
    ////from  www  .  j  a  va 2 s. c o  m
    BufferedInputStream bufferedInputStream = (BufferedInputStream) messageContext
            .getProperty(PassThroughConstants.BUFFERED_INPUT_STREAM);
    if (bufferedInputStream != null) {
        try {
            bufferedInputStream.reset();
            bufferedInputStream.mark(0);
        } catch (Exception e) {
            // just ignore the error
        }

    } else {
        bufferedInputStream = new BufferedInputStream(in);
        // TODO: need to handle properly for the moment lets use around 100k
        // buffer.
        bufferedInputStream.mark(128 * 1024);
        messageContext.setProperty(PassThroughConstants.BUFFERED_INPUT_STREAM, bufferedInputStream);
    }

    OMElement element = null;
    try {
        element = messageBuilder.getDocument(messageContext,
                bufferedInputStream != null ? bufferedInputStream : in);
    } catch (Exception e) {
        /*
        Remove bufferedinputstream content & continue: (for large payloads)
        reset bufferedInputStream can't be done in this situation
        */
        while ((bufferedInputStream.read()) > 0)
            ;
        messageContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        handleException("Error while building Passthrough stream", e);
    }
    if (element != null) {
        messageContext.setEnvelope(TransportUtils.createSOAPEnvelope(element));
        messageContext.setProperty(DeferredMessageBuilder.RELAY_FORMATTERS_MAP, messageBuilder.getFormatters());
        messageContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);

        earlyBuild = messageContext.getProperty(PassThroughConstants.RELAY_EARLY_BUILD) != null
                ? (Boolean) messageContext.getProperty(PassThroughConstants.RELAY_EARLY_BUILD)
                : earlyBuild;

        if (!earlyBuild) {
            processAddressing(messageContext);
        }
    }
    return;
}

From source file:org.trustedanalytics.metadata.utils.ContentDetectionUtils.java

private static boolean notConsumingDetectJsonInStream(BufferedInputStream in) {
    byte[] bytes = new byte[MAX_BYTES_READ_WHILE_PROBING_TYPE];
    boolean ret = false;
    in.mark(MAX_BYTES_READ_WHILE_PROBING_TYPE);
    try {//from   ww w  .  jav  a2s.com
        int bytesRead = in.read(bytes, 0, MAX_BYTES_READ_WHILE_PROBING_TYPE);
        if (bytesRead > 0 && canBeJson(new String(bytes))) {
            ret = true;
        }
        in.reset();
    } catch (IOException e) {
        LOGGER.error("Error while guessing stream type", e);
    }
    in.mark(0);
    return ret;
}

From source file:Main.java

@SuppressWarnings("SameParameterValue")
public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height) throws IOException {
    URL url = new URL(uri);
    BufferedInputStream is = null;
    try {// ww w  . j  av  a 2  s .co  m
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        is.mark(MAX_READ_LIMIT_PER_IMG);
        int scaleFactor = findScaleFactor(width, height, is);
        Log.d(TAG, "Scaling bitmap " + uri + " by factor " + scaleFactor + " to support " + width + "x" + height
                + "requested dimension");
        is.reset();
        return scaleBitmap(scaleFactor, is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.murati.oszk.audiobook.utils.BitmapHelper.java

@SuppressWarnings("SameParameterValue")
public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height) throws IOException {
    URL url = new URL(uri);
    BufferedInputStream is = null;
    try {/*  w ww .ja  va  2 s .  com*/
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        is.mark(MAX_READ_LIMIT_PER_IMG);
        int scaleFactor = findScaleFactor(width, height, is);
        LogHelper.d(TAG, "Scaling bitmap ", uri, " by factor ", scaleFactor, " to support ", width, "x", height,
                "requested dimension");
        is.reset();
        return scaleBitmap(scaleFactor, is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}