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.consol.citrus.admin.service.executor.AbstractExecuteCommand.java

public ProcessBuilder getProcessBuilder() {
    validateWorkingDirectory(workingDirectory);

    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);/* ww w.  j a v a  2 s . c  o m*/
        commands.add(BASH_OPTION_C);
    } else {
        commands.add(CMD);
        commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(workingDirectory);

    LOG.debug("Process builder commands: " + commands);
    return pb;
}

From source file:name.martingeisse.ecobuild.util.CommandLineToolInvocation.java

@Override
protected void invoke(List<String> tokens) throws IOException {

    final ProcessBuilder processBuilder = new ProcessBuilder(tokens);
    processBuilder.directory(getWorkingDirectory());
    processBuilder.redirectErrorStream(true);
    final Process process;
    try {//w w w . j ava  2s  . c o m
        process = processBuilder.start();
    } catch (IOException e) {
        getLogger().logError(
                "Exception while starting tool. Command Line: " + getCommand() + " / " + tokens.get(0));
        throw e;
    }
    final MyLoggerWriter loggerWriter = new MyLoggerWriter(getLogger());
    IOUtils.copy(process.getInputStream(), loggerWriter);
    loggerWriter.endStartedLine();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new ToolBuildException("An InterruptedException occurred", e);
    }

}

From source file:com.consol.citrus.admin.launcher.process.ExecuteCommand.java

public ProcessBuilder getProcessBuilder() {
    validateWorkingDirectory(workingDirectory);

    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);//www  .  j  ava  2  s.  com
        commands.add(BASH_OPTION_C);
    } else {
        commands.add(CMD);
        commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand(command));

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(workingDirectory);

    LOG.trace("Returning ProcessBuilder for command:" + commands);
    return pb;
}

From source file:org.codehaus.mojo.exec.ExtendedExecutor.java

@Override
protected Process launch(CommandLine command, Map<String, String> env, File dir) throws IOException {
    if (dir != null && !dir.exists()) {
        throw new IOException(dir + " doesn't exist.");
    }//from  w ww .j  a va  2  s . c o  m
    ProcessBuilder pb = new ProcessBuilder(command.toStrings());
    pb.environment().putAll(env);
    pb.directory(dir);
    if (inheritIo) {
        pb.inheritIO();
    }
    return pb.start();
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

public static boolean dcmsnd(File inputDirFile, boolean throwException) throws Exception {
    InputStream is = null;//from   www .  ja  v  a 2s. com
    InputStreamReader isr = null;
    BufferedReader br = null;
    FileWriter tagFileWriter = null;
    boolean success = false;
    try {
        String aeTitle = EPADConfig.aeTitle;
        String dicomServerIP = EPADConfig.dicomServerIP;
        String dicomServerPort = EPADConfig.dicomServerPort;
        String dicomServerTitleAndPort = aeTitle + "@" + dicomServerIP + ":" + dicomServerPort;

        dicomServerTitleAndPort = dicomServerTitleAndPort.trim();

        String dirPath = inputDirFile.getAbsolutePath();
        if (pathContainsSpaces(dirPath))
            dirPath = escapeSpacesInDirPath(dirPath);

        File dir = new File(dirPath);
        int nbFiles = -1;
        if (dir != null) {
            String[] filePaths = dir.list();
            if (filePaths != null)
                nbFiles = filePaths.length;
        }
        log.info("./dcmsnd: sending " + nbFiles + " file(s) - command: ./dcmsnd " + dicomServerTitleAndPort
                + " " + dirPath);

        String[] command = { "./dcmsnd", dicomServerTitleAndPort, dirPath };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmsnd");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerDICOMBinDir();
        script = new File(dicomScriptsDir, "dcmsnd");
        if (!script.exists())
            throw new Exception("No script found:" + script.getAbsolutePath());
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmsend output: " + line);
        }

        try {
            int exitValue = process.waitFor();
            log.info("DICOM send exit value is: " + exitValue);
            if (exitValue == 0)
                success = true;
        } catch (InterruptedException e) {
            log.warning("Didn't send DICOM files in: " + inputDirFile.getAbsolutePath(), e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error"))
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        return success;
    } catch (Exception e) {
        log.warning("DicomSendTask failed to send DICOM files", e);
        if (e instanceof IllegalStateException && throwException) {
            throw e;
        }
        if (throwException) {
            throw new IllegalStateException("DicomSendTask failed to send DICOM files", e);
        }
        return success;
    } catch (OutOfMemoryError oome) {
        log.warning("DicomSendTask out of memory: ", oome);
        if (throwException) {
            throw new IllegalStateException("DicomSendTask out of memory: ", oome);
        }
        return success;
    } finally {
        IOUtils.closeQuietly(tagFileWriter);
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
}

From source file:VASSAL.tools.io.ProcessLauncher.java

/**
 * Launches a process./*from ww  w .  j a v a  2s  .  co m*/
 *
 * @param workDir the process' working directory
 * @param stdout the stream where the process' STDOUT is redirected
 * @param stderr the stream where the process' STDERR is redirected
 * @param args the command-line arguments
 *
 * @throws IOException if the process fails to launch
 */
public ProcessWrapper launch(File workDir, InputStreamPump stdoutPump, InputStreamPump stderrPump,
        String... args) throws IOException {
    logger.info("launching " + StringUtils.join(args, ' '));

    final ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(workDir);

    final Process proc = pb.start();
    final ProcessCallable pcall = new ProcessCallable(proc, stdoutPump, stderrPump, exec);
    final Future<Integer> future = exec.submit(pcall);

    return new ProcessWrapper(future, proc.getInputStream(), proc.getErrorStream(), proc.getOutputStream());
}

From source file:org.eclipse.smila.utils.scriptexecution.UnixScriptExecutor.java

/**
 * {@inheritDoc}/*from  w ww. ja v  a  2s . co  m*/
 */
public int execute(final File file) throws IOException, InterruptedException {

    final String shell = System.getenv(SHELL_ENV_NAME);

    if (shell == null || shell.trim().length() == 0) {
        throw new RuntimeException("Environment variable '" + SHELL_ENV_NAME + "' is not set");
    }

    final ProcessBuilder processBuilder = new ProcessBuilder(shell);
    processBuilder.directory(file.getParentFile());
    processBuilder.redirectErrorStream(true);

    final Process shellProcess = processBuilder.start();

    InputStream inputStream = null;

    try {

        inputStream = new FileInputStream(file);

        final OutputStream shellProcessOutputStream = shellProcess.getOutputStream();

        IOUtils.copy(inputStream, shellProcessOutputStream);

        shellProcessOutputStream.close();

        final int retVal = shellProcess.waitFor();

        LogHelper.debug(_log, shellProcess.getInputStream());

        return retVal;

    } finally {

        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.InitialConfig.java

private void createArchive(String locationName) {
    try {// w ww  .ja  va 2  s  .c  o  m

        String[] cmdLine = new String[] { m_binDirectory + INITIAL_CONFIG, locationName };
        ProcessBuilder pb = new ProcessBuilder(cmdLine);
        java.lang.Process proc = pb.directory(new File(m_tmpDirectory)).start();
        LOG.debug("Executing: " + StringUtils.join(cmdLine, " "));
        proc.waitFor();

        if (proc.exitValue() != 0) {
            throw new UserException("Script finished with exit code: " + proc.exitValue());
        }
    } catch (IOException e) {
        throw new UserException(e);
    } catch (InterruptedException e) {
        throw new UserException(e);
    }
}

From source file:org.apache.nifi.registry.provider.hook.ScriptEventHookProvider.java

@Override
public void handle(final Event event) {
    List<String> command = new ArrayList<>();
    command.add(scriptFile.getAbsolutePath());
    command.add(event.getEventType().name());

    for (EventField arg : event.getFields()) {
        command.add(arg.getValue());//  w ww .  j av  a  2s.  c o  m
    }

    final String commandString = StringUtils.join(command, " ");
    final ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(workDirFile);
    LOGGER.debug("Execution of " + commandString);

    try {
        builder.start();
    } catch (IOException e) {
        LOGGER.error("Execution of {0} failed with: {1}",
                new Object[] { commandString, e.getLocalizedMessage() }, e);
    }
}

From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java

/**
 * Runs Maven in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir                The directory below src/test/resources to run maven in.
 * @param extraArgs          The extra arguments (if any) for Maven.
 * @return The standard output.//from w  w  w  .  j  a  v a 2s .  c o m
 * @throws Exception When the execution failed.
 */
private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String m2Home = System.getenv("M2_HOME");
    String flywayVersion = System.getProperty("flywayVersion");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(m2Home + "/bin/mvn" + extension);
    args.add("-Dflyway.version=" + flywayVersion);
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}