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.pbccrc.zsls.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/*from   w  w  w.j  av a  2s  .  c o m*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            boolean overErrMsg = false;
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    if (!overErrMsg) {
                        if (line.length() + errMsg.length() > ERR_MSG_BUFF_SIZE)
                            overErrMsg = true;
                        else {
                            errMsg.append(line);
                            errMsg.append(System.getProperty("line.separator"));
                        }
                    }
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = clock.getTime();
    }
}

From source file:org.pshdl.model.simulation.codegenerator.DartCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {//w  w w  . jav  a 2s.  c o m
        IHDLInterpreterFactory<NativeRunner> _xblockexpression = null;
        {
            final String dartCode = this.generateMainCode();
            final File binDir = new File(tempDir, "bin");
            boolean _mkdirs = binDir.mkdirs();
            boolean _not = (!_mkdirs);
            if (_not) {
                throw new IllegalArgumentException(("Failed to create Directory " + binDir));
            }
            File _file = new File(binDir, "dut.dart");
            Files.write(dartCode, _file, StandardCharsets.UTF_8);
            final File testRunnerDir = new File(DartCodeGenerator.TESTRUNNER_DIR);
            final File testRunner = new File(testRunnerDir, "bin/darttestrunner.dart");
            String _name = testRunner.getName();
            File _file_1 = new File(binDir, _name);
            Files.copy(testRunner, _file_1);
            final File yaml = new File(testRunnerDir, "pubspec.yaml");
            String _name_1 = yaml.getName();
            File _file_2 = new File(tempDir, _name_1);
            Files.copy(yaml, _file_2);
            File _file_3 = new File(binDir, "packages");
            Path _path = _file_3.toPath();
            File _file_4 = new File(testRunnerDir, "packages");
            Path _path_1 = _file_4.toPath();
            java.nio.file.Files.createSymbolicLink(_path, _path_1);
            File _file_5 = new File(tempDir, "packages");
            Path _path_2 = _file_5.toPath();
            File _file_6 = new File(testRunnerDir, "packages");
            Path _path_3 = _file_6.toPath();
            java.nio.file.Files.createSymbolicLink(_path_2, _path_3);
            _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() {
                public NativeRunner newInstance() {
                    try {
                        String _name = testRunner.getName();
                        String _plus = ("bin/" + _name);
                        ProcessBuilder _processBuilder = new ProcessBuilder(DartCodeGenerator.DART_EXEC, _plus,
                                DartCodeGenerator.this.unitName, DartCodeGenerator.this.library);
                        ProcessBuilder _directory = _processBuilder.directory(tempDir);
                        ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                        final Process dartRunner = _redirectErrorStream.start();
                        InputStream _inputStream = dartRunner.getInputStream();
                        OutputStream _outputStream = dartRunner.getOutputStream();
                        return new NativeRunner(_inputStream, _outputStream, DartCodeGenerator.this.em,
                                dartRunner, 5, ((("Dart " + DartCodeGenerator.this.library) + ".")
                                        + DartCodeGenerator.this.unitName));
                    } catch (Throwable _e) {
                        throw Exceptions.sneakyThrow(_e);
                    }
                }
            };
        }
        return _xblockexpression;
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.craftercms.deployer.git.processor.ShellProcessor.java

@Override
public void doProcess(SiteConfiguration siteConfiguration, PublishedChangeSet changeSet)
        throws PublishingException {
    checkConfiguration(siteConfiguration);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, siteConfiguration.getSiteId()));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {/*from  w w  w.  j  a  va 2  s  . c om*/
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java

public String createImage(String name, String path, String baseImage) {

    String format = null;/*from   w w w  . j  a  v  a 2  s .  co  m*/
    try {
        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> name(" + name + "), path(" + path + ") ");

        if (!existsImage(name)) {
            //If the image does not exist, create it

            if (path.trim().endsWith(".iso")) {
                format = "iso";

            } else if (name.contains(baseImage)) {
                // TODO: create the image, base image does not require volume
                String[] fileSplit = path.split("[.]");
                format = fileSplit[fileSplit.length - 1];
            } else {
                format = this.IMG_DEFAULT_DISK_FORMAT;
            }

            System.out.println(
                    "DRP4ONE-OneExtraFuncs.createImage()> crating image=" + name + " with format=" + format);

            // TODO: create the image at the OpenStack repository
            ArrayList<String> myCmd = new ArrayList<String>();
            myCmd.add("glance");
            myCmd.add("add");
            myCmd.add(String.format("id=%s", name));
            myCmd.add(String.format("name=%s", name));
            myCmd.add(String.format("disk_format=%s", format));
            myCmd.add(String.format("container_format=%s", this.IMG_DEFAULT_CONTAINER_FORMAT));
            myCmd.add(String.format("is_public=%s", this.IMG_DEFAULT_IS_PUBLIC));

            ProcessBuilder pb = new ProcessBuilder(myCmd);
            pb.redirectErrorStream(true);

            // Set up the environment to communicate with OpenStack
            Map<String, String> envir = pb.environment();
            envir.put("OS_AUTH_URL", this.OS_AUTH_URL);
            envir.put("OS_TENANT_ID", this.OS_TENANT_ID);
            envir.put("OS_TENANT_NAME", this.OS_TENANT_NAME);
            envir.put("OS_USERNAME", this.OS_USERNAME);
            envir.put("OS_PASSWORD", this.OS_PASSWORD);

            // Execute the command specified with its environment
            Process p = pb.start();

            OutputStream pos = p.getOutputStream();

            InputStream fis = new FileInputStream(new File(path));
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = fis.read(buffer)) != -1) {
                pos.write(buffer, 0, read);
            }
            // Close the file stream
            fis.close();
            // Close the process stream. If not, OpenStack keeps the image at "Saving" status
            pos.close();

            //TODO: verify error creating image

            //                if (or.isError()) {
            //                    //TODO: if error creating image...
            //                    System.out.println("DRP4ONE-OneExtraFuncs.createImage()> Error creating image: " + name);
            //
            //                } else {
            //                    //TODO: if ok creating image 
            //                    System.out.println("DRP4ONE-OneExtraFuncs.createImage()> OK creating image: " + name);
            //                    int imgID = Integer.parseInt(or.getMessage());
            //                    //TODO: not leave while image not ready to being used
            //                    while (i.stateString() != "READY") {
            //                        String tmpState = i.stateString();
            //                        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> STATE(imgID=" + imgID + "): " + tmpState);
            //                        Thread.sleep(3000);
            //                    }
            //                }
        } else {
            //If the image already exists, don't create it
            //TODO: return the identifier
            return name;
        }
    } catch (Exception e) {
        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> name(" + name + "), path(" + path + ") ");
        e.printStackTrace();
    }

    return name;
}

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

public void cleanBroker()
{
    if (_brokerClean != null)
    {//from w ww . ja v a2  s .c  om
        _logger.info("clean: " + _brokerClean);

        try
        {
            ProcessBuilder pb = new ProcessBuilder(_brokerClean.split("\\s+"));
            pb.redirectErrorStream(true);
            Process clean = pb.start();
            new Piper(clean.getInputStream(),_brokerOutputStream).start();

            clean.waitFor();

            _logger.info("clean exited: " + clean.exitValue());
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java

public String createImage(OVFDisk disk, String pathLocalBaseImage) {
    //        disk_format=qcow2
    //The disk_format field specifies the format of the image file. In this case, the image file format is QCOW2, which can be verified using the file command:
    ///*w w w  .  jav a  2s  .  c o m*/
    //$ file stackimages/cirros.img
    //Other valid formats are raw, vhd, vmdk, vdi, iso, aki, ari and ami.

    //        container-format=bare
    //The container-format field is required by the glance image-create command but isn't actually used by any of the OpenStack services, so the value specified here has no effect on system behavior. We specify bare to indicate that the image file is not in a file format that contains metadata about the virtual machine.
    //
    //Because the value is not used anywhere, it safe to always specify bare as the container format, although the command will accept other formats: ovf, aki, ari, ami.
    //        glance image-create --name centos63-image --disk-format=qcow2 --container-format=raw --is-public=True < ./centos63.qcow2
    //        glance add name=cirros-0.3.0-x86_64 disk_format=qcow2 container_format=bare < stackimages/cirros.img

    System.out.println(
            "DRP4OST-this.createImage()> disk.getHref()=" + disk.getHref() + "disk.getId()" + disk.getId());

    String imagePath = disk.getHref(); //"/home/smendoza/cirros-0.3.0-x86_64-disk.img";
    String name = imagePath.trim().substring(imagePath.lastIndexOf("/") + 1, imagePath.length());
    //        String name = disk.getId();        
    //        String name = disk.getId() + "_" + (new Random()).nextInt(99999999);
    String diskFormat = "qcow2"; // permitted: img, raw, vhd, vmdk, vdi, iso, aki, ari and ami
    boolean download = false;
    String openStackID = null;

    try {
        // execution of the add command 
        //            Process p = Runtime.getRuntime().exec(cmdAdd, env);

        // Obtained the arguments from 'glance help add'
        ArrayList<String> myCmd = new ArrayList<String>();
        myCmd.add("glance");
        myCmd.add("add");
        //            myCmd.add(String.format("id=%s", disk.getId()));
        myCmd.add(String.format("name=%s", name));
        myCmd.add(String.format("disk_format=%s", diskFormat));
        myCmd.add(String.format("container_format=%s", this.IMG_DEFAULT_CONTAINER_FORMAT));
        myCmd.add(String.format("is_public=%s", this.IMG_DEFAULT_IS_PUBLIC));

        if (disk.getHref().startsWith("http://")) {
            //The image has been already downloaded and merged, and is staying at pathLocalBaseImage
            imagePath = pathLocalBaseImage;
            download = false;
        } else {
            // App will add the full path
            download = false;
            if (!disk.getHref().startsWith("/")) {
                //Incomplete path, necessary to add default path (img.default.path parameter)
                imagePath = this.IMG_DEFAULT_PATH + "/" + imagePath;
            } else {
                //Complete path (expected), not necessary to add nothing
            }
        }

        ProcessBuilder pb = new ProcessBuilder(myCmd);
        pb.redirectErrorStream(true);

        // Set up the environment to communicate with OpenStack
        Map<String, String> envir = pb.environment();
        envir.put("OS_AUTH_URL", this.OS_AUTH_URL);
        envir.put("OS_TENANT_ID", this.OS_TENANT_ID);
        envir.put("OS_TENANT_NAME", this.OS_TENANT_NAME);
        envir.put("OS_USERNAME", this.OS_USERNAME);
        envir.put("OS_PASSWORD", this.OS_PASSWORD);

        // Execute the command specified with its environment
        Process p = pb.start();

        InputStream pis = p.getInputStream();

        // if image not downloaded, it will have to uploaded 
        if (!download) {
            OutputStream pos = p.getOutputStream();

            File imgFile = new File(imagePath);
            System.out.println("DRP4OST-OStackClient.createImage()> START UPLOADING (" + imgFile.getPath()
                    + ") TO OPENSTACK REPOSITORY");
            if (imgFile.exists()) {
                InputStream fis = new FileInputStream(imgFile);
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = fis.read(buffer)) != -1) {
                    pos.write(buffer, 0, read);
                }
                // Close the file stream
                fis.close();
                System.out.println("DRP4OST-OStackClient.createImage()> FINISH UPLOADING (" + imgFile.getPath()
                        + ")TO OPENSTACK REPOSITORY");
            } else {
                System.out.println("DRP4OST-OStackClient.createImage()> The file " + imgFile.getPath()
                        + " does not exist! Abort VM creation!");
                throw new Exception("DRP4OST-OStackClient.createImage()> The file " + imgFile.getPath()
                        + " does not exist! Abort VM instance creation!");
            }

            // Close the process stream. If not, OpenStack keeps the image at "Saving" status
            pos.close();
        } else {
            System.out.println(
                    "DRP4OST-OStackClient.createImage()> The image is expected to be download automatically by OpenStack-glance from "
                            + imagePath);
        }
        System.out.println("DRP4OST-OStackClient.createImage()> glance output: " + ImageMerge.ISToString(pis));
        pis.close();

        openStackID = getImageID(name);

        System.out.println("DRP4OST-OStackClient.createImage()> getImageStatus(" + openStackID + ")="
                + getImageStatus(openStackID));

        // Wait while hte image is not ready to be used
        while (!getImageStatus(openStackID).equals("ACTIVE")) {
            System.out.println("DRP4OST-OStackClient.createImage()> getImageStatus(" + openStackID + ")="
                    + getImageStatus(openStackID));
            Thread.sleep(1000);
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new DRPOSTException("Exception creating the image", StatusCodes.BAD_REQUEST);
    }
    return openStackID;
}

From source file:org.craftercms.cstudio.publishing.processor.ShellProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    checkConfiguration(parameters, target);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, parameters.get(FileUploadServlet.PARAM_SITE)));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(parameters, changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {//w ww.  j  av a2 s .c  o  m
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:com.photon.phresco.plugins.xcode.Instrumentation.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Instrumentation command" + command);

    try {//  www . j a va  2  s . c  o  m
        outputFolder = project.getBasedir().getAbsolutePath();
        File f = new File(outputFolder);
        File files[] = f.listFiles();
        for (File file : files) {
            if (file.getName().startsWith("Run 1") || file.getName().endsWith(".trace")) {
                FileUtils.deleteDirectory(file);
            }
        }
    } catch (IOException e) {
        getLog().error(e);
    }

    Runnable runnable = new Runnable() {
        public void run() {
            ProcessBuilder pb = new ProcessBuilder(command);
            //device takes the highest priority
            if (StringUtils.isNotBlank(deviceid)) {
                pb.command().add("-w");
                pb.command().add(deviceid);
            }
            pb.command().add("-t");
            pb.command().add(template);

            if (StringUtils.isNotBlank(appPath)) {
                pb.command().add(appPath);
            } else {
                getLog().error("Application should not be empty");
            }
            if (StringUtils.isNotBlank(script)) {
                pb.command().add("-e");
                pb.command().add("UIASCRIPT");
                String scriptPath = project.getBasedir().getAbsolutePath() + File.separator + script;
                pb.command().add(scriptPath);
            } else {
                getLog().error("script is empty");
            }

            pb.command().add("-e");
            pb.command().add("UIARESULTSPATH");
            pb.command().add(outputFolder);

            // Include errors in output
            pb.redirectErrorStream(true);

            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                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) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error(e);
            }

        }

    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    getLog().info("Thread started");
    try {
        //Thread.sleep(5000);
        t.join();
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    preparePlistResult();
    generateXMLReport(project.getBasedir().getAbsolutePath() + File.separator + plistResult);
}

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

public void startBroker(int port) throws Exception
{
    port = getPort(port);// www.  jav a 2 s.c om

    // 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.apache.qpid.test.utils.QpidBrokerTestCase.java

public void startBroker(int port, TestBrokerConfiguration testConfiguration, XMLConfiguration virtualHosts, boolean managementMode) throws Exception
{
    port = getPort(port);/*from w  w  w .  j  a v  a2 s.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);
    }
}