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:io.wcm.maven.plugins.nodejs.mojo.Task.java

private void setNodePath(ProcessBuilder pbuilder, NodeInstallationInformation information) {
    final Map<String, String> environment = pbuilder.environment();
    String pathVariableName = PATH_VARIABLE_NAME;
    String pathValue = environment.get(pathVariableName);
    if (Os.isFamily(Os.FAMILY_WINDOWS) || Os.isFamily(Os.FAMILY_WIN9X)) {
        for (String key : environment.keySet()) {
            if (PATH_VARIABLE_NAME.equalsIgnoreCase(key)) {
                pathVariableName = key;//  w  w w.ja v  a 2 s  .  co m
                pathValue = environment.get(key);
            }
        }
    }
    if (pathValue == null) {
        environment.put(pathVariableName, information.getNodeExecutable().getParent());
    } else {
        environment.put(pathVariableName,
                information.getNodeExecutable().getParent() + File.pathSeparator + pathValue);
    }
}

From source file:husky.server.HuskyMaster.java

@Override
public void run() {
    try {/*  w w w .java  2  s .  c  o m*/
        LOG.info("Starting husky master process");
        ProcessBuilder mHuskyMasterProcess = new ProcessBuilder(getCommands());
        if (!mAppMaster.getLdLibraryPath().isEmpty()) {
            mHuskyMasterProcess.environment().put("LD_LIBRARY_PATH", mAppMaster.getLdLibraryPath());
        }
        mHuskyMasterProcess.redirectOutput(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"));
        mHuskyMasterProcess.redirectError(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr"));
        Process p = mHuskyMasterProcess.start();
        p.waitFor();
        if (p.exitValue() == 0) {
            LOG.info("Husky master exits successfully");
        } else {
            LOG.info("Husky master exits with code " + p.exitValue());
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, " Failed to start c++ husky master process: ", e);
    } finally {
        if (!mAppMaster.getLogPathToHDFS().isEmpty()) {
            try {
                mAppMaster.getFileSystem().copyFromLocalFile(false, true,
                        new Path[] { new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"),
                                new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr") },
                        new Path(mAppMaster.getLogPathToHDFS()));
            } catch (IOException e) {
                LOG.log(Level.INFO, "Failed to upload logs of husky master to hdfs", e);
            }
        }
    }
}

From source file:edu.uci.ics.asterix.event.management.EventExecutor.java

public void executeEvent(Node node, String script, List<String> args, boolean isDaemon, Cluster cluster,
        Pattern pattern, IOutputHandler outputHandler, AsterixEventServiceClient client) throws IOException {
    List<String> pargs = new ArrayList<String>();
    pargs.add("/bin/bash");
    pargs.add(client.getEventsHomeDir() + File.separator + AsterixEventServiceUtil.EVENT_DIR + File.separator
            + EXECUTE_SCRIPT);/*from  w w  w. j a  va2  s  . c  om*/
    StringBuffer envBuffer = new StringBuffer(IP_LOCATION + "=" + node.getClusterIp() + " ");
    boolean isMasterNode = node.getId().equals(cluster.getMasterNode().getId());

    if (!node.getId().equals(EventDriver.CLIENT_NODE_ID) && cluster.getEnv() != null) {
        for (Property p : cluster.getEnv().getProperty()) {
            if (p.getKey().equals("JAVA_HOME")) {
                String val = node.getJavaHome() == null ? p.getValue() : node.getJavaHome();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else if (p.getKey().equals(EventUtil.NC_JAVA_OPTS)) {
                if (!isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals(EventUtil.CC_JAVA_OPTS)) {
                if (isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals("LOG_DIR")) {
                String val = node.getLogDir() == null ? p.getValue() : node.getLogDir();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else {
                envBuffer.append(p.getKey() + "=" + p.getValue() + " ");
            }

        }
        pargs.add(cluster.getUsername() == null ? System.getProperty("user.name") : cluster.getUsername());
    }

    StringBuffer argBuffer = new StringBuffer();
    if (args != null && args.size() > 0) {
        for (String arg : args) {
            argBuffer.append(arg + " ");
        }
    }

    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().put(IP_LOCATION, node.getClusterIp());
    pb.environment().put(CLUSTER_ENV, envBuffer.toString());
    pb.environment().put(SCRIPT, script);
    pb.environment().put(ARGS, argBuffer.toString());
    pb.environment().put(DAEMON, isDaemon ? "true" : "false");

    Process p = pb.start();
    if (!isDaemon) {
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        StringWriter writer = new StringWriter();
        IOUtils.copy(bis, writer, "UTF-8");
        String result = writer.getBuffer().toString();
        OutputAnalysis analysis = outputHandler.reportEventOutput(pattern.getEvent(), result);
        if (!analysis.isExpected()) {
            throw new IOException(analysis.getErrorMessage() + result);
        }
    }
}

From source file:org.casbah.provider.openssl.OpenSslWrapper.java

public int executeCommand(InputStream input, OutputStream output, OutputStream error,
        final List<String> parameters) throws IOException, InterruptedException {
    List<String> fullParams = new ArrayList<String>(parameters);
    fullParams.add(0, opensslExecutable);
    ProcessBuilder processBuilder = new ProcessBuilder(fullParams);
    CyclicBarrier barrier = new CyclicBarrier(3);
    Map<String, String> env = processBuilder.environment();
    env.put(CASBAH_SSL_CA_ROOT, caRootDir.getAbsolutePath());
    Process proc = processBuilder.start();
    if (input != null) {
        BufferedOutputStream stdin = new BufferedOutputStream(proc.getOutputStream());
        IOUtils.copy(input, stdin);// ww w. j a v  a 2 s  .c om
        stdin.flush();
    }
    StreamConsumer outputConsumer = new StreamConsumer(output, proc.getInputStream(), barrier, TIMEOUT);
    StreamConsumer errorConsumer = new StreamConsumer(error, proc.getErrorStream(), barrier, TIMEOUT);
    outputConsumer.start();
    errorConsumer.start();
    int returnValue = proc.waitFor();
    try {
        barrier.await(TIMEOUT, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}

From source file:au.edu.unsw.cse.soc.federatedcloud.community.driven.cloudbase.connectors.docker.DockerConnector.java

@Override
public Result deploy(int resourceID) {
    String scriptFileLocation = "./tmp/" + resourceID + ".sh";
    //run the deployment script
    ProcessBuilder pb = new ProcessBuilder(scriptFileLocation);
    Map<String, String> env = pb.environment();
    pb.directory(new File("."));
    try {//  w  w w. java  2s.c o  m
        Process p = pb.start();

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            log.info(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            log.info(s);
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}

From source file:dk.netarkivet.wayback.aggregator.IndexAggregator.java

/**
 * Calls the Unix sort command with the options <code>$filesNames -o
 * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR.
 * <p>//from   www.  j  a v a2 s  . c  o  m
 * Sets the LC_ALL environment variable before making the call.
 *
 * @param files The files to merge and sort
 * @param outputFile The resulting sorted file
 * @param additionalArgs A list af extra arguments, which (if different from null) are added to the sort call.<p>
 * Note: If any of the args contain a whitespace the call will fail.
 */
private void processFiles(File[] files, File outputFile, List<String> additionalArgs) {
    if (files.length == 0) {
        // Empty file list will cause sort to wait for further input,
        // and the call will therefore never return
        return;
    }

    Process p = null;

    try {
        List<String> inputFileList = new LinkedList<String>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].exists() && files[i].isFile()) {
                inputFileList.add(files[i].getCanonicalPath());
            } else {
                log.warn("File " + files[i] + " doesn't exist or isn't a regular file, "
                        + "dropping from list of files to " + "sort and merge");
            }
        }
        List<String> cmd = new LinkedList<String>();
        // Prepare to run the unix sort command, see sort manual page for
        // details
        cmd.add("sort");
        cmd.addAll(inputFileList);
        cmd.add("-o");
        cmd.add(outputFile.getCanonicalPath());
        cmd.add("-T");
        cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR));
        if (additionalArgs != null && !additionalArgs.isEmpty()) {
            for (String argument : additionalArgs) {
                ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1,
                        "The argument '" + argument + "' contains spaces, this isn't allowed ");
            }
            cmd.addAll(additionalArgs);
        }
        ProcessBuilder pb = new ProcessBuilder(cmd);
        // Reset all locale definitions
        pb.environment().put("LC_ALL", "C");
        // Run the command in the user.dir directory
        pb.directory(new File(System.getProperty("user.dir")));
        p = pb.start();
        p.waitFor();
        if (p.exitValue() != 0) {
            log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue());
        }
    } catch (Exception e) {
        log.error("Failed to aggregate indexes ", e);
    }
}

From source file:alluxio.cli.AlluxioFrameworkIntegrationTest.java

private void startAlluxioFramework(Map<String, String> extraEnv) {
    String startScript = PathUtils.concatPath(Configuration.get(PropertyKey.HOME), "integration", "mesos",
            "bin", "alluxio-mesos-start.sh");
    ProcessBuilder pb = new ProcessBuilder(startScript, mMesosAddress);
    Map<String, String> env = pb.environment();
    env.putAll(extraEnv);/*w ww  .  ja v  a  2 s.c  o  m*/
    try {
        pb.start().waitFor();
    } catch (Exception e) {
        LOG.info("Failed to launch Alluxio on Mesos. Note that this test requires that "
                + "Mesos is currently running.");
        throw new RuntimeException(e);
    }
}

From source file:com.migratebird.script.runner.impl.Application.java

protected ProcessBuilder createProcessBuilder(List<String> commandWithArguments) {
    ProcessBuilder processBuilder = new ProcessBuilder(commandWithArguments);
    Map<String, String> processEnvironment = processBuilder.environment();
    processEnvironment.putAll(environmentVariables);
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}

From source file:org.geoserver.wfs.response.OGRWrapper.java

/**
 * Runs the specified command appending the output to the string builder and
 * returning the exit code/*from  w  ww.  j a  va2s  .c  om*/
 * 
 * @param cmd
 * @param sb
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
int run(List<String> cmd, StringBuilder sb) throws IOException, InterruptedException {
    // run the process and grab the output for error reporting purposes
    ProcessBuilder builder = new ProcessBuilder(cmd);
    if (gdalData != null)
        builder.environment().put("GDAL_DATA", gdalData);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null) {
        if (sb != null) {
            sb.append("\n");
            sb.append(line);
        }
    }
    return p.waitFor();
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

public void executeAll() throws IOException, InterruptedException {

    File target = new File("target");
    target.mkdir();/*w w w.  j  a v a  2  s . co  m*/

    ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean");
    Map<String, String> env = pb.environment();
    pb.directory(new File(homeDir, "linux"));
    File logFile = new File("log");
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    Process p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/make");
    pb.directory(new File(homeDir, "linux"));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf",
            "src/main/protobuf/sample.proto",
            "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl",
            "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf",
            "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}