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.github.vatbub.awsvpnlauncher.Main.java

/**
 * Copies {@code System.in} to new {@code InputStream}. Filters {@code CrLf}s ({@code \r\n} in Java) out and replaces them with a single {@code \n} ({@code \n} in Java)
 *
 * @return The {@code InputStream} to which the filtered contents are forwarded to.
 * @throws IOException If {@code System.in} cannot be read for any reason
 *//*  w ww  . j  a  v a 2s .  c om*/
private static InputStream copyAndFilterInputStream() throws IOException {
    PipedOutputStream forwardTo = new PipedOutputStream();
    PipedInputStream res = new PipedInputStream(forwardTo);
    Thread pipeThread = new Thread(() -> {
        while (true) {
            try {
                char ch = (char) System.in.read();
                if (ch != '\r' && !SystemUtils.IS_OS_MAC) {
                    forwardTo.write((int) ch);
                }
            } catch (IOException e) {
                FOKLogger.log(Main.class.getName(), Level.SEVERE,
                        "Stopped forwarding System in due to an exception", e);
                break;
            }
        }
    });
    pipeThread.setName("pipeThread");
    pipeThread.start();

    return res;
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void interruptOutput(final IProgressMonitor monitor, final int[] currentStep,
        final DefaultLogger consoleLogger, final boolean[] flag, final String[] defaultTaskName) {

    String threadName = "Monitor Output";
    if (current[0] != null && current[0].getName() != null) {
        linkBuffer.append(current[0].getName()).append("\n");
        threadName += (": " + current[0].getName());
    }/*from   www. ja  v  a 2s .c o  m*/

    outputThread = new Thread(threadName) {

        public void run() {
            try {
                final Module module = current[0];
                final int step = currentStep[0];
                PipedInputStream pipedIS = new PipedInputStream();
                PipedOutputStream pipedOS = new PipedOutputStream();
                pipedOS.connect(pipedIS);
                BufferedReader input = new BufferedReader(new InputStreamReader(pipedIS));
                PrintStream ps = new PrintStream(pipedOS);
                consoleLogger.setOutputPrintStream(ps);
                final String[] line = new String[1];
                String extactingStr = "[exec] Extracting";
                int length = "[exec]".length();
                while ((line[0] = input.readLine()) != null) {
                    if (module != current[0])
                        break;
                    if (!flag[0]) {
                        int index = line[0].indexOf(extactingStr);
                        if (index != -1) {
                            String file = line[0].substring(index + length);
                            monitor.subTask("[Step " + step + "]" + file);
                            if (module == null) {
                                if (data.isInstallShield()) {

                                    file = file.trim().replaceAll("Extracting\\s+", "");
                                    if (file.toLowerCase().indexOf("eclipse") > -1) {
                                        file = ("\\" + file);
                                        installBuffer.append(file + "\n");
                                    }
                                } else {
                                    file = file.trim().replaceAll("Extracting\\s+BRDPro", "");
                                    installBuffer.insert(0, file + "\n");
                                }

                            } else if (module.getType() == ModuleType.source
                                    && file.indexOf("eclipse\\plugins") > -1 && file.indexOf("source") > -1) {
                                String prefix = "\\eclipse\\dropins";
                                file = (prefix + "\\" + file.trim().replaceAll("Extracting\\s+", ""));
                                sourceBuffer.append(file).append("\n");
                            }
                        } else {
                            monitor.subTask(defaultTaskName[0]);
                        }
                        System.out.println(line[0]);
                    }
                }
                input.close();
                pipedIS.close();
                consoleLogger.setOutputPrintStream(System.out);
            } catch (IOException e) {

            }
        }
    };
    outputThread.start();

}

From source file:eu.scape_project.service.ConnectorService.java

private void addMetadata(final Session session, final Object metadata, final String path)
        throws RepositoryException {
    final StringBuilder sparql = new StringBuilder("PREFIX scape: <" + SCAPE_NAMESPACE + "> ");
    try {/*from   w  w w . j  a v a2s  .c  o m*/

        /* use piped streams to copy the data to the repo */
        final PipedInputStream dcSrc = new PipedInputStream();
        final PipedOutputStream dcSink = new PipedOutputStream();
        dcSink.connect(dcSrc);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    ConnectorService.this.marshaller.getJaxbMarshaller().marshal(metadata, dcSink);
                    dcSink.flush();
                    dcSink.close();
                } catch (JAXBException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                } catch (IOException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }
        }).start();

        final Datastream ds = datastreamService.createDatastream(session, path, "text/xml", null, dcSrc);
        final Node desc = ds.getNode();
        desc.addMixin("scape:metadata");

        final IdentifierTranslator subjects = new DefaultIdentifierTranslator();
        final String dsUri = subjects.getSubject(desc.getPath()).getURI();
        /* get the type of the metadata */
        String type = "unknown";
        String schema = "";

        if (metadata.getClass() == ElementContainer.class) {
            type = "dublin-core";
            schema = "http://purl.org/dc/elements/1.1/";
        } else if (metadata.getClass() == GbsType.class) {
            type = "gbs";
            schema = "http://books.google.com/gbs";
        } else if (metadata.getClass() == Fits.class) {
            type = "fits";
            schema = "http://hul.harvard.edu/ois/xml/ns/fits/fits_output";
        } else if (metadata.getClass() == AudioType.class) {
            type = "audiomd";
            schema = "http://www.loc.gov/audioMD/";
        } else if (metadata.getClass() == RecordType.class) {
            type = "marc21";
            schema = "http://www.loc.gov/MARC21/slim";
        } else if (metadata.getClass() == Mix.class) {
            type = "mix";
            schema = "http://www.loc.gov/mix/v20";
        } else if (metadata.getClass() == VideoType.class) {
            type = "videomd";
            schema = "http://www.loc.gov/videoMD/";
        } else if (metadata.getClass() == PremisComplexType.class) {
            type = "premis-provenance";
            schema = "info:lc/xmlns/premis-v2";
        } else if (metadata.getClass() == RightsComplexType.class) {
            type = "premis-rights";
            schema = "info:lc/xmlns/premis-v2";
        } else if (metadata.getClass() == TextMD.class) {
            type = "textmd";
            schema = "info:lc/xmlns/textmd-v3";
        }

        /* add a sparql query to set the type of this object */
        sparql.append("INSERT DATA {<" + dsUri + "> " + prefix(HAS_TYPE) + " '" + type + "'};");
        sparql.append("INSERT DATA {<" + dsUri + "> " + prefix(HAS_SCHEMA) + " '" + schema + "'};");

        ds.updatePropertiesDataset(subjects, sparql.toString());

    } catch (IOException e) {
        throw new RepositoryException(e);
    } catch (InvalidChecksumException e) {
        throw new RepositoryException(e);
    }
}

From source file:net.pms.dlna.DLNAResource.java

/**
 * Returns an InputStream of this DLNAResource that starts at a given time, if possible. Very useful if video chapters are being used.
 * @param range//from   w w  w. j a  va 2  s  .  c  om
 * @param mediarenderer
 * @return The inputstream
 * @throws IOException
 */
public InputStream getInputStream(Range range, RendererConfiguration mediarenderer) throws IOException {
    logger.trace("Asked stream chunk : " + range + " of " + getName() + " and player " + getPlayer());

    // shagrath: small fix, regression on chapters
    boolean timeseek_auto = false;
    // Ditlew - WDTV Live
    // Ditlew - We convert byteoffset to timeoffset here. This needs the stream to be CBR!
    int cbr_video_bitrate = mediarenderer.getCBRVideoBitrate();
    long low = range.isByteRange() && range.isStartOffsetAvailable() ? range.asByteRange().getStart() : 0;
    long high = range.isByteRange() && range.isEndLimitAvailable() ? range.asByteRange().getEnd() : -1;
    Range.Time timeRange = range.createTimeRange();

    if (getPlayer() != null && low > 0 && cbr_video_bitrate > 0) {
        int used_bit_rated = (int) ((cbr_video_bitrate + 256) * 1024 / 8 * 1.04); // 1.04 = container overhead
        if (low > used_bit_rated) {
            timeRange.setStart((double) (low / (used_bit_rated)));
            low = 0;

            // WDTV Live - if set to TS it asks multiple times and ends by
            // asking for an invalid offset which kills MEncoder
            if (timeRange.getStartOrZero() > getMedia().getDurationInSeconds()) {
                return null;
            }

            // Should we rewind a little (in case our overhead isn't accurate enough)
            int rewind_secs = mediarenderer.getByteToTimeseekRewindSeconds();
            timeRange.rewindStart(rewind_secs);

            // shagrath:
            timeseek_auto = true;
        }
    }

    // determine source of the stream
    if (getPlayer() == null) {
        // no transcoding
        if (this instanceof IPushOutput) {
            PipedOutputStream out = new PipedOutputStream();
            InputStream fis = new PipedInputStream(out);
            ((IPushOutput) this).push(out);

            if (low > 0) {
                fis.skip(low);
            }
            // http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035
            fis = wrap(fis, high, low);

            return fis;
        }

        InputStream fis;
        if (getFormat() != null && getFormat().isImage() && getMedia() != null
                && getMedia().getOrientation() > 1 && mediarenderer.isAutoRotateBasedOnExif()) {
            // seems it's a jpeg file with an orientation setting to take care of
            fis = ImagesUtil.getAutoRotateInputStreamImage(getInputStream(), getMedia().getOrientation());
            if (fis == null) { // error, let's return the original one
                fis = getInputStream();
            }
        } else {
            fis = getInputStream();
        }

        if (fis != null) {
            if (low > 0) {
                fis.skip(low);
            }

            // http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035
            fis = wrap(fis, high, low);

            if (timeRange.getStartOrZero() > 0 && this instanceof RealFile) {
                fis.skip(MpegUtil.getPositionForTimeInMpeg(((RealFile) this).getFile(),
                        (int) timeRange.getStartOrZero()));
            }
        }
        return fis;
    } else {
        // pipe transcoding result
        OutputParams params = new OutputParams(configuration);
        params.aid = getMediaAudio();
        params.sid = getMediaSubtitle();
        params.mediaRenderer = mediarenderer;
        timeRange.limit(getSplitRange());
        params.timeseek = timeRange.getStartOrZero();
        params.timeend = timeRange.getEndOrZero();
        params.shift_scr = timeseek_auto;

        if (this instanceof IPushOutput) {
            params.stdin = (IPushOutput) this;
        }

        // (re)start transcoding process if necessary
        if (externalProcess == null || externalProcess.isDestroyed()) {
            // first playback attempt => start new transcoding process
            logger.info("Starting transcode/remux of " + getName());
            externalProcess = getPlayer().launchTranscode(this, getMedia(), params);
            if (params.waitbeforestart > 0) {
                logger.trace("Sleeping for {} milliseconds", params.waitbeforestart);
                try {
                    Thread.sleep(params.waitbeforestart);
                } catch (InterruptedException e) {
                    logger.error(null, e);
                }
                logger.trace("Finished sleeping for " + params.waitbeforestart + " milliseconds");
            }
        } else if (params.timeseek > 0 && getMedia() != null && getMedia().isMediaparsed()
                && getMedia().getDurationInSeconds() > 0) {
            // time seek request => stop running transcode process and start new one
            logger.debug("Requesting time seek: " + params.timeseek + " seconds");
            params.minBufferSize = 1;
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    externalProcess.stopProcess();
                }
            };
            new Thread(r, "External Process Stopper").start();
            ProcessWrapper newExternalProcess = getPlayer().launchTranscode(this, getMedia(), params);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                logger.error(null, e);
            }
            if (newExternalProcess == null) {
                logger.trace("External process instance is null... sounds not good");
            }
            externalProcess = newExternalProcess;
        }
        if (externalProcess == null) {
            return null;
        }
        InputStream is = null;
        int timer = 0;
        while (is == null && timer < 10) {
            is = externalProcess.getInputStream(low);
            timer++;
            if (is == null) {
                logger.warn("External input stream instance is null... sounds not good, waiting 500ms");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        }

        // fail fast: don't leave a process running indefinitely if it's
        // not producing output after params.waitbeforestart milliseconds + 5 seconds
        // this cleans up lingering MEncoder web video transcode processes that hang
        // instead of exiting
        if (is == null && externalProcess != null && !externalProcess.isDestroyed()) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    logger.error("External input stream instance is null... stopping process");
                    externalProcess.stopProcess();
                }
            };
            new Thread(r, "Hanging External Process Stopper").start();
        }
        return is;
    }
}