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:org.jumpmind.symmetric.transport.internal.InternalTransportManager.java

public IOutgoingWithResponseTransport getFilePushTransport(final Node targetNode, final Node sourceNode,
        String securityToken, String registrationUrl) throws IOException {
    final PipedOutputStream pushOs = new PipedOutputStream();
    final PipedInputStream pushIs = new PipedInputStream(pushOs);

    final PipedOutputStream respOs = new PipedOutputStream();
    final PipedInputStream respIs = new PipedInputStream(respOs);

    runAtClient(targetNode.getSyncUrl(), pushIs, respOs, new IClientRunnable() {
        public void run(ISymmetricEngine engine, InputStream is, OutputStream os) throws Exception {
            // This should be basically what the push servlet does ...
            engine.getFileSyncService().loadFilesFromPush(sourceNode.getNodeId(), is, os);
        }//  w ww. ja  v  a 2  s. com
    });
    return new InternalOutgoingWithResponseTransport(pushOs, respIs);
}

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

@Test(groups = "standalone")
public void deferredInputStreamTrick()
        throws IOException, ExecutionException, TimeoutException, InterruptedException {
    try (AsyncHttpClient client = asyncHttpClient(getAsyncHttpClientConfig())) {
        BoundRequestBuilder r = client.prepareGet("http://localhost:" + port1 + "/deferredInputStreamTrick");

        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);/*from   w  w  w . java  2  s.  co  m*/
        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 {
            copy(is, cos);
        } finally {
            is.close();
            cos.close();
        }

        // now we don't need to be polite, since consuming and closing
        // BodyDeferringInputStream does all.
        // it all should be here now
        assertEquals(cos.getByteCount(), HALF_GIG);
    }
}

From source file:org.jumpmind.symmetric.transport.internal.InternalTransportManager.java

public IIncomingTransport getRegisterTransport(final Node client, String registrationUrl) throws IOException {

    final PipedOutputStream respOs = new PipedOutputStream();
    final PipedInputStream respIs = new PipedInputStream(respOs);

    runAtClient(registrationUrl, null, respOs, new IClientRunnable() {
        public void run(ISymmetricEngine engine, InputStream is, OutputStream os) throws Exception {
            // This should be basically what the registration servlet does
            // ...
            engine.getRegistrationService().registerNode(client, os, false);
        }// www .  j av  a2 s  .  co m
    });
    return new InternalIncomingTransport(respIs);
}

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

@Test(groups = { "standalone", "default_provider" })
public void deferredInputStreamTrick()
        throws IOException, ExecutionException, TimeoutException, InterruptedException {
    AsyncHttpClient client = getAsyncHttpClient(getAsyncHttpClientConfig());
    try {/*from   w  w w .java2  s .com*/
        BoundRequestBuilder r = client.prepareGet("http://127.0.0.1:" + port1 + "/deferredInputStreamTrick");

        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 {
            copy(is, cos);
        } finally {
            is.close();
            cos.close();
        }

        // now we don't need to be polite, since consuming and closing
        // BodyDeferringInputStream does all.
        // it all should be here now
        assertEquals(cos.getByteCount(), HALF_GIG);
    } finally {
        client.close();
    }
}

From source file:org.mule.service.http.impl.service.client.async.ResponseBodyDeferringAsyncHandler.java

@Override
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
    // body arrived, can handle the partial response
    if (!input.isPresent()) {
        if (bodyPart.isLast()) {
            // no need to stream response, we already have it all
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Single part (size = {}bytes).", bodyPart.getBodyByteBuffer().remaining());
            }//from w  w w. ja  v  a 2s.  c  om
            responseBuilder.accumulate(bodyPart);
            handleIfNecessary();
            return CONTINUE;
        } else {
            output = new PipedOutputStream();
            input = of(new PipedInputStream(output, bufferSize));
        }
    }
    if (LOGGER.isDebugEnabled()) {
        int bodyLength = bodyPart.getBodyByteBuffer().remaining();
        LOGGER.debug("Multiple parts (part size = {} bytes, PipedInputStream buffer size = {} bytes).",
                bodyLength, bufferSize);
        if (bufferSize - input.get().available() < bodyLength) {
            //TODO - MULE-10550: Process to detect blocking of non-io threads should take care of this
            LOGGER.debug(
                    "SELECTOR BLOCKED! No room in piped stream to write {} bytes immediately. There are still has {} bytes unread",
                    LOGGER, input.get().available());
        }
    }
    handleIfNecessary();
    try {
        bodyPart.writeTo(output);
    } catch (IOException e) {
        this.onThrowable(e);
        return ABORT;
    }
    return CONTINUE;
}

From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

protected Set<Integer> getOpenNMSProcesses() {
    LOG.trace("getOpenNMSProcesses()");
    final Set<Integer> processes = new HashSet<Integer>();

    final String jps = getResourceLocator().findBinary("jps");

    LOG.trace("jps = {}", jps);

    DataInputStream input = null;
    PsParser parser = null;//  w w  w.ja v  a  2s.co  m
    PipedInputStream pis = null;
    PipedOutputStream output = new PipedOutputStream();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5000));

    if (jps != null) {
        CommandLine command = CommandLine.parse(jps + " -v");
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);

        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join();
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);

            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("Failed to run '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }
    }

    LOG.trace("looking for ps");
    final String ps = getResourceLocator().findBinary("ps");
    if (ps != null) {

        // try Linux/Mac style
        CommandLine command = CommandLine.parse(ps + " aww -o pid -o args");
        output = new PipedOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);

        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join(MAX_PROCESS_WAIT);
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);

            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("error running '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }

        if (processes.size() == 0) {
            // try Solaris style
            command = CommandLine.parse(ps + " -ea -o pid -o args");
            output = new PipedOutputStream();
            streamHandler = new PumpStreamHandler(output, System.err);

            try {
                LOG.trace("executing '{}'", command);
                pis = new PipedInputStream(output);
                input = new DataInputStream(pis);
                parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
                parser.start();
                executor.setStreamHandler(streamHandler);
                int exitValue = executor.execute(command);
                IOUtils.closeQuietly(output);
                parser.join(MAX_PROCESS_WAIT);
                processes.addAll(parser.getProcesses());
                LOG.trace("finished '{}'", command);

                if (exitValue != 0) {
                    LOG.debug("error running '{}': exit value was {}", command, exitValue);
                }
            } catch (final Exception e) {
                LOG.debug("error running '{}'", command, e);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(pis);
                IOUtils.closeQuietly(output);
            }
        }
    }

    if (processes.size() == 0) {
        LOG.warn("Unable to find any OpenNMS processes.");
    }

    return processes;
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

private void handleFile(Path inputFile, Path outputFile) throws IOException {
    boolean justCopy = true;
    boolean justSkip = false;

    if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) {
        justCopy = false;/* www  .  java  2s  .  c om*/
        //Filter the file
        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8"));
        BufferedWriter fileWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8"));
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself

        boolean firstLine = true;
        String line = null;
        long kept = 0;
        long skipped = 0;
        long total = 0;

        int moduleColumn = -1;

        while ((line = fileReader.readLine()) != null) {
            total++;
            //Write this line into the CSV parser
            pos.write(line.getBytes());
            pos.write("\r\n".getBytes());
            pos.flush();
            String[] fields = csvReader.readNext();

            boolean correctModule = false;
            for (String ms : moduleStrings_) {
                if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) {
                    correctModule = true;
                    break;
                }
            }

            if (firstLine || correctModule) {
                kept++;
                fileWriter.write(line);
                fileWriter.write("\r\n");
            } else {
                //don't write line
                skipped++;
            }

            if (firstLine) {

                log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString());
                firstLine = false;
                if (fields.length < 2) {
                    log("txt file doesn't look like a data file - abort and just copy.");
                    justCopy = true;
                    break;
                }
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("moduleId")) {
                        moduleColumn = i;
                        break;
                    }
                }
                if (moduleColumn < 0) {
                    log("No moduleId column found - skipping file");
                    justSkip = true;
                    break;
                }
            }
        }

        fileReader.close();
        csvReader.close();
        fileWriter.close();

        if (!justCopy) {
            log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in "
                    + inputDirectory.toPath().relativize(inputFile).toString());
        }
    }

    if (justCopy) {
        //Just copy the file
        Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING);
        log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString());
    }

    if (justSkip) {
        Files.delete(outputFile);
        log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString()
                + " because it doesn't contain a moduleId");
    }
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * Same as {@link java.net.URLConnection#getOutputStream()}.
 * <p>/*ww w .  j  av a  2  s  . com*/
 * This implementation creates a {@link PipedOutputStream} to the Apache entity input stream.
 * It is strongly advised to <b>write to the returned stream in another thread</b>.
 * @see PipedOutputStream
 * @see PipedInputStream
 * @return an output stream that writes to this connection.
 * @throws java.io.IOException if an I/O error occurs while creating the output stream.
 */
@objid("79282b13-7e13-42d5-9917-892c78a155bd")
@Override
public OutputStream getOutputStream() throws IOException {
    if (!this.dooutput)
        throw new IllegalStateException("This is not an output connection");

    if (this.req != null && !(this.req instanceof HttpPut))
        throw new IllegalStateException("This is not an output connection");

    PipedOutputStream outPipe = new PipedOutputStream();
    PipedInputStream snk = new PipedInputStream(outPipe);
    outPipe.connect(snk);

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(snk);

    HttpPut pr = (HttpPut) getRequest();
    pr.setEntity(entity);
    return outPipe;
}

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

@Test(groups = "standalone")
public void deferredInputStreamTrickWithFailure()
        throws IOException, ExecutionException, TimeoutException, InterruptedException {
    try (AsyncHttpClient client = asyncHttpClient(getAsyncHttpClientConfig())) {
        BoundRequestBuilder r = client/*w w w.j a  va2s  . c om*/
                .prepareGet("http://localhost:" + 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!
        }
    }
}

From source file:Console.java

public ConsoleTextArea() {
    super();//from ww  w. ja  va  2  s  . c  o m
    history = new java.util.Vector<String>();
    console1 = new ConsoleWriter(this);
    ConsoleWriter console2 = new ConsoleWriter(this);
    out = new PrintStream(console1);
    err = new PrintStream(console2);
    PipedOutputStream outPipe = new PipedOutputStream();
    inPipe = new PrintWriter(outPipe);
    in = new PipedInputStream();
    try {
        outPipe.connect(in);
    } catch (IOException exc) {
        exc.printStackTrace();
    }
    getDocument().addDocumentListener(this);
    addKeyListener(this);
    setLineWrap(true);
    setFont(new Font("Monospaced", 0, 12));
}