Search in sources :

Example 46 with TestElement

use of org.apache.jmeter.testelement.TestElement in project jmeter by apache.

the class Move method getParentNode.

private JMeterTreeNode getParentNode(JMeterTreeNode currentNode) {
    JMeterTreeNode parentNode = (JMeterTreeNode) currentNode.getParent();
    TestElement te = currentNode.getTestElement();
    if (te instanceof TestPlan || te instanceof WorkBench) {
        // So elements can only be added as children
        parentNode = null;
    }
    return parentNode;
}
Also used : TestPlan(org.apache.jmeter.testelement.TestPlan) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) TestElement(org.apache.jmeter.testelement.TestElement) WorkBench(org.apache.jmeter.testelement.WorkBench)

Example 47 with TestElement

use of org.apache.jmeter.testelement.TestElement in project jmeter by apache.

the class Proxy method run.

/**
     * Main processing method for the Proxy object
     */
@Override
public void run() {
    // Check which HTTPSampler class we should use
    String httpSamplerName = target.getSamplerTypeName();
    HttpRequestHdr request = new HttpRequestHdr(httpSamplerName);
    SampleResult result = null;
    HeaderManager headers = null;
    HTTPSamplerBase sampler = null;
    final boolean isDebug = log.isDebugEnabled();
    if (isDebug) {
        log.debug(port + "====================================================================");
    }
    SamplerCreator samplerCreator = null;
    try {
        // Now, parse initial request (in case it is a CONNECT request)
        byte[] ba = request.parse(new BufferedInputStream(clientSocket.getInputStream()));
        if (ba.length == 0) {
            if (isDebug) {
                log.debug(port + "Empty request, ignored");
            }
            // hack to skip processing
            throw new JMeterException();
        }
        if (isDebug) {
            log.debug(port + "Initial request: " + new String(ba));
        }
        outStreamClient = clientSocket.getOutputStream();
        if ((request.getMethod().startsWith(HTTPConstants.CONNECT)) && (outStreamClient != null)) {
            if (isDebug) {
                log.debug(port + "Method CONNECT => SSL");
            }
            // write a OK response to browser, to engage SSL exchange
            // $NON-NLS-1$
            outStreamClient.write(("HTTP/1.0 200 OK\r\n\r\n").getBytes(SampleResult.DEFAULT_HTTP_ENCODING));
            outStreamClient.flush();
            // With ssl request, url is host:port (without https:// or path)
            // $NON-NLS-1$
            String[] param = request.getUrl().split(":");
            if (param.length == 2) {
                if (isDebug) {
                    log.debug(port + "Start to negotiate SSL connection, host: " + param[0]);
                }
                clientSocket = startSSL(clientSocket, param[0]);
            } else {
                // Should not happen, but if it does we don't want to continue 
                log.error("In SSL request, unable to find host and port in CONNECT request: " + request.getUrl());
                // hack to skip processing
                throw new JMeterException();
            }
            // Re-parse (now it's the http request over SSL)
            try {
                ba = request.parse(new BufferedInputStream(clientSocket.getInputStream()));
            } catch (IOException ioe) {
                // most likely this is because of a certificate error
                // param.length is 2 here
                final String url = " for '" + param[0] + "'";
                log.warn(port + "Problem with SSL certificate" + url + "? Ensure browser is set to accept the JMeter proxy cert: " + ioe.getMessage());
                // won't work: writeErrorToClient(HttpReplyHdr.formInternalError());
                // Generate result (if nec.) and populate it
                result = generateErrorResult(result, request, ioe, "\n**ensure browser is set to accept the JMeter proxy certificate**");
                // hack to skip processing
                throw new JMeterException();
            }
            if (isDebug) {
                log.debug(port + "Reparse: " + new String(ba));
            }
            if (ba.length == 0) {
                log.warn(port + "Empty response to http over SSL. Probably waiting for user to authorize the certificate for " + request.getUrl());
                // hack to skip processing
                throw new JMeterException();
            }
        }
        samplerCreator = SAMPLERFACTORY.getSamplerCreator(request, pageEncodings, formEncodings);
        sampler = samplerCreator.createAndPopulateSampler(request, pageEncodings, formEncodings);
        /*
             * Create a Header Manager to ensure that the browsers headers are
             * captured and sent to the server
             */
        headers = request.getHeaderManager();
        sampler.setHeaderManager(headers);
        // Needed for HTTPSampler2
        sampler.threadStarted();
        if (isDebug) {
            log.debug(port + "Execute sample: " + sampler.getMethod() + " " + sampler.getUrl());
        }
        result = sampler.sample();
        // Find the page encoding and possibly encodings for forms in the page
        // in the response from the web server
        String pageEncoding = addPageEncoding(result);
        addFormEncodings(result, pageEncoding);
        writeToClient(result, new BufferedOutputStream(clientSocket.getOutputStream()));
        samplerCreator.postProcessSampler(sampler, result);
    } catch (JMeterException jme) {
    // ignored, already processed
    } catch (UnknownHostException uhe) {
        log.warn(port + "Server Not Found.", uhe);
        writeErrorToClient(HttpReplyHdr.formServerNotFound());
        // Generate result (if nec.) and populate it
        result = generateErrorResult(result, request, uhe);
    } catch (IllegalArgumentException e) {
        log.error(port + "Not implemented (probably used https)", e);
        writeErrorToClient(HttpReplyHdr.formNotImplemented("Probably used https instead of http. " + "To record https requests, see " + "<a href=\"http://jmeter.apache.org/usermanual/component_reference.html#HTTP(S)_Test_Script_Recorder\">HTTP(S) Test Script Recorder documentation</a>"));
        // Generate result (if nec.) and populate it
        result = generateErrorResult(result, request, e);
    } catch (Exception e) {
        log.error(port + "Exception when processing sample", e);
        writeErrorToClient(HttpReplyHdr.formInternalError());
        // Generate result (if nec.) and populate it
        result = generateErrorResult(result, request, e);
    } finally {
        if (sampler != null && isDebug) {
            log.debug(port + "Will deliver sample " + sampler.getName());
        }
        /*
             * We don't want to store any cookies in the generated test plan
             */
        if (headers != null) {
            // Always remove cookies
            headers.removeHeaderNamed(HTTPConstants.HEADER_COOKIE);
            // Remove additional headers
            for (String hdr : HEADERS_TO_REMOVE) {
                headers.removeHeaderNamed(hdr);
            }
        }
        if (// deliverSampler allows sampler to be null, but result must not be null
        result != null) {
            List<TestElement> children = new ArrayList<>();
            if (captureHttpHeaders) {
                children.add(headers);
            }
            if (samplerCreator != null) {
                children.addAll(samplerCreator.createChildren(sampler, result));
            }
            target.deliverSampler(sampler, children.toArray(new TestElement[children.size()]), result);
        }
        try {
            clientSocket.close();
        } catch (Exception e) {
            log.error(port + "Failed to close client socket", e);
        }
        if (sampler != null) {
            // Needed for HTTPSampler2
            sampler.threadFinished();
        }
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) TestElement(org.apache.jmeter.testelement.TestElement) HTMLParseException(org.apache.jmeter.protocol.http.parser.HTMLParseException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) JMeterException(org.apache.jorphan.util.JMeterException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager) HTTPSamplerBase(org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase) JMeterException(org.apache.jorphan.util.JMeterException) BufferedInputStream(java.io.BufferedInputStream) SampleResult(org.apache.jmeter.samplers.SampleResult) BufferedOutputStream(java.io.BufferedOutputStream)

Example 48 with TestElement

use of org.apache.jmeter.testelement.TestElement in project jmeter by apache.

the class ProxyControlGui method buildNodesModel.

private void buildNodesModel(JMeterTreeNode node, String parentName, int level) {
    String separator = " > ";
    if (node != null) {
        for (int i = 0; i < node.getChildCount(); i++) {
            StringBuilder name = new StringBuilder();
            JMeterTreeNode cur = (JMeterTreeNode) node.getChildAt(i);
            TestElement te = cur.getTestElement();
            /*
                 * Will never be true. Probably intended to use
                 * org.apache.jmeter.threads.ThreadGroup rather than
                 * java.lang.ThreadGroup However, that does not work correctly;
                 * whereas treating it as a Controller does. if (te instanceof
                 * ThreadGroup) { name.append(parent_name);
                 * name.append(cur.getName()); name.append(separator);
                 * buildNodesModel(cur, name.toString(), level); } else
                 */
            if (te instanceof Controller) {
                name.append(parentName);
                name.append(cur.getName());
                TreeNodeWrapper tnw = new TreeNodeWrapper(cur, name.toString());
                targetNodesModel.addElement(tnw);
                name.append(separator);
                buildNodesModel(cur, name.toString(), level + 1);
            } else if (te instanceof TestPlan || te instanceof WorkBench) {
                name.append(cur.getName());
                name.append(separator);
                buildNodesModel(cur, name.toString(), 0);
            }
        // Ignore everything else
        }
    }
}
Also used : TestPlan(org.apache.jmeter.testelement.TestPlan) TreeNodeWrapper(org.apache.jmeter.control.gui.TreeNodeWrapper) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) TestElement(org.apache.jmeter.testelement.TestElement) Controller(org.apache.jmeter.control.Controller) RecordingController(org.apache.jmeter.protocol.http.control.RecordingController) WorkBench(org.apache.jmeter.testelement.WorkBench)

Example 49 with TestElement

use of org.apache.jmeter.testelement.TestElement in project jmeter by apache.

the class ProxyControl method replaceValues.

/**
     * Scan all test elements passed in for values matching the value of any of
     * the variables in any of the variable-holding elements in the collection.
     *
     * @param sampler
     *            A TestElement to replace values on
     * @param configs
     *            More TestElements to replace values on
     * @param variables
     *            Collection of Arguments to use to do the replacement, ordered
     *            by ascending priority.
     */
private void replaceValues(TestElement sampler, TestElement[] configs, Collection<Arguments> variables) {
    // Build the replacer from all the variables in the collection:
    ValueReplacer replacer = new ValueReplacer();
    for (Arguments variable : variables) {
        final Map<String, String> map = variable.getArgumentsAsMap();
        // Drop any empty values (Bug 45199)
        map.values().removeIf(""::equals);
        replacer.addVariables(map);
    }
    try {
        boolean cachedRegexpMatch = regexMatch;
        replacer.reverseReplace(sampler, cachedRegexpMatch);
        for (TestElement config : configs) {
            if (config != null) {
                replacer.reverseReplace(config, cachedRegexpMatch);
            }
        }
    } catch (InvalidVariableException e) {
        log.warn("Invalid variables included for replacement into recorded " + "sample", e);
    }
}
Also used : InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) Arguments(org.apache.jmeter.config.Arguments) ValueReplacer(org.apache.jmeter.engine.util.ValueReplacer) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement)

Example 50 with TestElement

use of org.apache.jmeter.testelement.TestElement in project jmeter by apache.

the class ProxyControl method notifySampleListeners.

/**
     * This will notify sample listeners directly within the Proxy of the
     * sampling that just occurred -- so that we have a means to record the
     * server's responses as we go.
     *
     * @param event
     *            sampling event to be delivered
     */
private void notifySampleListeners(SampleEvent event) {
    JMeterTreeModel treeModel = getJmeterTreeModel();
    JMeterTreeNode myNode = treeModel.getNodeOf(this);
    Enumeration<JMeterTreeNode> kids = myNode.children();
    while (kids.hasMoreElements()) {
        JMeterTreeNode subNode = kids.nextElement();
        if (subNode.isEnabled()) {
            TestElement testElement = subNode.getTestElement();
            if (testElement instanceof SampleListener) {
                ((SampleListener) testElement).sampleOccurred(event);
            }
        }
    }
}
Also used : JMeterTreeModel(org.apache.jmeter.gui.tree.JMeterTreeModel) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) SampleListener(org.apache.jmeter.samplers.SampleListener)

Aggregations

TestElement (org.apache.jmeter.testelement.TestElement)83 Test (org.junit.Test)27 ConfigTestElement (org.apache.jmeter.config.ConfigTestElement)26 TestSampler (org.apache.jmeter.junit.stubs.TestSampler)21 JMeterTreeNode (org.apache.jmeter.gui.tree.JMeterTreeNode)18 TestPlan (org.apache.jmeter.testelement.TestPlan)12 ArrayList (java.util.ArrayList)9 IllegalUserActionException (org.apache.jmeter.exceptions.IllegalUserActionException)9 StringProperty (org.apache.jmeter.testelement.property.StringProperty)7 Controller (org.apache.jmeter.control.Controller)6 JMeterTreeModel (org.apache.jmeter.gui.tree.JMeterTreeModel)6 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)6 TreePath (javax.swing.tree.TreePath)5 GuiPackage (org.apache.jmeter.gui.GuiPackage)5 ActionEvent (java.awt.event.ActionEvent)4 IOException (java.io.IOException)4 LinkedList (java.util.LinkedList)4 Arguments (org.apache.jmeter.config.Arguments)4 WorkBench (org.apache.jmeter.testelement.WorkBench)4 TestElementProperty (org.apache.jmeter.testelement.property.TestElementProperty)4