Search in sources :

Example 56 with HTTPSamplerBase

use of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase in project jmeter by apache.

the class TestHttpRequestHdr method testEncodedArguments.

private void testEncodedArguments(String url) throws Exception {
    // A HTTP GET request, with encoding not known
    String contentEncoding = "";
    String queryString = "abc%3FSPACE=a+b&space=a%20b&query=What%3F";
    String testGetRequest = "GET " + url + "?" + queryString + " HTTP/1.1\r\n\r\n";
    // Use null for url and contentEncoding, to simulate that HttpRequestHdr do not
    // know the encoding for the page
    HTTPSamplerBase s = getSamplerForRequest(null, testGetRequest, null);
    assertEquals(HTTPConstants.GET, s.getMethod());
    assertEquals(queryString, s.getQueryString());
    assertEquals(contentEncoding, s.getContentEncoding());
    // Check arguments
    Arguments arguments = s.getArguments();
    assertEquals(3, arguments.getArgumentCount());
    // When the encoding is not known, the argument will get the encoded value, and the "encode?" set to false
    checkArgument((HTTPArgument) arguments.getArgument(0), "abc%3FSPACE", "a+b", "a+b", contentEncoding, false);
    checkArgument((HTTPArgument) arguments.getArgument(1), "space", "a%20b", "a%20b", contentEncoding, false);
    checkArgument((HTTPArgument) arguments.getArgument(2), "query", "What%3F", "What%3F", contentEncoding, false);
    // A HTTP GET request, with UTF-8 encoding
    contentEncoding = "UTF-8";
    queryString = "abc%3FSPACE=a+b&space=a%20b&query=What%3F";
    testGetRequest = "GET " + url + "?" + queryString + " HTTP/1.1\r\n\r\n";
    s = getSamplerForRequest(url, testGetRequest, contentEncoding);
    assertEquals(HTTPConstants.GET, s.getMethod());
    String expectedQueryString = "abc%3FSPACE=a+b&space=a+b&query=What%3F";
    assertEquals(expectedQueryString, s.getQueryString());
    assertEquals(contentEncoding, s.getContentEncoding());
    // Check arguments
    arguments = s.getArguments();
    assertEquals(3, arguments.getArgumentCount());
    checkArgument((HTTPArgument) arguments.getArgument(0), "abc?SPACE", "a b", "a+b", contentEncoding, true);
    checkArgument((HTTPArgument) arguments.getArgument(1), "space", "a b", "a+b", contentEncoding, true);
    checkArgument((HTTPArgument) arguments.getArgument(2), "query", "What?", "What%3F", contentEncoding, true);
    // A HTTP POST request, with unknown encoding
    contentEncoding = "";
    String postBody = "abc%3FSPACE=a+b&space=a%20b&query=What%3F";
    String testPostRequest = "POST " + url + " HTTP/1.1\r\n" + "Content-type: " + HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED + "\r\n" + "Content-length: " + getBodyLength(postBody, contentEncoding) + "\r\n" + "\r\n" + postBody;
    // Use null for url and contentEncoding, to simulate that HttpRequestHdr do not
    // know the encoding for the page
    s = getSamplerForRequest(null, testPostRequest, null);
    assertEquals(HTTPConstants.POST, s.getMethod());
    assertEquals(queryString, s.getQueryString());
    assertEquals(contentEncoding, s.getContentEncoding());
    assertFalse(s.getDoMultipart());
    // Check arguments
    arguments = s.getArguments();
    assertEquals(3, arguments.getArgumentCount());
    // When the encoding is not known, the argument will get the encoded value, and the "encode?" set to false
    checkArgument((HTTPArgument) arguments.getArgument(0), "abc%3FSPACE", "a+b", "a+b", contentEncoding, false);
    checkArgument((HTTPArgument) arguments.getArgument(1), "space", "a%20b", "a%20b", contentEncoding, false);
    checkArgument((HTTPArgument) arguments.getArgument(2), "query", "What%3F", "What%3F", contentEncoding, false);
    // A HTTP POST request, with UTF-8 encoding
    contentEncoding = "UTF-8";
    postBody = "abc?SPACE=a+b&space=a%20b&query=What?";
    testPostRequest = "POST " + url + " HTTP/1.1\n" + "Content-type: " + HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED + "\r\n" + "Content-length: " + getBodyLength(postBody, contentEncoding) + "\r\n" + "\r\n" + postBody;
    s = getSamplerForRequest(url, testPostRequest, contentEncoding);
    assertEquals(HTTPConstants.POST, s.getMethod());
    expectedQueryString = "abc%3FSPACE=a+b&space=a+b&query=What%3F";
    assertEquals(expectedQueryString, s.getQueryString());
    assertEquals(contentEncoding, s.getContentEncoding());
    assertFalse(s.getDoMultipart());
    // Check arguments
    arguments = s.getArguments();
    assertEquals(3, arguments.getArgumentCount());
    checkArgument((HTTPArgument) arguments.getArgument(0), "abc?SPACE", "a b", "a+b", contentEncoding, true);
    checkArgument((HTTPArgument) arguments.getArgument(1), "space", "a b", "a+b", contentEncoding, true);
    checkArgument((HTTPArgument) arguments.getArgument(2), "query", "What?", "What%3F", contentEncoding, true);
}
Also used : Arguments(org.apache.jmeter.config.Arguments) HTTPSamplerBase(org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)

Example 57 with HTTPSamplerBase

use of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase 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(target.getPrefixHTTPSampleName(), httpSamplerName, target.getHTTPSampleNamingMode(), target.getHttpSampleNameFormat());
    request.setDetectGraphQLRequest(target.getDetectGraphQLRequest());
    SampleResult result = null;
    HeaderManager headers = null;
    HTTPSamplerBase sampler = null;
    final boolean isDebug = log.isDebugEnabled();
    log.debug("{} ====================================================================", port);
    SamplerCreator samplerCreator = null;
    try {
        JMeterContextService.getContext().setRecording(true);
        // Now, parse initial request (in case it is a CONNECT request)
        byte[] ba = request.parse(new BufferedInputStream(clientSocket.getInputStream()));
        if (ba.length == 0) {
            log.debug("{} Empty request, ignored", port);
            // hack to skip processing
            throw new JMeterException();
        }
        if (isDebug) {
            @SuppressWarnings("DefaultCharset") final String // NOSONAR False positive
            reparsed = new String(ba);
            log.debug("{} Initial request: {}", port, reparsed);
        }
        // Use with SSL connection
        OutputStream outStreamClient = clientSocket.getOutputStream();
        if (request.getMethod().startsWith(HTTPConstants.CONNECT) && (outStreamClient != null)) {
            log.debug("{} Method CONNECT => SSL", port);
            // write a OK response to browser, to engage SSL exchange
            outStreamClient.write(// $NON-NLS-1$
            "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) {
                log.debug("{} Start to negotiate SSL connection, host: {}", port, 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("{} Problem with SSL certificate for url {}? Ensure browser is set to accept the JMeter proxy cert: {}", port, url, ioe.getMessage());
                // 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) {
                @SuppressWarnings("DefaultCharset") final String // NOSONAR False positive
                reparsed = new String(ba);
                log.debug("{} Reparse: {}", port, reparsed);
            }
            if (ba.length == 0) {
                log.warn("{} Empty response to http over SSL. Probably waiting for user to authorize the certificate for {}", port, request.getUrl());
                // hack to skip processing
                throw new JMeterException();
            }
        }
        samplerCreator = SAMPLERFACTORY.getSamplerCreator(request, pageEncodings, formEncodings);
        sampler = samplerCreator.createAndPopulateSampler(request, pageEncodings, formEncodings);
        sampler.setUseKeepAlive(false);
        /*
             * 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("{} Execute sample: {} and url {}", port, 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("{} Server Not Found.", port, uhe);
        writeErrorToClient(HttpReplyHdr.formServerNotFound());
        // Generate result (if nec.) and populate it
        result = generateErrorResult(result, request, uhe);
    } catch (IllegalArgumentException e) {
        log.error("{} Not implemented (probably used https)", port, 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("{} Exception when processing sample", port, e);
        writeErrorToClient(HttpReplyHdr.formInternalError());
        // Generate result (if nec.) and populate it
        result = generateErrorResult(result, request, e);
    } finally {
        if (sampler != null && isDebug) {
            log.debug("{} Will deliver sample {}", port, 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("{} Failed to close client socket", port, e);
        }
        if (sampler != null) {
            // Needed for HTTPSampler2
            sampler.threadFinished();
        }
        JMeterContextService.getContext().setRecording(false);
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) DataOutputStream(java.io.DataOutputStream) OutputStream(java.io.OutputStream) 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 58 with HTTPSamplerBase

use of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase in project jmeter by apache.

the class ProxyControl method prepareTree.

private boolean prepareTree(final JMeterTreeModel treeModel, long deltaT, SamplerInfo info) {
    HTTPSamplerBase sampler = info.sampler;
    JMeterTreeNode myTarget = info.target;
    int cachedGroupingMode = info.groupingMode;
    boolean prefixChanged = false;
    if (oldPrefix == null || !oldPrefix.equals(info.prefix)) {
        oldPrefix = info.prefix;
        prefixChanged = true;
    }
    if (deltaT > sampleGap || prefixChanged) {
        String controllerName = StringUtils.defaultString(getPrefixHTTPSampleName(), sampler.getName());
        if (!myTarget.isLeaf() && cachedGroupingMode == GROUPING_ADD_SEPARATORS) {
            addDivider(treeModel, myTarget);
        }
        if (cachedGroupingMode == GROUPING_IN_SIMPLE_CONTROLLERS) {
            addSimpleController(treeModel, myTarget, controllerName);
        }
        if (cachedGroupingMode == GROUPING_IN_TRANSACTION_CONTROLLERS) {
            addTransactionController(treeModel, myTarget, controllerName);
        }
        // Remember this was first in its batch
        return true;
    }
    return false;
}
Also used : JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) HTTPSamplerBase(org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)

Example 59 with HTTPSamplerBase

use of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase in project jmeter by apache.

the class HttpTestSampleGui method modifyTestElement.

/**
 * Modifies a given TestElement to mirror the data in the gui components.
 * <p>
 * {@inheritDoc}
 */
@Override
public void modifyTestElement(TestElement sampler) {
    sampler.clear();
    urlConfigGui.modifyTestElement(sampler);
    final HTTPSamplerBase samplerBase = (HTTPSamplerBase) sampler;
    samplerBase.setImageParser(retrieveEmbeddedResources.isSelected());
    enableConcurrentDwn(retrieveEmbeddedResources.isSelected());
    samplerBase.setConcurrentDwn(concurrentDwn.isSelected());
    samplerBase.setConcurrentPool(concurrentPool.getText());
    samplerBase.setMD5(useMD5.isSelected());
    samplerBase.setEmbeddedUrlRE(embeddedAllowRE.getText());
    samplerBase.setEmbeddedUrlExcludeRE(embeddedExcludeRE.getText());
    if (!isAJP) {
        samplerBase.setIpSource(sourceIpAddr.getText());
        samplerBase.setIpSourceType(sourceIpType.getSelectedIndex());
        samplerBase.setProperty(HTTPSamplerBase.PROXYSCHEME, proxyScheme.getText(), "");
        samplerBase.setProperty(HTTPSamplerBase.PROXYHOST, proxyHost.getText(), "");
        samplerBase.setProperty(HTTPSamplerBase.PROXYPORT, proxyPort.getText(), "");
        samplerBase.setProperty(HTTPSamplerBase.PROXYUSER, proxyUser.getText(), "");
        samplerBase.setProperty(HTTPSamplerBase.PROXYPASS, String.valueOf(proxyPass.getPassword()), "");
        samplerBase.setProperty(HTTPSamplerBase.IMPLEMENTATION, httpImplementation.getSelectedItem().toString(), "");
        samplerBase.setProperty(HTTPSamplerBase.CONNECT_TIMEOUT, connectTimeOut.getText());
        samplerBase.setProperty(HTTPSamplerBase.RESPONSE_TIMEOUT, responseTimeOut.getText());
    }
    super.configureTestElement(sampler);
}
Also used : HTTPSamplerBase(org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)

Example 60 with HTTPSamplerBase

use of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase in project jmeter by apache.

the class HttpTestSampleGui method createTestElement.

/**
 * {@inheritDoc}
 */
@Override
public TestElement createTestElement() {
    HTTPSamplerBase sampler = new HTTPSamplerProxy();
    modifyTestElement(sampler);
    return sampler;
}
Also used : HTTPSamplerProxy(org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy) HTTPSamplerBase(org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)

Aggregations

HTTPSamplerBase (org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)65 Test (org.junit.jupiter.api.Test)40 SampleResult (org.apache.jmeter.samplers.SampleResult)20 Arguments (org.apache.jmeter.config.Arguments)18 HTTPSampleResult (org.apache.jmeter.protocol.http.sampler.HTTPSampleResult)14 HTTPNullSampler (org.apache.jmeter.protocol.http.sampler.HTTPNullSampler)6 HttpTestSampleGui (org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui)5 NodeList (org.w3c.dom.NodeList)4 MalformedURLException (java.net.MalformedURLException)3 URL (java.net.URL)3 ArrayList (java.util.ArrayList)3 HTTPFileArg (org.apache.jmeter.protocol.http.util.HTTPFileArg)3 Sampler (org.apache.jmeter.samplers.Sampler)3 NamedNodeMap (org.w3c.dom.NamedNodeMap)3 ClientCookie (org.apache.http.cookie.ClientCookie)2 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)2 Argument (org.apache.jmeter.config.Argument)2 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)2 JMeterContext (org.apache.jmeter.threads.JMeterContext)2 Node (org.w3c.dom.Node)2