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:com.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image./*from  ww w  . j a va 2  s.  c o  m*/
 *
 * @param stream input stream.
 * @param file file name
 * @param fileName name of file
 * @param conf connector configuration
 * @throws IOException when error occurs.
 */
public static void createTmpThumb(final InputStream stream, final File file, final String fileName,
        final IConfiguration conf) throws IOException {

    BufferedInputStream bufferedIS = new BufferedInputStream(stream);
    bufferedIS.mark(Integer.MAX_VALUE);
    BufferedImage image = ImageIO.read(bufferedIS);
    if (image == null) {
        throw new IOException("Wrong file");
    }
    Dimension dimension = createThumbDimension(image, conf.getImgWidth(), conf.getImgHeight());
    if (image.getHeight() == dimension.height && image.getWidth() == dimension.width) {
        bufferedIS.reset();
        writeUntouchedImage(bufferedIS, file);
    } else {
        resizeImage(image, dimension.width, dimension.height, conf.getImgQuality(), file);
    }
    stream.close();
}

From source file:com.afis.jx.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it resizes the image.
 *
 * @param stream input stream./* w  w  w .  j a  v  a 2 s  .com*/
 * @param file file name
 * @param fileName name of file
 * @param conf connector configuration
 * @throws IOException when error occurs.
 */
public static void createTmpThumb(final InputStream stream, final File file, final String fileName,
        final IConfiguration conf) throws IOException {

    BufferedInputStream bufferedIS = new BufferedInputStream(stream);
    bufferedIS.mark(Integer.MAX_VALUE);
    BufferedImage image = ImageIO.read(bufferedIS);
    if (image == null) {
        throw new IOException("Wrong file");
    }
    Dimension dimension = createThumbDimension(image, conf.getImgWidth(), conf.getImgHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() == dimension.height && image.getWidth() == dimension.width)) {
        bufferedIS.reset();
        writeUntouchedImage(bufferedIS, file);
    } else {
        resizeImage(image, dimension.width, dimension.height, conf.getImgQuality(), file);
    }
    stream.close();
}

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

private static Bitmap decodeStream(InputStream is, int desiredWidth, int desiredHeight) {
    Bitmap b = null;//from w ww.  j  a va 2  s  . c  om
    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.//from   www . j  a v a 2s  .  co  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:com.clov4r.moboplayer.android.nil.codec.SubtitleJni.java

private static String getFilecharset(File sourceFile) {
    if (!sourceFile.getAbsolutePath().endsWith("srt")) {
        return "UTF-8";
    }/*from w  ww .j  a v  a2 s .com*/
    String charset = "UTF-8";
    byte[] first3Bytes = new byte[3];
    try {
        boolean checked = false;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
        bis.mark(0);
        int read = bis.read(first3Bytes, 0, 3);
        if (read == -1) {
            return charset;
        } else 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;
        }
        // bis.reset();
        if (!checked) {
            int loc = 0;
            while ((read = bis.read()) != -1) {
                loc++;
                if (read >= 0xF0) {
                    charset = "GBK";
                    break;
                }
                if (0x80 <= read && read <= 0xBF) {
                    charset = "GBK";
                    break;
                }
                if (0xC0 <= read && read <= 0xDF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF)
                        continue;
                    else {
                        charset = "GBK";
                        break;
                    }
                } else if (0xE0 <= read && read <= 0xEF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            charset = "UTF-8";
                            break;
                        } else {
                            charset = "GBK";
                            break;
                        }
                    } else {
                        charset = "GBK";
                        break;
                    }
                }
            }
        }
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return charset;
}

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

private static ErrorElements deserializeXml(HttpResponse response) throws IllegalStateException, IOException //    throws NotFound, InvalidToken, ServiceFailure, NotAuthorized,
//    NotFound, IdentifierNotUnique, UnsupportedType,
//    InsufficientResources, InvalidSystemMetadata, NotImplemented,
//    InvalidCredentials, InvalidRequest, IOException {
{
    ErrorElements ee = new ErrorElements();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc;//from  w  w  w . ja va 2  s  .com

    int httpCode = response.getStatusLine().getStatusCode();
    if (response.getEntity() != null) {
        BufferedInputStream bErrorStream = new BufferedInputStream(response.getEntity().getContent());
        bErrorStream.mark(5000); // good for resetting up to 5000 bytes

        String detailCode = null;
        String description = null;
        String name = null;
        int errorCode = -1;
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(bErrorStream);
            Element root = doc.getDocumentElement();
            root.normalize();
            if (root.getNodeName().equalsIgnoreCase("error")) {
                if (root.hasAttribute("errorCode")) {
                    try {
                        errorCode = Integer.getInteger(root.getAttribute("errorCode"));
                    } catch (NumberFormatException nfe) {
                        System.out.println("errorCode unexpectedly not able to parse to int,"
                                + " using http status for creating exception");
                        errorCode = httpCode;
                    }
                }
                if (errorCode != httpCode) //            throw new ServiceFailure("1000","errorCode in message body doesn't match httpStatus");
                {
                    System.out.println("errorCode in message body doesn't match httpStatus,"
                            + " using errorCode for creating exception");
                }
                if (root.hasAttribute("detailCode")) {
                    detailCode = root.getAttribute("detailCode");
                } else {
                    detailCode = "detail code is Not Set!";
                }
                if (root.hasAttribute("name")) {
                    name = root.getAttribute("name");
                } else {
                    name = "Exception";
                }
                Node child = root.getFirstChild();
                do {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equalsIgnoreCase("description")) {
                            Element element = (Element) child;
                            description = element.getTextContent();
                            break;
                        }
                    }
                } while ((child = child.getNextSibling()) != null);
            } else {
                description = domToString(doc);
                detailCode = "detail code was never Set!";
            }
        } catch (TransformerException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (SAXException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (IOException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (ParserConfigurationException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        }

        ee.setCode(errorCode);
        ee.setName(name);
        ee.setDetailCode(detailCode);
        ee.setDescription(description);
    }
    return ee;
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private static InputStream maybeDecompress(InputStream input) throws IOException {
    // Due to a bug, Jira sometimes returns double-compressed responses. See JRA-37608
    BufferedInputStream buffered = new BufferedInputStream(input, 2);
    buffered.mark(2);
    int[] buf = new int[2];
    buf[0] = buffered.read();/*from  w  w  w .j a v a  2s . c om*/
    buf[1] = buffered.read();
    buffered.reset();
    int header = (buf[1] << 8) | buf[0];
    if (header == GZIPInputStream.GZIP_MAGIC) {
        return new GZIPInputStream(buffered);
    } else {
        return buffered;
    }
}

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   w  w  w. j  av  a  2s  . 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:com.linkedin.pinot.core.startree.StarTreeSerDe.java

/**
 * Utility method to StarTree version./*from  w ww  .j  av  a2s  .  com*/
 * Presence of {@ref #MAGIC_MARKER} indicates on-heap format, while its
 * absence indicates on-heap format.
 *
 * @param bufferedInputStream
 * @return
 * @throws IOException
 */
public static StarTreeFormatVersion getStarTreeVersion(BufferedInputStream bufferedInputStream)
        throws IOException {
    byte[] magicBytes = new byte[MAGIC_MARKER_SIZE_IN_BYTES];

    bufferedInputStream.mark(MAGIC_MARKER_SIZE_IN_BYTES);
    bufferedInputStream.read(magicBytes, 0, MAGIC_MARKER_SIZE_IN_BYTES);
    bufferedInputStream.reset();

    LBufferAPI lBuffer = new LBuffer(MAGIC_MARKER_SIZE_IN_BYTES);
    lBuffer.readFrom(magicBytes, 0);
    long magicMarker = lBuffer.getLong(0);

    if (magicMarker == MAGIC_MARKER) {
        return StarTreeFormatVersion.OFF_HEAP;
    } else {
        return StarTreeFormatVersion.ON_HEAP;
    }
}

From source file:org.docx4j.openpackaging.packages.OpcPackage.java

/**
 * Convenience method to create a WordprocessingMLPackage
 * or PresentationMLPackage/*from ww w.j  a  v a2  s . c  o m*/
 * from an inputstream (.docx/.docxm, .ppxtx or Flat OPC .xml).
 * It detects the convenient format inspecting two first bytes of stream (magic bytes). 
 * For office 2007 'x' formats, these two bytes are 'PK' (same as zip file)  
  *
 * @param inputStream
 *            The docx file 
 * @param password
 *            The password, if the file is password protected (compound)
 *            
 * @Since 2.8.0           
 */
public static OpcPackage load(final InputStream inputStream, String password) throws Docx4JException {
    //try to detect the type of file using a bufferedinputstream
    final BufferedInputStream bis = new BufferedInputStream(inputStream);
    bis.mark(0);
    final byte[] firstTwobytes = new byte[2];
    int read = 0;
    try {
        read = bis.read(firstTwobytes);
        bis.reset();
    } catch (final IOException e) {
        throw new Docx4JException("Error reading from the stream", e);
    }
    if (read != 2) {
        throw new Docx4JException("Error reading from the stream (no bytes available)");
    }
    if (firstTwobytes[0] == 'P' && firstTwobytes[1] == 'K') { // 50 4B
        return OpcPackage.load(bis, Filetype.ZippedPackage, null);
    } else if (firstTwobytes[0] == (byte) 0xD0 && firstTwobytes[1] == (byte) 0xCF) {
        // password protected docx is a compound file, with signature D0 CF 11 E0 A1 B1 1A E1
        log.info("Detected compound file");
        return OpcPackage.load(bis, Filetype.Compound, password);
    } else {
        //Assume..
        log.info("Assuming Flat OPC XML");
        return OpcPackage.load(bis, Filetype.FlatOPC, null);
    }
}