Example usage for java.io PushbackInputStream PushbackInputStream

List of usage examples for java.io PushbackInputStream PushbackInputStream

Introduction

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

Prototype

public PushbackInputStream(InputStream in, int size) 

Source Link

Document

Creates a PushbackInputStream with a pushback buffer of the specified size, and saves its argument, the input stream in, for later use.

Usage

From source file:eu.europeana.uim.sugarcrmclient.internal.ExtendedSaajSoapMessageFactory.java

/**
 * Checks for the UTF-8 Byte Order Mark, and removes it if present. The SAAJ RI cannot cope with these BOMs.
 *
 * @see <a href="http://jira.springframework.org/browse/SWS-393">SWS-393</a>
 * @see <a href="http://unicode.org/faq/utf_bom.html#22">UTF-8 BOMs</a>
 *//*from   w w  w  .  ja v a2s. c o m*/
private InputStream checkForUtf8ByteOrderMark(InputStream inputStream) throws IOException {
    PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
    byte[] bom = new byte[3];
    if (pushbackInputStream.read(bom) != -1) {
        // check for the UTF-8 BOM, and remove it if there. See SWS-393
        if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
            pushbackInputStream.unread(bom);
        }
    }
    return pushbackInputStream;
}

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);//  ww  w  .  j av  a 2s. c om
    return bb[0] == 'H' && bb[1] == 'T' && bb[2] == 'T' && bb[3] == 'P' ? deserializeResponse(pis)
            : deserializeRequest(pis);
}

From source file:org.apache.abdera.protocol.server.multipart.AbstractMultipartCollectionAdapter.java

private MultipartInputStream getMultipartStream(RequestContext request)
        throws IOException, ParseException, IllegalArgumentException {
    String boundary = request.getContentType().getParameter(BOUNDARY_PARAM);

    if (boundary == null) {
        throw new IllegalArgumentException("multipart/related stream invalid, boundary parameter is missing.");
    }//from ww  w. j  a v  a2 s . c  o  m

    boundary = "--" + boundary;

    String type = request.getContentType().getParameter(TYPE_PARAM);
    if (!(type != null && MimeTypeHelper.isAtom(type))) {
        throw new ParseException(
                "multipart/related stream invalid, type parameter should be " + Constants.ATOM_MEDIA_TYPE);
    }

    PushbackInputStream pushBackInput = new PushbackInputStream(request.getInputStream(), 2);
    pushBackInput.unread("\r\n".getBytes());

    return new MultipartInputStream(pushBackInput, boundary.getBytes());
}

From source file:org.commoncrawl.hadoop.io.deprecated.ArcFileReader.java

/**
 * Costructs a new ArcFileReader object with specified block size (for
 * allocations)/*from   www  .  j  a va2s.c om*/
 */
public ArcFileReader() {

    super(_dummyStream, new Inflater(true), _blockSize);
    // set up buffer queue ...
    _consumerQueue = new LinkedBlockingQueue<BufferItem>(_bufferQueueSize);
    // setup the proper stream...
    super.in = new PushbackInputStream(new InputStream() {

        ByteBuffer _activeBuffer = null;
        byte oneByteArray[] = new byte[1];

        @Override
        public int read() throws IOException {
            if (read(oneByteArray, 0, 1) != -1) {
                return oneByteArray[0] & 0xff;
            }
            return -1;
        }

        @Override
        public int read(byte b[], int off, int len) throws IOException {
            if (_activeBuffer == null || _activeBuffer.remaining() == 0) {
                BufferItem nextItem = null;
                try {
                    // when io timeout is not specified, block indefinitely...
                    if (_ioTimeoutValue == -1) {
                        nextItem = _consumerQueue.take();
                    }
                    // otherwise wait for specified time on io
                    else {
                        nextItem = _consumerQueue.poll(_ioTimeoutValue, TimeUnit.MILLISECONDS);

                        if (nextItem == null) {
                            throw new IOException("IO Timeout waiting for Buffer");
                        }
                    }

                } catch (InterruptedException e) {
                    throw new IOException("Thread Interrupted waiting for Buffer");
                }

                if (nextItem._buffer == null) {
                    _eosReached = true;
                    // EOF CONDITION ...
                    return -1;
                } else {
                    _activeBuffer = nextItem._buffer;
                }
            }
            final int sizeAvailable = _activeBuffer.remaining();
            final int readSize = Math.min(sizeAvailable, len);

            _activeBuffer.get(b, off, readSize);

            _streamPos += readSize;

            return readSize;
        }
    }, _blockSize);
}

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

/**
 * Create an asset and determine its format.
 * @param id id of asset/*from w  ww. 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: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
 *///w w  w . jav  a 2  s.c  o  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;
}

From source file:org.jahia.utils.zip.legacy.ZipInputStream.java

/**
 * Creates a new ZIP input stream.//from   w  ww .  j  av  a2 s  .c o  m
 * @param in the actual input stream
 */
public ZipInputStream(InputStream in) {
    super(new PushbackInputStream(in, 512), new Inflater(true), 512);
    usesDefaultInflater = true;
    if (in == null) {
        throw new NullPointerException("in is null");
    }
}

From source file:org.talend.dataprep.schema.xls.XlsUtils.java

/**
 * read workbook xml spec to get non hidden sheets
 *
 * @param inputStream// ww w .  j  av a 2  s  .  c  om
 * @return
 */
public static List<String> getActiveSheetsFromWorkbookSpec(InputStream inputStream) throws XMLStreamException {
    // If doesn't support mark, wrap up
    if (!inputStream.markSupported()) {
        inputStream = new PushbackInputStream(inputStream, 8);
    }
    XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream);
    try {
        /*
         *
         * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook
         * xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
         * xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <fileVersion appName="xl"
         * lastEdited="5" lowestEdited="5" rupBuild="9303" codeName="{8C4F1C90-05EB-6A55-5F09-09C24B55AC0B}"/>
         * <workbookPr codeName="ThisWorkbook" defaultThemeVersion="124226"/> <bookViews> <workbookView xWindow="0"
         * yWindow="732" windowWidth="22980" windowHeight="8868" firstSheet="1" activeTab="8"/> </bookViews>
         * <sheets> <sheet name="formdata" sheetId="4" state="hidden" r:id="rId1"/> <sheet name="MONDAY" sheetId="1"
         * r:id="rId2"/> <sheet name="TUESDAY" sheetId="8" r:id="rId3"/> <sheet name="WEDNESDAY" sheetId="10"
         * r:id="rId4"/> <sheet name="THURSDAY" sheetId="11" r:id="rId5"/> <sheet name="FRIDAY" sheetId="12"
         * r:id="rId6"/> <sheet name="SATURDAY" sheetId="13" r:id="rId7"/> <sheet name="SUNDAY" sheetId="14"
         * r:id="rId8"/> <sheet name="WEEK SUMMARY" sheetId="15" r:id="rId9"/> </sheets>
         *
         */
        // we only want sheets not with state=hidden

        List<String> names = new ArrayList<>();

        while (streamReader.hasNext()) {
            switch (streamReader.next()) {
            case START_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheet")) {
                    Map<String, String> attributesValues = getAttributesNameValue(streamReader);
                    if (!attributesValues.isEmpty()) {
                        String sheetState = attributesValues.get("state");
                        if (!StringUtils.equals(sheetState, "hidden")) {
                            String sheetName = attributesValues.get("name");
                            names.add(sheetName);
                        }
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheets")) {
                    // shortcut to stop parsing
                    return names;
                }
                break;
            default:
                // no op
            }
        }
        return names;
    } finally {
        if (streamReader != null) {
            streamReader.close();
        }
    }
}

From source file:com.trsst.server.AbstractMultipartAdapter.java

private MultipartInputStream getMultipartStream(RequestContext request, InputStream inputStream)
        throws IOException, ParseException, IllegalArgumentException {
    String boundary = request.getContentType().getParameter(BOUNDARY_PARAM);

    if (boundary == null) {
        throw new IllegalArgumentException("multipart/related stream invalid, boundary parameter is missing.");
    }// ww  w .j  a  v a  2 s .co m

    boundary = "--" + boundary;

    String type = request.getContentType().getParameter(TYPE_PARAM);
    if (!(type != null && MimeTypeHelper.isAtom(type))) {
        throw new ParseException(
                "multipart/related stream invalid, type parameter should be " + Constants.ATOM_MEDIA_TYPE);
    }

    PushbackInputStream pushBackInput = new PushbackInputStream(inputStream, 2);
    pushBackInput.unread("\r\n".getBytes());

    return new MultipartInputStream(pushBackInput, boundary.getBytes());
}