Example usage for java.io PushbackInputStream read

List of usage examples for java.io PushbackInputStream read

Introduction

In this page you can find the example usage for java.io PushbackInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:edu.mayo.trilliumbridge.webapp.TransformerController.java

/**
 * From http://stackoverflow.com/a/9737529/656853
 *///from  w  w w . j av a2 s.  c o  m
private InputStream checkForUtf8BOMAndDiscardIfAny(InputStream inputStream) throws IOException {
    PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
    byte[] bom = new byte[3];
    if (pushbackInputStream.read(bom) != -1) {
        if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
            pushbackInputStream.unread(bom);
        }
    }
    return pushbackInputStream;
}

From source file:net.rptools.assets.supplier.AbstractURIAssetSupplier.java

/**
 * Create an asset and determine its format.
 * @param id id of asset//from  www  . ja v  a2  s.  c o  m
 * @param type type of asset
 * @param listener listener to inform of (partial) completion
 * @param assetLength length, if known, or -1
 * @param stream stream to read
 * @return asset
 * @throws IOException I/O problems
 */
@ThreadPolicy(ThreadPolicy.ThreadId.ANY)
protected AssetImpl newAsset(final String id, final Type type, final AssetListener listener,
        final int assetLength, final InputStream stream) throws IOException {
    final InputStream input = new InputStreamInterceptor(getComponent().getFramework(), id, assetLength, stream,
            listener, getNotifyInterval());
    final PushbackInputStream pushbackStream = new PushbackInputStream(input, PUSHBACK_LIMIT);
    final byte[] firstBytes = new byte[PUSHBACK_LIMIT];
    final int actualLength = pushbackStream.read(firstBytes);
    if (actualLength != -1) {
        pushbackStream.unread(firstBytes, 0, actualLength);
    }

    final ByteArrayInputStream bais = new ByteArrayInputStream(firstBytes);
    final String mimeType = URLConnection.guessContentTypeFromStream(bais);
    LOGGER.debug("mimeType={}, actualLength={}", mimeType, actualLength);

    // read in image
    AssetImpl asset = null;
    switch (type) {
    case IMAGE:
        asset = new AssetImpl(new Image(pushbackStream));
        asset.setMimetype(mimeType);
        break;
    case TEXT:
        asset = new AssetImpl(IOUtils.toString(pushbackStream, StandardCharsets.UTF_8.name()));
        asset.setMimetype(mimeType);
        break;
    default:
        break;
    }
    if (listener != null) {
        listener.notify(id, asset);
    }
    return asset;
}

From source file:libepg.ts.reader.Reader2.java

/**
 * ??????<br>//from   www. j a  v a 2s .co  m
 * 1:???????????1??????<br>
 * 2:?????????????<br>
 * 3:??????1??????<br>
 * ???????????<br>
 * 4:1?<br>
 *
 * @return ???
 */
public synchronized List<TsPacket> getPackets() {
    ByteBuffer packetBuffer = ByteBuffer.allocate(TsPacket.TS_PACKET_BYTE_LENGTH.PACKET_LENGTH.getByteLength());
    byte[] byteData = new byte[1];

    //?
    List<TsPacket> packets = new ArrayList<>();

    FileInputStream fis = null;
    PushbackInputStream pis = null;
    try {

        fis = new FileInputStream(this.TSFile);
        pis = new PushbackInputStream(fis);

        boolean tipOfPacket = false;//?

        long count = 0;

        //??????1??????
        while (pis.read(byteData) != EOF) {

            //???????????????
            if ((byteData[0] == TsPacket.TS_SYNC_BYTE) && (tipOfPacket == false)) {
                tipOfPacket = true;
                if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) {
                    LOG.trace(
                            "???????????1????");
                }
                pis.unread(byteData);
            }

            if (tipOfPacket == true) {
                byte[] tsPacketData = new byte[TsPacket.TS_PACKET_BYTE_LENGTH.PACKET_LENGTH.getByteLength()];
                if (pis.read(tsPacketData) != EOF) {
                    if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) {
                        LOG.trace(
                                "??????????????");
                    }
                    packetBuffer.put(tsPacketData);
                } else {
                    break;
                }
            }

            if (packetBuffer.remaining() == 0) {
                byte[] BeforeCutDown = packetBuffer.array();
                byte[] AfterCutDown = new byte[packetBuffer.position()];
                System.arraycopy(BeforeCutDown, 0, AfterCutDown, 0, AfterCutDown.length);

                //??????????
                TsPacket tsp = new TsPacket(AfterCutDown);

                //                        LOG.debug(Hex.encodeHexString(tsp.getData()));
                if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) {
                    LOG.trace(
                            "1???????? ");
                    LOG.trace(tsp.toString());
                }

                if (tsp.getTransport_error_indicator() != 0) {
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(
                                "??1????????????????????");
                        LOG.warn(tsp);
                        LOG.warn(TSFile);
                    }
                    tipOfPacket = false;
                } else {
                    packets.add(tsp);
                    count++;
                }
                packetBuffer.clear();
                tipOfPacket = false;

                if (this.readLimit != null && count >= this.readLimit) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info(
                                "????????????? ?? = "
                                        + this.readLimit);
                    }
                    break;
                }
            }

        }
        if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) {
            LOG.trace("?????????");
            LOG.trace(" = " + Hex.encodeHexString(packetBuffer.array()));
        }

        pis.close();
        fis.close();
        LOG.info("??? = " + count);

    } catch (FileNotFoundException e) {
        LOG.fatal("?????", e);
    } catch (IOException e) {
        LOG.fatal("???", e);
    }
    return Collections.unmodifiableList(packets);
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public HttpMessage deserialize(InputStream is) throws IOException, HttpException {
    PushbackInputStream pis = new PushbackInputStream(is, 4);
    byte[] bb = new byte[4];
    Check.illegalargument.assertTrue(4 == pis.read(bb), "premature end of stream");
    pis.unread(bb);/*from w  w w  . j  a  v a 2 s  .c om*/
    return bb[0] == 'H' && bb[1] == 'T' && bb[2] == 'T' && bb[3] == 'P' ? deserializeResponse(pis)
            : deserializeRequest(pis);
}

From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java

private InputStream checkForUtf8BOMAndDiscardIfAny(InputStream inputStream) throws IOException {
    PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
    byte[] bom = new byte[3];
    if (pushbackInputStream.read(bom) != -1) {
        if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
            pushbackInputStream.unread(bom);
        }//from w  w  w.j a  v  a 2  s . c  o m
    }
    return pushbackInputStream;
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

private InputStream stripUtf8Bom(InputStream inputStream) throws IOException {
    PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
    byte[] bom = new byte[3];
    if (pushbackInputStream.read(bom) != -1) {
        if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
            pushbackInputStream.unread(bom);
        }//from  w  w w  . ja  v  a2s . c o m
    }
    return pushbackInputStream;
}

From source file:jef.tools.XMLUtils.java

/**
 * XML//from   www.  j  a  v a  2 s . c o  m
 * 
 * @param in
 *            ?
 * @param charSet
 *            ?
 * @param ignorComment
 *            
 * @return Document. DOM
 * @throws SAXException
 *             ?
 * @throws IOException
 *             
 */
public static Document loadDocument(InputStream in, String charSet, boolean ignorComments,
        boolean namespaceAware) throws SAXException, IOException {
    DocumentBuilder db = REUSABLE_BUILDER.get().getDocumentBuilder(ignorComments, namespaceAware);
    InputSource is = null;
    // ????charset
    if (charSet == null) {// ?200???
        byte[] buf = new byte[200];
        PushbackInputStream pin = new PushbackInputStream(in, 200);
        in = pin;
        int len = pin.read(buf);
        if (len > 0) {
            pin.unread(buf, 0, len);
            charSet = getCharsetInXml(buf, len);
        }
    }
    if (charSet != null) {
        is = new InputSource(new XmlFixedReader(new InputStreamReader(in, charSet)));
        is.setEncoding(charSet);
    } else { // ?
        Reader reader = new InputStreamReader(in, "UTF-8");// XML???Reader??Reader?XML?
        is = new InputSource(new XmlFixedReader(reader));
    }
    Document doc = db.parse(is);
    doc.setXmlStandalone(true);// True???standalone="no"
    return doc;

}

From source file:XmlReader.java

private XmlReader(InputStream stream) throws IOException {
    super(stream);

    PushbackInputStream pb;
    byte buf[];//from w w  w  .jav  a2 s.c o m
    int len;

    /*if (stream instanceof PushbackInputStream)
        pb = (PushbackInputStream) stream;
    else*/
    /**
     * Commented out the above code to make sure it works when the
     * document is accessed using http. URL connection in the code uses
     * a PushbackInputStream with size 7 and when we try to push back
     * MAX which default value is set to 512 we get and exception. So
     * that's why we need to wrap the stream irrespective of what type
     * of stream we start off with.
     */
    pb = new PushbackInputStream(stream, MAXPUSHBACK);

    //
    // See if we can figure out the character encoding used
    // in this file by peeking at the first few bytes.
    //
    buf = new byte[4];
    len = pb.read(buf);
    if (len > 0)
        pb.unread(buf, 0, len);

    if (len == 4)
        switch (buf[0] & 0x0ff) {
        case 0:
            // 00 3c 00 3f == illegal UTF-16 big-endian
            if (buf[1] == 0x3c && buf[2] == 0x00 && buf[3] == 0x3f) {
                setEncoding(pb, "UnicodeBig");
                return;
            }
            // else it's probably UCS-4
            break;

        case '<': // 0x3c: the most common cases!
            switch (buf[1] & 0x0ff) {
            // First character is '<'; could be XML without
            // an XML directive such as "<hello>", "<!-- ...",
            // and so on.
            default:
                break;

            // 3c 00 3f 00 == illegal UTF-16 little endian
            case 0x00:
                if (buf[2] == 0x3f && buf[3] == 0x00) {
                    setEncoding(pb, "UnicodeLittle");
                    return;
                }
                // else probably UCS-4
                break;

            // 3c 3f 78 6d == ASCII and supersets '<?xm'
            case '?':
                if (buf[2] != 'x' || buf[3] != 'm')
                    break;
                //
                // One of several encodings could be used:
                // Shift-JIS, ASCII, UTF-8, ISO-8859-*, etc
                //
                useEncodingDecl(pb, "UTF8");
                return;
            }
            break;

        // 4c 6f a7 94 ... some EBCDIC code page
        case 0x4c:
            if (buf[1] == 0x6f && (0x0ff & buf[2]) == 0x0a7 && (0x0ff & buf[3]) == 0x094) {
                useEncodingDecl(pb, "CP037");
                return;
            }
            // whoops, treat as UTF-8
            break;

        // UTF-16 big-endian
        case 0xfe:
            if ((buf[1] & 0x0ff) != 0xff)
                break;
            setEncoding(pb, "UTF-16");
            return;

        // UTF-16 little-endian
        case 0xff:
            if ((buf[1] & 0x0ff) != 0xfe)
                break;
            setEncoding(pb, "UTF-16");
            return;

        // default ... no XML declaration
        default:
            break;
        }

    //
    // If all else fails, assume XML without a declaration, and
    // using UTF-8 encoding.
    //
    setEncoding(pb, "UTF-8");
}

From source file:org.apache.pulsar.io.file.utils.GZipFiles.java

/**
 * Returns true if the given file is a gzip file.
 */// w ww.  ja v a 2s. com
@SuppressWarnings("deprecation")
public static boolean isGzip(File f) {

    InputStream input = null;
    try {
        input = new FileInputStream(f);
        PushbackInputStream pb = new PushbackInputStream(input, 2);
        byte[] signature = new byte[2];
        int len = pb.read(signature); //read the signature
        pb.unread(signature, 0, len); //push back the signature to the stream
        // check if matches standard gzip magic number
        return (signature[0] == (byte) 0x1f && signature[1] == (byte) 0x8b);
    } catch (final Exception e) {
        return false;
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.apache.synapse.format.hessian.HessianMessageBuilder.java

/**
 * Reads the first four bytes of the inputstream to detect whether the message represents a
 * fault message. Once a fault message has been detected, a property used to mark fault messages
 * is stored in the Axis2 message context. The implementaton uses a PushbackInputStream to be
 * able to put those four bytes back at the end of processing.
 *
 * @param   messageContext  the Axis2 message context
 * @param   inputStream     the inputstream to read the Hessian message
 *
 * @return  the wrapped (pushback) input stream
 *
 * @throws  IOException  if an I/O error occurs
 *///from w w  w.  j  av  a2 s  .co  m
private PushbackInputStream detectAndMarkMessageFault(final MessageContext messageContext,
        final InputStream inputStream) throws IOException {

    int bytesToRead = 4;
    PushbackInputStream pis = new PushbackInputStream(inputStream, bytesToRead);
    byte[] headerBytes = new byte[bytesToRead];
    int n = pis.read(headerBytes);

    // checking fourth byte for fault marker
    if (n == bytesToRead) {
        if (headerBytes[bytesToRead - 1] == HessianConstants.HESSIAN_V1_FAULT_IDENTIFIER
                || headerBytes[bytesToRead - 1] == HessianConstants.HESSIAN_V2_FAULT_IDENTIFIER) {
            messageContext.setProperty(BaseConstants.FAULT_MESSAGE, SynapseConstants.TRUE);
            if (log.isDebugEnabled()) {
                log.debug("Hessian fault detected, marking in Axis2 message context");
            }
        }
        pis.unread(headerBytes);
    } else if (n > 0) {
        byte[] bytesRead = new byte[n];
        System.arraycopy(headerBytes, 0, bytesRead, 0, n);
        pis.unread(bytesRead);
    }
    return pis;
}