Example usage for java.io BufferedInputStream mark

List of usage examples for java.io BufferedInputStream mark

Introduction

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

Prototype

public synchronized void mark(int readlimit) 

Source Link

Document

See the general contract of the mark method of InputStream.

Usage

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);

    //boundary is sequence of ASCII characters with prefix "--" and terminated with CRLF
    if (in.read() != MultipartStream.DASH || in.read() != MultipartStream.DASH) {
        in.reset();//from  w ww . ja va2s  .c  o  m
        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:Main.java

public static Bitmap decode(InputStream in, int reqWidth, int reqHeight) throws IOException {
    BufferedInputStream inputStream = new BufferedInputStream(in);
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//from w w  w  .  j a  v  a2s  .  c  om
    inputStream.mark(64 * 1024);
    BitmapFactory.decodeStream(inputStream, null, options);
    inputStream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeStream(inputStream, null, options);
}

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 {//www . j  av a  2 s .  c  o  m
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        is.mark(MAX_READ_LIMIT_PER_IMG);
        int scaleFactor = findScaleFactor(width, height, is);
        is.reset();
        return scaleBitmap(scaleFactor, is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

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 {//from   w ww. j a  v  a  2s  . c om
        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:org.trustedanalytics.metadata.utils.ContentDetectionUtils.java

private static Optional<MediaType> notConsumingGuessContentTypeFromStream(BufferedInputStream bin)
        throws IOException {
    Optional<MediaType> type = Optional.empty();
    bin.mark(MAX_BYTES_READ_WHILE_PROBING_TYPE);
    try {//w  w w.java 2s .c  om
        String guess = URLConnection.guessContentTypeFromStream(bin);
        if (guess != null) {
            type = MediaType.fromString(guess);
        }
    } catch (IOException e) {
        LOGGER.error("Error while guessing stream type", e);
    }
    bin.reset();
    bin.mark(0);
    return type;
}

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 {/*from www.  j  a v  a2  s.c  o m*/
        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();
        }
    }
}

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 w ww  .java2  s. 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:org.fcrepo.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*ww  w.ja v  a 2 s .co 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:cn.guoyukun.spring.utils.FileCharset.java

public static String getCharset(final BufferedInputStream is) {
    String charset = DEFAULT_CHARSET;
    byte[] first3Bytes = new byte[3];
    try {//from w  w w . j a  v  a2  s . co m
        boolean checked = false;
        is.mark(0);
        int read = is.read(first3Bytes, 0, 3);
        if (read == -1)
            return charset;
        if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
            charset = "UTF-16LE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
            charset = "UTF-16BE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                && first3Bytes[2] == (byte) 0xBF) {
            charset = "UTF-8";
            checked = true;
        }
        is.reset();
        if (!checked) {
            int loc = 0;

            while ((read = is.read()) != -1 && loc < 100) {
                loc++;
                if (read >= 0xF0)
                    break;
                if (0x80 <= read && read <= 0xBF) // ?BFGBK
                    break;
                if (0xC0 <= read && read <= 0xDF) {
                    read = is.read();
                    if (0x80 <= read && read <= 0xBF) // ? (0xC0 - 0xDF)
                        // (0x80
                        // - 0xBF),?GB?
                        continue;
                    else
                        break;
                } else if (0xE0 <= read && read <= 0xEF) {// ??
                    read = is.read();
                    if (0x80 <= read && read <= 0xBF) {
                        read = is.read();
                        if (0x80 <= read && read <= 0xBF) {
                            charset = "UTF-8";
                            break;
                        } else
                            break;
                    } else
                        break;
                }
            }
        }
        is.reset();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return charset;
}

From source file:org.opf_labs.fmts.fidget.TikaIdentifier.java

static final IdentificationResult fromStream(final MimeTypes mimeRepo, final InputStream stream, URI loc) {
    // Get a buffered input stream that supports marks
    BufferedInputStream mrkStr = new BufferedInputStream(stream);
    assert (mrkStr.markSupported());
    // put the mark at the begining, and should be comfortable for Tika id
    // length//  w w  w .  j  av  a  2 s . co m
    mrkStr.mark(mimeRepo.getMinLength() * 2);
    // identify and time
    long start = new Date().getTime();
    MediaType mime = identify(mimeRepo, stream, loc);
    long duration = new Date().getTime() - start;
    // Now reset the stream and hash
    IdentificationResult result;
    try {
        mrkStr.reset();
        result = new IdentificationResult(hash64K(stream), loc, mime, duration);
    } catch (IOException excep) {
        // OK couldn't read or hash stream, record error and what we have
        result = new IdentificationResult("", IdentificationResult.ERROR_LOC, mime, duration);
    }
    return result;
}