Example usage for java.io PipedOutputStream close

List of usage examples for java.io PipedOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this piped output stream and releases any system resources associated with this stream.

Usage

From source file:com.symbian.driver.engine.Utils.java

/**
 * @param aCmd/*from  w w  w.  j  a v  a2 s  .  c  o  m*/
 * @param aFirstParameter
 * @param aSecondParameter
 * @return
 * @throws JStatException
 * @throws IOException
 * @throws TimeLimitExceededException
 */
public static final BufferedReader executeOnDevice(final int aCmd, final String aFirstParameter,
        final String aSecondParameter) throws JStatException, IOException, TimeLimitExceededException {
    PipedOutputStream lPipedOutputStream = new PipedOutputStream();
    PipedInputStream lPipedInputStream = new PipedInputStream(lPipedOutputStream);

    try {
        if (aFirstParameter == null && aSecondParameter == null) {
            new ExecuteOnDevice(aCmd).doTask(true, EngineTests.TIMEOUT, false);
        } else if (aFirstParameter != null && aSecondParameter == null) {
            new ExecuteOnDevice(aCmd, aFirstParameter).doTask(true, EngineTests.TIMEOUT, false);
        } else if (aFirstParameter != null && aSecondParameter != null) {
            new ExecuteOnDevice(aCmd, aFirstParameter, aSecondParameter).doTask(true, EngineTests.TIMEOUT,
                    false);
        }
    } catch (ParseException lParseException) {
        throw new IOException("Could not read transport. " + lParseException.getMessage());
    }

    BufferedReader lBufferedReader = new BufferedReader(new InputStreamReader(lPipedInputStream));
    //      lPipedInputStream.close();
    lPipedOutputStream.close();

    return lBufferedReader;
}

From source file:org.grails.plugin.platform.events.push.EventsPushHandler.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    InputStream stream = req.getInputStream();
    final String topic = readPacket(stream);
    if (topic == null || topic.isEmpty()) {
        return;//  w  w  w  .j a  va 2s. c om
    }

    final String type = readPacket(stream);
    if (type == null || type.isEmpty()) {
        return;
    }

    if (type.equals(TYPE_STRING)) {
        grailsEvents.event(topic, readPacket(stream), EventsPushConstants.FROM_BROWSERS, null, null, null);
    } else if (type.equals(TYPE_JSON)) {
        grailsEvents.event(topic, new JsonSlurper().parse(new BufferedReader(new InputStreamReader(stream))),
                EventsPushConstants.FROM_BROWSERS, null, null, null);
    } else if (type.equals(TYPE_BINARY)) {
        PipedOutputStream pipeOut = new PipedOutputStream();
        PipedInputStream pipeIn = new PipedInputStream(pipeOut, 4096);
        grailsEvents.event(topic, pipeIn, EventsPushConstants.FROM_BROWSERS, null, null, null);
        IOUtils.copy(stream, pipeOut);
        pipeOut.close();

    } else if (type.equals(TYPE_REGISTER)) {
        AtmosphereResource targetResource = null;
        for (AtmosphereResource r : broadcasterFactory.lookup(EventsPushConstants.GLOBAL_TOPIC)
                .getAtmosphereResources()) {
            if (r.uuid().equalsIgnoreCase(((AtmosphereRequest) req).resource().uuid())) {
                targetResource = r;
                break;
            }
        }
        if (targetResource != null) {
            targetResource.addEventListener(
                    new AtmosphereRegistrationsHandler(registerTopics(topic, targetResource)));
        }
    } else if (type.equals(TYPE_UNREGISTER)) {
    }
}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyBuilder.java

/**
 * Returns the configuration XML document of a view
 * /*from w  w  w . j a  v a 2s  .c  om*/
 * @param view
 * @param logger
 * @return
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
private Document getViewConfigXmlDocument(View view, final PrintStream logger)
        throws IOException, SAXException, ParserConfigurationException {
    XStream2 xStream2 = new XStream2(new DomDriver("UTF-8"));
    xStream2.omitField(View.class, "owner");
    xStream2.omitField(View.class, "name"); // this field causes disaster when overwriting.

    PipedOutputStream sout = new PipedOutputStream();
    PipedInputStream sin = new PipedInputStream(sout);

    xStream2.toXML(view, sout);
    sout.close();

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }
    });
    return builder.parse(sin);
}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyBuilder.java

/**
 * Returns a InputStream of a XML document.
 * /*from   w  w w . j a va  2 s  .  co  m*/
 * @param doc
 * @return
 * @throws TransformerException
 * @throws IOException
 */
private InputStream getInputStreamFromDocument(Document doc) throws TransformerException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    PipedOutputStream sout = new PipedOutputStream();
    PipedInputStream sin = new PipedInputStream(sout);
    transformer.transform(new DOMSource(doc), new StreamResult(sout));
    sout.close();

    return sin;
}

From source file:com.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (!(res instanceof Folder)) {
            if (res.isExternalResource()) {
                ExternalResourceService service = ResourceUtils
                        .getExternalResourceService(ResourceUtils.getType(res));
                return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
            } else {
                return resourceService.getContentStream(res.getPath());
            }/* w ww  .jav  a  2 s.c o m*/
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {
        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();
    return inStream;
}

From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (res.isExternalResource()) {
            ExternalResourceService service = ResourceUtils
                    .getExternalResourceService(ResourceUtils.getType(res));
            return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
        } else {// w ww. j a  va 2  s .  c om
            return resourceService.getContentStream(res.getPath());
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {

        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();

    return inStream;
}

From source file:custom.SevenZFileExt.java

public InputStream getInputStream(final int bufferSize) {
    final PipedInputStream in = new PipedInputStream(bufferSize);
    try {//from w  w w .  java2 s. c o  m
        final PipedOutputStream out = new PipedOutputStream(in);
        Thread thread = new Thread(() -> {
            try {
                byte[] buffer = new byte[bufferSize];
                int len = read(buffer);
                while (len > 0) {
                    try {
                        out.write(buffer, 0, len);
                        len = read(buffer);
                    } catch (Exception ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
                out.flush();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        });
        thread.setName("GenerateInputStreamSeven7File");
        thread.start();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return in;
}

From source file:edu.umn.msi.tropix.common.io.impl.AsyncStreamCopierImplTest.java

@Test(groups = "unit", timeOut = 1000, invocationCount = 10)
public void close() throws IOException, InterruptedException {
    final AsyncStreamCopierImpl copier = new AsyncStreamCopierImpl();
    final Reference<Thread> threadReference = new Reference<Thread>();
    final Reference<Throwable> throwableReference = new Reference<Throwable>();
    copier.setExecutor(new Executor() {
        public void execute(final Runnable runnable) {
            final Thread thread = new Thread(runnable);
            threadReference.set(thread);
            thread.start();//  w  ww  .  j a v a 2 s  .  c  om
            thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                public void uncaughtException(final Thread arg0, final Throwable throwable) {
                    throwableReference.set(throwable);
                }
            });
        }
    });
    final PipedOutputStream pipedOutputStream = new PipedOutputStream();
    final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
    final ByteArrayOutputStream copiedStream = new ByteArrayOutputStream();
    copier.copy(pipedInputStream, copiedStream, true);
    Thread.sleep(3);
    assert new String(copiedStream.toByteArray()).equals("");
    pipedOutputStream.write("Hello ".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello ")) {
        Thread.sleep(1);
    }
    pipedOutputStream.write("World!".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello World!")) {
        Thread.sleep(1);
    }
    assert threadReference.get().isAlive();
    pipedOutputStream.close();
    while (threadReference.get().isAlive()) {
        Thread.sleep(1);
    }
    assert throwableReference.get() == null;
}

From source file:SubmitResults.java

private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req,
        final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder,
        final String newIdent) {

    File ammendedFile = null;//  w w w  . jav  a  2s .c o m

    final File instanceFile = new File(filePath);

    if (formStatus != null) {
        System.out.println("Setting form status in header: " + formStatus);
        req.setHeader("form_status", formStatus); // smap add form_status header
    } else {
        System.out.println("Form Status null");
    }

    if (newIdent != null) {
        // Transform the survey ID
        try {
            System.out.println("Transformaing Instance file: " + instanceFile);
            PipedInputStream in = new PipedInputStream();
            final PipedOutputStream outStream = new PipedOutputStream(in);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8"));
                        Transformer transformer = TransformerFactory.newInstance()
                                .newTransformer(new StreamSource(xslStream));
                        StreamSource source = new StreamSource(instanceFile);
                        StreamResult out = new StreamResult(outStream);
                        transformer.setParameter("surveyId", newIdent);
                        transformer.transform(source, out);
                        outStream.close();
                    } catch (TransformerConfigurationException e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerFactoryConfigurationError e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    } catch (IOException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    }
                }
            }).start();
            System.out.println("Saving stream to file");
            ammendedFile = saveStreamTemp(in);
        } catch (Exception e) {
            parent.appendToStatus("Error changing ident: " + e.toString());
        }
    }

    /*
     * Add submission file as file body, hence save to temporary file first
     */
    if (newIdent == null) {
        ct = ContentType.create("text/xml");
        entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
    } else {
        FileBody fb = new FileBody(ammendedFile);
        entityBuilder.addPart("xml_submission_file", fb);
    }

    parent.appendToStatus("Instance file path: " + instanceFile.getPath());

    /*
     *  find all files referenced by the survey
     *  Temporarily check to see if the parent directory is "uploadedSurveys". If it is
     *   then we will need to scan the submission file to get the list of attachments to 
     *   send. 
     *  Alternatively this is a newly submitted survey stored in its own directory just as
     *  surveys are stored on the phone.  We can then just add all the surveys that are in 
     *  the same directory as the submission file.
     */
    File[] allFiles = instanceFile.getParentFile().listFiles();

    // add media files ignoring invisible files and the submission file
    List<File> files = new ArrayList<File>();
    for (File f : allFiles) {
        String fileName = f.getName();
        if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file    
            files.add(f);
        }
    }

    for (int j = 0; j < files.size(); j++) {

        File f = files.get(j);
        String fileName = f.getName();
        ct = ContentType.create(getContentType(parent, fileName));
        FileBody fba = new FileBody(f, ct, fileName);
        entityBuilder.addPart(fileName, fba);

    }

    req.setEntity(entityBuilder.build());

    return ammendedFile;
}

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 {/* w  w  w  .j  a  v  a 2 s  . 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);
    }
}