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.geode.internal.cache.BackupJUnitTest.java

private void execute(File script, boolean expectFailure) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
    pb.redirectErrorStream(true);
    Process process = pb.start();

    InputStream is = process.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;//from  w ww .ja v  a  2  s .c om
    while ((line = br.readLine()) != null) {
        System.out.println("OUTPUT:" + line);
        // TODO validate output
    }

    int result = process.waitFor();
    boolean isWindows = script.getName().endsWith("bat");
    // On Windows XP, the process returns 0 even though we exit with a non-zero status.
    // So let's not bother asserting the return value on XP.
    if (!isWindows) {
        if (expectFailure) {
            assertEquals(1, result);
        } else {
            assertEquals(0, result);
        }
    }

}

From source file:jenkins.plugins.asqatasun.AsqatasunRunner.java

public void callService() throws IOException, InterruptedException {
    File logFile = AsqatasunRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");/*from w w w  .j a va 2s. co m*/
    File scenarioFile = AsqatasunRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    listener.getLogger().print("Launching asqatasun runner with the following options : ");
    listener.getLogger().print(pb.command());
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.forceDelete(logFile);
    }

    FileUtils.forceDelete(scenarioFile);
}

From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandlerWindowsRegistrationCommand.java

private String getCurrentProtocolHandlerRegistryValue() {
    BufferedReader stdout = null;
    String line;//ww w.j  av a2  s  . c om

    try {
        final ProcessBuilder pb = new ProcessBuilder("reg", //$NON-NLS-1$
                "query", //$NON-NLS-1$
                PROTOCOL_HANDLER_REGISTRY_PATH, "/ve"); //$NON-NLS-1$
        pb.redirectErrorStream(true);

        final Process cmd = pb.start();
        int rc = cmd.waitFor();

        if (rc == 0) {
            stdout = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
            while ((line = stdout.readLine()) != null) {
                int idx = 0;
                /* @formatter:off
                 * the output contains at most one line like 
                 * 
                 *    (Default)    REG_EXPAND_SZ    "%USERPROFILE%\.vsts\latestIDE.cmd" "%1"
                 * 
                 * @formatter:on
                 */
                if ((idx = line.indexOf(PROTOCOL_HANDLER_REG_VALUE_TYPE)) < 0) {
                    continue;
                }

                return line.substring(idx + PROTOCOL_HANDLER_REG_VALUE_TYPE.length()).trim();
            }
        }
    } catch (final InterruptedException e) {
        log.warn("Protocol handler registration has been cancelled."); //$NON-NLS-1$
    } catch (final Exception e) {
        log.error("Error accessing Windows registry:", e); //$NON-NLS-1$
    } finally {
        tryClose(stdout);
    }

    return null;
}

From source file:runtime.daemon.ProcessLauncher.java

private void ExecuteJob() {

    if (DEBUG && logger.isDebugEnabled())
        logger.debug("Job Started");

    MPJProcessTicket pTicket = new MPJProcessTicket();

    try {//from  w  w  w.j  a  v  a2  s .  co  m

        String ticketString = getStringFromInputStream(sockserver.getInputStream());

        if (ticketString != "")
            pTicket.FromXML(ticketString);
        if (DEBUG && logger.isDebugEnabled()) {
            logger.debug(pTicket.ToXML(false).toXmlString());
        }

    } catch (IOException e3) {
        e3.printStackTrace();
        return;
    }

    if (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev")) {
        JvmProcessCount = pTicket.getProcessCount();
    } else if (pTicket.getDeviceName().equals("hybdev")) {
        JvmProcessCount = 1;
    }

    OutputHandler[] outputThreads = new OutputHandler[JvmProcessCount];
    p = new Process[JvmProcessCount];
    argManager = new ProcessArgumentsManager(pTicket);
    String[] arguments = argManager.GetArguments(pTicket);

    for (int j = 0; j < JvmProcessCount; j++) {
        if (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev")) {
            String rank = new String("" + (pTicket.getStartingRank() + j));
            arguments[argManager.getRankArgumentIndex()] = rank;
            if (pTicket.isProfiler())
                arguments[1] = "-tau:node=" + rank;
        }
        if (pTicket.isDebug()
                && (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev"))) {
            arguments[argManager
                    .getDebugArgumentIndex()] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address="
                            + (pTicket.getDebugPort() + j * 2);
        }

        else if (pTicket.isDebug() && pTicket.getDeviceName().equals("hybdev")) {
            arguments[argManager
                    .getDebugArgumentIndex()] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address="
                            + (pTicket.getDebugPort());
        }

        if (DEBUG && logger.isDebugEnabled()) {
            for (int i = 0; i < arguments.length; i++) {
                logger.debug("arguments[" + i + "] = " + arguments[i]);
            }
        }

        ProcessBuilder pb = new ProcessBuilder(arguments);
        pb.directory(new File(pTicket.getWorkingDirectory()));
        pb.redirectErrorStream(true);

        if (DEBUG && logger.isDebugEnabled()) {
            logger.debug("starting the process ");
        }
        try {
            p[j] = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
         * Step 4: Start a new thread to handle output from this particular JVM.
         * FIXME: Now this seems like a good amount of overhead. If we start 4
         * JVMs on a quad-core CPU, we also start 4 additional threads to handle
         * I/O. Is it possible to get rid of this overhead?
         */
        outputThreads[j] = new OutputHandler(p[j], sockserver);
        outputThreads[j].start();

        if (DEBUG && logger.isDebugEnabled()) {
            logger.debug("started the process ");
        }
    } // end for loop.

    // Wait for the I/O threads to finish. They finish when
    // their corresponding JVMs finish.
    for (int j = 0; j < JvmProcessCount; j++) {
        try {
            outputThreads[j].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (DEBUG && logger.isDebugEnabled()) {
        logger.debug("Stopping the output");
    }

    if (sockserver != null && !sockserver.isClosed() && !sockserver.isOutputShutdown()) {
        OutputStream outToServer = null;
        try {
            outToServer = sockserver.getOutputStream();

            DataOutputStream out = new DataOutputStream(outToServer);
            out.write("EXIT".getBytes(), 0, "EXIT".getBytes().length);

            if (DEBUG && logger.isDebugEnabled())
                logger.debug("Job Finished");

            if (!DEBUG || !logger.isDebugEnabled()) {
                FileUtils.deleteDirectory(new File(argManager.getUsersDir()));
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (!sockserver.isClosed())
                try {
                    outToServer.close();
                    sockserver.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
    try {
        killProcesses();
    } catch (Exception e) {
        e.printStackTrace();
    }
    MPJDaemon.servSockets.remove(sockserver);
    if (DEBUG && logger.isDebugEnabled()) {
        logger.debug("\n\n ** .. execution ends .. ** \n\n");
    }

}

From source file:archive_v1.Retrieve.java

public void execRetrieve(String filename) {
    String execRetrieveCommand = null;

    execRetrieveCommand = "tar xvf /dev/st0 -C /u01/restore archive/" + filename;

    Process proc = null;//from ww w.  j  av a2 s  .c  o  m
    String output = null;
    try {

        ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", execRetrieveCommand);
        builder.redirectErrorStream(true);
        proc = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        output = reader.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.isi.wings.execution.engine.api.impl.distributed.DistributedExecutionEngine.java

@Override
public ProcessStatus call() throws Exception {
    File tempdir = File.createTempFile(planName + "-", "-" + exeName);
    if (!tempdir.delete() || !tempdir.mkdirs())
        throw new Exception("Cannot create temp directory");

    ProcessStatus status = new ProcessStatus();
    try {//ww w. ja v a  2  s  . c  o  m
        File codef = new File(this.codeBinary);
        codef.setExecutable(true);

        PrintWriter fout = null;
        if (outfilepath != null) {
            File f = new File(outfilepath);
            f.getParentFile().mkdirs();
            fout = new PrintWriter(f);
        }

        ProcessBuilder pb = new ProcessBuilder(args);
        pb.directory(tempdir);
        pb.redirectErrorStream(true);

        // Set environment variables
        for (String var : this.environment.keySet())
            pb.environment().put(var, this.environment.get(var));

        this.process = pb.start();

        // Read output stream
        StreamGobbler outputGobbler = new StreamGobbler(this.process.getInputStream(), fout);
        outputGobbler.start();

        // Wait for the process to exit
        this.process.waitFor();

        status.setExitValue(this.process.exitValue());
        status.setLog(outputGobbler.getLog());
    } catch (InterruptedException e) {
        if (this.process != null) {
            //System.out.println("Stopping remote process");
            this.process.destroy();
        }
        status.setLog("!! Stopping Remotely !! .. " + exeName);
        status.setExitValue(-1);
    } catch (Exception e) {
        status.setLog(e.getMessage());
        status.setExitValue(-1);
    }

    // Delete temp directory
    FileUtils.deleteDirectory(tempdir);
    return status;
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param command//  w w  w  .j  a v  a2  s. c o m
 * @throws IOException
 * @throws InterruptedException
 */
private void executeCommand(String command) throws IOException, InterruptedException {

    log.info("Command command[" + command + "]");

    ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s"));

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();

    StringWriter output = new StringWriter();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    try {
        int ch;
        while ((ch = reader.read()) != -1) {
            output.write(ch);
        }
    } finally {
        reader.close();
    }

    int result = process.waitFor();

    log.info("Command returnCode[" + result + "] output[" + output.toString() + "]");

    if (result != 0) {
        throw new IOException("Execute command Error command[" + command + "] returnCode[" + result
                + "] output[" + output.toString() + "]");
    }
}

From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java

protected void testPerformance(TestCase basisJob, TestCase testJob) throws Throwable {

    //cache serialized form to save time on repeated test iterations
    byte[] controlData = serializeJob(new TestProcess(testThreads, testLoop, basisJob));
    byte[] testData = serializeJob(new TestProcess(testThreads, testLoop, testJob));
    StatisticsMBean controlStats = new StatisticsMBean();
    controlStats.setUnits("nanoseconds");
    StatisticsMBean testStats = new StatisticsMBean();
    testStats.setUnits("nanoseconds");

    ServerSocket listener = new ServerSocket(0);
    try {//ww  w  . j a  v  a 2 s . c om
        int port = listener.getLocalPort();

        ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + separator + "/bin/java",
                "-server", "-cp", System.getProperty("java.class.path"), TestProcess.class.getName(),
                String.valueOf(port));
        pb.redirectErrorStream(false);

        //run several iterations of the test, alternating between instrumented and not
        //to absorb the affects of garbage collection.
        for (int i = 0; i < TEST_ITERATIONS; ++i) {
            System.out.println("iteration " + i);
            //switch the order of test / control runs during iteration to reduce any
            //bias that order might cause
            if (i % 2 == 0) {
                runTest(listener, pb, testStats, testData);
                runTest(listener, pb, controlStats, controlData);
            } else {
                runTest(listener, pb, controlStats, controlData);
                runTest(listener, pb, testStats, testData);
            }
            assertEquals("basis and test have same sample size after iteration " + i, controlStats.getCount(),
                    testStats.getCount());
        }
    } finally {
        listener.close();
    }

    double basisNanos = controlStats.getAverageTime();
    double cpuCoefficient = basisNanos / (double) expectedBasis;

    double expectedAverage = cpuCoefficient * averageOverhead;
    double expectedMax = cpuCoefficient * maxOverhead;

    System.out.println("control:\n" + controlStats);
    System.out.println("test:\n" + testStats);
    System.out.println("CPU Coefficient: " + cpuCoefficient);
    System.out.println("basisNanos: " + basisNanos);

    //compute the overhead as the difference between instrumented and uninstrumented
    //runs.  we want the per-event overhead to be less than .5 ms.
    double delta = testStats.getAverageTime() - basisNanos;
    //deltaWorst, my favorite sausage.  mmmmmm, dellltttaaaWwwwooorrsstt.
    double deltaWorst = testStats.getMaxTime() - controlStats.getMaxTime();

    System.out.println("Maximum expected average overhead: " + expectedAverage);
    System.out.println("Average overhead: " + delta);
    System.out.println("Maximum expected worst case overhead: " + expectedMax);
    System.out.println("Worst case overhead: " + deltaWorst);

    assertTrue("Average overhead per method cannot exceed " + expectedAverage + "ns [ " + delta + " ]",
            delta <= expectedAverage);

    assertTrue("Worst case per method overhead cannot exceed " + expectedMax + "ns [ " + deltaWorst + " ]",
            deltaWorst <= expectedMax);
}

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

@Override
public void generate(final String url, final File outputFile) {
    if (logger.isDebugEnabled()) {
        logger.debug("Generate ScreenShot: " + url);
    }/*  w w w.j av a  2 s  .  co  m*/

    if (outputFile.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("The screenshot file exists: " + outputFile.getAbsolutePath());
        }
        return;
    }

    final File parentFile = outputFile.getParentFile();
    if (!parentFile.exists()) {
        parentFile.mkdirs();
    }
    if (!parentFile.isDirectory()) {
        logger.warn("Not found: " + parentFile.getAbsolutePath());
        return;
    }

    final String outputPath = outputFile.getAbsolutePath();
    final List<String> cmdList = new ArrayList<>();
    for (final String value : commandList) {
        cmdList.add(value.replace("${url}", url).replace("${outputFile}", outputPath));
    }

    ProcessBuilder pb = null;
    Process p = null;

    if (logger.isDebugEnabled()) {
        logger.debug("ScreenShot 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 screenshot of " + url, e);
    }
    if (task != null) {
        task.cancel();
        task = null;
    }

    if (outputFile.isFile() && outputFile.length() == 0) {
        logger.warn("ScreenShot File is empty. URL is " + url);
        if (outputFile.delete()) {
            logger.info("Deleted: " + outputFile.getAbsolutePath());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("ScreenShot File: " + outputPath);
    }
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private void startPostmaster() throws IOException {
    final StopWatch watch = new StopWatch();
    watch.start();/* w  w w.j  a  va 2s  . c o m*/
    Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");

    final List<String> args = Lists.newArrayList(pgBin("postgres"), "-D", dataDirectory.getPath(), "-p",
            Integer.toString(port), "-i", "-F");

    for (final Entry<String, String> config : postgresConfig.entrySet()) {
        args.add("-c");
        args.add(config.getKey() + "=" + config.getValue());
    }

    final ProcessBuilder builder = new ProcessBuilder(args);
    builder.redirectErrorStream(true);
    builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    postmaster = builder.start();
    LOG.info("{} postmaster started as {} on port {}.  Waiting up to {}ms for server startup to finish.",
            instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);

    Runtime.getRuntime().addShutdownHook(newCloserThread());

    waitForServerStartup(watch);
}