Example usage for java.io PipedOutputStream PipedOutputStream

List of usage examples for java.io PipedOutputStream PipedOutputStream

Introduction

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

Prototype

public PipedOutputStream() 

Source Link

Document

Creates a piped output stream that is not yet connected to a piped input stream.

Usage

From source file:com.sshtools.daemon.scp.ScpServer.java

private void scp(String args) throws IOException {
    log.debug("Parsing ScpServer options " + args);

    //   Parse the command line for supported options
    String[] a = StringUtil.current().allParts(args, " ");
    destination = null;/*from w  w w.ja  v a  2s  .  c o  m*/
    directory = false;
    from = false;
    to = false;
    recursive = false;
    verbosity = 0;

    boolean remote = false;

    for (int i = 0; i < a.length; i++) {
        if (a[i].startsWith("-")) {
            String s = a[i].substring(1);

            for (int j = 0; j < s.length(); j++) {
                char ch = s.charAt(j);

                switch (ch) {
                case 't':
                    to = true;

                    break;

                case 'd':
                    directory = true;

                    break;

                case 'f':
                    from = true;

                    break;

                case 'r':
                    recursive = true;

                    break;

                case 'v':
                    verbosity++;

                    break;

                case 'p':
                    preserveAttributes = true;

                    break;

                default:
                    log.warn("Unsupported argument, allowing to continue.");
                }
            }
        } else {
            if (destination == null) {
                destination = a[i];
            } else {
                throw new IOException("More than one destination supplied " + a[i]);
            }
        }
    }

    if (!to && !from) {
        throw new IOException("Must supply either -t or -f.");
    }

    if (destination == null) {
        throw new IOException("Destination not supplied.");
    }

    log.debug("Destination is " + destination);
    log.debug("Recursive is " + recursive);
    log.debug("Directory is " + directory);
    log.debug("Verbosity is " + verbosity);
    log.debug("From is " + from);
    log.debug("To is " + to);
    log.debug("Preserve Attributes " + preserveAttributes);

    //   Start the SCP server
    log.debug("Creating pipes");
    pipeIn = new PipedOutputStream();
    pipeErr = new PipedOutputStream();
    pipeOut = new PipedInputStream();
    in = new PipedInputStream(pipeIn);
    err = new PipedInputStream(pipeErr);
    out = new PipedOutputStream(pipeOut);
}

From source file:com.streamsets.datacollector.bundles.SupportBundleManager.java

/**
 * Return InputStream from which a new generated resource bundle can be retrieved.
 *///ww  w. j av a2s  .  c o m
public SupportBundle generateNewBundleFromInstances(List<BundleContentGenerator> generators,
        BundleType bundleType) throws IOException {
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = new PipedOutputStream();
    inputStream.connect(outputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

    executor.submit(() -> generateNewBundleInternal(generators, bundleType, zipOutputStream));

    String bundleName = generateBundleName(bundleType);
    String bundleKey = generateBundleDate(bundleType) + "/" + bundleName;

    return new SupportBundle(bundleKey, bundleName, inputStream);
}

From source file:org.grails.plugin.platform.events.push.EventsPushHandler.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    InputStream stream = req.getInputStream();
    final String topic = readPacket(stream);
    if (topic == null || topic.isEmpty()) {
        return;/*from  www .j  av  a  2  s .  c  o  m*/
    }

    final String type = readPacket(stream);
    if (type == null || type.isEmpty()) {
        return;
    }

    if (type.equals(TYPE_STRING)) {
        grailsEvents.event(topic, readPacket(stream), EventsPushConstants.FROM_BROWSERS, null, null, null);
    } else if (type.equals(TYPE_JSON)) {
        grailsEvents.event(topic, new JsonSlurper().parse(new BufferedReader(new InputStreamReader(stream))),
                EventsPushConstants.FROM_BROWSERS, null, null, null);
    } else if (type.equals(TYPE_BINARY)) {
        PipedOutputStream pipeOut = new PipedOutputStream();
        PipedInputStream pipeIn = new PipedInputStream(pipeOut, 4096);
        grailsEvents.event(topic, pipeIn, EventsPushConstants.FROM_BROWSERS, null, null, null);
        IOUtils.copy(stream, pipeOut);
        pipeOut.close();

    } else if (type.equals(TYPE_REGISTER)) {
        AtmosphereResource targetResource = null;
        for (AtmosphereResource r : broadcasterFactory.lookup(EventsPushConstants.GLOBAL_TOPIC)
                .getAtmosphereResources()) {
            if (r.uuid().equalsIgnoreCase(((AtmosphereRequest) req).resource().uuid())) {
                targetResource = r;
                break;
            }
        }
        if (targetResource != null) {
            targetResource.addEventListener(
                    new AtmosphereRegistrationsHandler(registerTopics(topic, targetResource)));
        }
    } else if (type.equals(TYPE_UNREGISTER)) {
    }
}

From source file:org.sonar.scanner.report.ReportPublisherTest.java

@Test
public void test_ws_parameters() throws Exception {
    ReportPublisher underTest = new ReportPublisher(settings, wsClient, server, contextPublisher, reactor, mode,
            mock(TempFolder.class), new ReportPublisherStep[0]);

    settings.setProperty(CoreProperties.PROJECT_ORGANIZATION_PROPERTY, "MyOrg");

    WsResponse response = mock(WsResponse.class);

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in = new PipedInputStream(out);
    WsCe.SubmitResponse.newBuilder().build().writeTo(out);
    out.close();/*from   w  w w.ja va 2  s. c  o m*/

    when(response.failIfNotSuccessful()).thenReturn(response);
    when(response.contentStream()).thenReturn(in);

    when(wsClient.call(any(WsRequest.class))).thenReturn(response);
    underTest.upload(temp.newFile());

    ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
    verify(wsClient).call(capture.capture());

    WsRequest wsRequest = capture.getValue();
    assertThat(wsRequest.getParams()).containsOnly(entry("organization", "MyOrg"),
            entry("projectKey", "struts"));
}

From source file:org.asynchttpclient.async.BodyDeferringAsyncHandlerTest.java

@Test(groups = { "standalone", "default_provider" })
public void deferredInputStreamTrickWithFailure()
        throws IOException, ExecutionException, TimeoutException, InterruptedException {
    AsyncHttpClient client = getAsyncHttpClient(getAsyncHttpClientConfig());

    try {// w  w w .  j av a  2 s .  co  m
        BoundRequestBuilder r = client
                .prepareGet("http://127.0.0.1:" + port1 + "/deferredInputStreamTrickWithFailure")
                .addHeader("X-FAIL-TRANSFER", Boolean.TRUE.toString());
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(pos);

        Future<Response> f = r.execute(bdah);

        BodyDeferringInputStream is = new BodyDeferringInputStream(f, bdah, pis);

        Response resp = is.getAsapResponse();
        assertNotNull(resp);
        assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
        assertEquals(resp.getHeader("content-length"), String.valueOf(HALF_GIG));
        // "consume" the body, but our code needs input stream
        CountingOutputStream cos = new CountingOutputStream();
        try {
            try {
                copy(is, cos);
            } finally {
                is.close();
                cos.close();
            }
            fail("InputStream consumption should fail with IOException!");
        } catch (IOException e) {
            // good!
        }
    } finally {
        client.close();
    }
}

From source file:org.wikidata.wdtk.client.DumpProcessingOutputAction.java

/**
 * Creates a separate thread for writing into the given output stream and
 * returns a pipe output stream that can be used to pass data to this
 * thread.//from w w w  . ja  v a2s  .  c o m
 * <p>
 * This code is inspired by
 * http://stackoverflow.com/questions/12532073/gzipoutputstream
 * -that-does-its-compression-in-a-separate-thread
 * 
 * @param outputStream
 *            the stream to write to in the thread
 * @return a new stream that data should be written to
 * @throws IOException
 *             if the pipes could not be created for some reason
 */
protected OutputStream getAsynchronousOutputStream(final OutputStream outputStream) throws IOException {
    final int SIZE = 1024 * 1024 * 10;
    final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos, SIZE);

    final FinishableRunnable run = new FinishableRunnable() {

        volatile boolean finish = false;
        volatile boolean hasFinished = false;

        @Override
        public void finish() {
            this.finish = true;
            while (!this.hasFinished) {
                // loop until thread is really finished
            }
        }

        @Override
        public void run() {
            try {
                byte[] bytes = new byte[SIZE];
                // Note that we finish really gently here, writing all data
                // that is still in the input first (in theory, new data
                // could arrive asynchronously, so that the thread never
                // finishes, but this is not the intended mode of
                // operation).
                for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) {
                    outputStream.write(bytes, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                close(pis);
                close(outputStream);
                this.hasFinished = true;
            }
        }
    };

    new Thread(run, "async-output-stream").start();

    this.outputStreams.add(new Closeable() {
        @Override
        public void close() throws IOException {
            run.finish();
        }
    });

    return pos;
}

From source file:org.lockss.util.TestStreamUtil.java

public void testReadBufShortRead() throws Exception {
    byte[] snd1 = { '0', '1', 0, '3' };
    final int len = 12;
    final byte[] buf = new byte[len];
    PipedOutputStream outs = new PipedOutputStream();
    final InputStream ins = new PipedInputStream(outs);
    final Exception[] ex = { null };
    final int[] res = { 0 };
    Thread th = new Thread() {
        public void run() {
            try {
                res[0] = StreamUtil.readBytes(ins, buf, len);
                StreamUtil.readBytes(ins, buf, len);
            } catch (IOException e) {
                ex[0] = e;/*from  ww  w .  jav  a  2  s  . c  o  m*/
            }
        }
    };
    th.start();
    outs.write(snd1);
    outs.close();
    th.join();

    assertEquals(snd1.length, res[0]);
    assertEquals(null, ex[0]);
}

From source file:org.whitesource.agent.utils.ZipUtils.java

private static void fillExportStreamCompress(InputStream inputStream, OutputStream outputStream) {
    try {/*w  w w.  j a  v a2  s .  c  o m*/
        try (PipedInputStream pipedInputStream = new PipedInputStream()) {
            try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) {
                pipedInputStream.connect(pipedOutputStream);

                Runnable producer = new Runnable() {
                    @Override
                    public void run() {
                        produceCompressDataFromStream(inputStream, pipedOutputStream);
                    }
                };
                Runnable consumer = new Runnable() {
                    @Override
                    public void run() {
                        consumeCompressData(pipedInputStream, outputStream);
                    }
                };

                transferData(producer, consumer);
            }
        }
    } catch (IOException e) {
        // logger.error("Failed to produce data :", e);
    }
}

From source file:de.upb.wdqa.wdvd.FeatureExtractor.java

private static InputStream getPipedDumpFileStream(final InputStream inputStream) throws IOException {
    final PipedOutputStream pipedOutputStream = new PipedOutputStream();
    final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream, BUFFER_SIZE);

    new Thread("Dump File Reader") {
        @Override//from  w  w  w . ja va  2  s .c om
        public void run() {
            try {
                IOUtils.copy(inputStream, pipedOutputStream);

                inputStream.close();
                pipedOutputStream.close();
            } catch (Throwable t) {
                logger.error("", t);
            }
        }
    }.start();

    return pipedInputStream;
}

From source file:org.lockss.util.TestStreamUtil.java

public void testReadBufMultipleRead() throws Exception {
    byte[] snd1 = { '0', '1', 0, '3' };
    byte[] snd2 = { '4', '5', '6', '7', '8', '9', 'a', 'b' };
    byte[] exp = { '0', '1', 0, '3', '4', '5', '6', '7', '8', '9', 'a', 'b' };
    final int len = exp.length;
    final byte[] buf = new byte[len];
    PipedOutputStream outs = new PipedOutputStream();
    final InputStream ins = new PipedInputStream(outs);
    final Exception[] ex = { null };
    final int[] res = { 0 };
    Thread th = new Thread() {
        public void run() {
            try {
                res[0] = StreamUtil.readBytes(ins, buf, len);
            } catch (IOException e) {
                ex[0] = e;//from  w  ww . j a v  a2 s.c  o  m
            }
        }
    };
    th.start();
    outs.write(snd1);
    TimerUtil.guaranteedSleep(100);
    outs.write(snd2);
    outs.flush();
    th.join();

    assertEquals(exp, buf);
    assertEquals(len, res[0]);
    assertNull(ex[0]);
    outs.close();
}