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.sipfoundry.sipxconfig.cfgmgt.AgentRunner.java

/**
 * Run a full job at a location. Update job table for any failures in either running the
 * command or errors in stderr/*ww  w  .j  a  v  a  2  s .  com*/
 */
void runJob(Location location, String label, String command) {
    PipedOutputStream log = null;
    Serializable job = m_jobContext.schedule(label, location);
    AgentResults results = new AgentResults();
    Stack<String> errs;
    try {
        m_jobContext.start(job);
        log = new PipedOutputStream();
        PipedInputStream in = new PipedInputStream(log);
        results.parse(in);
        int status = runCommand(command, log);
        errs = results.getResults(1000);
        if (errs.size() > 0) {
            String err = location.getFqdn() + ':' + errs.pop();
            ConfigManagerImpl.fail(m_jobContext, label, job, new ConfigException(err));
            while (!errs.empty()) {
                // Tricky alert - show additional errors as new jobs
                Serializable jobErr = m_jobContext.schedule(label, location);
                m_jobContext.start(jobErr);
                err = location.getFqdn() + ':' + errs.pop();
                ConfigManagerImpl.fail(m_jobContext, label, jobErr, new ConfigException(err));
            }
        } else if (status != 0 && errs.size() == 0) {
            String msg = format("Agent run on %s finshed but returned error code %d", location.getFqdn(),
                    status);
            ConfigManagerImpl.fail(m_jobContext, label, job, new ConfigException(msg));
        } else {
            m_jobContext.success(job);
        }
    } catch (Exception e) {
        ConfigManagerImpl.fail(m_jobContext, label, job, e);
    } finally {
        IOUtils.closeQuietly(log);
    }
}

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

public IIncomingTransport getFilePullTransport(Node remote, final Node local, String securityToken,
        Map<String, String> requestProperties, String registrationUrl) throws IOException {
    final PipedOutputStream respOs = new PipedOutputStream();
    final PipedInputStream respIs = new PipedInputStream(respOs);

    runAtClient(remote.getSyncUrl(), null, respOs, new IClientRunnable() {
        public void run(ISymmetricEngine engine, InputStream is, OutputStream os) throws Exception {
            IOutgoingTransport transport = new InternalOutgoingTransport(respOs, null);
            ProcessInfo processInfo = engine.getStatisticManager()
                    .newProcessInfo(new ProcessInfoKey(engine.getNodeService().findIdentityNodeId(),
                            local.getNodeId(), ProcessType.FILE_SYNC_PULL_HANDLER));
            try {
                engine.getFileSyncService().sendFiles(processInfo, local, transport);
                processInfo.setStatus(Status.OK);
            } catch (RuntimeException ex) {
                processInfo.setStatus(Status.ERROR);
                throw ex;
            }//  ww w  .  j a  va2  s .  co  m
            transport.close();
        }
    });
    return new InternalIncomingTransport(respIs);
}

From source file:ReaderInputStream.java

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

From source file:org.hawkular.rest.ResponseUtil.java

private static <T> InputStream pageToStream(Page<T> page, ObjectMapper mapper, Runnable callback)
        throws IOException {
    final PipedOutputStream outs = new PipedOutputStream();
    final PipedInputStream ins = new PipedInputStream() {
        @Override//from  w  ww.j  a va 2s  . com
        public void close() throws IOException {
            outs.close();
            super.close();
        }
    };
    outs.connect(ins);
    mapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    PageToStreamThreadPool.getInstance().submit(() -> {
        try (Page<T> closeablePage = page;
                PipedOutputStream out = outs;
                SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
            for (T element : closeablePage) {
                sequenceWriter.write(element);
                sequenceWriter.flush();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Unable to convert page to input stream.", e);
        } finally {
            callback.run();
        }
    });
    return ins;
}

From source file:org.openlaszlo.data.XMLGrabber.java

/**
 * Convert incoming XML to ... XML /* ww w .j a  v a  2s .c om*/
 *
 * This method is called convertToSWF for historical reasons, and nobody
 * has changed the API call name yet. 
 *
 * A dataset will look like this:
 * <resultset>
 * <body>
 *   <weather sourceurl="http://www.srh.noaa.gov/zipcity.php?inputstring=02460">
 *    <radar src="http://www.laszlosystems.com:80/weather/small/kbox.jpg"/>
 *    <satellite src="http://www.laszlosystems.com:80/weather/thumbs/ECI8.JPG"/>
 *   </weather>
 * </body>
 * <headers>
 * <header name="Date" value="Thu, 29 Dec 2005 03:49:46 GMT"/>
 * <header name="Server" value="Apache/2.0.44 (Unix) mod_ssl/2.0.44 OpenSSL/0.9.6b DAV/2 mod_jk/1.2.1 PHP/4.3.0"/>
 * </headers>
 * </resultset>
 */
@Override
public InputStream convertToSWF(Data data, HttpServletRequest req, HttpServletResponse res)
        throws ConversionException, IOException {

    try {
        PipedOutputStream pout = new PipedOutputStream();
        PipedInputStream in = new PipedInputStream(pout);

        XmlSerializer serializer;
        XmlPullParser parser;
        parser = getXPPFactory().newPullParser();
        InputStream dstream = data.getInputStream();
        Reader reader = FileUtils.getXMLStreamReader(dstream, "UTF-8");
        parser.setInput(reader);
        serializer = factory.newSerializer();
        serializer.setOutput(pout, "UTF-8");

        HttpMethodBase request = ((HttpData) data).getRequest();

        final String sendheaders = req.getParameter("sendheaders");

        XMLCopyThread worker = new XMLCopyThread(pout, parser, serializer, request, sendheaders);
        worker.start();

        return in;
    } catch (XmlPullParserException ex) {
        throw new ConversionException("Parsing XML: " + ex.getMessage());
    }
}

From source file:hudson.scm.subversion.CheckoutUpdater.java

@Override
public UpdateTask createTask() {
    return new UpdateTask() {
        private static final long serialVersionUID = 8349986526712487762L;

        @Override// w  w  w .j ava 2 s .  c o  m
        public List<External> perform() throws IOException, InterruptedException {
            final SVNUpdateClient svnuc = clientManager.getUpdateClient();
            final List<External> externals = new ArrayList<External>(); // store discovered externals to here

            listener.getLogger().println("Cleaning local Directory " + location.getLocalDir());
            Util.deleteContentsRecursive(new File(ws, location.getLocalDir()));

            // buffer the output by a separate thread so that the update operation
            // won't be blocked by the remoting of the data
            PipedOutputStream pos = new PipedOutputStream();
            StreamCopyThread sct = new StreamCopyThread("svn log copier", new PipedInputStream(pos),
                    listener.getLogger());
            sct.start();

            try {

                SVNRevision r = getRevision(location);

                String revisionName = r.getDate() != null ? fmt.format(r.getDate()) : r.toString();

                listener.getLogger()
                        .println("Checking out " + location.remote + " at revision " + revisionName);

                File local = new File(ws, location.getLocalDir());
                SubversionUpdateEventHandler eventHandler = new SubversionUpdateEventHandler(
                        new PrintStream(pos), externals, local, location.getLocalDir());
                svnuc.setEventHandler(eventHandler);
                svnuc.setExternalsHandler(eventHandler);
                svnuc.setIgnoreExternals(location.isIgnoreExternalsOption());

                SVNDepth svnDepth = getSvnDepth(location.getDepthOption());
                svnuc.doCheckout(location.getSVNURL(), local.getCanonicalFile(), SVNRevision.HEAD, r, svnDepth,
                        true);
            } catch (SVNCancelException e) {
                if (isAuthenticationFailedError(e)) {
                    e.printStackTrace(listener.error("Failed to check out " + location.remote));
                    return null;
                } else {
                    listener.error("Subversion checkout has been canceled");
                    throw (InterruptedException) new InterruptedException().initCause(e);
                }
            } catch (SVNException e) {
                e.printStackTrace(listener.error("Failed to check out " + location.remote));
                throw new IOException("Failed to check out " + location.remote, e);
            } finally {
                try {
                    pos.close();
                } finally {
                    try {
                        sct.join(); // wait for all data to be piped.
                    } catch (InterruptedException e) {
                        throw new IOException2("interrupted", e);
                    }
                }
            }

            return externals;
        }
    };
}

From source file:org.pentaho.webpackage.deployer.archive.impl.WebPackageURLConnection.java

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

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

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

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

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

From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    logs = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;//from  w w  w . j  a  v a 2s .  c  o  m

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

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

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

@Override
public String slurpOutput(final String commandString, final boolean ignoreExitCode) {
    final CommandLine command = CommandLine.parse(commandString);
    LOG.debug("running: {}", commandString);

    final Map<String, String> environment = new HashMap<String, String>(System.getenv());
    environment.put("COLUMNS", "2000");
    DataInputStream input = null;
    PipedInputStream pis = null;/*  w  w w  .  java  2  s.  c  o  m*/
    OutputSuckingParser parser = null;
    String outputText = null;
    final DefaultExecutor executor = new DefaultExecutor();

    final PipedOutputStream output = new PipedOutputStream();
    final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output);
    executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait));
    executor.setStreamHandler(streamHandler);
    if (ignoreExitCode) {
        executor.setExitValues(null);
    }

    try {
        LOG.trace("executing '{}'", commandString);
        pis = new PipedInputStream(output);
        input = new DataInputStream(pis);
        parser = new OutputSuckingParser(input);
        parser.start();
        final int exitValue = executor.execute(command, environment);
        IOUtils.closeQuietly(output);
        parser.join(m_maxProcessWait);
        if (!ignoreExitCode && exitValue != 0) {
            LOG.debug("error running '{}': exit value was {}", commandString, exitValue);
        } else {
            outputText = parser.getOutput();
        }
        LOG.trace("finished '{}'", commandString);
    } catch (final Exception e) {
        LOG.debug("Failed to run '{}'", commandString, e);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(pis);
    }

    return outputText;
}

From source file:de.upb.wdqa.wdvd.processors.output.CsvFeatureWriter.java

private static OutputStream getPipedOutputStreamStream(final OutputStream outputStream) throws IOException {
    final int BUFFER_SIZE = 1 * 1024 * 1024;

    final PipedOutputStream pipedOutputStream = new PipedOutputStream();
    final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream, BUFFER_SIZE);

    new Thread("Label Writer Output Stream") {
        @Override//from w  w  w . j av a2  s  . c  o  m
        public void run() {
            try {
                IOUtils.copy(pipedInputStream, outputStream);

                pipedInputStream.close();
                outputStream.close();
            } catch (Throwable t) {
                logger.error("", t);
            }
        }
    }.start();

    return pipedOutputStream;
}