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(PipedInputStream snk) throws IOException 

Source Link

Document

Creates a piped output stream connected to the specified piped input stream.

Usage

From source file:io.syndesis.project.converter.DefaultProjectGenerator.java

private InputStream createTarInputStream(GenerateProjectRequest request) throws IOException {
    PipedInputStream is = new PipedInputStream();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    PipedOutputStream os = new PipedOutputStream(is);
    executor.submit(generateAddProjectTarEntries(request, os));

    return is;//from  www . ja  v a  2s . c  om
}

From source file:org.geoserver.wfs.xslt.XSLTOutputFormat.java

@Override
protected void write(final FeatureCollectionResponse featureCollection, OutputStream output,
        Operation operation) throws IOException, ServiceException {
    // get the transformation we need
    TransformInfo info = locateTransformation(featureCollection, operation);
    Transformer transformer = repository.getTransformer(info);
    // force Xalan to indent the output
    if (transformer.getOutputProperties() != null
            && "yes".equals(transformer.getOutputProperties().getProperty("indent"))) {
        try {//from   ww w .ja  va2s . co m
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } catch (IllegalArgumentException e) {
            LOGGER.log(Level.FINE, "Could not set indent amount", e);
            // in case it's not Xalan
        }
    }

    // prepare the fake operation we're providing to the source output format
    final Operation sourceOperation = buildSourceOperation(operation, info);

    // lookup the operation we are going to use
    final Response sourceResponse = findSourceResponse(sourceOperation, info);
    if (sourceResponse == null) {
        throw new WFSException("Could not locate a response that can generate the desired source format '"
                + info.getSourceFormat() + "' for transformation '" + info.getName() + "'");

    }

    // prepare the stream connections, so that we can do the transformation on the fly
    PipedInputStream pis = new PipedInputStream();
    final PipedOutputStream pos = new PipedOutputStream(pis);

    // submit the source output format execution, tracking exceptions
    Future<Void> future = executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            try {
                sourceResponse.write(featureCollection, pos, sourceOperation);
            } finally {
                // close the stream to make sure the transformation won't keep on waiting
                pos.close();
            }

            return null;
        }
    });

    // run the transformation
    TransformerException transformerException = null;
    try {
        transformer.transform(new StreamSource(pis), new StreamResult(output));
    } catch (TransformerException e) {
        transformerException = e;
    } finally {
        pis.close();
    }

    // now handle exceptions, starting from the source
    try {
        future.get();
    } catch (Exception e) {
        throw new WFSException(
                "Failed to run the output format generating the source for the XSTL transformation", e);
    }
    if (transformerException != null) {
        throw new WFSException("Failed to run the the XSTL transformation", transformerException);
    }

}

From source file:org.fedoraproject.eclipse.packager.SourcesFile.java

/**
 * Saves the sources file to the underlying file.
 * @throws CoreException/*from  w ww. ja v  a 2 s . c o m*/
 */
public void save() throws CoreException {

    final PipedInputStream in = new PipedInputStream();
    // create an OutputStream with the InputStream from above as input
    PipedOutputStream out = null;
    try {
        out = new PipedOutputStream(in);
        PrintWriter pw = new PrintWriter(out);
        for (Map.Entry<String, String> entry : sources.entrySet()) {
            pw.println(entry.getValue() + "  " + entry.getKey()); //$NON-NLS-1$
        }
        pw.close();
        out.close();
        final IFile file = sourcesFile;

        Job job = new Job(FedoraPackagerText.SourcesFile_saveJob) {

            @Override
            public IStatus run(IProgressMonitor monitor) {
                try {
                    // Potentially long running so do as job.
                    file.setContents(in, false, true, monitor);
                    file.getParent().refreshLocal(IResource.DEPTH_ONE, null);
                } catch (CoreException e) {
                    e.printStackTrace();
                }
                return Status.OK_STATUS;
            }
        };
        job.schedule();
        try {
            job.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, PackagerPlugin.PLUGIN_ID,
                MessageFormat.format(FedoraPackagerText.SourcesFile_saveFailedMsg, sourcesFile.getName())));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Nothing to do
            }
        }
    }
}

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

/**
 * Downloads the backup to local file//ww w  .  j a  v  a  2  s  .  c om
 * @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 ww. j a va2 s  .co 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: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();//from  w w  w .j  ava  2s . co 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();
    }/*  w  ww. j  ava  2 s.  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:nl.esciencecenter.xenon.adaptors.filesystems.webdav.WebdavFileSystem.java

@Override
public OutputStream writeToFile(Path file, long size) throws XenonException {

    Path absFile = toAbsolutePath(file);
    assertPathNotExists(absFile);/*from  w  w  w.  j a  v a  2s  . c  o m*/
    assertParentDirectoryExists(absFile);

    try {
        PipedInputStream in = new PipedInputStream(4096);
        PipedOutputStream out = new PipedOutputStream(in);

        // Create a separate thread here to handle the writing
        new StreamToFileWriter(getFilePath(absFile), in).start();

        return out;
    } catch (Exception e) {
        throw new XenonException(ADAPTOR_NAME, "Failed to open stream for writing", e);
    }
}

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  a  v a2s.co 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;
}