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: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);
}

From source file:ReaderInputStream.java

/** Creates new input stream from the given reader.
 * Uses the platform default encoding./*  www . j a  v a2 s .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;//w w w . j  a  v a  2 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:com.github.brandtg.switchboard.MysqlLogPuller.java

/**
 * Creates an agent to listen to MySQL changes (via binlog).
 *
 * @param database/*w w w.j  av a2 s  .  c  o m*/
 *  The MySQL database name
 * @param sourceAddress
 *  The switchboard server address from which to pull events
 * @param sinkAddress
 *  The local listener port to receive raw binlog data
 * @param lastIndex
 *  The last index that was processed by whoever is constructing this (if -1, processed none)
 */
public MysqlLogPuller(String database, InetSocketAddress sourceAddress, InetSocketAddress sinkAddress,
        long lastIndex) {
    this.database = database;
    this.lastIndex = lastIndex;
    this.sourceAddress = sourceAddress;
    this.sinkAddress = sinkAddress;
    this.inputStream = new PipedInputStream();
    this.outputStream = new PipedOutputStream();
    this.isStarted = new AtomicBoolean();
}

From source file:org.pircbotx.PircBotXOutputTest.java

@BeforeMethod
public void botSetup() throws Exception {
    //Setup bot//from w  ww.  j  a  v  a2  s .com
    inputLatch = new CountDownLatch(1);
    bot = new PircBotX() {
        @Override
        protected InputThread createInputThread(Socket socket, BufferedReader breader) {
            return new InputThread(bot, socket, breader) {
                @Override
                public void run() {
                    //Do nothing
                }
            };
        }
    };
    bot.setListenerManager(new GenericListenerManager());
    bot.setNick("PircBotXBot");
    bot.setName("PircBotXBot");
    bot.setMessageDelay(0L);

    //Setup streams for bot
    PipedOutputStream out = new PipedOutputStream();
    //Create an input stream that we'll kill later
    in = new ByteArrayInputStream("".getBytes());
    Socket socket = mock(Socket.class);
    when(socket.isConnected()).thenReturn(true);
    when(socket.getInputStream()).thenReturn(in);
    when(socket.getOutputStream()).thenReturn(out);
    socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket("example.com", 6667, null, 0)).thenReturn(socket);

    //Setup ability to read from bots output
    botOut = new BufferedReader(new InputStreamReader(new PipedInputStream(out)));

    //Connect the bot to the socket
    bot.connect("example.com", 6667, null, socketFactory);

    //Make sure the bot is connected
    verify(socketFactory).createSocket("example.com", 6667, null, 0);

    //Setup useful vars
    aUser = bot.getUser("aUser");
    aChannel = bot.getChannel("#aChannel");
}

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

@Override
public TagFromRegistryInterface<OutputHandle> redirectingOutput() {
    return new PullImage(client, config, name, tag, new PipedOutputStream(), listener);
}

From source file:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private <T> JobResult<T> executeStreaming(JobRequest jobRequest, ReaderConsumer<T> consumer)
        throws IOException {
    PipedOutputStream stdOut = new PipedOutputStream();
    ByteArrayOutputStream stdErr = new ByteArrayOutputStream();

    Executor executor = buildExecutor(new PumpStreamHandler(stdOut, stdErr, jobRequest.getInputStream()));
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(jobRequest.getCommandLine(), jobRequest.getEnvironment(), resultHandler);

    T result = consumer.consume(new BufferedReader(new InputStreamReader(new PipedInputStream(stdOut))));

    try {//ww  w  .  j a v  a  2s. c  om
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        executor.getWatchdog().destroyProcess();
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }

    return JobResult.<T>builder()
            .result(resultHandler.getExitValue() == 0 ? JobResult.Result.SUCCESS : JobResult.Result.FAILURE)
            .killed(executor.getWatchdog().killedProcess()).output(result).error(stdErr.toString()).build();
}

From source file:com.github.brandtg.switchboard.FileLogAggregator.java

/**
 * An agent that aggregates logs from multiple sources and multiplexes them.
 *
 * @param sources/*from  w  w w . j a  va  2s. c  o m*/
 *  A set of source switchboard servers from which to pull logs
 * @param separator
 *  The line delimiter (after this is reached, lines will be output to outputStream)
 * @param outputStream
 *  OutputStream to which all multiplexed logs are piped
 */
public FileLogAggregator(Set<InetSocketAddress> sources, char separator, OutputStream outputStream)
        throws IOException {
    this.separator = separator;
    this.outputStream = outputStream;
    this.isShutdown = new AtomicBoolean(true);
    this.eventExecutors = new NioEventLoopGroup();
    this.logReceivers = new HashMap<>();
    this.inputStreams = new HashMap<>();
    this.listener = new Object();
    this.muxExecutor = Executors.newSingleThreadExecutor();
    this.stringBuffers = new HashMap<>();

    for (InetSocketAddress source : sources) {
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        LogReceiver logReceiver = new LogReceiver(new InetSocketAddress(0), eventExecutors, pos);
        logReceiver.registerListener(listener);
        logReceivers.put(source, logReceiver);
        inputStreams.put(source, pis);
        stringBuffers.put(source, new StringBuffer());
    }
}

From source file:org.guvnor.ala.build.maven.executor.MavenCliOutputTest.java

@Test
public void buildAppAndWaitForMavenOutputTest() throws IOException {
    final GitHub gitHub = new GitHub();
    gitHub.getRepository("salaboy/drools-workshop", new HashMap<String, String>() {
        {//from   w ww. jav a2s  .c  o m
            put("out-dir", tempPath.getAbsolutePath());
        }
    });

    final Optional<Source> _source = new GitConfigExecutor(new InMemorySourceRegistry())
            .apply(new GitConfigImpl(tempPath.getAbsolutePath(), "master",
                    "https://github.com/salaboy/drools-workshop", "drools-workshop", "true"));

    assertTrue(_source.isPresent());
    final Source source = _source.get();

    boolean buildProcessReady = false;
    Throwable error = null;
    PipedOutputStream baosOut = new PipedOutputStream();
    PipedOutputStream baosErr = new PipedOutputStream();
    final PrintStream out = new PrintStream(baosOut, true);
    final PrintStream err = new PrintStream(baosErr, true);

    //Build the project in a different thread
    new Thread(() -> {
        buildMavenProject(source, out, err);
    }).start();

    // Use the PipeOutputStream to read the execution output and validate that the application was built. 
    StringBuilder sb = new StringBuilder();
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new InputStreamReader(new PipedInputStream(baosOut)));
    String line;

    while (!(buildProcessReady || error != null)) {

        if ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("\n");
            if (line.contains("Building war:")) {
                buildProcessReady = true;
                out.close();
                err.close();
                baosOut.close();
                baosErr.close();

            }
        }

    }

    assertTrue(sb.toString().contains("Building war:"));
    assertTrue(buildProcessReady);
    assertTrue(error == null);

}

From source file:com.ibm.stocator.fs.swift.SwiftOutputStream.java

/**
 * Default constructor//from www .  j a  v a 2  s  .  com
 *
 * @param account JOSS account object
 * @param url URL connection
 * @param contentType content type
 * @param metadata input metadata
 * @param connectionManager SwiftConnectionManager
 * @throws IOException if error
 */
public SwiftOutputStream(JossAccount account, URL url, final String contentType, Map<String, String> metadata,
        SwiftConnectionManager connectionManager) throws IOException {
    mUrl = url;
    totalWritten = 0;
    mAccount = account;
    client = connectionManager.createHttpConnection();
    request = new HttpPut(mUrl.toString());
    request.addHeader("X-Auth-Token", account.getAuthToken());
    if (metadata != null && !metadata.isEmpty()) {
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue());
        }
    }

    PipedOutputStream out = new PipedOutputStream();
    final PipedInputStream in = new PipedInputStream();
    out.connect(in);
    execService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    mOutputStream = out;
    Callable<Void> task = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            InputStreamEntity entity = new InputStreamEntity(in, -1);
            entity.setChunked(true);
            entity.setContentType(contentType);
            request.setEntity(entity);

            LOG.debug("HTTP PUT request {}", mUrl.toString());
            HttpResponse response = client.execute(request);
            int responseCode = response.getStatusLine().getStatusCode();
            LOG.debug("HTTP PUT response {}. Response code {}", mUrl.toString(), responseCode);
            if (responseCode == 401) { // Unauthorized error
                mAccount.authenticate();
                request.removeHeaders("X-Auth-Token");
                request.addHeader("X-Auth-Token", mAccount.getAuthToken());
                LOG.warn("Token recreated for {}.  Retry request", mUrl.toString());
                response = client.execute(request);
                responseCode = response.getStatusLine().getStatusCode();
            }
            if (responseCode >= 400) { // Code may have changed from retrying
                throw new IOException("HTTP Error: " + responseCode + " Reason: "
                        + response.getStatusLine().getReasonPhrase());
            }

            return null;
        }
    };
    futureTask = execService.submit(task);
}