Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.artificer.test.server.atom.services.BatchResourceTest.java

/**
 * This also tests the zipPackage method of the {@link org.artificer.server.atom.services.BatchResource} class, but it is
 * more thorough.  It tests adding new content, updating existing content, etc.
 *///from   w ww .  j  av a 2 s.com
@Test
public void testZipPackage_Multi() throws Exception {
    ArtificerArchive archive = null;
    InputStream xsd1ContentStream = null;
    InputStream wsdlContentStream = null;
    File zipFile = null;
    InputStream zipStream = null;
    ClientRequest request = null;

    WsdlDocument wsdlDoc = createWsdlArtifact();
    XmlDocument xmlDoc = createXmlArtifact();

    String xsdUuid = null;
    String wsdlUuid = null;
    String xmlUuid = null;

    try {
        // Create a test s-ramp archive
        archive = new ArtificerArchive();

        // A new XSD document
        xsd1ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/PO.xsd");
        BaseArtifactType metaData = new XsdDocument();
        metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT);
        metaData.setUuid(UUID.randomUUID().toString()); // will be ignored
        metaData.setName("PO.xsd");
        archive.addEntry("schemas/PO.xsd", metaData, xsd1ContentStream);
        // Update an existing WSDL document (content and meta-data)
        wsdlContentStream = this.getClass().getResourceAsStream("/sample-files/wsdl/sample-updated.wsdl");
        metaData = wsdlDoc;
        metaData.setVersion("2.0");
        ArtificerModelUtils.setCustomProperty(metaData, "foo", "bar");
        archive.addEntry("wsdl/sample.wsdl", metaData, wsdlContentStream);
        // Update an existing XML document (meta-data only)
        metaData = xmlDoc;
        metaData.setVersion("3.0");
        ArtificerModelUtils.setCustomProperty(metaData, "far", "baz");
        archive.addEntry("core/PO.xml", metaData, null);

        zipFile = archive.pack();
        zipStream = FileUtils.openInputStream(zipFile);

        // Now POST the archive to the s-ramp repository (POST to /s-ramp as application/zip)
        request = clientRequest("/s-ramp");
        request.body(MediaType.APPLICATION_ZIP, zipStream);
        ClientResponse<MultipartInput> clientResponse = request.post(MultipartInput.class);

        // Process the response - it should be multipart/mixed with each part being
        // itself an http response with a code, content-id, and an s-ramp atom entry
        // body
        MultipartInput response = clientResponse.getEntity();
        List<InputPart> parts = response.getParts();
        Map<String, HttpResponseBean> respMap = new HashMap<String, HttpResponseBean>();
        for (InputPart part : parts) {
            String id = part.getHeaders().getFirst("Content-ID");
            HttpResponseBean rbean = part.getBody(HttpResponseBean.class, null);
            respMap.put(id, rbean);
        }

        // Should be three responses.
        Assert.assertEquals(3, respMap.size());
        Assert.assertTrue(respMap.keySet().contains("<schemas/PO.xsd@package>"));
        Assert.assertTrue(respMap.keySet().contains("<wsdl/sample.wsdl@package>"));
        Assert.assertTrue(respMap.keySet().contains("<core/PO.xml@package>"));

        // Assertions for artifact 1 (PO.xsd)
        HttpResponseBean httpResp = respMap.get("<schemas/PO.xsd@package>");
        Assert.assertEquals(201, httpResp.getCode());
        Assert.assertEquals("Created", httpResp.getStatus());
        Entry entry = (Entry) httpResp.getBody();
        BaseArtifactType artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("PO.xsd", artifact.getName());
        Assert.assertNull(artifact.getVersion());
        Long size = ((XsdDocument) artifact).getContentSize();
        Assert.assertTrue(size >= 2376L);
        xsdUuid = artifact.getUuid();

        // Assertions for artifact 2 (sample.wsdl)
        httpResp = respMap.get("<wsdl/sample.wsdl@package>");
        Assert.assertEquals(200, httpResp.getCode());
        Assert.assertEquals("OK", httpResp.getStatus());
        entry = (Entry) httpResp.getBody();
        artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("sample.wsdl", artifact.getName());
        Assert.assertEquals("2.0", artifact.getVersion());
        wsdlUuid = artifact.getUuid();

        // Assertions for artifact 3 (PO.xml)
        httpResp = respMap.get("<core/PO.xml@package>");
        Assert.assertEquals(200, httpResp.getCode());
        Assert.assertEquals("OK", httpResp.getStatus());
        entry = (Entry) httpResp.getBody();
        artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("PO.xml", artifact.getName());
        Assert.assertEquals("3.0", artifact.getVersion());
        xmlUuid = artifact.getUuid();
    } finally {
        IOUtils.closeQuietly(xsd1ContentStream);
        IOUtils.closeQuietly(wsdlContentStream);
        ArtificerArchive.closeQuietly(archive);
        IOUtils.closeQuietly(zipStream);
        FileUtils.deleteQuietly(zipFile);
    }

    // Verify by querying
    // Do a query using GET with query params
    Map<String, BaseArtifactType> artyMap = new HashMap<String, BaseArtifactType>();
    request = clientRequest("/s-ramp/xsd/XsdDocument");
    ClientResponse<Feed> response = request.get(Feed.class);
    Feed feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/xsd/XsdDocument/" + uuid);
        BaseArtifactType artifact = ArtificerAtomUtils
                .unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = clientRequest("/s-ramp/wsdl/WsdlDocument");
    response = request.get(Feed.class);
    feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/wsdl/WsdlDocument/" + uuid);
        BaseArtifactType artifact = ArtificerAtomUtils
                .unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = clientRequest("/s-ramp/core/XmlDocument");
    response = request.get(Feed.class);
    feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/core/XmlDocument/" + uuid);
        BaseArtifactType artifact = ArtificerAtomUtils
                .unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }

    Assert.assertEquals(3, artyMap.size());

    // Assertions for artifact 1 (PO.xsd)
    BaseArtifactType artifact = artyMap.get(xsdUuid);
    Assert.assertEquals("PO.xsd", artifact.getName());
    Assert.assertNull(artifact.getVersion());

    // Assertions for artifact 2 (sample.wsdl)
    artifact = artyMap.get(wsdlUuid);
    Assert.assertEquals("sample.wsdl", artifact.getName());
    Assert.assertEquals("2.0", artifact.getVersion());

    // Assertions for artifact 3 (PO.xml)
    artifact = artyMap.get(xmlUuid);
    Assert.assertEquals("PO.xml", artifact.getName());
    Assert.assertEquals("3.0", artifact.getVersion());
}

From source file:org.artificer.ui.server.servlets.ArtifactUploadServlet.java

/**
 * Uploads a single artifact to the S-RAMP repository.
 * @param artifactType// w w w  . j  av  a  2 s . co m
 * @param fileName
 * @param tempFile
 * @param responseParams
 * @throws Exception
 */
private void uploadSingleArtifact(String artifactType, String fileName, File tempFile,
        Map<String, String> responseParams) throws Exception {
    InputStream contentStream = null;
    try {
        contentStream = FileUtils.openInputStream(tempFile);
        BaseArtifactType artifact;
        if (artifactType != null) {
            artifact = ArtificerApiClientAccessor.getClient().uploadArtifact(ArtifactType.valueOf(artifactType),
                    contentStream, fileName);
        } else {
            artifact = ArtificerApiClientAccessor.getClient().uploadArtifact(contentStream, fileName);
        }
        ArtifactType responseArtifactType = ArtifactType.valueOf(artifact);
        responseParams.put("model", responseArtifactType.getModel());
        responseParams.put("type", responseArtifactType.getType());
        responseParams.put("uuid", artifact.getUuid());
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

From source file:org.artificer.ui.server.servlets.OntologyUploadServlet.java

/**
 * Uploads a single ontology to the S-RAMP repository.
 * @param tempFile//from ww  w. j  a  v a2s  . c  o m
 * @param responseParams
 * @throws Exception
 */
private void uploadSingleOntology(File tempFile, Map<String, String> responseParams) throws Exception {
    InputStream contentStream = null;
    try {
        contentStream = FileUtils.openInputStream(tempFile);
        RDF ontology = ArtificerApiClientAccessor.getClient().uploadOntology(contentStream);

        if (ontology.getOtherAttributes() != null) {
            responseParams.put("namespace", ontology.getOtherAttributes()
                    .get(new QName("http://www.w3.org/XML/1998/namespace", "base")));
            QName uuid = new QName(ArtificerConstants.SRAMP_NS, "uuid");
            if (ontology.getOtherAttributes().get(uuid) != null) {
                responseParams.put("uuid", ontology.getOtherAttributes().get(uuid));
            }
        }

        responseParams.put("id", ontology.getOntology().getID());
        responseParams.put("label", ontology.getOntology().getLabel());
        responseParams.put("comment", ontology.getOntology().getComment());
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Loads a BDVal model from disk. BDVal models are generated with the
 * {@link org.bdval.DiscoverAndValidate} tools (BDVal).
 *
 * @param options specific options to use when loading the model
 * @throws IOException            if there is a problem accessing the model
 * @throws ClassNotFoundException if the type of the model is not recognized
 *///from w  w  w  .  j a v a  2  s.c  om
public void load(final DAVOptions options) throws IOException, ClassNotFoundException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }
    properties.clear();
    properties.setDelimiterParsingDisabled(true);
    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));

            // the platform is more than one entry in the zip, so here we pass the whole zip
            trainingPlatform = options.trainingPlatform = loadPlatform(zipFile);

            if (isConsensusModel()) {
                int index = 0;
                final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>();
                String nextFilename;
                while ((nextFilename = (String) properties
                        .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) {
                    modelJurorFilePrefixes.add(nextFilename);
                    index++;
                }

                delegate = new ConsensusBDVModel(modelFilenamePrefix,
                        modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()]));
                delegate.load(options);
                setGeneList(convertTrainingPlatformToGeneList(options));
                return;
            } else {
                probesetScaleMeanMap = options.probesetScaleMeanMap = loadMeansMap(
                        zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(meansMapFilename))));
                probesetScaleRangeMap = options.probesetScaleRangeMap = loadRangeMap(
                        zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(rangeMapFilename))));
                setGeneList(convertTrainingPlatformToGeneList(options));
            }

            final String modelParameters = properties.getString("training.classifier.parameters");

            LOG.info("Loading model " + modelFilename);
            final InputStream modelStream = zipFile
                    .getInputStream(zipFile.getEntry(FilenameUtils.getName(modelFilename)));
            helper = ClassificationModel.load(modelStream, modelParameters);
            LOG.info("Model loaded.");

            options.classiferClass = helper.classifier.getClass();
            // we don't have a way to inspect the saved model for parameters used during training:
            options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters);
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
        final Properties properties = loadProperties(FileUtils.openInputStream(propertyFile), options);

        trainingPlatform = options.trainingPlatform = (GEOPlatformIndexed) BinIO.loadObject(platformFilename);

        if (isConsensusModel()) {
            int index = 0;
            final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>();
            String nextFilename = null;
            while ((nextFilename = (String) properties
                    .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) {
                modelJurorFilePrefixes.add(nextFilename);
                index++;
            }

            delegate = new ConsensusBDVModel(modelFilenamePrefix,
                    modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()]));
            delegate.load(options);
            setGeneList(convertTrainingPlatformToGeneList(options));
            return;
        } else {
            probesetScaleMeanMap = options.probesetScaleMeanMap = (Object2DoubleMap<MutableString>) BinIO
                    .loadObject(modelFilenamePrefix + ".means");
            if (LOG.isDebugEnabled()) {
                LOG.debug("Number of entries in means map = " + probesetScaleMeanMap.size());
            }
            probesetScaleRangeMap = options.probesetScaleRangeMap = (Object2DoubleMap<MutableString>) BinIO
                    .loadObject(modelFilenamePrefix + ".ranges");
            if (LOG.isDebugEnabled()) {
                LOG.debug("Number of entries in range map = " + probesetScaleRangeMap.size());
            }
            setGeneList(convertTrainingPlatformToGeneList(options));
        }

        final String modelParameters = properties.getString("training.classifier.parameters");

        LOG.info("Loading model " + modelFilename);
        helper = ClassificationModel.load(modelFilename, modelParameters);
        LOG.info("Model loaded.");

        options.classiferClass = helper.classifier.getClass();
        // we don't have a way to inspect the saved model for parameters used during training:
        options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters);
    }
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * @param options specific options to use when loading the properties
 * @throws IOException if there is a problem accessing the properties
 *//*  w w w  .  j a va2s. c o m*/
private void loadProperties(final DAVOptions options) throws IOException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }

    properties.clear();

    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        if (propertyFile.exists() && propertyFile.canRead()) {
            LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
            properties.addAll(loadProperties(FileUtils.openInputStream(propertyFile), options));
        }
    }
}

From source file:org.bdval.DAVMode.java

/**
 * Reads data from a file and stores it into a {@link edu.mssm.crover.tables.Table}.
 *
 * @param fileName Name of the file to read
 * @return A table that contains data read from the input file
 * @throws SyntaxErrorException       if there is an error in the file
 * @throws IOException                if the input file cannot be read
 * @throws UnsupportedFormatException if the file format is not recognized
 *///  ww  w  .j av  a  2  s .  c  om
protected Table readInputFile(final String fileName)
        throws IOException, SyntaxErrorException, UnsupportedFormatException {
    System.out.print("Reading input " + fileName + "... ");
    final Table table;
    Reader reader = null;
    try {
        // get a reader object for the file and store the file extension
        final InputStream inputStream = FileUtils.openInputStream(new File(fileName));
        String fileExtension = FilenameUtils.getExtension(fileName);
        if ("gz".equalsIgnoreCase(fileExtension)) {
            reader = new InputStreamReader(new GZIPInputStream(inputStream));
            // strip the ".gz" to get the "real" extension
            fileExtension = FilenameUtils.getExtension(FilenameUtils.getBaseName(fileName));
        } else {
            reader = new InputStreamReader(inputStream);
        }

        if ("soft".equalsIgnoreCase(fileExtension)) {
            if (fileName.contains("GDS")) { // GEO dataset
                final TableReader tableReader = new GeoDataSetReader();
                table = tableReader.read(reader);
            } else if (fileName.contains("GSE")) { // GEO series
                table = readGeoSeries(reader);
            } else {
                throw new UnsupportedFormatException(fileName);
            }
        } else if ("res".equalsIgnoreCase(fileExtension)) {
            final TableReader tableReader = new WhiteheadResReader();
            table = tableReader.read(reader);
        } else if ("tmm".equalsIgnoreCase(fileExtension)) {
            final TableReader tableReader = new ColumbiaTmmReader();
            table = tableReader.read(reader);
        } else if ("iconix".equalsIgnoreCase(fileExtension)) {
            final TableReader tableReader = new IconixReader();
            table = tableReader.read(reader);
        } else if ("cologne".equalsIgnoreCase(fileExtension)) {
            final TableReader tableReader = new CologneReader();
            table = tableReader.read(reader);
        } else {
            throw new UnsupportedFormatException(fileName);
        }

        if (table == null) {
            System.err.println("The input file could not be read. ");
            System.exit(1);
        }
        System.out.println("done");
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return table;
}

From source file:org.broadinstitute.gatk.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run./*  w ww .jav  a2s  .  c  o  m*/
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        String message = String.format("Unable to start command: %s\nReason: %s",
                StringUtils.join(builder.command(), " "), e.getMessage());
        throw new ReviewedGATKException(message);
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedGATKException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedGATKException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedGATKException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedGATKException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:org.broadinstitute.sting.gatk.report.GATKReportParser.java

public void parse(File file) throws IOException {
    InputStream stream = FileUtils.openInputStream(file);
    try {//from  w  w  w.  j ava 2 s .c o  m
        parse(stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.broadinstitute.sting.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run.// ww  w .  j  ava2s . c  om
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        throw new ReviewedStingException(
                "Unable to start command: " + StringUtils.join(builder.command(), " "));
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedStingException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedStingException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedStingException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedStingException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:org.carewebframework.help.chm.maven.ChmSource.java

/**
 * Wraps a chm file as an IResourceIterator.
 * // w  ww . j  av a2  s. c o  m
 * @param chmFile The chm file.
 */
public ChmSource(String chmFile) {
    try (InputStream inp = FileUtils.openInputStream(new File(chmFile));) {
        chmExtractor = new ChmExtractor(inp);
        entries = buildEntryList();
        iterator = entries.iterator();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}