Example usage for java.lang ProcessBuilder environment

List of usage examples for java.lang ProcessBuilder environment

Introduction

In this page you can find the example usage for java.lang ProcessBuilder environment.

Prototype

Map environment

To view the source code for java.lang ProcessBuilder environment.

Click Source Link

Usage

From source file:org.jboss.qa.jenkins.test.executor.utils.MavenCli.java

public void run() throws Exception {
    final List<String> cmd = new ArrayList<>();

    // Maven//from w  ww. j a va  2  s .c  o m
    if (OSDetector.isWindows()) {
        // TODO(mbasovni): Not yet tested!
        cmd.add("cmd");
        cmd.add("/c");
        cmd.add(mavenHome + "/bin/mvn.bat");
    } else {
        cmd.add("/bin/bash");
        cmd.add(mavenHome + "/bin/mvn");
    }

    // Maven opts
    if (xms != null) {
        mavenOpts.add("-Xms" + xms);
    }
    if (xmx != null) {
        mavenOpts.add("-Xmx" + xmx);
    }
    if (maxPermSize != null) {
        mavenOpts.add("-XX:MaxPermSize=" + maxPermSize);
    }

    // Path to POM file
    cmd.add("-f");
    cmd.add(pom.getAbsolutePath());

    cmd.addAll(goals);

    // Profiles
    if (!profiles.isEmpty()) {
        cmd.add("-P" + StringUtils.join(profiles, ","));
    }

    // Projects
    if (!projects.isEmpty()) {
        cmd.add("-pl");
        cmd.add(StringUtils.join(projects, ","));
    }

    // If project list is specified, also build projects required by the list
    if (alsoMake) {
        cmd.add("-am");
    }

    // Only fail the build afterwards; allow all non-impacted builds to continue
    if (failAtEnd) {
        cmd.add("-fae");
    }

    // System properties
    for (Map.Entry<String, String> entry : sysProps.entrySet()) {
        cmd.add(String.format("-D%s=%s", entry.getKey(), entry.getValue()));
    }

    if (params != null) {
        cmd.addAll(params);
    }

    final ProcessBuilder processBuilder = new ProcessBuilder(cmd);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    processBuilder.environment().put("JAVA_HOME", javaHome.getAbsolutePath());
    processBuilder.environment().put("M2_HOME", mavenHome.getAbsolutePath());
    processBuilder.environment().put("MAVEN_OTPS", StringUtils.join(mavenOpts, " "));

    log.debug("===========");
    log.debug("Process arguments: " + cmd.toString());
    log.debug("JAVA_HOME={}", processBuilder.environment().get("JAVA_HOME"));
    log.debug("M2_HOME={}", processBuilder.environment().get("M2_HOME"));
    log.debug("MAVEN_OTPS={}", processBuilder.environment().get("MAVEN_OTPS"));

    final Process process = processBuilder.start();
    process.waitFor();

    if (process.exitValue() != 0) {
        log.error("Maven execution failed with exit code: " + process.exitValue());
    }
}

From source file:com.netflix.genie.agent.execution.statemachine.actions.SetUpJobAction.java

private File createJobEnvironmentFile(final File jobDirectory, final List<File> setUpFiles,
        final Map<String, String> serverProvidedEnvironment, final Map<String, String> extraEnvironment)
        throws SetUpJobException {
    final Path genieDirectory = PathUtils.jobGenieDirectoryPath(jobDirectory);
    final Path envScriptPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE);
    final Path envScriptLogPath = PathUtils.composePath(genieDirectory, JobConstants.LOGS_PATH_VAR,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_LOG_FILE_NAME);
    final Path envScriptOutputPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_OUTPUT_FILE_NAME);

    // Copy env script from resources to genie directory
    try {/* w ww.  ja va2  s. co m*/
        Files.copy(new ClassPathResource(JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE).getInputStream(),
                envScriptPath, StandardCopyOption.REPLACE_EXISTING);
        // Make executable
        envScriptPath.toFile().setExecutable(true, true);
    } catch (final IOException e) {
        throw new SetUpJobException("Could not copy environment script resource: ", e);
    }

    // Set up process that executes the script
    final ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

    processBuilder.environment().putAll(serverProvidedEnvironment);
    processBuilder.environment().putAll(extraEnvironment);

    final List<String> commandArgs = Lists.newArrayList(envScriptPath.toString(),
            envScriptOutputPath.toString(), envScriptLogPath.toString());

    setUpFiles.forEach(f -> commandArgs.add(f.getAbsolutePath()));

    processBuilder.command(commandArgs);

    // Run the setup script
    final int exitCode;
    try {
        exitCode = processBuilder.start().waitFor();
    } catch (final IOException e) {
        throw new SetUpJobException("Could not execute environment setup script", e);
    } catch (final InterruptedException e) {
        throw new SetUpJobException("Interrupted while waiting for environment setup script", e);
    }

    if (exitCode != 0) {
        throw new SetUpJobException("Non-zero exit code from environment setup script: " + exitCode);
    }

    // Check and return the output file
    final File envScriptOutputFile = envScriptOutputPath.toFile();

    if (!envScriptOutputFile.exists()) {
        throw new SetUpJobException("Expected output file does not exist: " + envScriptOutputPath.toString());
    }

    return envScriptOutputFile;
}

From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java

/**
 * Constructs and executes a SOAP message.  For {@code basic} authentication, YADA uses the 
 * java soap api, and the {@link SOAPConnection} object stored in the query object.  For 
 * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC}
 * in {@link #YADA_BIN}. /*w  w w  .  j a  va 2  s. c om*/
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    String result = "";
    resetCountParameter(yq);
    SOAPConnection connection = (SOAPConnection) yq.getConnection();
    for (int row = 0; row < yq.getData().size(); row++) {
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();
        String soapUrl = yq.getSoap(row);

        try {
            this.endpoint = new URL(soapUrl);
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes());

            // Assume a SOAP message was built previously
            MimeHeaders mimeHeaders = message.getMimeHeaders();
            if ("basic".equals(this.soapAuth.toLowerCase())) {
                mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken));
                mimeHeaders.addHeader("SOAPAction", this.soapAction);
                mimeHeaders.addHeader("Content-Type", "text/xml");
                SOAPHeader header = message.getSOAPHeader();
                SOAPBody body = message.getSOAPBody();
                header.detachNode();

                l.debug("query:\n" + this.queryString);

                try {
                    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new ByteArrayInputStream(this.soapData.getBytes()));

                    //SOAPBodyElement docElement = 
                    body.addDocument(xml);

                    Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass));

                    SOAPMessage response = connection.call(message, this.endpoint);
                    try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) {
                        response.writeTo(responseOutputStream);
                        result = responseOutputStream.toString();
                    }
                } catch (IOException e) {
                    String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
                l.debug("SOAP Body:\n" + result);
            } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase())
                    || "negotiate".equals(this.soapAuth.toLowerCase())) {
                ArrayList<String> args = new ArrayList<>();
                args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC);
                args.add("-X");
                args.add("-s");
                args.add(this.soapSource + this.soapPath);
                args.add("-u");
                args.add(this.soapDomain + "\\" + this.soapUser);
                args.add("-p");
                args.add(this.soapPass);
                args.add("-a");
                args.add(this.soapAuth);
                args.add("-q");
                args.add(this.soapData);
                args.add("-t");
                args.add(this.soapAction);
                String[] cmds = args.toArray(new String[0]);
                l.debug("Executing soap request via script: " + Arrays.toString(cmds));
                String s = null;
                try {
                    ProcessBuilder pb = new ProcessBuilder(args);
                    l.debug(pb.environment().toString());
                    pb.redirectErrorStream(true);
                    Process p = pb.start();
                    try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        while ((s = si.readLine()) != null) {
                            l.debug(s);
                            if (null == result) {
                                result = "";
                            }
                            result += s;
                        }
                    }
                } catch (IOException e) {
                    String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'.  Make sure the curl executable is still accessible.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
            }
        } catch (SOAPException e) {
            String msg = "There was a problem creating or executing the SOAP message, or receiving the response.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (SAXException e) {
            String msg = "Unable to parse SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (ParserConfigurationException e) {
            String msg = "There was a problem creating the xml document for the SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (YADAResourceException e) {
            String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC;
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (MalformedURLException e) {
            String msg = "Can't create URL from provided source and path.";
            throw new YADAAdaptorExecutionException(msg, e);
        } finally {
            try {
                ConnectionFactory.releaseResources(connection, yq.getSoap().get(0));
            } catch (YADAConnectionException e) {
                l.error(e.getMessage());
            }
        }

        yqr.addResult(row, result);

    }

}

From source file:com.mgmtp.jfunk.core.ui.JFunkFrame.java

private void runScripts() {
    try {/*from   w  w  w  .  j  a v a 2s  .co m*/
        TreePath[] paths = tree.getSelectionPaths();

        if (paths == null) {
            JOptionPane.showMessageDialog(JFunkFrame.this, "No script(s) selected!", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        String testSystem;
        boolean parallel = false;
        if (StringUtils.equals((String) parallelComboBox.getSelectedItem(), "yes")) {
            parallel = true;
        }
        testSystem = testSystemsModel.getSelectedItem();

        int threads = (Integer) threadCountComboBox.getSelectedItem();

        List<String> commandsList = new ArrayList<String>(paths.length + 5);
        commandsList.add("cmd.exe");
        commandsList.add("/X");
        commandsList.add("/C");
        commandsList.add("start");
        commandsList.add("run_testskript.bat");
        //Threadcount wird als argument weiter gereicht.
        commandsList.add("-threadcount=" + threads);
        //Flag parallel wird als Parameter weiter gereicht.
        if (parallel) {
            commandsList.add("-parallel");
        }

        if (paths.length == 1) {
            commandsList.add(((File) paths[0].getLastPathComponent()).getPath());
        } else {
            boolean hasScriptOrDir = false;
            for (TreePath path : paths) {
                File file = (File) path.getLastPathComponent();
                if (file.isFile()) {
                    commandsList.add(file.getPath());
                    hasScriptOrDir = true;
                }
            }
            if (!hasScriptOrDir) {
                // Es wurden nur Verzeichnisse ausgewhlt.
                // Erstes Verzeichnis nehmen!
                commandsList.add(((File) paths[0].getLastPathComponent()).getPath());
            }
        }

        final ProcessBuilder pb = new ProcessBuilder(commandsList);
        pb.environment().put("EXIT_AFTER_RUNNING", "true");
        StringBuilder opts = new StringBuilder(
                "-Djfunk.props.file=" + jFunkPropertyFilesModel.getSelectedItem());
        opts.append(" -Dtestsystem=" + testSystem);
        String mailConfig = mailConfigurationsModel.getSelectedItem();
        if (!StringUtils.equals(mailConfig, "default")) {
            opts.append(" -Dsystem.properties.mailconfig=email_accounts/" + mailConfig + "." + PROPS_SUFFIX);
        }
        pb.environment().put("APP_OPTS", opts.toString());
        pb.start();
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
        JOptionPane.showMessageDialog(JFunkFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:io.mesosphere.mesos.frameworks.cassandra.executor.ProdObjectFactory.java

@Override
@NotNull//from  w  w w  .ja v a2 s .com
public WrappedProcess launchCassandraNodeTask(@NotNull final Marker taskIdMarker,
        @NotNull final CassandraServerRunTask serverRunTask) throws LaunchNodeException {
    try {
        writeCassandraServerConfig(taskIdMarker, serverRunTask.getVersion(),
                serverRunTask.getCassandraServerConfig());
    } catch (final IOException e) {
        throw new LaunchNodeException("Failed to prepare instance files", e);
    }

    final ProcessBuilder processBuilder = new ProcessBuilder(serverRunTask.getCommandList())
            .directory(new File(System.getProperty("user.dir")))
            .redirectOutput(new File("cassandra-stdout.log")).redirectError(new File("cassandra-stderr.log"));
    for (final TaskEnv.Entry entry : serverRunTask.getCassandraServerConfig().getTaskEnv().getVariablesList()) {
        processBuilder.environment().put(entry.getName(), entry.getValue());
    }
    processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home"));
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting Process: {}", processBuilderToString(processBuilder));
    try {
        return new ProdWrappedProcess(processBuilder.start());
    } catch (final IOException e) {
        throw new LaunchNodeException("Failed to start process", e);
    }
}

From source file:org.godhuli.rhipe.RHMRHelper.java

void setup(Configuration cfg, String argv, boolean doPipe) {
    try {//from  ww  w .  ja va  2 s.co  m
        //        InetAddress addr = InetAddress.getLocalHost();
        //        hostname = addr.getHostName();
        doPartitionRelatedSetup(cfg);
        String squote = cfg.get("rhipe_string_quote");
        if (squote == null)
            squote = "";

        REXPHelper.setFieldSep(cfg.get("mapred.field.separator", " "));
        REXPHelper.setStringQuote(squote);

        BUFFER_SIZE = cfg.getInt("rhipe_stream_buffer", 10 * 1024);
        joinDelay_ = cfg.getLong("rhipe_joindelay_milli", 0);
        nonZeroExitIsFailure_ = cfg.getBoolean("rhipe_non_zero_exit_is_failure", true);
        doPipe_ = doPipe;
        thisfs = FileSystem.get(cfg);

        Class<?> _kc = null;

        if (callID.equals("Mapper")) {
            if (cfg.getInt("mapred.reduce.tasks", 0) == 0)
                _kc = Class.forName(cfg.get("rhipe_outputformat_keyclass"));
            else
                _kc = Class.forName(cfg.get("rhipe_map_output_keyclass"));
        } else {
            _kc = Class.forName(cfg.get("rhipe_outputformat_keyclass"));
        }
        keyclass = _kc.asSubclass(RHBytesWritable.class);

        if (cfg.get("rhipe_output_folder") != null)
            outputFolder = new Path(cfg.get("rhipe_output_folder"));
        if (!doPipe_)
            return;
        copyFile = cfg.get("rhipe_copy_file").equals("TRUE") ? true : false;
        String[] argvSplit = argv.split(" ");
        String prog = argvSplit[0];
        Environment childEnv = (Environment) env().clone();
        cfg.set("io_sort_mb", cfg.get("io.sort.mb"));
        addJobConfToEnvironment(cfg, childEnv);
        childEnv.put("TMPDIR", System.getProperty("java.io.tmpdir"));
        // Start the process
        ProcessBuilder builder = new ProcessBuilder(argvSplit);
        builder.environment().putAll(childEnv.toMap());
        sim = builder.start();
        clientOut_ = new DataOutputStream(new BufferedOutputStream(sim.getOutputStream(), BUFFER_SIZE));
        clientIn_ = new DataInputStream(new BufferedInputStream(sim.getInputStream(), BUFFER_SIZE));
        clientErr_ = new DataInputStream(new BufferedInputStream(sim.getErrorStream()));
        startTime_ = System.currentTimeMillis();
        LOG.info(callID + ":" + "Started external program:" + argv);
        errThread_ = new MRErrorThread();
        LOG.info(callID + ":" + "Started Error Thread");
        errThread_.start();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("configuration exception", e);
    }
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args, File outputFile)
        throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);//from www  .j a va 2  s.com
    pb.environment().put("BASEDIR", project.getBasedir().getAbsolutePath());
    final Process p;
    ByteArrayOutputStream stdoutBaos = null;
    ByteArrayOutputStream stderrBaos = null;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    if (outputFile == null) {
        stdoutBaos = new ByteArrayOutputStream();
        copyIO(p.getInputStream(), stdoutBaos);
    } else {
        try {
            copyIO(p.getInputStream(), new FileOutputStream(outputFile));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Failed to copy output to : " + outputFile.getAbsolutePath(), e);
        }
    }
    stderrBaos = new ByteArrayOutputStream();
    copyIO(p.getErrorStream(), stderrBaos);
    copyIO(System.in, p.getOutputStream());
    try {
        boolean error = false;
        if (p.waitFor() != 0) {
            error = true;
        }
        if (getLog().isDebugEnabled() && stdoutBaos != null) {
            getLog().debug(stdoutBaos.toString());
        }
        if (getLog().isErrorEnabled() && stderrBaos != null) {
            getLog().error(stderrBaos.toString());
        }
        if (error) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Create a BnfHeritrixController object.
 *
 * @param files/*  w  ww.  j  a  va  2 s .  c o  m*/
 *            Files that are used to set up Heritrix.
 */
public AbstractJMXHeritrixController(HeritrixFiles files) {
    ArgumentNotValid.checkNotNull(files, "HeritrixFile files");
    this.files = files;

    SystemUtils.checkPortNotUsed(guiPort);
    SystemUtils.checkPortNotUsed(jmxPort);

    hostName = SystemUtils.getLocalHostName();

    try {
        log.info("Starting Heritrix for " + this);
        /*
         * To start Heritrix, we need to do the following (taken from the
         * Heritrix startup shell script): - set heritrix.home to base dir
         * of Heritrix stuff - set com.sun.management.jmxremote.port to JMX
         * port - set com.sun.management.jmxremote.ssl to false - set
         * com.sun.management.jmxremote.password.file to JMX password file -
         * set heritrix.out to heritrix_out.log - set
         * java.protocol.handler.pkgs=org.archive.net - send processOutput &
         * stderr into heritrix.out - let the Heritrix GUI-webserver listen
         * on all available network interfaces: This is done with argument
         * "--bind /" (default is 127.0.0.1) - listen on a specific port
         * using the port argument: --port <GUI port>
         *
         * We also need to output something like the following to
         * heritrix.out: `date Starting heritrix uname -a java -version
         * JAVA_OPTS ulimit -a
         */
        File heritrixOutputFile = files.getHeritrixOutput();
        StringBuilder settingProperty = new StringBuilder();
        for (File file : Settings.getSettingsFiles()) {
            settingProperty.append(File.pathSeparator);

            String absolutePath = file.getAbsolutePath();
            // check that the settings files not only exist but
            // are readable
            boolean readable = new File(absolutePath).canRead();
            if (!readable) {
                final String errMsg = "The file '" + absolutePath + "' is missing. ";
                log.warn(errMsg);
                throw new IOFailure("Failed to read file '" + absolutePath + "'");
            }
            settingProperty.append(absolutePath);
        }
        if (settingProperty.length() > 0) {
            // delete last path-separator
            settingProperty.deleteCharAt(0);
        }

        List<String> allOpts = new LinkedList<String>();
        allOpts.add(new File(new File(System.getProperty("java.home"), "bin"), "java").getAbsolutePath());
        allOpts.add("-Xmx" + Settings.get(HarvesterSettings.HERITRIX_HEAP_SIZE));
        allOpts.add("-Dheritrix.home=" + files.getCrawlDir().getAbsolutePath());

        String jvmOptsStr = Settings.get(HarvesterSettings.HERITRIX_JVM_OPTS);
        if ((jvmOptsStr != null) && (!jvmOptsStr.isEmpty())) {
            String[] add = jvmOptsStr.split(" ");
            allOpts.addAll(Arrays.asList(add));
        }

        allOpts.add("-Dcom.sun.management.jmxremote.port=" + jmxPort);
        allOpts.add("-Dcom.sun.management.jmxremote.ssl=false");
        // check that JMX password and access files are readable.
        // TODO This should probably be extracted to a method?
        File passwordFile = files.getJmxPasswordFile();
        String pwAbsolutePath = passwordFile.getAbsolutePath();
        if (!passwordFile.canRead()) {
            final String errMsg = "Failed to read the password file '" + pwAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        File accessFile = files.getJmxAccessFile();
        String acAbsolutePath = accessFile.getAbsolutePath();
        if (!accessFile.canRead()) {
            final String errMsg = "Failed to read the access file '" + acAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        allOpts.add("-Dcom.sun.management.jmxremote.password.file=" + new File(pwAbsolutePath));
        allOpts.add("-Dcom.sun.management.jmxremote.access.file=" + new File(acAbsolutePath));
        allOpts.add("-Dheritrix.out=" + heritrixOutputFile.getAbsolutePath());
        allOpts.add("-Djava.protocol.handler.pkgs=org.archive.net");
        allOpts.add("-Ddk.netarkivet.settings.file=" + settingProperty);
        allOpts.add(Heritrix.class.getName());
        allOpts.add("--bind");
        allOpts.add("/");
        allOpts.add("--port=" + guiPort);
        allOpts.add("--admin=" + getHeritrixAdminName() + ":" + getHeritrixAdminPassword());

        String[] args = allOpts.toArray(new String[allOpts.size()]);
        log.info("Starting Heritrix process with args" + Arrays.toString(args));
        log.debug("The JMX timeout is set to " + TimeUtils.readableTimeInterval(JMXUtils.getJmxTimeout()));

        ProcessBuilder builder = new ProcessBuilder(args);

        updateEnvironment(builder.environment());
        FileUtils.copyDirectory(new File("lib/heritrix"), files.getCrawlDir());
        builder.directory(files.getCrawlDir());
        builder.redirectErrorStream(true);
        writeSystemInfo(heritrixOutputFile, builder);
        FileUtils.appendToFile(heritrixOutputFile, "Working directory: " + files.getCrawlDir());
        addProcessKillerHook();
        heritrixProcess = builder.start();
        ProcessUtils.writeProcessOutput(heritrixProcess.getInputStream(), heritrixOutputFile,
                collectionThreads);
    } catch (IOException e) {
        throw new IOFailure("Error starting Heritrix process", e);
    }
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, File dir, Writer pOut, Writer pErr)
        throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();

    int out = 0;//from w  w w .ja  v a 2  s  .  com
    String pCmdString = ArrayUtils.toString(pCmd);
    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = Runtime.getRuntime().exec(pCmd, null, dir);
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmd + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, Writer pOut, Writer pErr) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();

    int out = 0;/*from   w  ww .j  a v a2s . c o  m*/
    String pCmdString = ArrayUtils.toString(pCmd);
    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = Runtime.getRuntime().exec(pCmd);
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } catch (Exception e) {
        //System.out.println(e.fillInStackTrace().toString());
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms");
    }

    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}