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:ee.ria.xroad.confproxy.util.ConfProxyHelper.java

/**
 * Invoke the configuration client script to check whether the downloaded
 * global configuration is valid according to the provided source anchor.
 * @param sourceAnchor path to the source anchor xml file
 * @throws Exception if an configuration client error occurs
 *//*from   www . j  a  v  a2  s  .  co m*/
public static void validateConfiguration(final String sourceAnchor) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(ConfProxyProperties.getDownloadScriptPath(), sourceAnchor);
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    log.info("Running '{} {}' ...", ConfProxyProperties.getDownloadScriptPath(), sourceAnchor);
    runConfClient(pb);
}

From source file:org.jsweet.test.transpiler.AbstractTest.java

public static int runTsc(String... files) throws IOException {
    String[] args;/*from  w ww .ja va 2  s.  c o  m*/
    if (System.getProperty("os.name").startsWith("Windows")) {
        args = new String[] { "cmd", "/c", "tsc --target ES3" };
    } else {
        args = new String[] { "tsc", "--target", "ES3" };
    }
    args = ArrayUtils.addAll(args, files);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.redirectErrorStream(true);
    Process process = pb.start();

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        return process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Run command cmd in separate process in directory
 *
 * @param directory    run in this directory
 * @param cmd          command to run/*w  w w .j a  v  a2 s  .  co  m*/
 * @param errorMessage error message if process didn't finish with exit value 0
 * @return stdout combined with stderr
 * @throws Exception
 */
public static String runCmd(File directory, List<String> cmd, String errorMessage) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(directory);
    pb.redirectErrorStream(true); // error sent to output stream
    Process p = pb.start();

    // get output stream to string
    String s;
    StringBuilder sb = new StringBuilder();
    BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((s = stdout.readLine()) != null) {
        logger.info(s);
        sb.append(s);
        sb.append('\n');
    }
    String sbs = sb.toString();
    int exitValue = p.waitFor();
    if (exitValue != 0)
        throw new Exception(errorMessage + " exit value " + exitValue + "  " + sbs);
    return sbs;
}

From source file:com.google.dart.tools.designer.model.HtmlRenderHelper.java

/**
 * @return the image of given HTML content, may be <code>null</code>.
 *//*w  w  w  .  ja va  2  s  .  c  om*/
public static Image renderImage(final String content) {
    try {
        File tempFile = File.createTempFile("htmlRender", ".html");
        try {
            IOUtils2.writeBytes(tempFile, content.getBytes());
            // start DumpRenderTree
            if (processOutputStream == null) {
                String path;
                {
                    Bundle bundle = DartDesignerPlugin.getDefault().getBundle();
                    URL url = bundle.getEntry("lib/DumpRenderTree.app/Contents/MacOS/DumpRenderTree");
                    path = FileLocator.toFileURL(url).getPath();
                }
                //        ProcessBuilder builder = new ProcessBuilder(path, "-p", tempFile.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(path, "-p", "-");
                builder.redirectErrorStream(true);
                Process process = builder.start();
                processOutputStream = process.getOutputStream();
                processInputStream = process.getInputStream();
                processReader = new BufferedReader(new InputStreamReader(processInputStream));
            }
            long start = System.nanoTime();
            // XXX
            //        processOutputStream.write((tempFile.getAbsolutePath() + "\n").getBytes());
            processOutputStream
                    .write(("http://127.0.0.1:3030/Users/scheglov/dart/dwc_first/web/out/dwc_first.html\n")
                            .getBytes());
            processOutputStream.flush();
            // read tree
            while (true) {
                String line = processReader.readLine();
                System.out.println(line);
                if (line.isEmpty()) {
                    break;
                }
            }
            // read image
            {
                processReader.readLine(); // ActualHash:
                processReader.readLine(); // Content-Type: image/png
                String lengthLine = processReader.readLine(); // Content-Length: 5546
                int pngLength = Integer.parseInt(StringUtils.removeStart(lengthLine, "Content-Length: "));
                //          System.out.println("pngLength: " + pngLength);
                char[] pngChars = new char[pngLength];
                readFully(processReader, pngChars);
                byte[] pngBytes = new String(pngChars).getBytes();
                Image image = new Image(null, new ByteArrayInputStream(pngBytes));
                System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
                return image;
            }
            //
            //        {
            //          SessionInputBuffer buffer = new AbstractSessionInputBuffer() {
            //            {
            //              init(processInputStream, 1024, new BasicHttpParams());
            //            }
            //
            //            @Override
            //            public boolean isDataAvailable(int timeout) throws IOException {
            //              return false;
            //            }
            //          };
            //          LineParser lineParser = new BasicLineParser(new ProtocolVersion("HTTP", 1, 1));
            //          HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(
            //              buffer,
            //              lineParser,
            //              new DefaultHttpResponseFactory(),
            //              new BasicHttpParams());
            //          HttpResponse response = parser.parse();
            //          System.out.println(response);
            //          HttpParams params = new BasicHttpParams();
            //          SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
            //          HttpMessageParser<BasicHttpResponse> parser = new DefaultResponseParser(
            //              inbuffer,
            //              BasicLineParser.DEFAULT,
            //              new DefaultHttpResponseFactory(),
            //              params);
            //
            //          HttpResponse response = parser.parse();
            //        }
            //        while (true) {
            //          String line = processReader.readLine();
            //          System.out.println(line);
            //        }
            //
            //        byte[] bytes = IOUtils2.readBytes(processInputStream);
            //        int exitValue = process.exitValue();
            //        System.out.println("bytes: " + bytes.length);
            //        System.out.println("bytesTime: " + (System.nanoTime() - start) / 1000000.0);
            //        String output = new String(bytes);
            //        System.out.println(StringUtils.substring(output, -10, 0));
            ////        System.out.println(output);
            //        //
            //        int pngOffset = output.indexOf("Content-Type: image/png");
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        Image image = new Image(null, new ByteArrayInputStream(bytes, pngOffset, bytes.length
            //            - pngOffset));
            //        System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
            //        return image;
        } finally {
            tempFile.delete();
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

private static Process remoteInvoke(String cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("vagrant", "ssh", "cc", "-c", "MANAGIX_HOME=/tmp/asterix/ " + cmd);
    File cwd = new File(asterixProjectDir.toString() + "/" + CLUSTER_BASE);
    pb.directory(cwd);/*  ww w.j  av a2s .com*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    return p;
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

protected static String runProcess(String[] commandLine) throws IOException {
    StringBuilder cl = new StringBuilder();
    for (String i : commandLine) {
        cl.append(i);/*from ww w .  j  a  v  a  2 s  . c o m*/
        cl.append(" ");
    }

    String result = "";

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    Map<String, String> env = builder.environment();
    env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
    builder.redirectErrorStream(true);
    Process process = builder.start();

    String line;

    InputStream stdout = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }

    boolean isProcessRunning = true;
    int maxRetries = 60;

    do {
        try {
            isProcessRunning = process.exitValue() < 0;
        } catch (IllegalThreadStateException ex) {
            System.out.println("Process not terminated. Waiting ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException iex) {
                //nothing todo
            }
            maxRetries--;
        }
    } while (isProcessRunning && maxRetries > 0);
    System.out.println("Process has terminated");
    if (process.exitValue() != 0) {
        throw new IllegalStateException("Exit value not equal to 0: " + result);
    }
    if (maxRetries == 0 && isProcessRunning) {
        System.out.println("Process does not terminate. Try to kill the process now.");
        process.destroy();
    }

    return result;
}

From source file:com.atlassian.labs.bamboo.git.edu.nyu.cs.javagit.client.cli.ProcessUtilities.java

/**
 * Runs the command specified in the command line with the specified working directory. The
 * IParser is used to parse the response given by the command line.
 *
 * @param workingDirectory//from   www . j ava  2s  . co m
 *          The working directory in with which to start the process.
 * @param commandLine
 *          The command line to run.
 * @param parser
 *          The parser to use to parse the command line's response.
 * @return The command response from the <code>IParser</code>.
 * @throws IOException
 *           Thrown if there are problems with the subprocess.
 * @throws JavaGitException
 */
public static CommandResponse runCommand(File workingDirectory, List<String> commandLine, IParser parser)
        throws IOException, JavaGitException {
    ProcessBuilder pb = new ProcessBuilder(commandLine);
    LOG.debug("Command:" + commandLine);
    if (workingDirectory != null) {
        pb.directory(workingDirectory);
    }

    pb.redirectErrorStream(true);

    Process p = startProcess(pb);
    getProcessOutput(p, parser);
    waitForAndDestroyProcess(p, parser);

    return parser.getResponse();
}

From source file:ee.ria.xroad.confproxy.util.ConfProxyHelper.java

/**
 * Invoke the configuration client script to download the global
 * configuration from the source defined in the provided source anchor.
 * @param path where the downloaded files should be placed
 * @param sourceAnchor path to the source anchor xml file
 * @return downloaded configuration directory
 * @throws Exception if an configuration client error occurs
 *//*from   www.java2  s . c o  m*/
public static ConfigurationDirectory downloadConfiguration(final String path, final String sourceAnchor,
        final int version) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(ConfProxyProperties.getDownloadScriptPath(), sourceAnchor, path,
            String.format("%d", version));
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    log.info("Running '{} {} {} {}' ...", ConfProxyProperties.getDownloadScriptPath(), sourceAnchor, path,
            version);
    runConfClient(pb);
    if (version != SystemProperties.CURRENT_GLOBAL_CONFIGURATION_VERSION) {
        return new ConfigurationDirectoryV1(path);
    } else {
        return new ConfigurationDirectoryV2(path);
    }
}

From source file:gool.executor.Command.java

/**
 * Executes a command in the specified working directory.
 * /* ww w  .  j  av  a  2  s .  c o  m*/
 * @param workingDir
 *            the working directory.
 * @param params
 *            the command to execute and its parameters.
 * @return the console output.
 */
public static String exec(File workingDir, List<String> params, Map<String, String> env) {
    try {
        StringBuffer buffer = new StringBuffer();

        ProcessBuilder pb = new ProcessBuilder(params);
        pb.directory(workingDir);

        for (Entry<String, String> e : env.entrySet()) {
            pb.environment().put(e.getKey(), e.getValue());
        }
        Process p = pb.redirectErrorStream(true).start();

        p.getOutputStream().close();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line).append("\n");
        }

        int retval = p.waitFor();

        if (retval != 0) {
            throw new CommandException(
                    "The command execution returned " + retval + " as return value... !\n" + buffer);
        }

        return buffer.toString();
    } catch (IOException e) {
        throw new CommandException(e);
    } catch (InterruptedException e) {
        throw new CommandException("It seems the process was killed", e);
    }
}

From source file:functionaltests.RestFuncTHelper.java

public static void startRestfulSchedulerWebapp(int nbNodes) throws Exception {
    // Kill all children processes on exit
    org.apache.log4j.BasicConfigurator.configure(new org.apache.log4j.varia.NullAppender());
    CookieBasedProcessTreeKiller.registerKillChildProcessesOnShutdown("rest_tests");

    List<String> cmd = new ArrayList<>();
    String javaPath = RestFuncTUtils.getJavaPathFromSystemProperties();
    cmd.add(javaPath);/*from  w  w w .j a  v  a2 s  .  c  o m*/
    cmd.add("-Djava.security.manager");
    cmd.add(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine() + toPath(serverJavaPolicy));

    cmd.add(CentralPAPropertyRepository.PA_HOME.getCmdLine() + getSchedHome());
    cmd.add(PASchedulerProperties.SCHEDULER_HOME.getCmdLine() + getSchedHome());
    cmd.add(PAResourceManagerProperties.RM_HOME.getCmdLine() + getRmHome());

    cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getCmdLine()
            + System.getProperty("rm.deploy.dropDB", "true"));
    cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(rmHibernateConfig));

    cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_DROPDB.getCmdLine()
            + System.getProperty("scheduler.deploy.dropDB", "true"));
    cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(schedHibernateConfig));

    cmd.add(CentralPAPropertyRepository.PA_COMMUNICATION_PROTOCOL.getCmdLine() + "pnp");
    cmd.add(PNPConfig.PA_PNP_PORT.getCmdLine() + "1200");

    cmd.add("-cp");
    cmd.add(getClassPath());
    cmd.add(SchedulerStarter.class.getName());
    cmd.add("-ln");
    cmd.add("" + nbNodes);

    ProcessBuilder processBuilder = new ProcessBuilder(cmd);
    processBuilder.redirectErrorStream(true);
    schedProcess = processBuilder.start();

    ProcessStreamReader out = new ProcessStreamReader("scheduler-output: ", schedProcess.getInputStream());
    out.start();

    // RM and scheduler are on the same url
    String port = "1200";
    String url = "pnp://localhost:" + port + "/";

    // Connect a scheduler client
    SchedulerAuthenticationInterface schedAuth = SchedulerConnection.waitAndJoin(url,
            TimeUnit.SECONDS.toMillis(60));
    schedulerPublicKey = schedAuth.getPublicKey();
    Credentials schedCred = RestFuncTUtils.createCredentials("admin", "admin", schedulerPublicKey);
    scheduler = schedAuth.login(schedCred);

    // Connect a rm client
    RMAuthentication rmAuth = RMConnection.waitAndJoin(url, TimeUnit.SECONDS.toMillis(60));
    Credentials rmCredentials = getRmCredentials();
    rm = rmAuth.login(rmCredentials);

    restServerUrl = "http://localhost:8080/rest/";
    restfulSchedulerUrl = restServerUrl + "scheduler";

    await().atMost(Duration.FIVE_MINUTES).until(restIsStarted());
}