Example usage for java.io PipedInputStream PipedInputStream

List of usage examples for java.io PipedInputStream PipedInputStream

Introduction

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

Prototype

public PipedInputStream(int pipeSize) 

Source Link

Document

Creates a PipedInputStream so that it is not yet #connect(java.io.PipedOutputStream) connected and uses the specified pipe size for the pipe's buffer.

Usage

From source file:org.pircbotx.CAPTest.java

public void runTest(String cap, final OutputParser callback) throws Exception {
    final MutableObject<Exception> connectionException = new MutableObject<Exception>();
    botInWrite = new PipedOutputStream();
    botIn = new BufferedInputStream(new PipedInputStream(botInWrite));
    botOut = new ByteArrayOutputStream() {
        @Override//from   w ww  . j a  v  a2s .  c o  m
        public synchronized void write(byte[] bytes, int i, int i1) {
            super.write(bytes, i, i1);
            String outputText = new String(bytes, i, i1).trim();

            try {
                try {
                    String callbackText = callback.handleOutput(outputText);
                    if (callbackText == null)
                        //Will close bots input loop
                        botInWrite.close();
                    else if (!callbackText.equals("")) {
                        botInWrite.write((callbackText + "\r\n").getBytes());
                        botInWrite.flush();
                    }
                } catch (Exception ex) {
                    log.error("Recieved error, closing bot and escelating", ex);
                    connectionException.setValue(ex);
                    botInWrite.close();
                }
            } catch (IOException ex) {
                log.error("Recieved IO error, closing bot and escelating", ex);
                connectionException.setValue(ex);
                try {
                    botInWrite.close();
                } catch (Exception e) {
                    throw new RuntimeException("Can't close botInWrite", e);
                }
            }
        }
    };
    Socket socket = mock(Socket.class);
    when(socket.isConnected()).thenReturn(true);
    when(socket.getInputStream()).thenReturn(botIn);
    when(socket.getOutputStream()).thenReturn(botOut);

    Configuration.Builder configurationBuilder = TestUtils.generateConfigurationBuilder();

    SocketFactory socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket(
            InetAddress.getByName(configurationBuilder.getServers().get(0).getHostname()), 6667, null, 0))
                    .thenReturn(socket);

    configurationBuilder.getCapHandlers().clear();
    configurationBuilder.getCapHandlers().addAll(capHandlers);
    bot = new PircBotX(
            configurationBuilder.setSocketFactory(socketFactory).setAutoReconnect(false).buildConfiguration());

    botInWrite.write((":ircd.test CAP * LS :" + cap + "\r\n").getBytes());
    bot.connect();
    if (connectionException.getValue() != null)
        throw connectionException.getValue();
}

From source file:com.nts.alphamale.shell.AdbShellExecutor.java

/**
 * @param cmd adb /*from w  ww  .j  av a  2 s .  c om*/
 * @param synch   ? ? true: synchronous, false: asynchronous
 * @param  (ms)
 * @return Executor Standard Output? Map
 */
public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) {
    Map<String, Object> executorMap = new HashMap<String, Object>();
    DefaultExecutor executor = new DefaultExecutor();
    PipedOutputStream pos = new PipedOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err);
    streamHandler.setStopTimeout(timeoutMilliseconds);
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new PipedInputStream(pos));
    } catch (IOException e) {
        //log.error(e.getCause() + " : " + e.getMessage());
    }
    executor.setStreamHandler(streamHandler);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds);
    executor.setWatchdog(watchDog);
    try {
        if (synch)
            executor.execute(cmd);
        else
            executor.execute(cmd, new DefaultExecuteResultHandler());

        log.debug(cmd.toString());
        LineIterator li = IOUtils.lineIterator(dis, "UTF-8");
        if (li != null) {
            executorMap.put("executor", executor);
            executorMap.put("stdOut", li);
        }
    } catch (Exception e) {
        log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]");
    }
    return executorMap;
}

From source file:ee.ria.xroad.proxy.testsuite.testcases.AttachmentBig.java

@Override
protected Pair<String, InputStream> getRequestInput(boolean addUtf8Bom) throws Exception {
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    MultiPartOutputStream mpos = new MultiPartOutputStream(os);

    if (addUtf8Bom) {
        mpos.write(ByteOrderMark.UTF_8.getBytes());
    }/*from w w  w .j av a 2  s . co  m*/

    new Thread(new MpWriter(mpos)).start();

    return Pair.of("multipart/related; charset=UTF-8; " + "boundary=" + mpos.getBoundary(), (InputStream) is);
}

From source file:com.msopentech.odatajclient.engine.communication.request.ODataStreamManager.java

/**
 * Constructor./*from  w ww . ja  v a2  s .  com*/
 *
 * @param futureWrap wrapper of the Future object of the HttpResponse.
 * @param output stream to be piped to retrieve the payload.
 */
public ODataStreamManager(final Wrapper<Future<HttpResponse>> futureWrap, final PipedOutputStream output) {
    super(output);

    this.futureWrap = futureWrap;
    try {
        this.body = new PipedInputStream(getBodyStreamWriter());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    this.defaultBody = this.body;
}

From source file:org.apache.olingo.client.core.communication.request.AbstractODataStreamManager.java

/**
 * Constructor./*from www.  ja v a2s .co  m*/
 *
 * @param futureWrap wrapper of the Future object of the HttpResponse.
 * @param output stream to be piped to retrieve the payload.
 */
public AbstractODataStreamManager(final Wrapper<Future<HttpResponse>> futureWrap,
        final PipedOutputStream output) {
    super(output);

    this.futureWrap = futureWrap;
    try {
        this.body = new PipedInputStream(getBodyStreamWriter());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    this.defaultBody = this.body;
}

From source file:org.apache.xmlgraphics.util.io.Base64Test.java

private void innerBase64Test(final String action, final URL inputIn, final URL inputRef) throws IOException {
    URL ref = inputRef;/* www  . j  a v a2 s. c om*/
    final URL in = inputIn;
    InputStream inIS = in.openStream();

    if (action.equals("ROUND")) {
        ref = in;
    } else if (!action.equals("ENCODE") && !action.equals("DECODE")) {
        fail("Bad action string");
    }

    try (final InputStream refIS = ref.openStream()) {

        if (action.equals("ENCODE") || action.equals("ROUND")) {
            // We need to encode the incomming data
            try (final PipedOutputStream pos = new PipedOutputStream()) {
                try (final OutputStream os = new Base64EncodeStream(pos)) {

                    // Copy the input to the Base64 Encoder (in a seperate
                    // thread).
                    final Thread t = new StreamCopier(inIS, os);

                    // Read that from the piped output stream.
                    inIS = new PipedInputStream(pos);
                    t.start();
                }

                if (action.equals("DECODE") || action.equals("ROUND")) {
                    inIS = new Base64DecodeStream(inIS);
                }

                final boolean mismatch = compareStreams(inIS, refIS, action.equals("ENCODE"));

                if (!mismatch) {
                    fail("Wrong result");
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(inIS);
    }
}

From source file:ReaderInputStream.java

/** Creates new input stream from the given reader.
 * Uses the platform default encoding./* w  ww . j av  a 2s  .  c o  m*/
* @param reader Input reader
*/
public ReaderInputStream(Reader reader) throws IOException {
    this.reader = reader;
    pos = new PipedOutputStream();
    pis = new PipedInputStream(pos);
    osw = new OutputStreamWriter(pos);
}

From source file:net.unit8.longadeseo.plugin.PluginManager.java

public void afterService(DavResource resource) {
    for (PluginRegistry pluginRegistry : pluginRegistryList) {
        if (!pluginRegistry.isActive() || !pluginRegistry.isApplied(resource.getResourcePath()))
            continue;
        Plugin plugin = pluginRegistry.getPlugin();
        final PipedOutputStream out;
        InputStream in = null;//from ww  w .j  av a2  s .c om
        try {
            out = new PipedOutputStream();
            in = new PipedInputStream(out);
            resource.spool(new OutputContext() {
                public void setProperty(String propertyName, String propertyValue) {
                }

                public void setModificationTime(long modificationTime) {
                }

                public void setETag(String etag) {
                }

                public void setContentType(String contentType) {
                }

                public void setContentLength(long contentLength) {
                }

                public void setContentLanguage(String contentLanguage) {
                }

                public boolean hasStream() {
                    return true;
                }

                public OutputStream getOutputStream() {
                    return out;
                }
            });
            plugin.afterService(resource, in);
        } catch (IOException e) {
            throw new PluginExecutionException(e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:de.resol.vbus.LiveInputStreamTest.java

@Test
public void testReadHeader() throws Exception {
    byte[] refPacketBuffer1 = Hex.decodeHex(
            "aa362335331034430d2a0004080c00671014181c00272024282c00673034383c00274044484c00675054585c00276064686c00677074787c00270004080c0f581014181c0f182024282c0f583034383c0f184044484c0f58"
                    .toCharArray());//w ww.  java 2 s  . c o m
    byte[] refDgramBuffer1 = Hex.decodeHex("aa362335332034433353300332630851".toCharArray());
    byte[] refTgramBuffer1 = Hex
            .decodeHex("aa2211443330772e000c1824303c48000354606c7804101c70472834404c5864707f6c".toCharArray());
    byte[] refZeroBuffer1 = Hex.decodeHex("00000000000000000000000000000000".toCharArray());
    byte[] refMsbBuffer1 = Hex.decodeHex("80808080808080808080808080808080".toCharArray());

    String refPacketId1 = "13_2336_3335_10_4334";
    String refDgramId1 = "13_2336_3335_20_4334_0000";
    String refTgramId1 = "13_1122_3344_30_77";

    PipedInputStream refIs1 = new PipedInputStream(2048);
    PipedOutputStream refOs1 = new PipedOutputStream(refIs1);
    int refChannel1 = 0x13;

    LiveInputStream testIs = new LiveInputStream(refIs1, refChannel1);

    refOs1.write(refPacketBuffer1);

    assertEquals(refPacketId1, testIs.readHeader().getId());

    refOs1.write(refDgramBuffer1);
    refOs1.write(refTgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());
    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write a partial header (before protocol version)
    refOs1.write(refTgramBuffer1);
    refOs1.write(refDgramBuffer1, 0, 5);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    refOs1.write(refDgramBuffer1, 5, 11);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write a broken header (without sync byte)
    refOs1.write(refDgramBuffer1, 1, 15);
    refOs1.write(refTgramBuffer1);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write unknown version
    refOs1.write(refDgramBuffer1, 0, 5);
    refOs1.write(0x05);
    refOs1.write(refTgramBuffer1);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write partial packet (incomplete header)
    refOs1.write(refDgramBuffer1);
    refOs1.write(refPacketBuffer1, 0, 9);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    refOs1.write(refPacketBuffer1, 9, refPacketBuffer1.length - 9);

    assertEquals(refPacketId1, testIs.readHeader().getId());

    // write defect packet (header msb)
    refOs1.write(refPacketBuffer1, 0, 9);
    refOs1.write(refMsbBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write defect packet (header checksum)
    refOs1.write(refPacketBuffer1, 0, 9);
    refOs1.write(refZeroBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write partial packet (incomplete frame data)
    refOs1.write(refDgramBuffer1);
    refOs1.write(refPacketBuffer1, 0, 15);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    refOs1.write(refPacketBuffer1, 15, refPacketBuffer1.length - 15);

    assertEquals(refPacketId1, testIs.readHeader().getId());

    // write defect packet (frame data msb)
    refOs1.write(refPacketBuffer1, 0, refPacketBuffer1.length - 1);
    refOs1.write(refMsbBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write partial datagram
    refOs1.write(refTgramBuffer1);
    refOs1.write(refDgramBuffer1, 0, 15);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    refOs1.write(refDgramBuffer1, 15, refDgramBuffer1.length - 15);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write defect datagram
    refOs1.write(refDgramBuffer1, 0, 15);
    refOs1.write(refMsbBuffer1, 0, 1);
    refOs1.write(refTgramBuffer1);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write partial telegram (incomplete header)
    refOs1.write(refDgramBuffer1);
    refOs1.write(refTgramBuffer1, 0, 7);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    refOs1.write(refTgramBuffer1, 7, refTgramBuffer1.length - 7);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write defect telegram (header msb)
    refOs1.write(refTgramBuffer1, 0, 7);
    refOs1.write(refMsbBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write defect telegram (header checksum)
    refOs1.write(refTgramBuffer1, 0, 7);
    refOs1.write(refZeroBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // write partial telegram (incomplete frame data)
    refOs1.write(refDgramBuffer1);
    refOs1.write(refTgramBuffer1, 0, 15);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    refOs1.write(refTgramBuffer1, 15, refTgramBuffer1.length - 15);

    assertEquals(refTgramId1, testIs.readHeader().getId());

    // write defect telegram (frame data msb)
    refOs1.write(refTgramBuffer1, 0, refTgramBuffer1.length - 1);
    refOs1.write(refMsbBuffer1, 0, 1);
    refOs1.write(refDgramBuffer1);

    assertEquals(refDgramId1, testIs.readHeader().getId());

    // close pipe
    refOs1.close();

    assertEquals(null, testIs.readHeader());
}

From source file:ee.ria.xroad.common.RequestInputDataMultipart.java

@Override
public Pair<String, InputStream> getRequestInput() throws IOException {
    PipedOutputStream os = new PipedOutputStream();
    MultipartWriter mpWriter = attachmentInputStream == null
            ? new BigAttachmentWriter(os, testRequest, attachmentSize)
            : new CustomAttachmentWriter(os, soapBytes, attachmentInputStream);

    PipedInputStream is = new PipedInputStream(os);
    MultiPartOutputStream mpos = mpWriter.getMultipartOutputStream();

    new Thread(mpWriter).start();

    return Pair.of("multipart/related; charset=UTF-8; " + "boundary=" + mpos.getBoundary(), (InputStream) is);
}