Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:com.quartzdesk.executor.core.job.LocalCommandExecutorJob.java

@Override
protected void executeJob(JobExecutionContext context) throws JobExecutionException {
    log.debug("Inside job: {}", context.getJobDetail().getKey());

    JobDataMap jobDataMap = context.getMergedJobDataMap();

    // command/*from   ww  w .j  a va 2s . c  o  m*/
    String command = jobDataMap.getString(JDM_KEY_COMMAND);
    if (command == null) {
        throw new JobExecutionException("Missing required '" + JDM_KEY_COMMAND + "' job data map parameter.");
    }

    // command arguments (optional)
    String commandArgs = jobDataMap.getString(JDM_KEY_COMMAND_ARGS);

    // command work directory (optional)
    String commandWorkDir = jobDataMap.getString(JDM_KEY_COMMAND_WORK_DIR);
    File commandWorkDirFile = null;
    if (commandWorkDir != null) {
        commandWorkDirFile = new File(commandWorkDir);

        if (!commandWorkDirFile.exists() || !commandWorkDirFile.isDirectory()) {
            throw new JobExecutionException(
                    "Command work directory '" + commandWorkDirFile.getAbsolutePath() + "' specified in the '"
                            + JDM_KEY_COMMAND_WORK_DIR + "' job data map parameter does not exist.");
        }
    }

    // execute the command
    List<String> commandLine = prepareCommandLine(command, commandArgs);
    ProcessBuilder processBuilder = new ProcessBuilder(commandLine);

    processBuilder.redirectErrorStream(true);

    // set the process work directory if specified; otherwise the default work directory is used
    if (commandWorkDirFile != null) {
        processBuilder.directory(commandWorkDirFile);
    }

    // we could possibly set the process environment here
    //processBuilder.environment()

    try {
        log.info("Executing local command using command line: {}", commandLine);

        ExecutorService standardOutputExecutor = getProcessOutputExecutor(context);

        Process process = processBuilder.start();

        StandardOutputReaderCallable stdOutCallable = new StandardOutputReaderCallable(
                process.getInputStream());
        Future<String> stdOutDataFuture = standardOutputExecutor.submit(stdOutCallable);

        int exitCode = process.waitFor(); // wait for the process to finish

        log.debug("Local command finished with exit code: {}", exitCode);
        context.setResult(exitCode); // exit code is used as the job's execution result (visible in the QuartzDesk GUI)

        try {
            String output = stdOutDataFuture.get();
            if (StringUtils.isBlank(output)) {
                log.info("Local command produced no output.");
            } else {
                log.info("Local command produced the following output:{}{}", CommonConst.NL, output);
            }
        } catch (Exception e) // CancellationException, ExecutionException, InterruptedException
        {
            log.warn("Error getting process data.", e);
        }

        // if result != 0, we typically want to throw JobExecutionException indicating a job execution failure
        if (exitCode != 0) {
            throw new JobExecutionException("Command finished with non-zero exit code: " + exitCode);
        }
    } catch (IOException e) {
        throw new JobExecutionException("Error starting command process.", e);
    } catch (InterruptedException e) {
        throw new JobExecutionException("Command process has been interrupted.", e);
    }
}

From source file:org.broadinstitute.sting.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run./*from  ww w  . j  a v a 2  s.c  o m*/
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        throw new ReviewedStingException(
                "Unable to start command: " + StringUtils.join(builder.command(), " "));
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedStingException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedStingException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedStingException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedStingException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:com.thoughtworks.go.util.ProcessManager.java

public ProcessWrapper createProcess(String[] commandLine, String commandLineForDisplay, File workingDir,
        Map<String, String> envMap, EnvironmentVariableContext environmentVariableContext,
        ConsoleOutputStreamConsumer consumer, String processTag, String encoding, String errorPrefix) {
    ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing: " + commandLineForDisplay);
    }/*from   ww w.j a  v a  2s .c o m*/
    if (workingDir != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("[Command Line] Using working directory %s to start the process.",
                    workingDir.getAbsolutePath()));
        }
        processBuilder.directory(workingDir);
    }

    environmentVariableContext.setupRuntimeEnvironment(processBuilder.environment(), consumer);
    processBuilder.environment().putAll(envMap);

    Process process = startProcess(processBuilder, commandLineForDisplay);
    ProcessWrapper processWrapper = new ProcessWrapper(process, processTag, commandLineForDisplay, consumer,
            encoding, errorPrefix);
    processMap.putIfAbsent(process, processWrapper);
    return processWrapper;
}

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

protected CompilationResult runGradle(String... params) throws IOException, InterruptedException {
    setExecutable();//from  w ww  .j  a va  2s  .co 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:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java

private void initParticipantData() {
    File participantDataFile = new File(getDatabasePath() + getBtrRecordFileName());
    try {/*ww w.  j  a  v a 2s  . co  m*/
        Map<String, Data> inputData = instrumentExecutionService.getInputParametersValue(
                "INPUT_PARTICIPANT_BARCODE", "INPUT_PARTICIPANT_LAST_NAME", "INPUT_PARTICIPANT_FIRST_NAME",
                "INPUT_PARTICIPANT_GENDER", "INPUT_PARTICIPANT_HEIGHT", "INPUT_PARTICIPANT_WEIGHT",
                "INPUT_PARTICIPANT_ETHNIC_GROUP", "INPUT_PARTICIPANT_BIRTH_YEAR",
                "INPUT_PARTICIPANT_BIRTH_MONTH", "INPUT_PARTICIPANT_BIRTH_DAY", "INPUT_PARTICIPANT_PACEMAKER");

        FileOutputStream participantDataOuputStream = new FileOutputStream(participantDataFile);
        BtrInputGenerator inputGenerator = new BtrInputGenerator();
        participantDataOuputStream.write((inputGenerator.generateByteBuffer(inputData)).array());
        participantDataOuputStream.close();

    } catch (Exception ex) {
        throw new RuntimeException("Error writing ecg participant data file: ", ex);
    }

    List<String> command = new ArrayList<String>();
    command.add("cmd");
    command.add("/c");
    command.add(
            getExecutableForParticipantInfo() + " " + getBtrRecordFileName() + " " + getBtrDatabaseFileName());

    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new File(getDatabasePath()));

    try {
        log.info("Executing command '{}'", command);
        Process process = builder.start();
        log.info("Waiting for process '{}'", process);
        process.waitFor();
    } catch (IOException e) {
        log.error("Could not create external process.", e);
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        log.error("Error waiting for process to end.", e);
        throw new RuntimeException(e);
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * create a ProcessBuilder for restarting TMM to the updater
 * //from w  w w. j  a  v a  2 s.  c om
 * @return the process builder
 */
public static ProcessBuilder getPBforTMMupdate() {
    Path f = Paths.get("getdown.jar");
    if (!Files.exists(f)) {
        LOGGER.error("cannot start updater - getdown.jar not found.");
        return null; // when we are in SVN, return null = normal close
    }
    List<String> arguments = getJVMArguments();
    arguments.add(0, LaunchUtil.getJVMPath()); // java exe before JVM args
    arguments.add("-jar");
    arguments.add("getdown.jar");
    arguments.add(".");
    ProcessBuilder pb = new ProcessBuilder(arguments);
    pb.directory(Paths.get("").toAbsolutePath().toFile()); // set working directory (current TMM dir)
    return pb;
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * create a ProcessBuilder for restarting TMM
 * /*from   www  .j  av  a  2 s . c om*/
 * @return the process builder
 */
public static ProcessBuilder getPBforTMMrestart() {
    Path f = Paths.get("tmm.jar");
    if (!Files.exists(f)) {
        LOGGER.error("cannot restart TMM - tmm.jar not found.");
        return null; // when we are in SVN, return null = normal close
    }
    List<String> arguments = getJVMArguments();
    arguments.add(0, LaunchUtil.getJVMPath()); // java exe before JVM args
    arguments.add("-Dsilent=noupdate"); // start GD.jar instead of TMM.jar, since we don't have the libs in manifest
    arguments.add("-jar");
    arguments.add("getdown.jar");
    arguments.add(".");
    ProcessBuilder pb = new ProcessBuilder(arguments);
    pb.directory(Paths.get("").toAbsolutePath().toFile()); // set working directory (current TMM dir)
    return pb;
}

From source file:org.broadinstitute.gatk.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run./*  ww  w .j a  v a2s .  c  o  m*/
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        String message = String.format("Unable to start command: %s\nReason: %s",
                StringUtils.join(builder.command(), " "), e.getMessage());
        throw new ReviewedGATKException(message);
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedGATKException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedGATKException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedGATKException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedGATKException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java

private void fetchTaverna(String location, String name) throws Exception {
    File zipFile = new File(buildDirectory, name + ".zip");
    IOUtils.copy(new URL(location).openStream(), new FileOutputStream(zipFile));
    ProcessBuilder processBuilder = new ProcessBuilder("unzip", "-q", name);
    processBuilder.redirectErrorStream(true);
    processBuilder.directory(buildDirectory);
    System.out.println(processBuilder.command());
    Process process = processBuilder.start();
    waitFor(process);/*from  w w  w .j a va2  s  .c  om*/
}

From source file:org.ow2.proactive.scheduler.ext.matlab.worker.MatlabConnectionRImpl.java

protected Process createMatlabProcess(String runArg) throws Exception {
    // Attempt to run MATLAB
    final ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(this.matlabLocation);
    commandList.addAll(Arrays.asList(this.startUpOptions));
    commandList.add("-logfile");
    commandList.add(this.taskOutputFile.toString());
    commandList.add("-r");
    commandList.add(runArg);//  w w w . j  av  a2s.  c o m

    String[] command = (String[]) commandList.toArray(new String[commandList.size()]);

    ProcessBuilder b = new ProcessBuilder();
    // invalid on windows, it affects the starter only
    b.directory(this.workingDirectory);
    b.command(command);

    // Fix for SCHEDULING-1309: If MATLAB client uses RunAsMe option the MATLAB
    // worker jvm can crash if the client user has never started any MATLAB
    // session on the worker host

    // Since the user profile can be missing on Windows with RunAsMe, by setting
    // the MATLAB_PREFDIR variable to a writable dir (can be non-writable on Windows with RunAsMe)
    // the MATLAB doesn't crash no more

    Map<String, String> env = b.environment();

    // Transmit the prefdir as env variable
    String matlabPrefdir = System.getProperty(MATLAB_PREFDIR);
    if (matlabPrefdir != null) {
        env.put("MATLAB_PREFDIR", matlabPrefdir);
    }
    // Transmit the tmpdir as env variable
    String matlabTmpvar = System.getProperty(MATLAB_TASK_TMPDIR);
    if (matlabTmpvar != null) {
        env.put("TEMP", matlabTmpvar);
        env.put("TMP", matlabTmpvar);
    }

    return b.start();
}