Example usage for java.io PipedInputStream PipedInputStream

List of usage examples for java.io PipedInputStream PipedInputStream

Introduction

In this page you can find the example usage for java.io PipedInputStream PipedInputStream.

Prototype

public PipedInputStream() 

Source Link

Document

Creates a PipedInputStream so that it is not yet #connect(java.io.PipedOutputStream) connected .

Usage

From source file:com.unispezi.cpanelremotebackup.CPanelRemoteBackup.java

/**
 * Downloads the backup to local file/*from  w w w .  j a  v a2  s.c  o m*/
 * @param backupName      name of backup on server
 * @param outputDirectory target local directory
 * @param totalFileBytes  file size (for progress indicator)
 * @return file handle of downloaded file
 */
private File downloadBackupToFile(String backupName, String outputDirectory, long totalFileBytes) {
    final PipedInputStream ftpDataInStream = new PipedInputStream();
    File outFile = null;
    try {
        PipedOutputStream ftpDataOutStream = new PipedOutputStream(ftpDataInStream);

        outFile = new File(outputDirectory, backupName);
        if (outFile.createNewFile()) {
            final FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        synchronized (asyncThreadMonitor) {
                            bytesDownloaded = IOUtils.copy(ftpDataInStream, fileOutputStream);
                            if (bytesDownloaded > 0)
                                bytesDownloaded += 0;
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Exception in copy thread", e);
                    }
                }
            }).start();
        } else {
            com.unispezi.cpanelremotebackup.tools.Console
                    .println("ERROR: Cannot create \"" + outFile + "\", file already exists.");
        }

        com.unispezi.cpanelremotebackup.tools.Console
                .println("Downloading " + backupName + " to " + outFile.getPath() + " :");
        com.unispezi.cpanelremotebackup.tools.Console.print("0% ");

        FTPClient.ProgressListener listener = new FTPClient.ProgressListener() {
            int lastPrintedPercentage = 0;

            @Override
            public void progressPercentageReached(int percentage) {
                int percentageRounded = percentage / 10;
                if (percentageRounded > lastPrintedPercentage) {
                    lastPrintedPercentage = percentageRounded;
                    com.unispezi.cpanelremotebackup.tools.Console.print(percentageRounded * 10 + "% ");
                }
            }
        };

        ftp.downloadFile(backupName, ftpDataOutStream, listener, totalFileBytes);
        synchronized (asyncThreadMonitor) {
            com.unispezi.cpanelremotebackup.tools.Console
                    .println("\nDownloaded " + bytesDownloaded + " bytes successfully");
        }
    } catch (IOException e) {
        com.unispezi.cpanelremotebackup.tools.Console.println("ERROR: Cannot download backup: " + e);
    }
    return outFile;
}

From source file:ee.ria.xroad.proxy.clientproxy.ClientMessageProcessor.java

ClientMessageProcessor(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        HttpClient httpClient, IsAuthenticationData clientCert, OpMonitoringData opMonitoringData)
        throws Exception {
    super(servletRequest, servletResponse, httpClient);

    this.clientCert = clientCert;
    this.opMonitoringData = opMonitoringData;
    this.reqIns = new PipedInputStream();
    this.reqOuts = new PipedOutputStream(reqIns);
}

From source file:TestOpenMailRelay.java

/** Construct a GUI and some I/O plumbing to get the output
 * of "TestOpenMailRelay" into the "results" textfield.
 *//*from w w w  .j  a  v a  2 s  .c  o  m*/
public TestOpenMailRelayGUI() throws IOException {
    super("Tests for Open Mail Relays");
    PipedInputStream is;
    PipedOutputStream os;
    JPanel p;
    Container cp = getContentPane();
    cp.add(BorderLayout.NORTH, p = new JPanel());

    // The entry label and text field.
    p.add(new JLabel("Host:"));
    p.add(hostTextField = new JTextField(10));
    hostTextField.addActionListener(runner);

    p.add(goButton = new JButton("Try"));
    goButton.addActionListener(runner);

    JButton cb;
    p.add(cb = new JButton("Clear Log"));
    cb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            results.setText("");
        }
    });
    JButton sb;
    p.add(sb = new JButton("Save Log"));
    sb.setEnabled(false);

    results = new JTextArea(20, 60);
    // Add the text area to the main part of the window (CENTER).
    // Wrap it in a JScrollPane to make it scroll automatically.
    cp.add(BorderLayout.CENTER, new JScrollPane(results));

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    pack(); // end of GUI portion

    // Create a pair of Piped Streams.
    is = new PipedInputStream();
    os = new PipedOutputStream(is);

    iis = new BufferedReader(new InputStreamReader(is, "ISO8859_1"));
    ps = new PrintStream(os);

    // Construct and start a Thread to copy data from "is" to "os".
    new Thread() {
        public void run() {
            try {
                String line;
                while ((line = iis.readLine()) != null) {
                    results.append(line);
                    results.append("\n");
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "*** Input or Output error ***\n" + ex, "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }.start();
}

From source file:org.apache.james.blob.cassandra.CassandraBlobsDAO.java

@Override
public InputStream read(BlobId blobId) {
    PipedInputStream pipedInputStream = new PipedInputStream();
    readBlobParts(blobId).subscribe(new PipedStreamSubscriber(pipedInputStream));
    return pipedInputStream;
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

public void put(final String username, String resource, InputStream data, long length, String contentType,
        final char[] password) throws ResourceNotFoundException, IOException {

    final String[] path = resource.split("/");
    Resource parent = getResourceAt(getRootFolder(username), Arrays.copyOfRange(path, 0, path.length - 2));

    DBCollection files = mongo.getDataBase().getCollection("files");
    DBCollection contents = mongo.getDataBase().getCollection("contents");

    ContentDetector contentDetector = null;
    if (contentType == null) {
        PipedInputStream pipeIn = new PipedInputStream();
        PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
        TeeInputStream tee = new TeeInputStream(data, pipeOut, true);
        contentDetector = new ContentDetector(path[path.length - 1], pipeIn);
        contentDetector.start();//  w  w w . j a  v  a 2s  .c o  m
        data = tee;
    }

    final File dataFile = createDataFile(data, username, password);

    if (contentDetector != null) {
        try {
            contentDetector.join();
            contentType = contentDetector.getContentType();
        } catch (InterruptedException ex) {
            Logger.getLogger(MongoFileService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Resource child = getChild(parent, path[path.length - 1]);
    if (child != null) {
        DBObject filter = new BasicDBObject();
        filter.put("_id", child.getId());
        DBObject update = new BasicDBObject("modificationDate", new Date());
        update.put("contentLength", length);
        update.put("contentType", contentType);
        files.update(filter, new BasicDBObject("$set", update));

        contents.update(new BasicDBObject("resource", child.getId()),
                new BasicDBObject("$set", new BasicDBObject("file", dataFile.getAbsolutePath())));
    } else {
        DBObject childObj = new BasicDBObject();
        ObjectId objId = new ObjectId();
        childObj.put("_id", objId);
        childObj.put("user", username);
        childObj.put("name", path[path.length - 1]);
        childObj.put("parent", parent.getId());
        childObj.put("type", Resource.ResourceType.FILE.toString());
        childObj.put("creationDate", new Date());
        childObj.put("modificationDate", new Date());
        childObj.put("contentType", contentType);
        childObj.put("contentLength", length);

        files.insert(childObj);

        DBObject content = new BasicDBObject();
        content.put("resource", objId);
        content.put("file", dataFile.getAbsolutePath());

        contents.insert(content);

        files.update(new BasicDBObject("_id", parent.getId()),
                new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

        child = buildResource(childObj);
    }

    final String fContentType = contentType;
    final Resource fChild = child;
    new Thread() {
        public void run() {
            try {
                Map<String, String> metadata = extractionService.extractContent(path[path.length - 1],
                        readFile(dataFile, username, password), fContentType);

                metadata.put("name", path[path.length - 1]);

                indexService.remove(username, new String(password), fChild.getId().toString());
                indexService.index(username, new String(password), fChild.getId().toString(), metadata);
            } catch (Exception ex) {
                Logger.getLogger(MongoFileService.class.getName()).log(Level.SEVERE,
                        "Index failed for " + path[path.length - 1], ex);
            }
        }
    }.start();
}

From source file:org.apache.olingo.client.core.communication.response.AbstractODataResponse.java

@Override
public InputStream getRawResponse() {
    if (HttpStatus.SC_NO_CONTENT == getStatusCode()) {
        throw new NoContentException();
    }//ww  w. j a v a 2s . co m

    if (payload == null && batchInfo.isValidBatch()) {
        // get input stream till the end of item
        payload = new PipedInputStream();

        try {
            final PipedOutputStream os = new PipedOutputStream((PipedInputStream) payload);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        ODataBatchUtilities.readBatchPart(batchInfo, os, true);
                    } catch (Exception e) {
                        LOG.error("Error streaming batch item payload", e);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                }
            }).start();
        } catch (IOException e) {
            LOG.error("Error streaming payload response", e);
            throw new IllegalStateException(e);
        }
    }

    return payload;
}

From source file:com.streamsets.datacollector.bundles.SupportBundleManager.java

/**
 * Return InputStream from which a new generated resource bundle can be retrieved.
 *//*from   w  ww.j av  a2 s.  com*/
public SupportBundle generateNewBundleFromInstances(List<BundleContentGenerator> generators,
        BundleType bundleType) throws IOException {
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = new PipedOutputStream();
    inputStream.connect(outputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

    executor.submit(() -> generateNewBundleInternal(generators, bundleType, zipOutputStream));

    String bundleName = generateBundleName(bundleType);
    String bundleKey = generateBundleDate(bundleType) + "/" + bundleName;

    return new SupportBundle(bundleKey, bundleName, inputStream);
}

From source file:Console.java

public ConsoleTextArea() {
    super();/*w w w .j  av a 2 s .  co  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));
}

From source file:com.sshtools.daemon.scp.ScpServer.java

private void scp(String args) throws IOException {
    log.debug("Parsing ScpServer options " + args);

    //   Parse the command line for supported options
    String[] a = StringUtil.current().allParts(args, " ");
    destination = null;/*ww  w.  j av a 2 s .com*/
    directory = false;
    from = false;
    to = false;
    recursive = false;
    verbosity = 0;

    boolean remote = false;

    for (int i = 0; i < a.length; i++) {
        if (a[i].startsWith("-")) {
            String s = a[i].substring(1);

            for (int j = 0; j < s.length(); j++) {
                char ch = s.charAt(j);

                switch (ch) {
                case 't':
                    to = true;

                    break;

                case 'd':
                    directory = true;

                    break;

                case 'f':
                    from = true;

                    break;

                case 'r':
                    recursive = true;

                    break;

                case 'v':
                    verbosity++;

                    break;

                case 'p':
                    preserveAttributes = true;

                    break;

                default:
                    log.warn("Unsupported argument, allowing to continue.");
                }
            }
        } else {
            if (destination == null) {
                destination = a[i];
            } else {
                throw new IOException("More than one destination supplied " + a[i]);
            }
        }
    }

    if (!to && !from) {
        throw new IOException("Must supply either -t or -f.");
    }

    if (destination == null) {
        throw new IOException("Destination not supplied.");
    }

    log.debug("Destination is " + destination);
    log.debug("Recursive is " + recursive);
    log.debug("Directory is " + directory);
    log.debug("Verbosity is " + verbosity);
    log.debug("From is " + from);
    log.debug("To is " + to);
    log.debug("Preserve Attributes " + preserveAttributes);

    //   Start the SCP server
    log.debug("Creating pipes");
    pipeIn = new PipedOutputStream();
    pipeErr = new PipedOutputStream();
    pipeOut = new PipedInputStream();
    in = new PipedInputStream(pipeIn);
    err = new PipedInputStream(pipeErr);
    out = new PipedOutputStream(pipeOut);
}

From source file:ubicrypt.core.Utils.java

public static InputStream readIs(final Path path) {
    final PipedInputStream pis = new PipedInputStream();
    final AtomicLong pos = new AtomicLong(0);
    try {//from   w  w w. j av a2 s  .  c o  m
        final PipedOutputStream ostream = new PipedOutputStream(pis);
        final AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        final ByteBuffer buffer = ByteBuffer.allocate(1 << 16);
        channel.read(buffer, pos.get(), buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(final Integer result, final ByteBuffer buf) {
                try {
                    if (result == -1) {
                        ostream.close();
                        return;
                    }
                    final byte[] bytes = new byte[result];
                    System.arraycopy(buf.array(), 0, bytes, 0, result);
                    ostream.write(bytes);
                    ostream.flush();
                    if (result < 1 << 16) {
                        ostream.close();
                        return;
                    }
                    pos.addAndGet(result);
                    final ByteBuffer buffer = ByteBuffer.allocate(1 << 16);
                    channel.read(buffer, pos.get(), buffer, this);
                } catch (final IOException e) {
                    Throwables.propagate(e);
                }
            }

            @Override
            public void failed(final Throwable exc, final ByteBuffer attachment) {
                log.error(exc.getMessage(), exc);
            }
        });
    } catch (final IOException e) {
        if (e instanceof NoSuchFileException) {
            throw new NotFoundException(path);
        }
        Throwables.propagate(e);
    }
    return pis;
}