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) 

Source Link

Document

Creates a PushbackInputStream with a 1-byte pushback buffer, and saves its argument, the input stream in, for later use.

Usage

From source file:Main.java

public static void main(String[] args) {

    byte[] arrByte = new byte[1024];

    byte[] byteArray = new byte[] { 'j', 'a', 'v', 'a', '2', 's', '.', 'c', 'o', 'm' };

    // create object of PushbackInputStream class for specified stream
    InputStream is = new ByteArrayInputStream(byteArray);
    PushbackInputStream pis = new PushbackInputStream(is);

    try {/*from   www  . j  av  a2 s .  c o  m*/

        // read a char into our array
        pis.read(arrByte, 0, 3);

        // print arrByte
        for (int i = 0; i < 3; i++) {
            System.out.println((char) arrByte[i]);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:LineInputStream.java

/**
 * Read a line containing only ASCII characters from the input 
 * stream. A line is terminated by a CR or NL or CR-NL sequence.
 * A common error is a CR-CR-NL sequence, which will also terminate
 * a line.//  w  w  w  . ja  v a 2  s . c o m
 * The line terminator is not returned as part of the returned 
 * String. Returns null if no data is available. <p>
 *
 * This class is similar to the deprecated 
 * <code>DataInputStream.readLine()</code>
 */
public String readLine() throws IOException {
    InputStream in = this.in;
    char[] buf = lineBuffer;

    if (buf == null)
        buf = lineBuffer = new char[128];

    int c1;
    int room = buf.length;
    int offset = 0;

    while ((c1 = in.read()) != -1) {
        if (c1 == '\n') // Got NL, outa here.
            break;
        else if (c1 == '\r') {
            // Got CR, is the next char NL ?
            int c2 = in.read();
            if (c2 == '\r') // discard extraneous CR
                c2 = in.read();
            if (c2 != '\n') {
                // If not NL, push it back
                if (!(in instanceof PushbackInputStream))
                    in = this.in = new PushbackInputStream(in);
                ((PushbackInputStream) in).unread(c2);
            }
            break; // outa here.
        }

        // Not CR, NL or CR-NL ...
        // .. Insert the byte into our byte buffer
        if (--room < 0) { // No room, need to grow.
            buf = new char[offset + 128];
            room = buf.length - offset - 1;
            System.arraycopy(lineBuffer, 0, buf, 0, offset);
            lineBuffer = buf;
        }
        buf[offset++] = (char) c1;
    }

    if ((c1 == -1) && (offset == 0))
        return null;

    return String.copyValueOf(buf, 0, offset);
}

From source file:org.mcplissken.gateway.vertx.AsyncInputStream.java

public AsyncInputStream(InputStream in, int chunkSize) {
    if (in == null) {
        throw new NullPointerException("in");
    }/*from  w w  w  . j  a v  a 2s  .  c o m*/
    if (chunkSize <= 0) {
        throw new IllegalArgumentException("chunkSize: " + chunkSize + " (expected: a positive integer)");
    }

    if (in instanceof PushbackInputStream) {
        this.in = (PushbackInputStream) in;
    } else {
        this.in = new PushbackInputStream(in);
    }
    this.chunkSize = chunkSize;
    this.executor = Executors.newFixedThreadPool(10);
}

From source file:org.nuxeo.theme.html.JSMin.java

public JSMin(InputStream in, OutputStream out) {
    this.in = new PushbackInputStream(in);
    this.out = out;
}

From source file:org.mule.transport.stdio.StdioMessageReceiver.java

@Override
public void poll() {
    String encoding = endpoint.getEncoding();
    try {//from  w  ww  .  j  a va 2s  .  c  o  m
        if (sendStream) {
            PushbackInputStream in = new PushbackInputStream(inputStream);

            //Block until we have some data
            int i = in.read();
            //Roll back our read
            in.unread(i);
            MuleMessage message = createMuleMessage(in, encoding);
            routeMessage(message);
        } else {
            byte[] inputBuffer = new byte[bufferSize];
            int len = inputStream.read(inputBuffer);

            if (len == -1) {
                return;
            }

            StringBuffer fullBuffer = new StringBuffer(bufferSize);
            while (len > 0) {
                fullBuffer.append(new String(inputBuffer, 0, len));
                len = 0; // mark as read
                if (inputStream.available() > 0) {
                    len = inputStream.read(inputBuffer);
                }
            }

            // Each line is a separate message
            String[] lines = fullBuffer.toString().split(SystemUtils.LINE_SEPARATOR);
            for (int i = 0; i < lines.length; ++i) {
                MuleMessage message = createMuleMessage(lines[i], encoding);
                routeMessage(message);
            }
        }

        doConnect();
    } catch (Exception e) {
        getConnector().getMuleContext().getExceptionListener().handleException(e);
    }
}

From source file:imageviewer.util.PasswordGenerator.java

private final char[] getPassword(InputStream in, String prompt) throws IOException {

    MaskingThread mt = new MaskingThread(prompt);
    Thread thread = new Thread(mt);
    thread.start();//w ww. j a v  a2s . c  o  m

    char[] lineBuffer;
    char[] buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

    loop: while (true) {
        switch (c = in.read()) {
        case -1:
        case '\n':
            break loop;
        case '\r':
            int c2 = in.read();
            if ((c2 != '\n') && (c2 != -1)) {
                if (!(in instanceof PushbackInputStream))
                    in = new PushbackInputStream(in);
                ((PushbackInputStream) in).unread(c2);
            } else {
                break loop;
            }
        default:
            if (--room < 0) {
                buf = new char[offset + 128];
                room = buf.length - offset - 1;
                System.arraycopy(lineBuffer, 0, buf, 0, offset);
                Arrays.fill(lineBuffer, ' ');
                lineBuffer = buf;
            }
            buf[offset++] = (char) c;
            break;
        }
    }

    mt.stopMasking();
    if (offset == 0)
        return null;
    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');
    return ret;
}

From source file:org.p2pvpn.network.bittorrent.BitTorrentTracker.java

/**
 * Poll the tracker.// ww  w  .j  av  a  2 s. com
 * @param hash the hash of the cuttent network
 * @param port the local port
 * @return a Bencode-Map
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private Map<Object, Object> trackerRequest(byte[] hash, int port) throws MalformedURLException, IOException {
    String sUrl = tracker + "?info_hash=" + new String(new URLCodec().encode(hash)) + "&port=" + port
            + "&compact=1&peer_id=" + new String(new URLCodec().encode(peerId))
            + "&uploaded=0&downloaded=0&left=100";

    //System.out.println(sUrl);

    URL url = new URL(sUrl);
    PushbackInputStream in = new PushbackInputStream(url.openStream());
    return (Map<Object, Object>) Bencode.parseBencode(in);
}

From source file:offstage.crypt.ConfigFilesCrypt.java

/**
     * Reads user password from given input stream.
     *//*from  www.  ja  v a2s . c o  m*/
public static char[] readPassword(InputStream in) throws IOException {
    char[] lineBuffer;
    char[] buf;
    int i;

    buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

    loop: while (true) {
        switch (c = in.read()) {
        case -1:
        case '\n':
            break loop;

        case '\r':
            int c2 = in.read();
            if ((c2 != '\n') && (c2 != -1)) {
                if (!(in instanceof PushbackInputStream)) {
                    in = new PushbackInputStream(in);
                }
                ((PushbackInputStream) in).unread(c2);
            } else
                break loop;

        default:
            if (--room < 0) {
                buf = new char[offset + 128];
                room = buf.length - offset - 1;
                System.arraycopy(lineBuffer, 0, buf, 0, offset);
                Arrays.fill(lineBuffer, ' ');
                lineBuffer = buf;
            }
            buf[offset++] = (char) c;
            break;
        }
    }

    if (offset == 0) {
        return null;
    }

    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');

    return ret;
}

From source file:in.arun.faces.fo.pdf.FoOutputStream.java

private PdfResult buildPdf(FoOutputStream foOutput) {
    byte[] responseText = foOutput.getBytes();

    if (responseText == null) {
        return null;
    }/* w ww.  j av  a  2s.  c  o m*/

    PdfResult result = new PdfResult();

    try {
        PushbackInputStream pbis = new PushbackInputStream(
                new BufferedInputStream(new ByteArrayInputStream(responseText)));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        //Skip contentType text/html - Looking for bug fix!
        //pbis.skip(9);
        while (pbis.available() > 0) {
            pbis.mark(1);
            if (pbis.read() == '<') {
                pbis.unread('<');
                break;
            }
        }

        //Transforming XML to PDF
        FopFactory fopFactory = FopFactory.newInstance();
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, baos);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        Source src = new StreamSource(pbis);
        Result res = new SAXResult(fop.getDefaultHandler());

        transformer.transform(src, res);

        result.contentType = MimeConstants.MIME_PDF;
        result.content = baos.toByteArray();
    } catch (IOException | FOPException | TransformerException x) {
        logger.log(Level.SEVERE, "Error while trying to create PDF.", x);

        StringBuilder builder = new StringBuilder();

        builder.append(x.getMessage());
        builder.append("<br/>");

        builder.append("<pre>");
        String formattedFo = new String(responseText);
        formattedFo = formattedFo.replaceAll("<", "&lt;");
        formattedFo = formattedFo.replaceAll(">", "&gt;");
        builder.append(formattedFo);
        builder.append("</pre>");

        result.contentType = "text/html";
        result.content = builder.toString().getBytes();
    }

    return result;
}

From source file:org.wisdom.framework.vertx.AsyncInputStream.java

/**
 * Creates an instance of {@link org.wisdom.framework.vertx.AsyncInputStream}.
 *
 * @param vertx     the Vert.X instance//from  w  ww .  j a  v a  2 s.  co  m
 * @param executor  the executor used to read the chunk
 * @param in        the input stream to read
 * @param chunkSize the chunk size
 */
public AsyncInputStream(Vertx vertx, ExecutorService executor, InputStream in, int chunkSize) {
    if (in == null) {
        throw new NullPointerException("in");
    }
    if (vertx == null) {
        throw new NullPointerException("vertx");
    }
    this.vertx = vertx;
    if (chunkSize <= 0) {
        throw new IllegalArgumentException("chunkSize: " + chunkSize + " (expected: a positive integer)");
    }

    if (in instanceof PushbackInputStream) {
        this.in = (PushbackInputStream) in;
    } else {
        this.in = new PushbackInputStream(in);
    }
    this.chunkSize = chunkSize;
    this.executor = executor;
}