Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

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

Prototype

boolean redirectErrorStream

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

Click Source Link

Usage

From source file:org.opencb.bionetdb.app.cli.CommandExecutor.java

@Deprecated
private ProcessBuilder getProcessBuilder(File workingDirectory, String binPath, List<String> args,
        String logFilePath) {/* ww w.  jav  a2s .c om*/
    List<String> commandArgs = new ArrayList<>();
    commandArgs.add(binPath);
    commandArgs.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandArgs);

    // working directoy and error and output log outputs
    if (workingDirectory != null) {
        builder.directory(workingDirectory);
    }
    builder.redirectErrorStream(true);
    if (logFilePath != null) {
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    }

    return builder;
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/**
 * Executes a command with one argument, returning true if the command succeeds.
 * Gathers the output from stdout and stderr into the provided list of lines.
 *///  ww  w  .  java 2 s . c o m
private boolean execute(String command, File arg, List<String> lines) {
    ProcessBuilder pb = new ProcessBuilder(command, arg.getAbsolutePath());
    pb.redirectErrorStream(true); // redirect stderr to stdout
    try {
        Process proc = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        proc.waitFor();
        return proc.exitValue() == 0;
    } catch (Exception e) {
        log.error("Exception while executing: " + command + " " + arg, e);
        lines.add(e.getMessage());
        return false;
    }
}

From source file:org.panbox.desktop.common.vfs.backend.dropbox.DropboxClientIntegration.java

@Override
public boolean isClientRunning() {
    if (OS.getOperatingSystem().isLinux()) {
        try {//  ww  w. j a  va  2  s  .  c o m
            String pid = FileUtils
                    .readFileToString(new File(getClientConfigDir(), DropboxConstants.LINUX_PID_FILE));
            if (pid != null) {
                pid = pid.trim();
            }
            String ret = FileUtils.readFileToString(
                    new File(File.separator + "proc" + File.separator + pid + File.separator + "cmdline"));
            return ret.contains("dropbox");
        } catch (IOException e) {
            return false;
        }
    } else if (OS.getOperatingSystem().isWindows()) {
        try {
            ProcessBuilder pb = new ProcessBuilder("wmic", "process", "list");
            pb.redirectErrorStream(true);
            Process p = pb.start();
            p.getOutputStream().close();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String tmp = null;

            while ((tmp = br.readLine()) != null) {
                // System.out.println(tmp);
                if (tmp.toLowerCase().contains("dropbox.exe")) {
                    return true;
                }
            }
            p.waitFor();
        } catch (IOException | InterruptedException e) {
            logger.error("Failed to execute check for running Dropbox.exe: ", e);
        }
        return false;
    }
    return true;
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

protected static Process launchProcess(final String[] cmdlist, final Map<String, String> environment)
        throws IOException {
    ArrayList<String> buff = new ArrayList<String>();
    for (String tok : cmdlist) {
        if (!tok.isEmpty()) {
            buff.add(tok);//from w ww .  j  ava2 s .com
        }
    }

    ProcessBuilder builder = new ProcessBuilder(buff);
    builder.redirectErrorStream(true);
    Map<String, String> process_evn = builder.environment();
    for (Entry<String, String> entry : environment.entrySet()) {
        process_evn.put(entry.getKey(), entry.getValue());
    }

    return builder.start();
}

From source file:org.lantern.CommandLine.java

private void createProcess() {
    try {/*from w  w w.j av  a  2  s.  com*/
        ProcessBuilder builder = new ProcessBuilder(commandAndArgs);
        builder.redirectErrorStream(true);
        builder.environment().putAll(env);

        proc = builder.start();
        executed = true;
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
}

From source file:com.hivemq.maven.HiveMQMojo.java

/**
 * Starts the HiveMQ process with the given parameters
 *
 * @param commandParameters the parameters
 * @return the running HiveMQ process/*from   w ww  . j  a  v  a  2 s  .c  o m*/
 * @throws MojoExecutionException if the execution of HiveMQ did not work
 */
private Process startHiveMQ(final List<String> commandParameters) throws MojoExecutionException {
    final ProcessBuilder processBuilder = new ProcessBuilder(commandParameters);

    processBuilder.directory(hiveMQDir);
    processBuilder.redirectErrorStream(true);

    Process p;
    try {
        p = processBuilder.start();
    } catch (IOException e) {
        log.error("An error occured while starting HiveMQ:", e);
        throw new MojoExecutionException("An error occured while starting HiveMQ", e);
    }
    return p;
}

From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java

private void extractLocal() throws Exception {

    URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar");
    String homeDir = System.getProperty("user.home");
    String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar";
    File dest = new File(remoteJarFile);
    try {/* ww  w.j  ava  2 s.c om*/
        FileUtils.copyURLToFile(localJarUrl, dest);
    } catch (Exception e) {
        logger.error(e.toString());
    }

    String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY);
    String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY);
    String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY);
    String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY);
    String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1));
    String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY);
    // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY);
    String hdfsExtractLogFile = outputSchemaFile + ".log";

    String[] hadoopCmd = { "hadoop", "jar", remoteJarFile,
            "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile,
            "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile,
            "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster,
            "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList,
            "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread,
            "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" };
    // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab,
    ProcessBuilder pb = new ProcessBuilder(hadoopCmd);
    File logFile = new File(hdfsExtractLogFile);
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile));
    Process process = pb.start();
    int pid = -1;
    if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
        /* get the PID on unix/linux systems */
        try {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            pid = f.getInt(process);
        } catch (Throwable e) {
        }
    }
    logger.info("executue command [PID=" + pid + "]: " + hadoopCmd);

    // wait until this process finished.
    int execResult = process.waitFor();

    // if the process failed, log the error and throw exception
    if (execResult > 0) {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String errString = "HDFS Metadata Extract Error:\n";
        String line = "";
        while ((line = br.readLine()) != null)
            errString = errString.concat(line).concat("\n");
        logger.error("*** Process  failed, status: " + execResult);
        logger.error(errString);
        throw new Exception("Process + " + pid + " failed");
    }

}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected ProcessBuilder initCommand(String testName, int nb_iter) throws Exception {
    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(sci_tb_home);/*  ww  w  .ja v a  2 s . c  om*/
    pb.redirectErrorStream(true);
    int runAsMe = 0;

    if (System.getProperty("proactive.test.runAsMe") != null) {
        runAsMe = 1;
    }
    if (System.getProperty("scilab.test.leaks") != null) {
        testLeak = 1;
        leakFile = new File(test_home + fs + "JIMS.log");
        if (leakFile.exists()) {
            leakFile.delete();
        }
    }
    if (System.getProperty("scilab.bin.path") != null) {
        pb.command(System.getProperty("scilab.bin.path"), "-nw", "-f",
                (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(), "-args", schedURI.toString(),
                credFile.toString(), "" + nb_iter, testName, "" + runAsMe, "" + testLeak, "" + leakFile);
    } else {
        pb.command("scilab", "-nw", "-f", (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(),
                "-args", schedURI.toString(), credFile.toString(), "" + nb_iter, testName, "" + runAsMe,
                "" + testLeak, "" + leakFile);
    }
    return pb;
}

From source file:com.github.jrh3k5.mojo.flume.process.AgentProcessTest.java

/**
 * Test the construction of the Flume process.
 * //from w w  w . ja  v  a2s .  c o m
 * @throws Exception
 *             If any errors occur during the test run.
 */
@Test
public void testBuildFlumeProcess() throws Exception {
    final List<String> args = Arrays.asList("arg1", "arg2");
    final AgentProcess.ProcessBuilderProxy builderProxy = new AgentProcess.ProcessBuilderProxy(flumeDirectory,
            args);
    final ProcessBuilder builder = builderProxy.newProcessBuilder();
    assertThat(builder.command()).isEqualTo(args);
    assertThat(builder.directory()).isEqualTo(flumeDirectory);
    assertThat(builder.redirectErrorStream()).isTrue();
}

From source file:ca.phon.media.FFMpegMediaExporter.java

@Override
public void performTask() {
    super.setStatus(TaskStatus.RUNNING);

    // check options
    if (inputFile != null) {
        File f = new File(inputFile);
        if (!f.exists()) {
            IOException ex = new IOException("File not found");
            super.err = ex;
            super.setStatus(TaskStatus.ERROR);
            return;
        }/*from  w w w  .j  a  v  a2 s .c o m*/
    } else {
        IllegalArgumentException ex = new IllegalArgumentException("Input file cannot be null");
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
        return;
    }

    if (outputFile != null) {
        File f = new File(outputFile);
        File pf = f.getParentFile();

        if (!pf.exists()) {
            // try to create directories
            if (!pf.mkdirs()) {
                IOException ex = new IOException("Could not create output directory");
                super.err = ex;
                super.setStatus(TaskStatus.ERROR);
                return;
            }
        } else {
            if (!pf.isDirectory()) {
                IOException ex = new IOException(pf.getAbsolutePath() + " exists but is not a directory");
                super.err = ex;
                super.setStatus(TaskStatus.ERROR);
                return;
            }
        }
    } else {
        IllegalArgumentException ex = new IllegalArgumentException("Ouput file cannot be null");
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
        return;
    }

    List<String> cmdLine = getCmdLine();

    // setup process builder
    ProcessBuilder processBuilder = new ProcessBuilder(cmdLine);
    processBuilder.redirectErrorStream(true);
    try {
        // create process
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            LOGGER.info(line);
        }
        reader.close();

        super.setStatus(TaskStatus.FINISHED);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
    }

}