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:com.photon.phresco.plugins.xcode.CodeValidation.java

public void execute() throws MojoExecutionException {

    try {/*from w  w w .  j  ava2s.co  m*/
        ProcessBuilder pb = new ProcessBuilder(check);
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();

        commands.add("-o");
        commands.add("make");
        commands.add("xcodebuild");
        commands.add("-scheme");
        commands.add(scheme);
        commands.add("-project");
        commands.add(xcodeProject);
        commands.add("build");
        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    }
    createreport();
}

From source file:ch.entwine.weblounge.common.impl.util.process.ProcessExecutor.java

/**
 * Executes the process. During execution, {@link #onLineRead(String)} will be
 * called for process output. When finished, {@link #onProcessFinished(int)}
 * is called.//from  w w  w .j ava2  s .  co m
 * 
 * @throws ProcessExcecutorException
 *           if an error occurs during execution
 */
public final void execute() throws ProcessExcecutorException {
    BufferedReader in = null;
    Process process = null;
    StreamHelper errorStreamHelper = null;
    try {
        // create process.
        // no special working directory is set which means the working directory
        // of the current java process is used.
        ProcessBuilder pbuilder = new ProcessBuilder(commandLine);
        pbuilder.redirectErrorStream(redirectErrorStream);
        process = pbuilder.start();
        // Consume error stream if necessary
        if (!redirectErrorStream) {
            errorStreamHelper = new StreamHelper(process.getErrorStream());
        }
        // Read input and
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            if (!onLineRead(line))
                break;
        }

        // wait until the task is finished
        process.waitFor();
        int exitCode = process.exitValue();
        onProcessFinished(exitCode);
    } catch (Throwable t) {
        String msg = null;
        if (errorStreamHelper != null) {
            msg = errorStreamHelper.contentBuffer.toString();
        } else {
            msg = t.getMessage();
        }

        // TODO: What if the error stream has been redirected? Can we still get
        // the error message?

        throw new ProcessExcecutorException(msg, t);
    } finally {
        if (process != null)
            process.destroy();
        IOUtils.closeQuietly(in);
    }
}

From source file:org.sipfoundry.sipxconfig.admin.PackageUpdateManagerImpl.java

/**
 * Runs the sipxpackage command with a given argument.
 * @param argument The argument to pass to the sipxpackage command
 * @return A Process object for the running sipxpackage command
 * @throws IOException/*from  w w  w.  ja v  a  2s .com*/
 */
protected Process runPackageCommand(String argument) throws IOException {
    String binaryPath = m_adminContext.getLibExecDirectory() + File.separator + PACKAGE_BINARY;
    ProcessBuilder packageProcessBuilder = new ProcessBuilder(binaryPath, argument);
    packageProcessBuilder.redirectErrorStream(true);

    return packageProcessBuilder.start();
}

From source file:net.sf.jasperreports.phantomjs.PhantomJSProcess.java

public void startPhantomJS() {
    String mainScriptTempName = director.getScriptManager().getScriptFilename(PhantomJS.MAIN_SCRIPT_RESOURCE);
    String listenAddress = listenURI.getHost() + ":" + listenURI.getPort();
    int idleTimeout = director.getProcessIdleTimeout();

    List<String> command = new ArrayList<String>();
    command.add(director.getPhantomjsExecutablePath());
    String options = "";
    if (director.getOptions() != null) {
        for (PropertySuffix suffix : director.getOptions()) {
            String option = suffix.getValue();
            if (option != null && !option.trim().isEmpty()) {
                command.add(option.trim());
                options += option.trim() + " ";
            }//from w  w w  .  ja  v a 2  s.  co m
        }
    }

    command.add(mainScriptTempName);
    command.add("-listenAddress");
    command.add(listenAddress);
    command.add("-confirmMessage");
    command.add(PHANTOMJS_CONFIRMATION_MESSAGE);
    command.add("-idleTimeout");
    command.add(Integer.toString(idleTimeout));

    log.info("PhantomJS process " + id + " starting on port " + listenURI.getPort());
    if (log.isDebugEnabled()) {
        log.debug(id + " starting phantomjs process with command: " + director.getPhantomjsExecutablePath()
                + options + " \"" + mainScriptTempName + "\"" + " -listenAddress \"" + listenAddress + "\""
                + " -confirmMessage \"" + PHANTOMJS_CONFIRMATION_MESSAGE + "\"" + " -idleTimeout " + idleTimeout
                + "");
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(false);
    pb.directory(director.getScriptManager().getTempFolder());

    try {
        process = pb.start();

        ProcessOutputReader outputReader = new ProcessOutputReader(this);
        outputReader.start();
        boolean started = outputReader.waitConfirmation(director.getProcessStartTimeout());
        if (!started) {
            log.error("PhantomJS process " + id + " failed to start");//TODO lucianc write error output
            process.destroy();

            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_FAILED_START, (Object[]) null);
        }

        processConnection = new ProcessConnection(director, this);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:cz.cas.lib.proarc.common.process.AsyncProcess.java

@Override
public void run() {
    done.set(false);/*from w  ww .  jav a2  s  . c o m*/
    outputConsumer = null;
    exitCode = -1;
    ProcessBuilder pb = new ProcessBuilder(cmdLine);
    // for now redirect outputs into a single stream to eliminate
    // the need to run multiple threads to read each output
    pb.redirectErrorStream(true);
    pb.environment().putAll(env);
    try {
        Process process = pb.start();
        refProcess.set(process);
        outputConsumer = new OutputConsumer(process.getInputStream());
        outputConsumer.start();
        exitCode = process.waitFor();
        LOG.fine("Done " + cmdLine);
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, cmdLine.toString(), ex);
    } finally {
        done.set(true);
    }
}

From source file:org.dcm4che3.conf.core.storage.SingleJsonFileConfigurationStorage.java

private void commitToGitIfConfigured(String path) {
    if (makeGitCommitOnPersist) {

        try {//from   ww  w .  ja v  a 2  s.  c  o m
            ProcessBuilder processBuilder = new ProcessBuilder();

            processBuilder.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.INHERIT)
                    .directory(Paths.get(fileName).getParent().toFile());

            processBuilder.command("git", "init").start().waitFor();

            processBuilder.command("git", "add", "-A").start().waitFor();

            // add stacktrace to commitMsg
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            new RuntimeException().printStackTrace(ps);
            String niceStackTrace = baos.toString();
            niceStackTrace = niceStackTrace.replace("\"", "\\\"");
            String[] lines = niceStackTrace.split("\n");
            // remove the exception line itself
            niceStackTrace = String.join("\n", Arrays.copyOfRange(lines, 1, lines.length));

            String commitMsg = "\"Changed path " + path + "\n" + niceStackTrace + "\"";

            processBuilder.command("git", "commit", "-m", commitMsg).start().waitFor();

        } catch (Exception e) {
            throw new ConfigurationException("Cannot commit to git repo", e);
        }
    }
}

From source file:com.linkedin.restli.tools.idlgen.TestRestLiResourceModelExporter.java

private void compareFiles(String actualFileName, String expectedFileName) throws Exception {
    String actualContent = readFile(actualFileName);
    String expectedContent = readFile(expectedFileName);
    if (!actualContent.trim().equals(expectedContent.trim())) {
        // Ugh... gradle
        PrintStream actualStdout = new PrintStream(new FileOutputStream(FileDescriptor.out));
        actualStdout.println(/*from   w  ww .j  a v  a  2 s. c om*/
                "ERROR " + actualFileName + " does not match " + expectedFileName + " . Printing diff...");
        try {
            // TODO environment dependent, not cross platform
            ProcessBuilder pb = new ProcessBuilder("diff", expectedFileName, actualFileName);
            pb.redirectErrorStream();
            Process p = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;

            while ((line = reader.readLine()) != null) {
                actualStdout.println(line);
                //          System.out.println(line);
            }
        } catch (Exception e) {
            // TODO Setup log4j, find appropriate test harness used in R2D2
            actualStdout.println("Error printing diff: " + e.getMessage());
        }
        fail(actualFileName + " does not match " + expectedFileName);
    }
}

From source file:de.saly.es.example.tssl.plugin.test.multijvm.MultiJvmUnitTest.java

public void startCluster() throws Exception {
    final String separator = System.getProperty("file.separator");
    final String classpath = System.getProperty("java.class.path");
    final String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
    final ProcessBuilder processBuilder = new ProcessBuilder(path, "-Xmx1g", "-Xms1g", "-cp", classpath,
            Cluster.class.getCanonicalName());
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(Redirect.INHERIT);
    processes.add(processBuilder.start());
}

From source file:org.obiba.rserver.service.RServerService.java

private ProcessBuilder buildRProcess() {
    List<String> args = getArguments();
    log.info("Starting R server: {}", StringUtils.collectionToDelimitedString(args, " "));
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(getWorkingDirectory());
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(getRserveLogFile()));
    return pb;/*from w  w  w .j  a  va  2s  . c  om*/
}

From source file:org.apache.jackrabbit.webdav.simple.LitmusTest.java

public void testLitmus() throws Exception {
    File dir = new File("target", "litmus");
    String litmus = System.getProperty("litmus", "litmus");

    if (Boolean.getBoolean("jackrabbit.test.integration") && isLitmusAvailable(litmus)) {
        final Repository repository = JcrUtils
                .getRepository("jcr-jackrabbit://" + Text.escapePath(dir.getCanonicalPath()));
        Session session = repository.login(); // for the TransientRepository
        try {/*w  ww  . j a v a  2 s  .  c  om*/
            SocketConnector connector = new SocketConnector();
            connector.setHost("localhost");
            connector.setPort(Integer.getInteger("litmus.port", 0));

            Server server = new Server();
            server.addConnector(connector);

            ServletHolder holder = new ServletHolder(new SimpleWebdavServlet() {
                @Override
                public Repository getRepository() {
                    return repository;
                }
            });
            holder.setInitParameter("resource-config", "/config.xml");

            Context context = new Context(server, "/");
            context.setResourceBase("src/test/resources");
            context.addServlet(holder, "/*");
            server.addHandler(context);

            server.start();
            try {
                int port = connector.getLocalPort();
                String url = "http://localhost:" + port + "/default";

                ProcessBuilder builder = new ProcessBuilder(litmus, url, "admin", "admin");
                builder.directory(dir);
                builder.redirectErrorStream();

                assertLitmus(builder, "basic", 0);

                assertLitmus(builder, "http", 0);

                assertLitmus(builder, "props", 0);

                // FIXME: JCR-2637: WebDAV shallow copy test failure
                assertLitmus(builder, "copymove", 1);

                // FIXME: JCR-2638: Litmus locks test failures
                assertLitmus(builder, "locks", 1);
            } finally {
                server.stop();
            }
        } finally {
            session.logout();
        }
    }
}