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.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting dynomite server"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//from  w  w  w. j a va  2s  .c  om
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startDynomite = new ProcessBuilder(command);
    Map<String, String> env = startDynomite.environment();
    setEnv(env);

    startDynomite.directory(new File("/"));
    startDynomite.redirectErrorStream(true);
    Process starter = startDynomite.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Dynomite server. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Dynomite has an error", e);
    }
}

From source file:functionalTests.annotations.AptTest.java

private Result runApt() throws CompilationExecutionException {
    try {/*ww w. j  a va2s  . c  o m*/
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(_aptCommand));
        Map<String, String> env = processBuilder.environment();
        env.put("CLASSPATH", _classpath);

        Process aptProcess = processBuilder.start();

        BufferedReader stderr = new BufferedReader(new InputStreamReader(aptProcess.getErrorStream()));
        //flushOutput(stderr);

        return getResults(stderr);
    } catch (IOException ioExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand) + ".reason:"
                + ioExcp.getMessage();
        logger.error(msg, ioExcp);
        throw new CompilationExecutionException(msg, ioExcp);
    } catch (SecurityException secExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand)
                + "; security access violation.";
        logger.error(msg, secExcp);
        throw new CompilationExecutionException(msg, secExcp);
    }
}

From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanCommandCallable.java

@Override
public ScanCommandOutput call() {
    String commandToExecute = "command_not_yet_configured";
    try {//  ww w .  j  a  va 2 s  . c  om
        final ScanPaths scanPaths = scanPathsUtility
                .determineSignatureScannerPaths(scanCommand.getInstallDirectory());

        final List<String> cmd = scanCommand.createCommandForProcessBuilder(logger, scanPaths,
                scanCommand.getOutputDirectory().getAbsolutePath());
        cmd.add(scanCommand.getTargetPath());

        commandToExecute = createPrintableCommand(cmd);
        logger.info(String.format("Black Duck CLI command: %s", commandToExecute));

        final File standardOutFile = scanPathsUtility.createStandardOutFile(scanCommand.getOutputDirectory());
        try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) {
            final ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream);
            final ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            processBuilder.environment().putAll(intEnvironmentVariables.getVariables());

            if (!scanCommand.isDryRun()) {
                if (!StringUtils.isEmpty(scanCommand.getApiToken())) {
                    processBuilder.environment().put("BD_HUB_TOKEN", scanCommand.getApiToken());
                } else {
                    processBuilder.environment().put("BD_HUB_PASSWORD", scanCommand.getPassword());
                }
            }
            processBuilder.environment().put("BD_HUB_NO_PROMPT", "true");

            final Process blackDuckCliProcess = processBuilder.start();

            // The cli logs go the error stream for some reason
            final StreamRedirectThread redirectThread = new StreamRedirectThread(
                    blackDuckCliProcess.getErrorStream(), splitOutputStream);
            redirectThread.start();

            int returnCode = -1;
            try {
                returnCode = blackDuckCliProcess.waitFor();

                // the join method on the redirect thread will wait until the thread is dead
                // the thread will die when it reaches the end of stream and the run method is finished
                redirectThread.join();
            } finally {
                if (blackDuckCliProcess.isAlive()) {
                    blackDuckCliProcess.destroy();
                }
                if (redirectThread.isAlive()) {
                    redirectThread.interrupt();
                }
            }

            splitOutputStream.flush();

            logger.info(IOUtils.toString(blackDuckCliProcess.getInputStream(), StandardCharsets.UTF_8));

            logger.info("Black Duck Signature Scanner return code: " + returnCode);
            logger.info(
                    "You can view the logs at: '" + scanCommand.getOutputDirectory().getCanonicalPath() + "'");

            if (returnCode != 0) {
                return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute,
                        returnCode);
            }
        }
    } catch (final Exception e) {
        final String errorMessage = String.format("There was a problem scanning target '%s': %s",
                scanCommand.getTargetPath(), e.getMessage());
        return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute,
                errorMessage, e);
    }

    if (!scanCommand.isDryRun() && cleanupOutput) {
        FileUtils.deleteQuietly(scanCommand.getOutputDirectory());
    } else if (scanCommand.isDryRun() && cleanupOutput) {
        // delete everything except dry run files
        final File[] outputFiles = scanCommand.getOutputDirectory().listFiles();
        for (final File outputFile : outputFiles) {
            if (!DRY_RUN_FILES_TO_KEEP.contains(outputFile.getName())) {
                FileUtils.deleteQuietly(outputFile);
            }
        }
    }

    return ScanCommandOutput.SUCCESS(scanCommand.getName(), logger, scanCommand, commandToExecute);
}

From source file:com.synopsys.integration.executable.ProcessBuilderRunner.java

public ProcessBuilder createProcessBuilder(Executable executable) {
    final ProcessBuilder processBuilder = new ProcessBuilder(executable.getCommandWithArguments());
    processBuilder.directory(executable.getWorkingDirectory());
    final Map<String, String> processBuilderEnvironment = processBuilder.environment();
    for (final String key : executable.getEnvironmentVariables().keySet()) {
        populateEnvironmentMap(processBuilderEnvironment, key, executable.getEnvironmentVariables().get(key));
    }/*from   w ww.  ja  va 2 s  .c  o  m*/
    return processBuilder;
}

From source file:uk.ac.ox.it.ords.api.database.threads.RestoreThread.java

@Override
public void run() {
    Properties properties = ConfigurationConverter.getProperties(MetaConfiguration.getConfiguration());
    String postgres_bin = "";
    if (properties.containsKey("ords.postgresql.bin.path")) {
        postgres_bin = properties.getProperty("ords.postgresql.bin.path");
    }//from   www.java 2 s .c  o m

    /*
     *       ProcessBuilder processBuilder = new ProcessBuilder(postgres_bin+"pg_dump", 
    "-f", 
    file.toString(), 
    "-v", "-o", "-h", 
    database.getDatabaseServer(), 
    "-U", 
    server.getUsername(), database.getDbConsumedName());
            
     */
    ProcessBuilder processBuilder = new ProcessBuilder(postgres_bin + "psql", "-d", this.databaseName, "-h",
            this.server, "-U", this.databaseRole, "-f", this.dbFile.toString());
    processBuilder.environment().put("PGPASSWORD", this.databasePwd);
    DatabaseUploadService uploadService = DatabaseUploadService.Factory.getInstance();
    try {
        Process process = processBuilder.start();
        uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.IN_PROGRESS);
        InputStream is = process.getInputStream();
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader buffer = new BufferedReader(reader);
        String line;
        while ((line = buffer.readLine()) != null) {
            System.out.println(line);
            if (log.isDebugEnabled()) {
                log.debug(line);
            }
        }
        emailService.sendRestoreSuccessfulMessage();
        uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.FINISHED);
    } catch (Exception e) {
        log.error("ERROR", e);
        try {
            emailService.sendRestoreUnsuccessfulMessage(e.toString());
            uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.FAILED);
        } catch (Exception e1) {
            log.error("ERROR", e1);
            e1.printStackTrace();
        }
    }
}

From source file:android.databinding.compilationTest.BaseCompilationTest.java

protected CompilationResult runGradle(String... params) throws IOException, InterruptedException {
    setExecutable();//  w  w  w .  ja v  a  2s  . c o m
    File pathToExecutable = new File(testFolder, "gradlew");
    List<String> args = new ArrayList<>();
    args.add(pathToExecutable.getAbsolutePath());
    args.add("-P" + PRINT_ENCODED_ERRORS_PROPERTY + "=true");
    args.add("--project-cache-dir");
    args.add(new File("../.caches/", name.getMethodName()).getAbsolutePath());
    Collections.addAll(args, params);
    ProcessBuilder builder = new ProcessBuilder(args);
    builder.environment().putAll(System.getenv());
    String javaHome = System.getProperty("java.home");
    if (StringUtils.isNotBlank(javaHome)) {
        builder.environment().put("JAVA_HOME", javaHome);
    }
    builder.directory(testFolder);
    Process process = builder.start();
    String output = IOUtils.toString(process.getInputStream());
    String error = IOUtils.toString(process.getErrorStream());
    int result = process.waitFor();
    return new CompilationResult(result, output, error);
}

From source file:cz.cas.lib.proarc.common.process.AsyncProcess.java

@Override
public void run() {
    done.set(false);//  w w  w  .  j a  v  a 2 s .c  o m
    outputConsumer = null;
    exitCode = -1;
    ProcessBuilder pb = new ProcessBuilder(cmdLine);
    // for now redirect outputs into a single stream to eliminate
    // the need to run multiple threads to read each output
    pb.redirectErrorStream(true);
    pb.environment().putAll(env);
    try {
        Process process = pb.start();
        refProcess.set(process);
        outputConsumer = new OutputConsumer(process.getInputStream());
        outputConsumer.start();
        exitCode = process.waitFor();
        LOG.fine("Done " + cmdLine);
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, cmdLine.toString(), ex);
    } finally {
        done.set(true);
    }
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * A method which makes executing programs easier.
 * //w  w w. ja  va2 s. c  om
 * @param args
 * @param failureMsg
 * @param ioExceptionMsg
 * @throws MojoExecutionException
 */
public static InputStream exec(String[] args, File workingDir, String failureMsg, String ioExceptionMsg,
        String userInput) throws MojoExecutionException {
    /*
     * debug code which prints out the execution command-line. Enable if
     * neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
     * + " "); } System.err.println();
     */

    // Creates process with the defined language setting of LC_ALL=C
    // That way the textual output of certain commands is predictable.
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(workingDir);
    Map<String, String> env = pb.environment();
    env.put("LC_ALL", "C");

    Process p = null;

    try {

        p = pb.start();

        if (userInput != null) {
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            writer.println(userInput);
            writer.flush();
            writer.close();
        }
        int exitValue = p.waitFor();
        if (exitValue != 0) {
            print(p);
            throw new MojoExecutionException(
                    String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
    } catch (InterruptedException ie) {
        // Cannot happen.
        throw new MojoExecutionException("InterruptedException", ie);
    }
    return p.getInputStream();
}

From source file:uk.ac.sanger.cgp.wwdocker.workflow.DEWorkflow.java

@Override
public int cleanDockerPath(BaseConfiguration config) {
    String command = baseDockerCommand(config, null);
    String datastore = config.getString("datastoreDir");
    List<String> args = new ArrayList(Arrays.asList(command.split(" ")));
    args.add("/bin/bash");
    args.add("-c");
    args.add("rm -rf " + datastore + "/oozie-* " + datastore + "/*.ini " + datastore + "/logs.tar.gz "
            + datastore + "/toInclude.lst" + datastore + "/DEWorkflowData/dkfz/gtdownload-*.log");

    ProcessBuilder pb = new ProcessBuilder(args);

    Map<String, String> pEnv = pb.environment();
    pEnv.putAll(Config.getEnvs(config));
    logger.info("Executing: " + String.join(" ", args));
    int exitCode = -1;
    Process p = null;//from  ww w  .ja v  a  2s.  c  o m
    try {
        p = pb.start();
        String progErr = IOUtils.toString(p.getErrorStream());
        String progOut = IOUtils.toString(p.getInputStream());
        exitCode = p.waitFor();
        Utils.logOutput(progErr, Level.ERROR);
        Utils.logOutput(progOut, Level.TRACE);
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    return exitCode;
}

From source file:org.apache.hadoop.mpich.MpichContainerWrapper.java

public void run() {
    try {/*from   w w  w  .  j  a  va 2  s  .  co m*/
        clientSock = new Socket(ioServer, ioServerPort);
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));

        String hostName = InetAddress.getLocalHost().getHostName();
        System.out.println("Starting process " + executable + " on " + hostName);

        List<String> commands = new ArrayList<String>();
        commands.add(executable);
        if (appArgs != null && appArgs.length > 0) {
            commands.addAll(Arrays.asList(appArgs));
        }

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

        Map<String, String> evns = processBuilder.environment();
        evns.put("PMI_RANK", rank);
        evns.put("PMI_SIZE", np);
        evns.put("PMI_ID", pmiid);
        evns.put("PMI_PORT", pmiServer + ":" + pmiServerPort);

        if (this.isSpawn) {
            evns.put("PMI_SPAWNED", "1");
        }

        LOG.info("Starting process:");
        for (String cmd : commands) {
            LOG.info(cmd + "\n");
        }

        Process process = processBuilder.start();
        System.out.println("Process exit with value " + process.waitFor());
        System.out.println("EXIT");//Stopping IOThread
        clientSock.close();
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}