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:ch.cyberduck.core.cryptomator.features.CryptoChecksumCompute.java

protected Checksum compute(final InputStream in, final long offset, final ByteBuffer header,
        final NonceGenerator nonces) throws ChecksumException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Calculate checksum with header %s", header));
    }//from   w  ww  . j av  a2 s. c  om
    try {
        final PipedOutputStream source = new PipedOutputStream();
        final CryptoOutputStream<Void> out = new CryptoOutputStream<Void>(new VoidStatusOutputStream(source),
                cryptomator.getCryptor(), cryptomator.getCryptor().fileHeaderCryptor().decryptHeader(header),
                nonces, cryptomator.numberOfChunks(offset));
        final PipedInputStream sink = new PipedInputStream(source,
                PreferencesFactory.get().getInteger("connection.chunksize"));
        final ThreadPool pool = ThreadPoolFactory.get("checksum", 1);
        try {
            final Future execute = pool.execute(new Callable<TransferStatus>() {
                @Override
                public TransferStatus call() throws Exception {
                    if (offset == 0) {
                        source.write(header.array());
                    }
                    final TransferStatus status = new TransferStatus();
                    new StreamCopier(status, status).transfer(in, out);
                    return status;
                }
            });
            try {
                return delegate.compute(sink, new TransferStatus());
            } finally {
                try {
                    execute.get();
                } catch (InterruptedException e) {
                    throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"),
                            e.getMessage(), e);
                } catch (ExecutionException e) {
                    if (e.getCause() instanceof BackgroundException) {
                        throw (BackgroundException) e.getCause();
                    }
                    throw new DefaultExceptionMappingService().map(e.getCause());
                }
            }
        } finally {
            pool.shutdown(true);
        }
    } catch (ChecksumException e) {
        throw e;
    } catch (IOException | BackgroundException e) {
        throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(),
                e);
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.protocol.http.HttpURLConnection.java

@Override
public OutputStream getOutputStream() throws IOException {
    PipedOutputStream source = new PipedOutputStream();
    PipedInputStream sink = new PipedInputStream();
    source.connect(sink);/*from   w  ww. j a v a2s.c  o m*/
    RequestEntity entity = new InputStreamRequestEntity(sink);
    ((EntityEnclosingMethod) method).setRequestEntity(entity);
    return source;
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    out = new ByteArrayOutputStream();
    err = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;//  w ww . j a v  a  2s .  com

    TeeOutputStream teeOut = new TeeOutputStream(out, System.out);
    TeeOutputStream teeErr = new TeeOutputStream(err, System.err);

    return new PumpStreamHandler(teeOut, teeErr, inPiped);
}

From source file:vlove.virt.VirtBuilder.java

/**
 * Returns the exit value of the process.
 * //from w  ww. j  a  v a 2 s .  c  o m
 * @param out
 * @param err
 * @return
 * @throws VirtException
 */
public int createVirtualMachine(NewVmWizardModel newVm, StreamConsumer out, StreamConsumer err)
        throws VirtException {
    List<String> command = createVirtMachineCommand(newVm);
    if (command == null || command.size() < 1) {
        throw new VirtException("Command needs to be provided.");
    }

    try {
        Commandline cs = new Commandline();
        cs.setExecutable(command.get(0));
        if (command.size() > 1) {
            cs.addArguments(command.subList(1, command.size()).toArray(new String[] {}));
        }
        PipedOutputStream pOut = new PipedOutputStream();
        PipedInputStream pIs = new PipedInputStream(pOut);

        List<ConsumerListener> listeners = new ArrayList<>();
        listeners.add(new ConsumerListener(pOut, Pattern.compile("\\[sudo\\] password for \\w+:"), "password"));

        NestedStreamConsumer nOut = new NestedStreamConsumer(listeners, out);
        return CommandLineUtils.executeCommandLine(cs, pIs, nOut, err);
    } catch (CommandLineException ce) {
        throw new VirtException("Could not execute command.", ce);
    } catch (IOException ie) {
        throw new VirtException("Could not execute command.", ie);
    }
}

From source file:io.fabric8.docker.client.impl.ImportImage.java

@Override
public TagAsRepoInterface<OutputHandle> redirectingOutput() {
    return new ImportImage(client, config, source, tag, new PipedOutputStream(), listener);
}

From source file:org.jclouds.logging.internal.Wire.java

public InputStream tapAsynch(final String header, InputStream instream) {
    PipedOutputStream out = new PipedOutputStream();
    InputStream toReturn = new TeeInputStream(instream, out, true);
    final InputStream line;
    try {//from  www  . j a va2  s.  co  m
        line = new PipedInputStream(out);
        exec.submit(new Runnable() {
            public void run() {
                try {
                    wire(header, line);
                } finally {
                    IOUtils.closeQuietly(line);
                }
            }
        });
    } catch (IOException e) {
        logger.error(e, "Error tapping line");
    }
    return toReturn;
}

From source file:org.apache.oozie.cli.TestCLIParser.java

private String readCommandOutput(CLIParser parser, CLIParser.Command c) throws IOException {
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
    PipedOutputStream pipeOut = new PipedOutputStream();
    PipedInputStream pipeIn = new PipedInputStream(pipeOut, 1024 * 10);
    System.setOut(new PrintStream(pipeOut));

    parser.showHelp(c.getCommandLine());
    pipeOut.close();/*from w  w w  .  j a  v a2 s .co  m*/
    ByteStreams.copy(pipeIn, outBytes);
    pipeIn.close();
    return new String(outBytes.toByteArray());
}

From source file:net.i2cat.netconf.transport.VirtualTransport.java

public void connect(SessionContext sessionContext) throws TransportException {
    // let the transportId instance be GC'ed after connect();
    // this.transportId = transportId;
    log.info("Virtual transport");

    this.sessionContext = sessionContext;

    // TODO CHECK IF IT WORKS
    user = sessionContext.getUser();//from  www . j  a v  a2 s . c  om
    password = sessionContext.getPass();

    host = sessionContext.getHost();
    port = sessionContext.getPort();
    if (port < 0)
        port = 22;

    subsystem = sessionContext.getSubsystem();

    log.debug("user: " + user);
    log.debug("pass: " + (password != null ? "yes" : "no"));
    log.debug("hostname: " + host + ":" + port);
    log.debug("subsystem: " + subsystem);

    simHelper = new DummySimulatorHelper();

    // Check the type of responses
    simHelper.setResponseError(subsystem.equals("errorServer"));

    // this will fake the two endpoints of a tcp connection
    try {
        outStream = new PipedOutputStream();
        inStream = new PipedInputStream(outStream);

    } catch (IOException e) {
        throw new TransportException(e.getMessage());
    }

    closed = false;

    // notify handlers
    for (TransportListener handler : listeners)
        handler.transportOpened();

    startParsing();
}

From source file:examples.RdfSerializationExample.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  a2  s .  com*/
 * <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
 */
public static OutputStream asynchronousOutputStream(final OutputStream outputStream) throws IOException {
    final int SIZE = 1024 * 1024 * 10;
    final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos, SIZE);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                byte[] bytes = new byte[SIZE];
                for (int len; (len = pis.read(bytes)) > 0;) {
                    outputStream.write(bytes, 0, len);
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            } finally {
                close(pis);
                close(outputStream);
            }
        }
    }, "async-output-stream").start();
    return pos;
}

From source file:org.pentaho.osgi.platform.webjars.WebjarsURLConnection.java

@Override
public InputStream getInputStream() throws IOException {
    try {//  w  ww.  j  a v a  2 s .com
        final PipedOutputStream pipedOutputStream = new PipedOutputStream();
        PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

        // making this here allows to fail with invalid URLs
        final URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        final InputStream originalInputStream = urlConnection.getInputStream();

        transform_thread = EXECUTOR.submit(
                new WebjarsTransformer(url, originalInputStream, pipedOutputStream, this.minificationEnabled));

        return pipedInputStream;
    } catch (Exception e) {
        logger.error(getURL().toString() + ": Error opening url");

        throw new IOException("Error opening url", e);
    }
}