Search in sources :

Example 1 with SearchByClass

use of org.apache.jorphan.collections.SearchByClass in project jmeter by apache.

the class JMeter method runNonGui.

// run test in batch mode
private void runNonGui(String testFile, String logFile, boolean remoteStart, String remoteHostsString, boolean generateReportDashboard) {
    try {
        File f = new File(testFile);
        if (!f.exists() || !f.isFile()) {
            println("Could not open " + testFile);
            return;
        }
        FileServer.getFileServer().setBaseForScript(f);
        HashTree tree = SaveService.loadTree(f);
        // Deliberate use of deprecated ctor
        @SuppressWarnings("deprecation") JMeterTreeModel // Create non-GUI version to avoid headless problems
        treeModel = new JMeterTreeModel(new Object());
        JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
        treeModel.addSubTree(tree, root);
        // Hack to resolve ModuleControllers in non GUI mode
        SearchByClass<ReplaceableController> replaceableControllers = new SearchByClass<>(ReplaceableController.class);
        tree.traverse(replaceableControllers);
        Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults();
        for (ReplaceableController replaceableController : replaceableControllersRes) {
            replaceableController.resolveReplacementSubTree(root);
        }
        // Remove the disabled items
        // For GUI runs this is done in Start.java
        convertSubTree(tree);
        if (deleteResultFile) {
            SearchByClass<ResultCollector> resultListeners = new SearchByClass<>(ResultCollector.class);
            tree.traverse(resultListeners);
            Iterator<ResultCollector> irc = resultListeners.getSearchResults().iterator();
            while (irc.hasNext()) {
                ResultCollector rc = irc.next();
                File resultFile = new File(rc.getFilename());
                if (resultFile.exists()) {
                    resultFile.delete();
                }
            }
        }
        Summariser summer = null;
        //$NON-NLS-1$
        String summariserName = JMeterUtils.getPropDefault("summariser.name", "");
        if (summariserName.length() > 0) {
            log.info("Creating summariser <{}>", summariserName);
            println("Creating summariser <" + summariserName + ">");
            summer = new Summariser(summariserName);
        }
        ReportGenerator reportGenerator = null;
        if (logFile != null) {
            ResultCollector logger = new ResultCollector(summer);
            logger.setFilename(logFile);
            tree.add(tree.getArray()[0], logger);
            if (generateReportDashboard) {
                reportGenerator = new ReportGenerator(logFile, logger);
            }
        } else {
            // only add Summariser if it can not be shared with the ResultCollector
            if (summer != null) {
                tree.add(tree.getArray()[0], summer);
            }
        }
        // Used for remote notification of threads start/stop,see BUG 54152
        // Summariser uses this feature to compute correctly number of threads 
        // when NON GUI mode is used
        tree.add(tree.getArray()[0], new RemoteThreadsListenerTestElement());
        List<JMeterEngine> engines = new LinkedList<>();
        tree.add(tree.getArray()[0], new ListenToTest(remoteStart && remoteStop ? engines : null, reportGenerator));
        println("Created the tree successfully using " + testFile);
        if (!remoteStart) {
            JMeterEngine engine = new StandardJMeterEngine();
            engine.configure(tree);
            long now = System.currentTimeMillis();
            println("Starting the test @ " + new Date(now) + " (" + now + ")");
            engine.runTest();
            engines.add(engine);
        } else {
            //$NON-NLS-1$
            java.util.StringTokenizer st = new java.util.StringTokenizer(remoteHostsString, ",");
            List<String> hosts = new LinkedList<>();
            while (st.hasMoreElements()) {
                hosts.add((String) st.nextElement());
            }
            DistributedRunner distributedRunner = new DistributedRunner(this.remoteProps);
            // NOSONAR
            distributedRunner.setStdout(System.out);
            // NOSONAR
            distributedRunner.setStdErr(System.err);
            distributedRunner.init(hosts, tree);
            engines.addAll(distributedRunner.getEngines());
            distributedRunner.start();
        }
        startUdpDdaemon(engines);
    } catch (Exception e) {
        //NOSONAR
        System.out.println("Error in NonGUIDriver " + e.toString());
        log.error("Error in NonGUIDriver", e);
    }
}
Also used : HashTree(org.apache.jorphan.collections.HashTree) RemoteThreadsListenerTestElement(org.apache.jmeter.threads.RemoteThreadsListenerTestElement) JMeterTreeModel(org.apache.jmeter.gui.tree.JMeterTreeModel) Summariser(org.apache.jmeter.reporters.Summariser) ReportGenerator(org.apache.jmeter.report.dashboard.ReportGenerator) StringTokenizer(java.util.StringTokenizer) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) ReplaceableController(org.apache.jmeter.control.ReplaceableController) ResultCollector(org.apache.jmeter.reporters.ResultCollector) StandardJMeterEngine(org.apache.jmeter.engine.StandardJMeterEngine) SearchByClass(org.apache.jorphan.collections.SearchByClass) LinkedList(java.util.LinkedList) Date(java.util.Date) ConfigurationException(org.apache.jmeter.report.config.ConfigurationException) JMeterException(org.apache.jorphan.util.JMeterException) FileNotFoundException(java.io.FileNotFoundException) ConversionException(com.thoughtworks.xstream.converters.ConversionException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) GenerationException(org.apache.jmeter.report.dashboard.GenerationException) StringTokenizer(java.util.StringTokenizer) ClientJMeterEngine(org.apache.jmeter.engine.ClientJMeterEngine) JMeterEngine(org.apache.jmeter.engine.JMeterEngine) StandardJMeterEngine(org.apache.jmeter.engine.StandardJMeterEngine) DistributedRunner(org.apache.jmeter.engine.DistributedRunner) File(java.io.File)

Example 2 with SearchByClass

use of org.apache.jorphan.collections.SearchByClass in project jmeter by apache.

the class StandardJMeterEngine method run.

@Override
public void run() {
    log.info("Running the test!");
    running = true;
    /*
         * Ensure that the sample variables are correctly initialised for each run.
         */
    SampleEvent.initSampleVariables();
    JMeterContextService.startTest();
    try {
        PreCompiler compiler = new PreCompiler();
        test.traverse(compiler);
    } catch (RuntimeException e) {
        log.error("Error occurred compiling the tree:", e);
        JMeterUtils.reportErrorToUser("Error occurred compiling the tree: - see log file", e);
        // no point continuing
        return;
    }
    /**
         * Notification of test listeners needs to happen after function
         * replacement, but before setting RunningVersion to true.
         */
    // TL - S&E
    SearchByClass<TestStateListener> testListeners = new SearchByClass<>(TestStateListener.class);
    test.traverse(testListeners);
    // Merge in any additional test listeners
    // currently only used by the function parser
    testListeners.getSearchResults().addAll(testList);
    // no longer needed
    testList.clear();
    test.traverse(new TurnElementsOn());
    notifyTestListenersOfStart(testListeners);
    List<?> testLevelElements = new LinkedList<>(test.list(test.getArray()[0]));
    removeThreadGroups(testLevelElements);
    SearchByClass<SetupThreadGroup> setupSearcher = new SearchByClass<>(SetupThreadGroup.class);
    SearchByClass<AbstractThreadGroup> searcher = new SearchByClass<>(AbstractThreadGroup.class);
    SearchByClass<PostThreadGroup> postSearcher = new SearchByClass<>(PostThreadGroup.class);
    test.traverse(setupSearcher);
    test.traverse(searcher);
    test.traverse(postSearcher);
    TestCompiler.initialize();
    // for each thread group, generate threads
    // hand each thread the sampler controller
    // and the listeners, and the timer
    Iterator<SetupThreadGroup> setupIter = setupSearcher.getSearchResults().iterator();
    Iterator<AbstractThreadGroup> iter = searcher.getSearchResults().iterator();
    Iterator<PostThreadGroup> postIter = postSearcher.getSearchResults().iterator();
    ListenerNotifier notifier = new ListenerNotifier();
    int groupCount = 0;
    JMeterContextService.clearTotalThreads();
    if (setupIter.hasNext()) {
        log.info("Starting setUp thread groups");
        while (running && setupIter.hasNext()) {
            //for each setup thread group
            AbstractThreadGroup group = setupIter.next();
            groupCount++;
            String groupName = group.getName();
            log.info("Starting setUp ThreadGroup: " + groupCount + " : " + groupName);
            startThreadGroup(group, groupCount, setupSearcher, testLevelElements, notifier);
            if (serialized && setupIter.hasNext()) {
                log.info("Waiting for setup thread group: " + groupName + " to finish before starting next setup group");
                group.waitThreadsStopped();
            }
        }
        log.info("Waiting for all setup thread groups to exit");
        //wait for all Setup Threads To Exit
        waitThreadsStopped();
        log.info("All Setup Threads have ended");
        groupCount = 0;
        JMeterContextService.clearTotalThreads();
    }
    // The groups have all completed now                
    groups.clear();
    /*
         * Here's where the test really starts. Run a Full GC now: it's no harm
         * at all (just delays test start by a tiny amount) and hitting one too
         * early in the test can impair results for short tests.
         */
    JMeterUtils.helpGC();
    JMeterContextService.getContext().setSamplingStarted(true);
    // still running at this point, i.e. setUp was not cancelled
    boolean mainGroups = running;
    while (running && iter.hasNext()) {
        // for each thread group
        AbstractThreadGroup group = iter.next();
        //future Thread Group objects wouldn't execute.
        if (group instanceof SetupThreadGroup || group instanceof PostThreadGroup) {
            continue;
        }
        groupCount++;
        String groupName = group.getName();
        log.info("Starting ThreadGroup: " + groupCount + " : " + groupName);
        startThreadGroup(group, groupCount, searcher, testLevelElements, notifier);
        if (serialized && iter.hasNext()) {
            log.info("Waiting for thread group: " + groupName + " to finish before starting next group");
            group.waitThreadsStopped();
        }
    }
    // end of thread groups
    if (groupCount == 0) {
        // No TGs found
        log.info("No enabled thread groups found");
    } else {
        if (running) {
            log.info("All thread groups have been started");
        } else {
            log.info("Test stopped - no more thread groups will be started");
        }
    }
    //wait for all Test Threads To Exit
    waitThreadsStopped();
    // The groups have all completed now            
    groups.clear();
    if (postIter.hasNext()) {
        groupCount = 0;
        JMeterContextService.clearTotalThreads();
        log.info("Starting tearDown thread groups");
        if (mainGroups && !running) {
            // i.e. shutdown/stopped during main thread groups
            // re-enable for tearDown if necessary
            running = shutdown && tearDownOnShutdown;
        }
        while (running && postIter.hasNext()) {
            //for each setup thread group
            AbstractThreadGroup group = postIter.next();
            groupCount++;
            String groupName = group.getName();
            log.info("Starting tearDown ThreadGroup: " + groupCount + " : " + groupName);
            startThreadGroup(group, groupCount, postSearcher, testLevelElements, notifier);
            if (serialized && postIter.hasNext()) {
                log.info("Waiting for post thread group: " + groupName + " to finish before starting next post group");
                group.waitThreadsStopped();
            }
        }
        // wait for Post threads to stop
        waitThreadsStopped();
    }
    notifyTestListenersOfEnd(testListeners);
    JMeterContextService.endTest();
    if (JMeter.isNonGUI() && SYSTEM_EXIT_FORCED) {
        log.info("Forced JVM shutdown requested at end of test");
        // NOSONAR Intentional
        System.exit(0);
    }
}
Also used : AbstractThreadGroup(org.apache.jmeter.threads.AbstractThreadGroup) TestStateListener(org.apache.jmeter.testelement.TestStateListener) SearchByClass(org.apache.jorphan.collections.SearchByClass) LinkedList(java.util.LinkedList) ListenerNotifier(org.apache.jmeter.threads.ListenerNotifier) PostThreadGroup(org.apache.jmeter.threads.PostThreadGroup) SetupThreadGroup(org.apache.jmeter.threads.SetupThreadGroup)

Example 3 with SearchByClass

use of org.apache.jorphan.collections.SearchByClass in project jmeter by apache.

the class AbstractAction method popupCheckExistingFileListener.

/**
     * @param tree where check if listener has existing file
     * @return true if continue test, false otherwise
     */
protected boolean popupCheckExistingFileListener(HashTree tree) {
    SearchByClass<ResultCollector> resultListeners = new SearchByClass<>(ResultCollector.class);
    tree.traverse(resultListeners);
    Iterator<ResultCollector> irc = resultListeners.getSearchResults().iterator();
    while (irc.hasNext()) {
        ResultCollector rc = irc.next();
        File f = new File(rc.getFilename());
        if (f.exists()) {
            String[] option = new String[] { JMeterUtils.getResString("concat_result"), JMeterUtils.getResString("dont_start"), JMeterUtils.getResString("replace_file") };
            String question = MessageFormat.format(// $NON-NLS-1$
            JMeterUtils.getResString("ask_existing_file"), rc.getFilename());
            // Interactive question
            int response = JOptionPane.showOptionDialog(GuiPackage.getInstance().getMainFrame(), question, JMeterUtils.getResString("warning"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, option, option[0]);
            switch(response) {
                case JOptionPane.NO_OPTION:
                    // Exit without start the test
                    return false;
                case JOptionPane.CANCEL_OPTION:
                    // replace_file so delete the existing one
                    f.delete();
                    break;
                case JOptionPane.YES_OPTION:
                    // append is the default behaviour, so nothing to do
                    break;
                default:
                    return false;
            }
        }
    }
    return true;
}
Also used : ResultCollector(org.apache.jmeter.reporters.ResultCollector) File(java.io.File) SearchByClass(org.apache.jorphan.collections.SearchByClass)

Example 4 with SearchByClass

use of org.apache.jorphan.collections.SearchByClass in project jmeter by apache.

the class StandardJMeterEngine method configure.

// End of code to allow engine to be controlled remotely
@Override
public void configure(HashTree testTree) {
    // Is testplan serialised?
    SearchByClass<TestPlan> testPlan = new SearchByClass<>(TestPlan.class);
    testTree.traverse(testPlan);
    Object[] plan = testPlan.getSearchResults().toArray();
    if (plan.length == 0) {
        throw new RuntimeException("Could not find the TestPlan class!");
    }
    TestPlan tp = (TestPlan) plan[0];
    serialized = tp.isSerialized();
    tearDownOnShutdown = tp.isTearDownOnShutdown();
    active = true;
    test = testTree;
}
Also used : TestPlan(org.apache.jmeter.testelement.TestPlan) SearchByClass(org.apache.jorphan.collections.SearchByClass)

Aggregations

SearchByClass (org.apache.jorphan.collections.SearchByClass)4 File (java.io.File)2 LinkedList (java.util.LinkedList)2 ResultCollector (org.apache.jmeter.reporters.ResultCollector)2 ConversionException (com.thoughtworks.xstream.converters.ConversionException)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 SocketException (java.net.SocketException)1 Date (java.util.Date)1 StringTokenizer (java.util.StringTokenizer)1 ReplaceableController (org.apache.jmeter.control.ReplaceableController)1 ClientJMeterEngine (org.apache.jmeter.engine.ClientJMeterEngine)1 DistributedRunner (org.apache.jmeter.engine.DistributedRunner)1 JMeterEngine (org.apache.jmeter.engine.JMeterEngine)1 StandardJMeterEngine (org.apache.jmeter.engine.StandardJMeterEngine)1 IllegalUserActionException (org.apache.jmeter.exceptions.IllegalUserActionException)1 JMeterTreeModel (org.apache.jmeter.gui.tree.JMeterTreeModel)1 JMeterTreeNode (org.apache.jmeter.gui.tree.JMeterTreeNode)1 ConfigurationException (org.apache.jmeter.report.config.ConfigurationException)1