Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process with the specified environment and working directory.

Usage

From source file:de.unibi.cebitec.bibiserv.web.beans.runinthecloud.BashExecutor.java

/**
 * executeGridStarterScript starts the whole grid creation-procedure. One
 * the one hand it executes the just created startGrid.sh, scans in its
 * output and brings it to the JSF result-panel on confirmation.xhtml. On
 * the other side, at the end, it reads in the grid.properties file which
 * contains e.g. the public-dns of the EC2 instance which is needed to
 * redirect to the instance. All important informations from the
 * grid.properties will get stored to the db and can be easily looked up at
 * the BiBiServ-KeyChainModule.//from  ww w  .  j a  v  a2 s  .  com
 */
private void executeGridStarterScript() {
    final File bashFile = new File(tempDirectoryPath.toFile(), "");
    final String username = user.getId();

    Thread executeAndReadThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                Runtime r = Runtime.getRuntime();
                /**
                 * Start script as process.
                 */
                process = r.exec("/bin/bash startGrid.sh", null, bashFile.getAbsoluteFile());

                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

                /**
                 * Errorstream scanning.
                 */
                //                    BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    result.append(inputLine);
                    result.append("\n");
                }

                in.close();
                /**
                 * Read grid.properties to redirect to Ec2-instance.
                 */
                File gridInformation = new File(tempDirectoryPath.toFile(), gridPropertiesFile);
                InputStreamReader isr = new InputStreamReader(gridInformation.toURI().toURL().openStream());
                Properties gridJobInfo = new Properties();
                gridJobInfo.load(isr);
                String masterNodeDNS = gridJobInfo.getProperty("BIBIGRID_MASTER");
                String clusterId = gridJobInfo.getProperty("clusterId");
                redirectAddress.delete(0, redirectAddress.length());
                redirectAddress.append("http://");
                redirectAddress.append(masterNodeDNS);
                redirectAddress.append(":8080/");
                redirectAddress.append(toolID);

                dc.insertUniqueFolderID(username, tempDirectoryPath.getFileName().toString(), true);
                dc.insertJobIdAndRedirectToUniqueFolder(clusterId, redirectAddress.toString(),
                        tempDirectoryPath);

                readCompletely = true;
                active = false;
            } catch (IOException iex) {
                log.error(iex.getMessage(), iex);
            }
        }
    });
    executeAndReadThread.start();
}

From source file:eu.scape_project.tool.toolwrapper.toolwrapper_bash_debian_generator.DebianBashWrapperGenerator.java

private boolean buildPackage() {
    boolean success = true;
    log.info("generatePackage starting now...");
    Runtime rt = Runtime.getRuntime();
    BufferedReader br = null, br2 = null;
    try {//from w  w  w.  j a  v a  2  s . c  om
        // / usr/bin/dpkg-buildpackage
        Process exec = rt.exec("/usr/bin/debuild -us -uc -b", null, tempDebianDir);
        br = new BufferedReader(new InputStreamReader(exec.getInputStream(), Charset.defaultCharset()));
        br2 = new BufferedReader(new InputStreamReader(exec.getErrorStream(), Charset.defaultCharset()));
        success = (exec.waitFor() == 0);

        String line;
        while ((line = br.readLine()) != null) {
            log.info(line);
        }

        while ((line = br2.readLine()) != null) {
            log.error(line);
        }

    } catch (InterruptedException e) {
        success = false;
    } catch (IOException e) {
        success = false;
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(br2);
    }
    return success;
}

From source file:org.jboss.tools.tycho.sitegenerator.FetchSourcesFromManifests.java

private void createCombinedZipFile(File zipsDirectory, Set<File> zipFiles, int mode)
        throws MojoExecutionException {
    String combinedZipName = sourcesZip.getAbsolutePath();
    File combinedZipFile = new File(combinedZipName);
    String fullUnzipPath = zipsDirectory.getAbsolutePath() + File.separator + sourcesZipRootFolder;
    File fullUnzipDir = new File(fullUnzipPath);
    fullUnzipDir.mkdirs();//  w  ww.  j  av  a 2  s  . co m

    // unpack the zips into a temp folder
    for (File outputFile : zipFiles) {
        try {
            String zipFileName = zipsDirectory.getAbsolutePath() + File.separator + outputFile.getName();
            getLog().debug("Unpacking: " + zipFileName);
            getLog().debug("Unpack to: " + fullUnzipPath);
            // unpack zip
            unzipToDirectory(zipFileName, fullUnzipPath);
            File zipFile = new File(zipFileName);
            if (mode == PURGE_ZIPS) {
                // delete downloaded zip
                getLog().debug("Delete zip: " + zipFileName);
                zipFile.delete();
            } else if (mode == CACHE_ZIPS) {
                // move downloaded zip into cache folder
                getLog().debug("Cache " + zipFileName + " in " + this.zipCacheFolder);
                zipFile.renameTo(new File(this.zipCacheFolder, zipFile.getName()));
            }
        } catch (ZipException ex) {
            throw new MojoExecutionException(
                    "Error unpacking " + outputFile.toString() + " to " + fullUnzipPath, ex);
        } catch (IOException ex) {
            throw new MojoExecutionException(
                    "Error unpacking " + outputFile.toString() + " to " + fullUnzipPath, ex);
        }
    }

    // JBIDE-19814 - include local sources in jbosstools-project-SHA folder (jbosstools-build-sites or jbdevstudio-product)
    // get project name & SHA (from .git metadata) - needed for sourcesZipRootFolder/projectName-SHA folder
    Properties properties = new Properties();
    String projectURL = null;
    String projectName = null;
    String projectSHA = null;
    try {
        properties.load(new FileInputStream(
                this.project.getBuild().getDirectory() + File.separator + "git.properties")); // as defined by build-sites/aggregate/site/pom.xml
        getLog().debug("git.remote.origin.url = " + properties.get("git.remote.origin.url").toString()); // could be git@github.com:jbosstools/jbosstools... or git://github.com/jbosstools/jbosstools...
        projectURL = properties.get("git.remote.origin.url").toString();
        projectName = projectURL.replaceAll(".+/([^/]+).git", "$1");
        getLog().debug("git.commit.id = " + properties.get("git.commit.id").toString()); //5bfba37d042200ae71089678b6a441b57dd00d1f
        projectSHA = properties.get("git.commit.id").toString();
    } catch (IOException ex) {
        throw new MojoExecutionException(
                "Error loading " + this.project.getBuild().getDirectory() + File.separator + "git.properties",
                ex);
    }

    String localCleanSourcesDir = null;
    if (projectName != null) {
        if (projectSHA != null) {
            // might get projectName = git@github.com:dgolovin/jbdevstudio-product so scrub out invalid characters
            getLog().debug("projectName = " + projectName);
            localCleanSourcesDir = projectName.replaceAll("[@:/]+", "_") + "-" + projectSHA;
            getLog().debug("localCleanSourcesDir = " + localCleanSourcesDir);
        } else {
            throw new MojoExecutionException("Could not compute projectSHA!");
        }
    } else {
        throw new MojoExecutionException("Could not compute projectName or projectSHA!");
    }

    File repoRoot = null;
    try {
        repoRoot = GenerateRepositoryFacadeMojo.findRepoRoot(this.project.getBasedir());
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("Repo root not found in " + this.project.getBasedir(), ex);
    }
    getLog().debug("repoRoot = " + repoRoot);

    // clone local sources into combinedZipFile (dirty files revert to their clean state)
    File gitSourcesArchive = new File("/tmp/" + localCleanSourcesDir + ".zip"); // /tmp/jbosstools-build-sites-3df6b66f70691868e7cc4f1da70f1a0efb952dfc.zip
    getLog().debug("cd " + repoRoot + "; git archive --prefix " + localCleanSourcesDir + " -o "
            + gitSourcesArchive + " HEAD");
    String command = "git archive --prefix " + localCleanSourcesDir + "/ -o " + gitSourcesArchive + " HEAD";
    try {
        // Note: this can be run from any subfolder in the project tree, but if we run from the root we get everything (not just site/ but jbosstools-build-sites/aggregate/site/)
        // from http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command, null, repoRoot);
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
        errorGobbler.start();
        outputGobbler.start();
        int exitVal = proc.waitFor();
        getLog().debug("Runtime.getRuntime.exec() - exit value: " + exitVal);
        getLog().debug("Packed to: " + gitSourcesArchive);
        double filesize = gitSourcesArchive.length();
        getLog().debug(
                "Pack size: " + (filesize >= 1024 * 1024 ? String.format("%.1f", filesize / 1024 / 1024) + " M"
                        : String.format("%.1f", filesize / 1024) + " k"));
        unzipToDirectory(gitSourcesArchive, fullUnzipPath);
    } catch (IOException ex) {
        throw new MojoExecutionException(
                "Error cloning from " + repoRoot.toString() + " to " + gitSourcesArchive, ex);
    } catch (InterruptedException ex) {
        throw new MojoExecutionException(
                "Error cloning from " + repoRoot.toString() + " to " + gitSourcesArchive, ex);
    }

    // JBIDE-19798 - copy target/buildinfo/buildinfo*.json into sourcesZipRootFolder/buildinfo/
    File buildinfoFolder = new File(this.project.getBuild().getDirectory(), "buildinfo");
    if (buildinfoFolder.isDirectory()) {
        try {
            File buildinfoFolderCopy = new File(fullUnzipPath, "buildinfo");
            FileUtils.copyDirectory(buildinfoFolder, buildinfoFolderCopy);
            getLog().debug("Pack from: " + buildinfoFolderCopy);

            // remove dupe buildinfo/buildinfo_jbosstools-build-sites.json if projectName = jbosstools-build-sites (should not have an upstream that's the same as the local project)
            File dupeUpstreamBuildinfoFile = new File(
                    buildinfoFolderCopy + File.separator + "buildinfo_" + projectName + ".json");
            if (dupeUpstreamBuildinfoFile.isFile()) {
                dupeUpstreamBuildinfoFile.delete();
            }
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Error copying buildinfo files to " + fullUnzipPath + File.separator + "buildinfo", e);
        }
    } else {
        getLog().warn("No buildinfo files found in " + buildinfoFolder.toString());
    }

    // add the unzipped upstream sources & buildinfo into the existing local sources zip
    try {
        getLog().debug("Pack from: " + fullUnzipPath);
        zipDirectory(fullUnzipDir.getParentFile(), combinedZipFile);
        getLog().debug("Packed to: " + combinedZipFile.getAbsolutePath());
        double filesize = combinedZipFile.length();
        getLog().debug(
                "Pack size: " + (filesize >= 1024 * 1024 ? String.format("%.1f", filesize / 1024 / 1024) + " M"
                        : String.format("%.1f", filesize / 1024) + " k"));
    } catch (IOException e) {
        throw new MojoExecutionException("Error packing " + combinedZipFile, e);
    }

    // delete temp folder with upstream sources; delete temp zip with git archive sources
    try {
        getLog().debug("Delete dir: " + fullUnzipPath);
        FileUtils.deleteDirectory(new File(fullUnzipPath));
        gitSourcesArchive.delete();
    } catch (IOException ex) {
        throw new MojoExecutionException("IO Exception:", ex);
    }

}

From source file:org.alfresco.util.exec.RuntimeExec.java

/**
 * Executes the statement that this instance was constructed with an optional
 * timeout after which the command is asked to 
 * //w w  w  . ja va  2s.  co  m
 * @param properties the properties that the command might be executed with.
 * <code>null</code> properties will be treated as an empty string for substitution
 * purposes.
 * @param timeoutMs a timeout after which {@link Process#destroy()} is called.
 *        ignored if less than or equal to zero. Note this method does not guarantee
 *        to terminate the process (it is not a kill -9).
 * 
 * @return Returns the full execution results
 */
public ExecutionResult execute(Map<String, String> properties, final long timeoutMs) {
    int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1;

    // check that the command has been set
    if (command == null) {
        throw new AlfrescoRuntimeException("Runtime command has not been set: \n" + this);
    }

    // create the properties
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    String[] commandToExecute = null;
    try {
        // execute the command with full property replacement
        commandToExecute = getCommand(properties);
        final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory);
        process = thisProcess;
        if (timeoutMs > 0) {
            final String[] command = commandToExecute;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // Only try to kill the process if it is still running
                    try {
                        thisProcess.exitValue();
                    } catch (IllegalThreadStateException stillRunning) {
                        if (transformerDebugLogger.isDebugEnabled()) {
                            transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000)
                                    + " seconds). Killing process " + Arrays.deepToString(command));
                        }
                        thisProcess.destroy();
                    }
                }
            }, timeoutMs);
        }
    } catch (IOException e) {
        // The process could not be executed here, so just drop out with an appropriate error state
        String execOut = "";
        String execErr = e.getMessage();
        int exitValue = defaultFailureExitValue;
        ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut,
                execErr);
        logFullEnvironmentDump(result);
        return result;
    }

    // create the stream gobblers
    InputStreamReaderThread stdOutGobbler = new InputStreamReaderThread(process.getInputStream(), charset);
    InputStreamReaderThread stdErrGobbler = new InputStreamReaderThread(process.getErrorStream(), charset);

    // start gobbling
    stdOutGobbler.start();
    stdErrGobbler.start();

    // wait for the process to finish
    int exitValue = 0;
    try {
        if (waitForCompletion) {
            exitValue = process.waitFor();
        }
    } catch (InterruptedException e) {
        // process was interrupted - generate an error message
        stdErrGobbler.addToBuffer(e.toString());
        exitValue = defaultFailureExitValue;
    }

    if (waitForCompletion) {
        // ensure that the stream gobblers get to finish
        stdOutGobbler.waitForCompletion();
        stdErrGobbler.waitForCompletion();
    }

    // get the stream values
    String execOut = stdOutGobbler.getBuffer();
    String execErr = stdErrGobbler.getBuffer();

    // construct the return value
    ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut,
            execErr);

    // done
    logFullEnvironmentDump(result);
    return result;
}

From source file:org.gytheio.util.exec.RuntimeExec.java

/**
 * Executes the statement that this instance was constructed with an optional
 * timeout after which the command is asked to 
 * //from   ww w. jav  a2s .c o  m
 * @param properties the properties that the command might be executed with.
 * <code>null</code> properties will be treated as an empty string for substitution
 * purposes.
 * @param timeoutMs a timeout after which {@link Process#destroy()} is called.
 *        ignored if less than or equal to zero. Note this method does not guarantee
 *        to terminate the process (it is not a kill -9).
 * @param stdOutGobblerFactory the object used to create the output input stream reader
 *        If null the defaultInputStreamReaderThreadFactory will be used
 * @param stdErrGobblerFactory the object used to create the error input stream reader
 *        If null the defaultInputStreamReaderThreadFactory will be used
 * 
 * @return Returns the full execution results
 */
public ExecutionResult execute(Map<String, String> properties,
        InputStreamReaderThreadFactory stdOutGobblerFactory,
        InputStreamReaderThreadFactory stdErrGobblerFactory, final long timeoutMs) {
    int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1;

    // check that the command has been set
    if (command == null) {
        throw new GytheioRuntimeException("Runtime command has not been set: \n" + this);
    }

    if (stdOutGobblerFactory == null) {
        stdOutGobblerFactory = defaultInputStreamReaderThreadFactory;
    }
    if (stdErrGobblerFactory == null) {
        stdErrGobblerFactory = defaultInputStreamReaderThreadFactory;
    }

    // create the properties
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    String[] commandToExecute = null;
    try {
        // execute the command with full property replacement
        commandToExecute = getCommand(properties);
        final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory);
        process = thisProcess;
        if (timeoutMs > 0) {
            final String[] command = commandToExecute;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // Only try to kill the process if it is still running
                    try {
                        thisProcess.exitValue();
                    } catch (IllegalThreadStateException stillRunning) {
                        if (transformerDebugLogger.isDebugEnabled()) {
                            transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000)
                                    + " seconds). Killing process " + Arrays.deepToString(command));
                        }
                        thisProcess.destroy();
                    }
                }
            }, timeoutMs);
        }
    } catch (IOException e) {
        // The process could not be executed here, so just drop out with an appropriate error state
        String execOut = "";
        String execErr = e.getMessage();
        int exitValue = defaultFailureExitValue;
        ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut,
                execErr);
        logFullEnvironmentDump(result);
        return result;
    }

    // create the stream gobblers
    InputStreamReaderThread stdOutGobbler = stdOutGobblerFactory.createInstance(process.getInputStream(),
            charset);
    InputStreamReaderThread stdErrGobbler = stdErrGobblerFactory.createInstance(process.getErrorStream(),
            charset);

    // start gobbling
    stdOutGobbler.start();
    stdErrGobbler.start();

    // wait for the process to finish
    int exitValue = 0;
    try {
        if (waitForCompletion) {
            exitValue = process.waitFor();
        }
    } catch (InterruptedException e) {
        // process was interrupted - generate an error message
        stdErrGobbler.addToBuffer(e.toString());
        exitValue = defaultFailureExitValue;
    }

    if (waitForCompletion) {
        // ensure that the stream gobblers get to finish
        stdOutGobbler.waitForCompletion();
        stdErrGobbler.waitForCompletion();
    }

    // get the stream values
    String execOut = stdOutGobbler.getBuffer();
    String execErr = stdErrGobbler.getBuffer();

    // construct the return value
    ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut,
            execErr);

    // done
    logFullEnvironmentDump(result);
    return result;
}

From source file:org.smartfrog.avalanche.client.sf.apps.ca.InstallCA.java

public void generateCaCert(String passout, String validity) throws CAException {
    Runtime rt = Runtime.getRuntime();

    TxtFileHelper txt = new TxtFileHelper(confFile);
    String dirValue = null;//  w w  w  . j ava  2 s .  com
    try {
        if ((dirValue = txt.getValue(CAConstants.dir, CAConstants.separator, CAConstants.comment)) == null) {
            log.error("The value for 'dir' is not found in config file.");
            log.error("CA cannot be installed.");
            throw new CAException("The value for 'dir' is not found in config file.");
        }
    } catch (FileNotFoundException fnfe) {
        log.error("Error : ", fnfe);
        throw new CAException(fnfe);
    } catch (IOException ioe) {
        log.error("Error :", ioe);
        throw new CAException(ioe);
    }

    File configFile = new File(confFile);
    char sepChar = File.separatorChar;
    dirValue = dirValue.replace('\\', sepChar);
    dirValue = dirValue.replace('/', sepChar);
    File certDir = new File(dirValue);
    if (!FileUtils.checkDir(certDir)) {
        throw new CAException(
                "Error in accessing " + dirValue + "... " + "Please check log file for more information");
    }

    String cmd = new String(opensslDir + sepChar + "bin" + sepChar + "openssl");
    String privateKey = dirValue + sepChar + "private" + sepChar + "cakey.pem";
    String publicKey = dirValue + sepChar + CAConstants.caCertFile;

    cmd = cmd + " req -new -x509 -keyout " + privateKey + " -out " + publicKey + " -days " + validity
            + " -passout " + "pass:" + passout + " -config " + confFile;
    log.info("Cmd : " + cmd);

    BufferedReader cmdError = null;
    int exitVal = 0;
    try {
        Process p = rt.exec(cmd, null, certDir);
        cmdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        exitVal = p.waitFor();
        if (exitVal != 0) {
            log.error("Error in generating CA certificates...");
            String line = null;
            String error = null;
            if ((line = cmdError.readLine()) != null) {
                log.error(line);
                error = line;
                while ((line = cmdError.readLine()) != null) {
                    log.error(line);
                    error = error + "\n" + line;
                }
                throw new CAException(error);
            }
        }
    } catch (IOException ioe) {
        log.error(ioe);
        throw new CAException(ioe);
    } catch (InterruptedException ie) {
        log.error(ie);
        throw new CAException(ie);
    }

}

From source file:com.ephesoft.dcma.filebound.FileBoundExporter.java

private void executeCommand(final List<String> cmdList, final String connectionURL, final String userName,
        final String password, final String docFieldValues, final String loanNumberValue,
        final String projectName, final String loanNumberName, final String parameterFileName)
        throws DCMAApplicationException {
    InputStreamReader inputStreamReader = null;
    BufferedReader input = null;/* ww  w .j  av a  2  s.  c  om*/
    try {
        final Runtime runtime = Runtime.getRuntime();
        if (cmdList.isEmpty()) {
            LOGGER.error("No proper commands configured in resources");
            throw new DCMAApplicationException("No proper commands configured in resources");
        } else {
            String[] cmds = new String[cmdList.size()];
            for (int i = 0; i < cmdList.size(); i++) {
                if (cmdList.get(i).contains("cmd")) {
                    LOGGER.info("inside cmd");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("/c")) {
                    LOGGER.info("inside /c");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("FileBoundExport")) {
                    LOGGER.info("inside FileBoundExport");
                    cmds[i] = cmdList.get(i) + " \"" + connectionURL + "\" " + userName + " " + password + " \""
                            + projectName + FileBoundConstants.ESCAPED_SPACE + docFieldValues
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberName
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberValue
                            + FileBoundConstants.ESCAPED_SPACE + parameterFileName + "\"";
                }
            }
            LOGGER.info("command formed is :" + cmds[cmdList.size() - 1]);
            final Process process = runtime.exec(cmds, null,
                    new File(System.getenv(FileBoundConstants.FILEBOUND_BASE_PATH)));
            inputStreamReader = new InputStreamReader(process.getInputStream());
            input = new BufferedReader(inputStreamReader);
            String line = null;
            do {
                line = input.readLine();
                LOGGER.debug(line);
            } while (line != null);
            final int exitValue = process.exitValue();
            LOGGER.info("Command exited with error code no " + exitValue);
            if (exitValue != 0) {
                LOGGER.error("Non-zero exit value for filebound command found. So exiting the application");
                throw new DCMAApplicationException(
                        "Non-zero exit value for filebound command found. So exiting the application");
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while expoting ");
        throw new DCMAApplicationException("Exception while expoting ", e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
        } catch (IOException e) {
            LOGGER.error("Problem in closing stream");
        }
    }
}