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:com.cisco.dvbu.cmdline.vcs.spi.AbstractLifecycleListener.java

/**
 * Set the environment variables for the process
 *  /*from w  ww.j  a v a  2 s.  c  o m*/
 * @param processBuilder The process context
 */
private void setEnvironment(ProcessBuilder processBuilder) {

    // Setup the environment variables
    Map<String, String> env = processBuilder.environment();

    java.util.List<String> envList = new java.util.ArrayList<String>();
    // Retrieve the environment variables separated by a pipe
    envList = CommonUtils.getArgumentsList(envList, true, VCS_ENV, "|");
    // 2014-09-03 (cgoodric): make sure envList isn't empty
    if (envList != null) {
        // Loop through the list of VCS_ENV variables
        for (int i = 0; i < envList.size(); i++) {
            String envVar = envList.get(i).toString();
            // Retrieve the name=value pair
            java.util.StringTokenizer st = new java.util.StringTokenizer(envVar, "=");
            if (st.hasMoreTokens()) {
                // Retrieve the variable name token
                String property = st.nextToken();
                String propertyVal = "";
                try {
                    // Retrieve the variable value token
                    propertyVal = st.nextToken();
                } catch (Exception e) {
                }

                // Put the environment variable (name=value) pair back to the environment
                env.put(property, propertyVal);

                if (logger.isDebugEnabled()) {
                    logger.info(prefix + "Env Var: " + CommonUtils.maskCommand(envVar));
                }
            }
        }
    }
}

From source file:edu.umn.msi.tropix.common.execution.process.impl.ProcessFactoryImpl.java

public Process createProcess(final ProcessConfiguration processConfiguration) {
    final List<String> command = new LinkedList<String>();
    final String application = processConfiguration.getApplication();
    Preconditions.checkNotNull(application, "Attempted to create process with null application.");
    command.add(application);/*from w w  w . j a  va  2 s  . c om*/
    final List<String> arguments = processConfiguration.getArguments();
    if (arguments != null) {
        command.addAll(processConfiguration.getArguments());
    }
    LOG.trace("Creating process builder with commands " + Joiner.on(" ").join(command) + " in directory "
            + processConfiguration.getDirectory());
    final ProcessBuilder processBuilder = new ProcessBuilder(command);
    if (processConfiguration.getEnvironment() != null) {
        for (final Entry<String, String> entry : processConfiguration.getEnvironment().entrySet()) {
            processBuilder.environment().put(entry.getKey(), entry.getValue());
        }
    }
    processBuilder.directory(processConfiguration.getDirectory());

    java.lang.Process baseProcess = null;
    try {
        baseProcess = processBuilder.start();
    } catch (final IOException e) {
        throw new IllegalStateException(
                "Failed to start process corresponding to process configuration " + processConfiguration, e);
    }
    final ProcessImpl process = new ProcessImpl();
    process.setBaseProcess(baseProcess);
    return process;
}

From source file:org.jboss.tools.openshift.internal.common.core.util.CommandLocationLookupStrategy.java

/**
 * Use runtime.exec(String) /*  w  ww.ja  va2  s  . c  o  m*/
 * @param cmd
 * @return
 */
private Process createProcess(String[] cmd, boolean useSystemPath) {
    try {
        if (useSystemPath) {
            String pathresult = runCommand(pathCommand);
            ProcessBuilder pb = new ProcessBuilder(cmd);
            Map<String, String> env = pb.environment();
            env.put(pathvar, pathresult);
            return pb.start();
        } else {
            return Runtime.getRuntime().exec(cmd);
        }
    } catch (IOException ioe) {
        OpenShiftCommonCoreActivator.log(ioe);
        return null;
    }
}

From source file:com.joyent.manta.client.MantaClientFindIT.java

/**
 * This test sees if find() can find a large number of files spread across
 * many directories. It validates the results against the node.js Manta CLI
 * tool mls.//from   www  .  j av a  2  s .com
 *
 * This test is disabled by default because it is difficult to know if the
 * running system has the node.js CLI tools properly installed. Please run
 * this test manually on an as-needed basis.
 */
@Test(enabled = false)
public void findMatchesMfind() throws SecurityException, IOException, InterruptedException {
    ConfigContext context = mantaClient.getContext();
    String reports = context.getMantaHomeDirectory() + SEPARATOR + "reports" + SEPARATOR + "usage" + SEPARATOR
            + "summary";
    String[] cmd = new String[] { "mfind", reports };

    ProcessBuilder processBuilder = new ProcessBuilder(cmd);

    Map<String, String> env = processBuilder.environment();
    env.put("MANTA_URL", context.getMantaURL());
    env.put("MANTA_USER", context.getMantaUser());
    env.put("MANTA_KEY_ID", context.getMantaKeyId());

    long mFindStart = System.nanoTime();
    Process process = processBuilder.start();

    String charsetName = StandardCharsets.UTF_8.name();

    List<String> objects = new LinkedList<>();

    try (Scanner scanner = new Scanner(process.getInputStream(), charsetName)) {
        while (scanner.hasNextLine()) {
            objects.add(scanner.nextLine());
        }
    }

    System.err.println("Waiting for mfind to complete");
    Assert.assertEquals(process.waitFor(), 0, "mfind exited with an error");
    long mFindEnd = System.nanoTime();
    System.err.printf("mfind process completed in %d ms\n", Duration.ofNanos(mFindEnd - mFindStart).toMillis());

    long findStart = System.nanoTime();

    List<String> foundObjects;
    try (Stream<MantaObject> findStream = mantaClient.find(reports)) {
        foundObjects = findStream.map(MantaObject::getPath).collect(Collectors.toList());
    }

    long findEnd = System.nanoTime();
    System.err.printf("find() completed in %d ms\n", Duration.ofNanos(findEnd - findStart).toMillis());

    Assert.assertEqualsNoOrder(objects.toArray(), foundObjects.toArray());
}

From source file:com.lithium.flow.vault.AgentVault.java

private void startAgent(@Nonnull String password) {
    try {/*from  ww w.  j av  a2 s .  c  o  m*/
        int port = findFreePort();
        String agentPassword = Vaults.securePassword();

        Map<String, String> map = new HashMap<>();
        Store agentStore = new MemoryStore(map);
        Vault agentVault = new SecureVault(Configs.empty(), agentStore);
        agentVault.setup(agentPassword);
        agentVault.putValue("password", password);

        ProcessBuilder builder = new ProcessBuilder();
        builder.command(System.getProperty("java.home") + "/bin/java", "-Dagent.port=" + port,
                AgentServer.class.getName());
        builder.environment().put("CLASSPATH", System.getProperty("java.class.path"));
        Process process = builder.start();

        OutputStream out = process.getOutputStream();
        mapper.writeValue(out, map);
        out.close();

        store.putValue("vault.agent.port", String.valueOf(port));
        store.putValue("vault.agent.password", agentPassword);
    } catch (IOException e) {
        throw new VaultException("failed to start agent", e);
    }
}

From source file:com.taobao.adfs.util.Utilities.java

public static Process runCommand(String[] cmdArray, String extraPath, String libPath) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(cmdArray);
    Map<String, String> environment = processBuilder.environment();
    if (extraPath != null) {
        if (extraPath.isEmpty())
            extraPath = ".";
        environment.put("PATH", extraPath + ":" + environment.get("PATH"));
    }/*from   w w w  .  java  2  s  .co m*/
    if (libPath != null) {
        if (libPath.isEmpty())
            libPath = ".";
        environment.put("LD_LIBRARY_PATH", libPath + ":" + environment.get("LD_LIBRARY_PATH"));
    }
    return processBuilder.start();
}

From source file:org.apache.kudu.client.MiniKdc.java

private Process startProcessWithKrbEnv(String... argv) throws IOException {

    ProcessBuilder procBuilder = new ProcessBuilder(argv);
    procBuilder.environment().putAll(getEnvVars());
    LOG.debug("executing '{}', env: '{}'", Joiner.on(" ").join(procBuilder.command()),
            Joiner.on(", ").withKeyValueSeparator("=").join(procBuilder.environment()));
    return procBuilder.redirectErrorStream(true).start();
}

From source file:org.splandroid.tr.commons.KillableProcess.java

/**
 * Start the thread that will spawn the defined process as long as the process
 * is not running./*from ww  w.ja  v a  2 s  . c o m*/
 */
final public synchronized void start() {
    if (this.isRunning() == false) {
        // Generate a unique-ish name for the thread
        final int hash = cmdLine.hashCode();
        final String thrName = String.format("KillableProcess-%d", hash);

        // Build a thread that'll run the process
        thread = new Thread(thrName) {
            public void run() {
                // Launch the process and wait for completion
                try {
                    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
                    // Add the passed in environment
                    Map<String, String> procEnv = pb.environment();
                    for (ImmutablePair<String, String> p : envVars) {
                        procEnv.put(p.getLeft(), p.getRight());
                    }

                    // Add working directory
                    pb.directory(workingDir);
                    // Start the process
                    process = pb.start();
                    if (process != null) {
                        // Re-direct the streams
                        try {
                            streamHandler.setProcessInputStream(process.getOutputStream());
                            streamHandler.setProcessOutputStream(process.getInputStream());
                            streamHandler.setProcessErrorStream(process.getErrorStream());
                        } catch (Exception e) {
                            process.destroy();
                            throw e;
                        }
                        streamHandler.start();
                        final int retValue = process.waitFor();
                        streamHandler.stop();
                        procStatus.setReturnValue(retValue);
                    }
                } catch (Exception ex) {
                    procStatus.setException(ex);
                } finally {
                    finishSema.release();
                }
            }
        };
        thread.setDaemon(true);
        finishSema.acquireUninterruptibly();
        thread.start();
        killRequested = false;
    }
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private String getConnectorClasspath(Connector connector) throws IOException, InterruptedException {
    byte[] pom = new byte[0]; // TODO: Fix generation to use an Action projectGenerator.generatePom(connector);
    java.nio.file.Path tmpDir = Files.createTempDirectory("syndesis-connector");
    try {/*  w ww.ja va2s.  c  om*/
        Files.write(tmpDir.resolve("pom.xml"), pom);
        ArrayList<String> args = new ArrayList<>();
        args.add("mvn");
        args.add("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:build-classpath");
        if (localMavenRepoLocation != null) {
            args.add("-Dmaven.repo.local=" + localMavenRepoLocation);
        }
        ProcessBuilder builder = new ProcessBuilder().command(args)
                .redirectError(ProcessBuilder.Redirect.INHERIT).directory(tmpDir.toFile());
        Map<String, String> environment = builder.environment();
        environment.put("MAVEN_OPTS", "-Xmx64M");
        Process mvn = builder.start();
        try {
            String result = parseClasspath(mvn.getInputStream());
            if (mvn.waitFor() != 0) {
                throw new IOException(
                        "Could not get the connector classpath, mvn exit value: " + mvn.exitValue());
            }
            return result;
        } finally {
            mvn.getInputStream().close();
            mvn.getOutputStream().close();
        }
    } finally {
        FileSystemUtils.deleteRecursively(tmpDir.toFile());
    }
}

From source file:io.stallion.utils.ProcessHelper.java

public CommandResult run() {

    String cmdString = String.join(" ", args);
    System.out.printf("----- Execute command: %s ----\n", cmdString);
    ProcessBuilder pb = new ProcessBuilder(args);
    if (!empty(directory)) {
        pb.directory(new File(directory));
    }//from www .ja  v  a 2s .c om
    Map<String, String> env = pb.environment();
    CommandResult commandResult = new CommandResult();
    Process p = null;
    try {
        if (showDotsWhileWaiting == null) {
            showDotsWhileWaiting = !inheritIO;
        }

        if (inheritIO) {
            p = pb.inheritIO().start();
        } else {
            p = pb.start();
        }

        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));

        if (!empty(input)) {
            Log.info("Writing input to pipe {0}", input);
            IOUtils.write(input, p.getOutputStream(), UTF8);
            p.getOutputStream().flush();
        }

        while (p.isAlive()) {
            p.waitFor(1000, TimeUnit.MILLISECONDS);
            if (showDotsWhileWaiting == true) {
                System.out.printf(".");
            }
        }

        commandResult.setErr(IOUtils.toString(err));
        commandResult.setOut(IOUtils.toString(out));
        commandResult.setCode(p.exitValue());

        if (commandResult.succeeded()) {
            info("\n---- Command execution completed ----\n");
        } else {
            Log.warn("Command failed with error code: " + commandResult.getCode());
        }

    } catch (IOException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(999);
        commandResult.setEx(e);
    } catch (InterruptedException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(998);
        commandResult.setEx(e);
    }
    Log.fine(
            "\n\n----Start shell command result----:\nCommand:  {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n",
            cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr());
    return commandResult;
}