Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

In this page you can find the example usage for java.lang Process exitValue.

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:org.wso2.andes.test.utils.QpidBrokerTestCase.java

public void startBroker(int port) throws Exception
{
    port = getPort(port);//from   w ww  .j a  va  2s.co  m

    // Save any configuration changes that have been made
    saveTestConfiguration();
    saveTestVirtualhosts();

    if(_brokers.get(port) != null)
    {
        throw new IllegalStateException("There is already an existing broker running on port " + port);
    }

    if (_brokerType.equals(BrokerType.INTERNAL) && !existingInternalBroker())
    {
        setConfigurationProperty(ServerConfiguration.MGMT_CUSTOM_REGISTRY_SOCKET, String.valueOf(false));
        saveTestConfiguration();

        BrokerOptions options = new BrokerOptions();
        options.setConfigFile(_configFile.getAbsolutePath());
        options.addPort(port);

        addExcludedPorts(port, options);

        options.setJmxPort(getManagementPort(port));

        //Set the log config file, relying on the log4j.configuration system property
        //set on the JVM by the JUnit runner task in module.xml.
        options.setLogConfigFile(new URL(System.getProperty("log4j.configuration")).getFile());

        Broker broker = new Broker();
        _logger.info("starting internal broker (same JVM)");
        broker.startup(options);

        _brokers.put(port, new InternalBrokerHolder(broker));
    }
    else if (!_brokerType.equals(BrokerType.EXTERNAL))
    {
        String cmd = getBrokerCommand(port);
        _logger.info("starting external broker: " + cmd);
        ProcessBuilder pb = new ProcessBuilder(cmd.split("\\s+"));
        pb.redirectErrorStream(true);

        Map<String, String> env = pb.environment();

        String qpidHome = System.getProperty(QPID_HOME);
        env.put(QPID_HOME, qpidHome);

        //Augment Path with bin directory in QPID_HOME.
        env.put("PATH", env.get("PATH").concat(File.pathSeparator + qpidHome + "/bin"));

        //Add the test name to the broker run.
        // DON'T change PNAME, qpid.stop needs this value.
        env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\"");
        // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests
        env.put("QPID_WORK", getQpidWork(_brokerType, port));


        // Use the environment variable to set amqj.logging.level for the broker
        // The value used is a 'server' value in the test configuration to
        // allow a differentiation between the client and broker logging levels.
        if (System.getProperty("amqj.server.logging.level") != null)
        {
            setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level"));
        }

        // Add all the environment settings the test requested
        if (!_env.isEmpty())
        {
            for (Map.Entry<String, String> entry : _env.entrySet())
            {
                env.put(entry.getKey(), entry.getValue());
            }
        }


        // Add default test logging levels that are used by the log4j-test
        // Use the convenience methods to push the current logging setting
        // in to the external broker's QPID_OPTS string.
        if (System.getProperty("amqj.protocol.logging.level") != null)
        {
            setSystemProperty("amqj.protocol.logging.level");
        }
        if (System.getProperty("root.logging.level") != null)
        {
            setSystemProperty("root.logging.level");
        }


        String QPID_OPTS = " ";
        // Add all the specified system properties to QPID_OPTS
        if (!_propertiesSetForBroker.isEmpty())
        {
            for (String key : _propertiesSetForBroker.keySet())
            {
                QPID_OPTS += "-D" + key + "=" + _propertiesSetForBroker.get(key) + " ";
            }

            if (env.containsKey("QPID_OPTS"))
            {
                env.put("QPID_OPTS", env.get("QPID_OPTS") + QPID_OPTS);
            }
            else
            {
                env.put("QPID_OPTS", QPID_OPTS);
            }
        }
        Process process = pb.start();;

        Piper p = new Piper(process.getInputStream(),
                          _brokerOutputStream,
                            System.getProperty(BROKER_READY),
                            System.getProperty(BROKER_STOPPED));

        p.start();

        if (!p.await(30, TimeUnit.SECONDS))
        {
            _logger.info("broker failed to become ready (" + p.ready + "):" + p.getStopLine());
            //Ensure broker has stopped
            process.destroy();
            cleanBroker();
            throw new RuntimeException("broker failed to become ready:"
                                       + p.getStopLine());
        }

        try
        {
            //test that the broker is still running and hasn't exited unexpectedly
            int exit = process.exitValue();
            _logger.info("broker aborted: " + exit);
            cleanBroker();
            throw new RuntimeException("broker aborted: " + exit);
        }
        catch (IllegalThreadStateException e)
        {
            // this is expect if the broker started successfully
        }

        _brokers.put(port, new SpawnedBrokerHolder(process));
    }
}

From source file:org.pentaho.di.job.entries.pgpencryptfiles.GPG.java

/**
 * Runs GnuPG external program/*w ww  .  j a v  a2 s.  c om*/
 *
 * @param commandArgs
 *          command line arguments
 * @param inputStr
 *          key ID of the key in GnuPG's key database
 * @param fileMode
 * @return result
 * @throws KettleException
 */
private String execGnuPG(String commandArgs, String inputStr, boolean fileMode) throws KettleException {
    Process p;
    String command = getGpgExeFile() + " " + (fileMode ? "" : gnuPGCommand + " ") + commandArgs;

    if (log.isDebug()) {
        log.logDebug(BaseMessages.getString(PKG, "GPG.RunningCommand", command));
    }
    String retval;

    try {
        if (Const.isWindows()) {
            p = Runtime.getRuntime().exec(command);
        } else {
            ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", command);
            p = processBuilder.start();
        }
    } catch (IOException io) {
        throw new KettleException(BaseMessages.getString(PKG, "GPG.IOException"), io);
    }

    ProcessStreamReader psr_stdout = new ProcessStreamReader(p.getInputStream());
    ProcessStreamReader psr_stderr = new ProcessStreamReader(p.getErrorStream());
    psr_stdout.start();
    psr_stderr.start();
    if (inputStr != null) {
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        try {
            out.write(inputStr);
        } catch (IOException io) {
            throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionWrite"), io);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    // Ignore
                }
            }
        }
    }

    try {
        p.waitFor();

        psr_stdout.join();
        psr_stderr.join();
    } catch (InterruptedException i) {
        throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionWait"), i);
    }

    try {
        if (p.exitValue() != 0) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "GPG.Exception.ExistStatus", psr_stderr.getString()));
        }
    } catch (IllegalThreadStateException itse) {
        throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionillegalThreadStateException"),
                itse);
    } finally {
        p.destroy();
    }

    retval = psr_stdout.getString();

    return retval;

}

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Runs a command locally/*from   w ww .  j a  va2 s .co  m*/
 *
 * @param command command used to be run locally
 */
public void runLocalCommand(String command) throws Exception {

    String result = "";
    String line;
    Process p;
    try {
        p = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command });
        p.waitFor();
    } catch (java.io.IOException e) {
        this.commandExitStatus = 1;
        this.commandResult = "Error";
        return;
    }

    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        result += line;
    }

    input.close();
    this.commandResult = result;
    this.commandExitStatus = p.exitValue();

    p.destroy();

    if (p.isAlive()) {
        p.destroyForcibly();
    }

}

From source file:ExecHelper.java

/**
 * Take a process, record its standard error and standard out streams, wait for it to finish
 *
 * @param process process to watch//  ww w  .  ja  va2  s.c  om
 * @throws SecurityException if a security manager exists and its checkExec method doesn't allow creation of a subprocess.
 * @throws IOException - if an I/O error occurs
 * @throws NullPointerException - if cmdarray is null
 * @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0).
 *
 * @since ostermillerutils 1.06.00
 */
private ExecHelper(Process process, String charset) throws IOException {
    StringBuffer output = new StringBuffer();
    StringBuffer error = new StringBuffer();

    Reader stdout;
    Reader stderr;

    if (charset == null) {
        // This is one time that the system charset is appropriate,
        // don't specify a character set.
        stdout = new InputStreamReader(process.getInputStream());
        stderr = new InputStreamReader(process.getErrorStream());
    } else {
        stdout = new InputStreamReader(process.getInputStream(), charset);
        stderr = new InputStreamReader(process.getErrorStream(), charset);
    }
    char[] buffer = new char[1024];

    boolean done = false;
    boolean stdoutclosed = false;
    boolean stderrclosed = false;
    while (!done) {
        boolean readSomething = false;
        // read from the process's standard output
        if (!stdoutclosed && stdout.ready()) {
            readSomething = true;
            int read = stdout.read(buffer, 0, buffer.length);
            if (read < 0) {
                readSomething = true;
                stdoutclosed = true;
            } else if (read > 0) {
                readSomething = true;
                output.append(buffer, 0, read);
            }
        }
        // read from the process's standard error
        if (!stderrclosed && stderr.ready()) {
            int read = stderr.read(buffer, 0, buffer.length);
            if (read < 0) {
                readSomething = true;
                stderrclosed = true;
            } else if (read > 0) {
                readSomething = true;
                error.append(buffer, 0, read);
            }
        }
        // Check the exit status only we haven't read anything,
        // if something has been read, the process is obviously not dead yet.
        if (!readSomething) {
            try {
                this.status = process.exitValue();
                done = true;
            } catch (IllegalThreadStateException itx) {
                // Exit status not ready yet.
                // Give the process a little breathing room.
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ix) {
                    process.destroy();
                    throw new IOException("Interrupted - processes killed");
                }
            }
        }
    }

    this.output = output.toString();
    this.error = error.toString();
}

From source file:org.nuxeo.launcher.NuxeoLauncher.java

/**
 * Stops the server.//from www. ja v  a2  s  .co m
 *
 * Will try to call specific class for a clean stop, retry
 * {@link #STOP_NB_TRY}, waiting {@link #STOP_SECONDS_BEFORE_NEXT_TRY}
 * between each try, then kill the process if still running.
 */
public void stop(boolean logProcessOutput) {
    long startTime = new Date().getTime();
    long deltaTime;
    try {
        if (!isRunning()) {
            log.warn("Server is not running.");
            return;
        }
        if (!quiet) {
            System.out.print("\nStopping server...");
        }
        int nbTry = 0;
        boolean retry = false;
        int stopMaxWait = Integer.parseInt(
                configurationGenerator.getUserConfig().getProperty(STOP_MAX_WAIT_PARAM, STOP_MAX_WAIT_DEFAULT));
        do {
            List<String> stopCommand = new ArrayList<String>();
            stopCommand.add(getJavaExecutable().getPath());
            stopCommand.add("-cp");
            stopCommand.add(getShutdownClassPath());
            stopCommand.addAll(getNuxeoProperties());
            stopCommand.addAll(getServerProperties());
            setServerStopCommand(stopCommand);
            for (String param : params) {
                stopCommand.add(param);
            }
            ProcessBuilder pb = new ProcessBuilder(getOSCommand(stopCommand));
            pb.directory(configurationGenerator.getNuxeoHome());
            // pb = pb.redirectErrorStream(true);
            log.debug("Server command: " + pb.command());
            try {
                Process stopProcess = pb.start();
                ArrayList<ThreadedStreamGobbler> sgArray = logProcessStreams(stopProcess, logProcessOutput);
                stopProcess.waitFor();
                waitForProcessStreams(sgArray);
                boolean wait = true;
                while (wait) {
                    try {
                        if (stopProcess.exitValue() == 0) {
                            // Successful call for server stop
                            retry = false;
                        } else {
                            // Failed to call for server stop
                            retry = ++nbTry < STOP_NB_TRY;
                            if (!quiet) {
                                System.out.print(".");
                            }
                            Thread.sleep(STOP_SECONDS_BEFORE_NEXT_TRY * 1000);
                        }
                        wait = false;
                    } catch (IllegalThreadStateException e) {
                        // Stop call is still running
                        wait = true;
                        if (!quiet) {
                            System.out.print(".");
                        }
                        Thread.sleep(1000);
                    }
                }
                // Exit if there's no way to check for server stop
                if (processManager instanceof PureJavaProcessManager) {
                    log.warn("Can't check server status on your OS.");
                    return;
                }
                // Wait a few seconds for effective stop
                deltaTime = 0;
                do {
                    if (!quiet) {
                        System.out.print(".");
                    }
                    Thread.sleep(1000);
                    deltaTime = (new Date().getTime() - startTime) / 1000;
                } while (!retry && getPid() != null && deltaTime < stopMaxWait);
            } catch (InterruptedException e) {
                log.error(e);
            }
        } while (retry);
        if (getPid() == null) {
            log.warn("Server stopped.");
        } else {
            log.info("No answer from server, try to kill process " + pid + "...");
            processManager.kill(nuxeoProcess, pid);
            if (getPid() == null) {
                log.warn("Server forcibly stopped.");
            }
        }
    } catch (IOException e) {
        log.error("Could not manage process!", e);
    }
}

From source file:org.kepler.ssh.LocalExec.java

public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget)
        throws ExecException {
    _commandArr[_commandCount] = command;

    Runtime rt = Runtime.getRuntime();
    Process proc;

    // get the pwd/passphrase to the third party (and perform authentication
    // if not yet done)
    String pwd = SshSession.getPwdToThirdParty(thirdPartyTarget);

    try {/* w  w  w. j a  v  a 2  s.c om*/
        proc = rt.exec(_commandArr);
    } catch (Exception ex) {
        //ex.printStackTrace();
        throw new ExecException("Cannot execute cmd ** : " + _commandArr[_commandCount] + ex);
    }

    // System.out.println("%%% Process started");

    // the streams from the process: stdout and stderr
    BufferedReader out_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); // stdout
    BufferedReader err_in = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // stderr

    // the streams towards the caller: stdout and stderr
    BufferedWriter out_out = new BufferedWriter(new OutputStreamWriter(streamOut));
    BufferedWriter err_out = new BufferedWriter(new OutputStreamWriter(streamErr));

    BufferedWriter proc_in = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); // stdin

    String line; // Temp for each line of output.
    int exitVal = -32766;
    boolean readOut = true;
    boolean readErr = true;
    boolean finished = false;
    boolean checkForPwd = (pwd != null);
    char c[] = new char[256];
    int charsRead;

    // variables for the timeout checking
    long start = System.currentTimeMillis();
    long current = 0;
    long maxtime = timeout * 1000L;

    while (!finished) { // will stop when the process terminates or after
        // timeout
        // check the status of the process
        try {
            exitVal = proc.exitValue();
            finished = true; // process terminated so exit this loop after
                             // reading the buffers
        } catch (IllegalThreadStateException ex) {
            // process not yet terminated so we go further
        }

        // read stdout
        if (readOut) {
            try {
                while (out_in.ready()) {
                    charsRead = out_in.read(c, 0, 256);
                    out_out.write(c, 0, charsRead);

                    // System.out.println("%%% "+ new String(c, 0,
                    // charsRead));
                    /*
                     * try { proc_in.write("Anyadat\n", 0, 8); // send the
                     * password proc_in.flush(); } catch (Exception ex) {
                     * System.out.println("### "+ex);
                     * 
                     * }
                     */
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        // System.out.println("%%% Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStdout)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stdout: " + ioe + "</IOException>");
                readOut = false;
            }
        }

        // read stderr
        if (readErr) {
            try {
                while (err_in.ready()) {
                    charsRead = err_in.read(c, 0, 256);
                    err_out.write(c, 0, charsRead);
                    System.out.println("### " + new String(c, 0, charsRead));
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        System.out.println("### Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStderr)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stderr: " + ioe + "</IOException>");
                readErr = false;
            }
        }

        // sleep a bit to not overload the system
        if (!finished)
            try {
                java.lang.Thread.sleep(100);
            } catch (InterruptedException ex) {
            }

        // check timeout
        current = System.currentTimeMillis();
        if (timeout > 0 && maxtime < current - start) {
            log.error("Timeout: " + timeout + "s elapsed for command " + command);
            proc.destroy();
            throw new ExecTimeoutException(command);
            // exitVal = timeoutErrorCode;
            // finished = true;
        }

    }

    try {
        // flush to caller
        out_out.flush();
        err_out.flush();
        // close streams from/to child process
        out_in.close();
        err_in.close();
        proc_in.close();
    } catch (IOException ex) {
        log.error("Could not flush output streams: " + ex);
    }

    // System.out.println("ExitValue: " + exitVal);
    return exitVal;

}

From source file:com.netxforge.oss2.core.utilsII.ExecRunner.java

/**
 * The <code>exec(String, PrintWriter, PrintWriter)</code> method runs a
 * process inside of a watched thread. It returns the client's exit code and
 * feeds its STDOUT and STDERR to the passed-in streams.
 *
 * @return The command's return code//ww w .java 2 s.co  m
 * @param command
 *            The program or command to run
 * @param stdoutWriter
 *            java.io.PrintWriter
 * @param stderrWriter
 *            java.io.PrintWriter
 * @throws java.io.IOException
 *             thrown if a problem occurs
 * @throws java.lang.InterruptedException
 *             thrown if a problem occurs
 */
public int exec(final String command, final PrintWriter stdoutWriter, final PrintWriter stderrWriter)
        throws IOException, InterruptedException {

    // Default exit value is non-zero to indicate a problem.
    int exitVal = 1;

    // //////////////////////////////////////////////////////////////
    final Runtime rt = Runtime.getRuntime();
    Process proc;
    String[] cmd = null;

    // First get the start time & calculate comparison numbers
    final Date startTime = new Date();
    final long startTimeMs = startTime.getTime();
    final long maxTimeMs = startTimeMs + (maxRunTimeSecs * 1000);

    // //////////////////////////////////////////////////////////////
    // First determine the OS to build the right command string
    final String osName = System.getProperty("os.name");
    if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equals("Windows ME")) {
        cmd = new String[3];
        cmd[0] = WINDOWS_9X_ME_COMMAND_1;
        cmd[1] = WINDOWS_9X_ME_COMMAND_2;
        cmd[2] = command;
    } else if (osName.contains("Windows")) { // "Windows NT", "Windows 2000", etc.
        cmd = new String[3];
        cmd[0] = WINDOWS_NT_2000_COMMAND_1;
        cmd[1] = WINDOWS_NT_2000_COMMAND_2;
        cmd[2] = command;
    } else {
        // Linux (and probably other *nixes) prefers to be called
        // with each argument supplied separately, so we first
        // Tokenize it across spaces as the boundary.
        final StringTokenizer st = new StringTokenizer(command, " ");
        cmd = new String[st.countTokens()];
        int token = 0;
        while (st.hasMoreTokens()) {
            String tokenString = st.nextToken();
            cmd[token++] = tokenString;
        }
    }

    // Execute the command and start the two output gobblers
    if (cmd != null && cmd.length > 0) {
        proc = rt.exec(cmd);
    } else {
        throw new IOException("Insufficient commands!");
    }

    final StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), stdoutWriter);
    final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), stderrWriter);
    outputGobbler.start();
    errorGobbler.start();

    // Wait for the program to finish running and return the
    // exit value obtained from the executable
    while (true) {

        try {
            exitVal = proc.exitValue();
            break;
        } catch (final IllegalThreadStateException e) {

            // If we get this exception, then the process isn't
            // done executing and we determine if our time is up.
            if (maxRunTimeSecs > 0) {

                final Date endTime = new Date();
                final long endTimeMs = endTime.getTime();
                if (endTimeMs > maxTimeMs) {
                    // Time's up - kill the process and the gobblers and
                    // return
                    proc.destroy();
                    maxRunTimeExceeded = true;
                    stderrWriter.println(MAX_RUN_TIME_EXCEEDED_STRING);
                    outputGobbler.quit();
                    errorGobbler.quit();
                    return exitVal;

                } else {
                    // Time is not up yet so wait 100 ms before testing
                    // again
                    Thread.sleep(POLL_DELAY_MS);
                }

            }

        }

    }

    // //////////////////////////////////////////////////////////////
    // Wait for output gobblers to finish forwarding the output
    while (outputGobbler.isAlive() || errorGobbler.isAlive()) {
    }

    // //////////////////////////////////////////////////////////////
    // All done, flush the streams and return the exit value
    stdoutWriter.flush();
    stderrWriter.flush();
    return exitVal;

}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

public void startBroker(int port, TestBrokerConfiguration testConfiguration, XMLConfiguration virtualHosts, boolean managementMode) throws Exception
{
    port = getPort(port);//from   w  ww. ja v a 2s .c om
    String testConfig = saveTestConfiguration(port, testConfiguration);
    String virtualHostsConfig = saveTestVirtualhosts(port, virtualHosts);

    if(_brokers.get(port) != null)
    {
        throw new IllegalStateException("There is already an existing broker running on port " + port);
    }

    Set<Integer> portsUsedByBroker = guessAllPortsUsedByBroker(port);

    if (_brokerType.equals(BrokerType.INTERNAL) && !existingInternalBroker())
    {
        _logger.info("Set test.virtualhosts property to: " + virtualHostsConfig);
        setSystemProperty(TEST_VIRTUALHOSTS, virtualHostsConfig);
        setSystemProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, "false");
        BrokerOptions options = new BrokerOptions();

        options.setConfigurationStoreType(_brokerStoreType);
        options.setConfigurationStoreLocation(testConfig);
        options.setManagementMode(managementMode);

        //Set the log config file, relying on the log4j.configuration system property
        //set on the JVM by the JUnit runner task in module.xml.
        options.setLogConfigFile(_logConfigFile.getAbsolutePath());

        Broker broker = new Broker();
        _logger.info("Starting internal broker (same JVM)");
        broker.startup(options);

        _brokers.put(port, new InternalBrokerHolder(broker, System.getProperty("QPID_WORK"), portsUsedByBroker));
    }
    else if (!_brokerType.equals(BrokerType.EXTERNAL))
    {
        // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests
        final String qpidWork = getQpidWork(_brokerType, port);

        String[] cmd = _brokerCommandHelper.getBrokerCommand(port, testConfig, _brokerStoreType, _logConfigFile);
        if (managementMode)
        {
            String[] newCmd = new String[cmd.length + 1];
            System.arraycopy(cmd, 0, newCmd, 0, cmd.length);
            newCmd[cmd.length] = "-mm";
            cmd = newCmd;
        }
        _logger.info("Starting spawn broker using command: " + StringUtils.join(cmd, ' '));
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Map<String, String> processEnv = pb.environment();
        String qpidHome = System.getProperty(QPID_HOME);
        processEnv.put(QPID_HOME, qpidHome);
        //Augment Path with bin directory in QPID_HOME.
        processEnv.put("PATH", processEnv.get("PATH").concat(File.pathSeparator + qpidHome + "/bin"));

        //Add the test name to the broker run.
        // DON'T change PNAME, qpid.stop needs this value.
        processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + getTestName() + "\"");
        processEnv.put("QPID_WORK", qpidWork);

        // Use the environment variable to set amqj.logging.level for the broker
        // The value used is a 'server' value in the test configuration to
        // allow a differentiation between the client and broker logging levels.
        if (System.getProperty("amqj.server.logging.level") != null)
        {
            setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level"));
        }

        // Add all the environment settings the test requested
        if (!_env.isEmpty())
        {
            for (Map.Entry<String, String> entry : _env.entrySet())
            {
                processEnv.put(entry.getKey(), entry.getValue());
            }
        }

        String qpidOpts = "";

        // a synchronized hack to avoid adding into QPID_OPTS the values
        // of JVM properties "test.virtualhosts" and "test.config" set by a concurrent startup process
        synchronized (_propertiesSetForBroker)
        {
            // Add default test logging levels that are used by the log4j-test
            // Use the convenience methods to push the current logging setting
            // in to the external broker's QPID_OPTS string.
            setSystemProperty("amqj.protocol.logging.level");
            setSystemProperty("root.logging.level");
            setSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES);
            setSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES);
            setSystemProperty(TEST_VIRTUALHOSTS, virtualHostsConfig);

            // Add all the specified system properties to QPID_OPTS
            if (!_propertiesSetForBroker.isEmpty())
            {
                for (String key : _propertiesSetForBroker.keySet())
                {
                    qpidOpts += " -D" + key + "=" + _propertiesSetForBroker.get(key);
                }
            }
        }
        if (processEnv.containsKey("QPID_OPTS"))
        {
            qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts;
        }
        processEnv.put("QPID_OPTS", qpidOpts);

        // cpp broker requires that the work directory is created
        createBrokerWork(qpidWork);

        Process process = pb.start();

        Piper p = new Piper(process.getInputStream(),
                            _testcaseOutputStream,
                            System.getProperty(BROKER_READY),
                            System.getProperty(BROKER_STOPPED),
                            _interleaveBrokerLog ? _brokerLogPrefix : null);

        p.start();

        SpawnedBrokerHolder holder = new SpawnedBrokerHolder(process, qpidWork, portsUsedByBroker);
        if (!p.await(30, TimeUnit.SECONDS))
        {
            _logger.info("broker failed to become ready (" + p.getReady() + "):" + p.getStopLine());
            String threadDump = holder.dumpThreads();
            if (!threadDump.isEmpty())
            {
                _logger.info("the result of a try to capture thread dump:" + threadDump);
            }
            //Ensure broker has stopped
            process.destroy();
            cleanBrokerWork(qpidWork);
            throw new RuntimeException("broker failed to become ready:"
                                       + p.getStopLine());
        }

        try
        {
            //test that the broker is still running and hasn't exited unexpectedly
            int exit = process.exitValue();
            _logger.info("broker aborted: " + exit);
            cleanBrokerWork(qpidWork);
            throw new RuntimeException("broker aborted: " + exit);
        }
        catch (IllegalThreadStateException e)
        {
            // this is expect if the broker started successfully
        }

        _brokers.put(port, holder);
    }
}

From source file:org.moyrax.javascript.shell.Global.java

/**
 * If any of in, out, err is null, the corresponding process stream will be
 * closed immediately, otherwise it will be closed as soon as all data will be
 * read from/written to process/*from  www .  j ava 2s. c o  m*/
 */
private static int runProcess(String[] cmd, String[] environment, InputStream in, OutputStream out,
        OutputStream err) throws IOException {
    Process p;
    if (environment == null) {
        p = Runtime.getRuntime().exec(cmd);
    } else {
        p = Runtime.getRuntime().exec(cmd, environment);
    }
    PipeThread inThread = null, errThread = null;
    try {
        InputStream errProcess = null;
        try {
            if (err != null) {
                errProcess = p.getErrorStream();
            } else {
                p.getErrorStream().close();
            }
            InputStream outProcess = null;
            try {
                if (out != null) {
                    outProcess = p.getInputStream();
                } else {
                    p.getInputStream().close();
                }
                OutputStream inProcess = null;
                try {
                    if (in != null) {
                        inProcess = p.getOutputStream();
                    } else {
                        p.getOutputStream().close();
                    }

                    if (out != null) {
                        // Read process output on this thread
                        if (err != null) {
                            errThread = new PipeThread(true, errProcess, err);
                            errThread.start();
                        }
                        if (in != null) {
                            inThread = new PipeThread(false, in, inProcess);
                            inThread.start();
                        }
                        pipe(true, outProcess, out);
                    } else if (in != null) {
                        // No output, read process input on this thread
                        if (err != null) {
                            errThread = new PipeThread(true, errProcess, err);
                            errThread.start();
                        }
                        pipe(false, in, inProcess);
                        in.close();
                    } else if (err != null) {
                        // No output or input, read process err
                        // on this thread
                        pipe(true, errProcess, err);
                        errProcess.close();
                        errProcess = null;
                    }

                    // wait for process completion
                    for (;;) {
                        try {
                            p.waitFor();
                            break;
                        } catch (InterruptedException ex) {
                        }
                    }

                    return p.exitValue();
                } finally {
                    // pipe will close stream as well, but for reliability
                    // duplicate it in any case
                    if (inProcess != null) {
                        inProcess.close();
                    }
                }
            } finally {
                if (outProcess != null) {
                    outProcess.close();
                }
            }
        } finally {
            if (errProcess != null) {
                errProcess.close();
            }
        }
    } finally {
        p.destroy();
        if (inThread != null) {
            for (;;) {
                try {
                    inThread.join();
                    break;
                } catch (InterruptedException ex) {
                }
            }
        }
        if (errThread != null) {
            for (;;) {
                try {
                    errThread.join();
                    break;
                } catch (InterruptedException ex) {
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public String shellUtil(String cmd) throws HiveServerException {
    l4j.info("execute shell: " + cmd);
    Process subproc;
    StringBuffer res = new StringBuffer();

    try {//  ww w.jav a  2 s  .  c o m
        subproc = Runtime.getRuntime().exec(cmd);
    } catch (IOException ioe) {
        l4j.error("Runtime.getRuntime().exec()" + cmd + " failed.");
        l4j.error(ioe.getMessage());
        throw new HiveServerException("Run cmd" + cmd + " failed:" + ioe.getMessage());
    }

    if (subproc == null) {
        l4j.error("Runtime.getRuntime().exec()" + cmd + " failed.");
        throw new HiveServerException("Run cmd" + cmd + " failed.");
    }
    BufferedReader outBr = new BufferedReader(new InputStreamReader(subproc.getInputStream()));
    BufferedReader errBr = new BufferedReader(new InputStreamReader(subproc.getErrorStream()));
    try {
        subproc.waitFor();
    } catch (InterruptedException ie) {
        l4j.error(ie.getMessage());
        throw new HiveServerException("Run cmd" + cmd + " failed:" + " waitFor() Interrupted");
    }

    int ret = subproc.exitValue();
    try {
        if (ret == 0) {
            String lineStr;
            while ((lineStr = outBr.readLine()) != null) {
                if (res.length() > 0) {
                    res.append("\n");
                }
                res.append(lineStr);
            }
            l4j.info("Run cmd OK" + res.toString());
            return res.toString();
        } else {
            String lineStr;
            while ((lineStr = outBr.readLine()) != null) {
                if (res.length() > 0) {
                    res.append("\n");
                }
                res.append(lineStr);
            }

            while ((lineStr = errBr.readLine()) != null) {
                if (res.length() > 0) {
                    res.append("\n");
                }
                res.append(lineStr);
            }
            l4j.error(res.toString());
            throw new HiveServerException(res.toString());
        }
    } catch (IOException iex) {
        throw new HiveServerException("run cmd IOException");
    }
}