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.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 ww  . j  a va  2s .c  o  m*/
}

From source file:org.codelibs.fess.thumbnail.impl.CommandGenerator.java

protected void executeCommand(final String thumbnailId, final List<String> cmdList) {
    ProcessBuilder pb = null;
    Process p = null;// w w  w  .  j a  v  a 2 s.c  o m

    if (logger.isDebugEnabled()) {
        logger.debug("Thumbnail Command: " + cmdList);
    }

    TimerTask task = null;
    try {
        pb = new ProcessBuilder(cmdList);
        pb.directory(baseDir);
        pb.redirectErrorStream(true);

        p = pb.start();

        task = new ProcessDestroyer(p, cmdList);
        try {
            destoryTimer.schedule(task, commandTimeout);

            String line;
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
                while ((line = br.readLine()) != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(line);
                    }
                }
            } finally {
                IOUtils.closeQuietly(br);
            }

            p.waitFor();
        } catch (final Exception e) {
            p.destroy();
        }
    } catch (final Exception e) {
        logger.warn("Failed to generate a thumbnail of " + thumbnailId, e);
    }
    if (task != null) {
        task.cancel();
        task = null;
    }
}

From source file:org.opencastproject.sox.impl.SoxServiceImpl.java

private List<String> launchSoxProcess(List<String> command) throws SoxException {
    Process process = null;/*from   w  ww.j a va 2s.  c  o m*/
    BufferedReader in = null;
    try {
        logger.info("Start sox process {}", command);
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true); // Unfortunately merges but necessary for deadlock prevention
        process = pb.start();
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        process.waitFor();
        String line = null;
        List<String> stats = new ArrayList<String>();
        while ((line = in.readLine()) != null) {
            logger.info(line);
            stats.add(line);
        }
        if (process.exitValue() != 0)
            throw new SoxException("Sox process failed with error code: " + process.exitValue());
        logger.info("Sox process finished");
        return stats;
    } catch (IOException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } catch (InterruptedException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } finally {
        IoSupport.closeQuietly(in);
    }
}

From source file:com.urbancode.terraform.tasks.vmware.events.CloneVmCreatedEventListener.java

public void runCommand(String vmUser, String vmPassword, String vmRunCommand, List<String> args)
        throws IOException, InterruptedException {
    if (vmUser == null || vmPassword == null) {
        log.error("Either VM user or password were null. "
                + "They need to be specified in the template under the clone element.");
        throw new NullPointerException();
    }/*from w w w  . ja  va2s.c  om*/
    VirtualHost host = environment.fetchVirtualHost();
    host.waitForVmtools(router);
    String vmx = host.getVmxPath(router);
    String url = host.getUrl();
    String virtualHostUser = host.getUser();
    String virtualHostPassword = host.getPassword();
    List<String> commandLine = new ArrayList<String>();
    commandLine.add("vmrun");
    commandLine.add("-T");
    commandLine.add("server");
    commandLine.add("-h");
    commandLine.add(url);
    commandLine.add("-u");
    commandLine.add(virtualHostUser);
    commandLine.add("-p");
    commandLine.add(virtualHostPassword);
    commandLine.add("-gu");
    commandLine.add(vmUser);
    commandLine.add("-gp");
    commandLine.add(vmPassword);
    commandLine.add(vmRunCommand);
    commandLine.add(vmx);
    commandLine.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);
    Process process = builder.start();

    InputStream procIn = process.getInputStream();
    IOUtil.getInstance().discardStream(procIn);

    int exitCode = process.waitFor();
    if (exitCode != 0) {
        throw new IOException("Command failed with code " + exitCode);
    }
    log.info("ran command " + vmRunCommand + " " + args.get(0));
}

From source file:org.apache.htrace.util.HTracedProcess.java

public HTracedProcess(final File binPath, final File dataDir, final String host) throws IOException {
    // Create a notifier socket bound to a random port.
    ServerSocket listener = new ServerSocket(0);
    boolean success = false;
    Process process = null;/*from   ww  w.j  av  a 2  s. c  o m*/
    try {
        // Use a random port for the web address.  No 'scheme' yet.
        String webAddress = host + ":0";
        String logPath = new File(dataDir, "log.txt").getAbsolutePath();
        // Pass cmdline args to htraced to it uses our test dir for data.
        ProcessBuilder pb = new ProcessBuilder(binPath.toString(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath,
                "-Dweb.address=" + webAddress, "-Ddata.store.clear=true",
                "-Dstartup.notification.address=localhost:" + listener.getLocalPort(),
                "-Ddata.store.directories=" + dataDir.toString());
        pb.redirectErrorStream(true);
        // Inherit STDERR/STDOUT i/o; dumps on console for now.  Can add logs later.
        pb.inheritIO();
        pb.directory(dataDir);
        //assert pb.redirectInput() == Redirect.PIPE;
        //assert pb.redirectOutput().file() == dataDir;
        process = pb.start();
        assert process.getInputStream().read() == -1;
        StartupNotificationData data = readStartupNotification(listener);
        httpAddr = data.httpAddr;
        LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr
                + ", logging to " + logPath);
        success = true;
    } finally {
        if (!success) {
            // Clean up after failure
            if (process != null) {
                process.destroy();
                process = null;
            }
        }
        delegate = process;
        listener.close();
    }
}

From source file:org.kyasuda.docwaza.office.OfficeProcess.java

protected void determineOfficeVersion() throws IOException {

    File executable = OfficeUtils.getOfficeExecutable(officeHome);
    if (PlatformUtils.isWindows()) {
        versionDescriptor = OfficeVersionDescriptor.parseFromExecutableLocation(executable.getPath());
        return;/*from w  w  w.  j  a  v a  2 s  .  c  o  m*/
    }

    List<String> command = new ArrayList<String>();
    command.add(executable.getAbsolutePath());
    command.add("-help");
    command.add("-headless");
    command.add("-nocrashreport");
    command.add("-nofirststartwizard");
    command.add("-nolockcheck");
    command.add("-nologo");
    command.add("-norestore");
    command.add("-env:UserInstallation=" + OfficeUtils.toUrl(instanceProfileDir));
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    if (PlatformUtils.isWindows()) {
        addBasisAndUrePaths(processBuilder);
    }
    Process checkProcess = processBuilder.start();
    try {
        checkProcess.waitFor();
    } catch (InterruptedException e) {
        // NOP
    }
    InputStream in = checkProcess.getInputStream();
    String versionCheckOutput = read(in);
    versionDescriptor = new OfficeVersionDescriptor(versionCheckOutput);
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private void loadProgramSymbols(Program program, String tosPlatform) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(GET_SYMBOLS,
            program.getSourcePath() + "/build/" + tosPlatform + "/main.exe");

    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

    for (String line = in.readLine(); line != null; line = in.readLine()) {
        try {//from   w w  w .j a  v a 2  s .c  o  m
            log.debug("Program symbol line: " + line);

            String[] tokens = line.split("\\s");
            int address = Integer.parseInt(tokens[0], 16);
            int size = Integer.parseInt(tokens[1], 16);
            String module = tokens[2].substring(0, tokens[2].indexOf('.'));
            String symbol = tokens[2].substring(tokens[2].indexOf('.') + 1);

            log.debug("Address = " + address + "size = " + size + "module = " + module + "symbol = " + symbol);

            ProgramSymbolManagerImpl.getInstance().createProgramSymbol(program.getID(), module, symbol, address,
                    size);
        } catch (StringIndexOutOfBoundsException ex) {
            log.error(ex);
        }
    }
}

From source file:org.apache.storm.util.CoreUtil.java

@ClojureClass(className = "backtype.storm.util#launch-process")
public static java.lang.Process launchProcess(String command, Map<String, String> environment)
        throws IOException {
    String[] cmdlist = (new String("nohup " + command)).split(" ");
    ArrayList<String> buff = new ArrayList<String>();
    for (String tok : cmdlist) {
        if (!tok.isEmpty()) {
            buff.add(tok);//from   ww w .  j a  va2 s  .  c o m
        }
    }

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

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

private synchronized void runWorkflow(String command, String workflow, File outputsDirectory,
        boolean inputValues, boolean secure, boolean database) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder("sh", command);
    processBuilder.redirectErrorStream(true);
    processBuilder.directory(buildDirectory);
    List<String> args = processBuilder.command();
    for (File input : inputs) {
        if (inputValues) {
            args.add("-inputvalue");
            args.add(input.getName());/*from  ww  w. j a  v a 2s.c o m*/
            args.add(IOUtils.toString(new FileReader(input)));
        } else {
            args.add("-inputfile");
            args.add(input.getName());
            args.add(input.getAbsolutePath());
        }
    }
    args.add("-outputdir");
    args.add(outputsDirectory.getPath());
    if (secure) {
        args.add("-cmdir");
        args.add(getClass().getResource("/security").getFile());
        args.add("-cmpassword");
    }
    if (database) {
        args.add("-embedded");
    }
    args.add(workflow);
    Process process = processBuilder.start();
    if (secure) {
        PrintStream outputStream = new PrintStream(process.getOutputStream());
        outputStream.println("test");
        outputStream.flush();
    }
    waitFor(process);
}

From source file:oracle.CubistOracle.common.CubistOracle.java

/**
 * Following https://www.securecoding.cert.org/confluence/display/java/FIO07-J.+Do+not+let+external+processes+block+on+IO+buffers
 * I am going to rewrite this/*  w ww.  ja  v  a2  s  .c  o  m*/
 *
 * @param filestem
 * @return
 */

private String createCubistModel(String filestem) {
    try {
        String[] command = buildCommand(filestem);
        ProcessBuilder pb = new ProcessBuilder(command);
        if (t)
            log.trace("Invoking " + Arrays.toString(command));
        pb = pb.redirectErrorStream(true);
        Process p = pb.start();
        StringBuffer printErr = new StringBuffer();
        StringBuffer printOut = new StringBuffer();

        // Any error message?
        StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), System.err, printErr, true);

        // Any output?
        StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), System.out, printOut, t);

        errorGobbler.start();
        //if (t) {
        outputGobbler.start();
        //}

        int exitVal = p.waitFor();

        errorGobbler.join(); // Handle condition where the process ends before the threads finish
        //if (t) {
        outputGobbler.join();
        //}

        if (printErr.length() != 0) {
            throw new RuntimeException(printErr.toString());
        }
        if (cubistConfig.isPrintModelOnBuild()) {
            printOutputBuild(p);
        }
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not create CubistModel " + e.getMessage());
    }
    return modelString();
}