Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {/*from   ww w  .j  av a 2 s .  c om*/
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:husky.server.HuskyMaster.java

@Override
public void run() {
    try {/*from ww w .  j a  va 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:io.mesosphere.mesos.frameworks.cassandra.executor.ProdObjectFactory.java

@Override
@NotNull//from w w  w .j  a  va  2s  .co m
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:com.linkedin.pinot.integration.tests.ChaosMonkeyIntegrationTest.java

private Process runAdministratorCommand(String[] args) {
    String classpath = System.getProperty("java.class.path");
    List<String> completeArgs = new ArrayList<>();
    completeArgs.add("java");
    completeArgs.add("-Xms4G");
    completeArgs.add("-Xmx4G");
    completeArgs.add("-cp");
    completeArgs.add(classpath);/*from  w w w.jav a  2  s. c o m*/
    completeArgs.add(PinotAdministrator.class.getName());
    completeArgs.addAll(Arrays.asList(args));

    try {
        Process process = new ProcessBuilder(completeArgs).redirectError(ProcessBuilder.Redirect.INHERIT)
                .redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
        synchronized (_processes) {
            _processes.add(process);
        }
        return process;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.ingenieux.lambda.shell.LambdaShell.java

private static void runCommandArray(OutputStream os, String... args) throws Exception {
    PrintWriter pw = new PrintWriter(os, true);

    File tempPath = File.createTempFile("tmp-", ".sh");

    IOUtils.write(StringUtils.join(args, " "), new FileOutputStream(tempPath));

    List<String> processArgs = new ArrayList<>(Arrays.asList("/bin/bash", "-x", tempPath.getAbsolutePath()));

    ProcessBuilder psBuilder = new ProcessBuilder(processArgs).//
            redirectErrorStream(true);//

    final Process process = psBuilder.start();

    final Thread t = new Thread(() -> {
        try {//  www  .  j  a v a  2  s . com
            IOUtils.copy(process.getInputStream(), os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    t.start();

    process.waitFor();

    t.join();

    int resultCode = process.exitValue();
}

From source file:com.blackducksoftware.integration.hub.detect.util.executable.Executable.java

public ProcessBuilder createProcessBuilder() {
    final List<String> processBuilderArguments = createProcessBuilderArguments();
    final ProcessBuilder processBuilder = new ProcessBuilder(processBuilderArguments);
    processBuilder.directory(workingDirectory);
    final Map<String, String> processBuilderEnvironment = processBuilder.environment();
    final Map<String, String> systemEnv = System.getenv();
    for (final String key : systemEnv.keySet()) {
        populateEnvironmentMap(processBuilderEnvironment, key, systemEnv.get(key));
    }/*from ww  w . java 2  s  .c o m*/
    for (final String key : environmentVariables.keySet()) {
        populateEnvironmentMap(processBuilderEnvironment, key, environmentVariables.get(key));
    }
    return processBuilder;
}

From source file:com.frostwire.gui.bittorrent.SlideDownload.java

private void executeSlide(Slide slide) {
    List<String> command = new ArrayList<String>();
    command.add(getSaveLocation().getAbsolutePath());

    if (slide.executeParameters != null) {
        command.addAll(Arrays.asList(slide.executeParameters.split(" ")));
    }/*from w ww  .  j  a  va2  s  .c o  m*/

    BufferedReader br = null;
    ProcessBuilder pb = new ProcessBuilder(command);
    try {
        Process p = pb.start();

        //consume all output to avoid deadlock in some verisons of windows
        br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        while (br.readLine() != null) {
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:com.mbrlabs.mundus.assets.FbxConv.java

public void clear() {
    outputFormat = OUTPUT_FORMAT_G3DB;/*  w  w w  .  j a va  2 s.  c om*/
    verbose = false;
    flipTexture = false;
    input = null;
    output = null;
    pb = new ProcessBuilder(fbxBinary);
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java

/**
 * Returns when the process has exited without errors. This will wait for
 * the process to exist, therefore will block the current thread in which it
 * is running. If any errors occur, throws CoreException CoreException
 * @throws CoreException if any errors occur while the process is being
 * launched/* ww  w  .  j  a v  a  2s. c  om*/
 */
public void run() throws CoreException {
    Exception error = null;
    Process p = null;
    try {

        List<String> processArguments = getProcessArguments();

        if (processArguments == null || processArguments.isEmpty()) {
            throw new CoreException(getErrorStatus("No process arguments were found")); //$NON-NLS-1$
        } else {

            ProcessBuilder processBuilder = new ProcessBuilder(processArguments);

            // Set any environment variables
            Map<String, String> envVars = getEnvironmentVariables();
            if (envVars != null) {
                Map<String, String> actualVars = processBuilder.environment();
                if (actualVars != null) {
                    for (Entry<String, String> entry : envVars.entrySet()) {
                        actualVars.put(entry.getKey(), entry.getValue());
                    }
                }
            }

            p = processBuilder.start();

            if (p == null) {
                throw new CoreException(getErrorStatus("No process was created.")); //$NON-NLS-1$
            } else {

                StringBuffer errorBuffer = new StringBuffer();
                // Clear the input and error streams to prevent the
                // process
                // from blocking
                handleProcessIOAsynch(p, null, errorBuffer);

                p.waitFor();

                if (errorBuffer.length() > 0) {
                    throw new CoreException(getErrorStatus(errorBuffer.toString()));
                } else if (p.exitValue() != 0) {
                    throw new CoreException(getErrorStatus("process exit value: " + p.exitValue())); //$NON-NLS-1$
                }
            }
        }
    } catch (InterruptedException ex) {
        error = ex;
    } catch (IOException ioe) {
        error = ioe;
    } catch (SecurityException se) {
        error = se;
    } finally {
        if (p != null) {
            p.destroy();
        }
    }

    if (error != null) {
        throw error instanceof CoreException ? (CoreException) error : CloudErrorUtil.toCoreException(error);
    }

}

From source file:com.sastix.cms.common.services.htmltopdf.PdfImpl.java

public byte[] getPDF() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(getCommandAsArray());
    Process process = processBuilder.start();
    //Runtime runtime = Runtime.getRuntime();
    //Process process = runtime.exec(getCommandAsArray());

    for (Page page : pages) {
        if (page.getType().equals(PageType.htmlAsString)) {
            OutputStream stdInStream = process.getOutputStream();
            stdInStream.write(page.getSource().getBytes("UTF-8"));
            stdInStream.close();//from   w ww.j  a  v a  2  s  .  c om
        }
    }

    StreamEater outputStreamEater = new StreamEater(process.getInputStream());
    outputStreamEater.start();

    StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
    errorStreamEater.start();

    outputStreamEater.join();
    errorStreamEater.join();
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new RuntimeException("Process (" + getCommand() + ") exited with status code "
                + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
    }

    if (outputStreamEater.getError() != null) {
        throw outputStreamEater.getError();
    }

    if (errorStreamEater.getError() != null) {
        throw errorStreamEater.getError();
    }

    return outputStreamEater.getBytes();
}