Search in sources :

Example 6 with HeaderManager

use of org.apache.jmeter.protocol.http.control.HeaderManager in project jmeter by apache.

the class TestHeaderManager method testReplaceNoMatch.

@Test
public void testReplaceNoMatch() throws Exception {
    HeaderManager headerManager = new HeaderManager();
    headerManager.add(new Header("Referer", "https://jmeter.apache.org/changes.html"));
    headerManager.add(new Header("JSESSIONID", "AZAZDZDAFEFZEVZEZEVZEVZEVZZ"));
    int numberOfReplacements = headerManager.replace("JMeter.apache.org", "${host}", true);
    assertEquals(0, numberOfReplacements);
    assertEquals("Referer", headerManager.getHeader(0).getName());
    assertEquals("JSESSIONID", headerManager.getHeader(1).getName());
    assertEquals("https://jmeter.apache.org/changes.html", headerManager.getHeader(0).getValue());
    assertEquals("AZAZDZDAFEFZEVZEZEVZEVZEVZZ", headerManager.getHeader(1).getValue());
    headerManager = new HeaderManager();
    headerManager.add(new Header("Referer", "https://jmeter.apache.org/changes.html"));
    headerManager.add(new Header("JSESSIONID", "AZAZDZDAFEFZEVZEZEVZEVZEVZZ"));
    numberOfReplacements = headerManager.replace("JMeterx.apache.org", "${host}", false);
    assertEquals(0, numberOfReplacements);
    assertEquals("Referer", headerManager.getHeader(0).getName());
    assertEquals("JSESSIONID", headerManager.getHeader(1).getName());
    assertEquals("https://jmeter.apache.org/changes.html", headerManager.getHeader(0).getValue());
    assertEquals("AZAZDZDAFEFZEVZEZEVZEVZEVZZ", headerManager.getHeader(1).getValue());
}
Also used : Header(org.apache.jmeter.protocol.http.control.Header) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager) Test(org.junit.Test)

Example 7 with HeaderManager

use of org.apache.jmeter.protocol.http.control.HeaderManager in project jmeter by apache.

the class TestHeaderManager method testReplace.

@Test
public void testReplace() throws Exception {
    HeaderManager headerManager = new HeaderManager();
    headerManager.add(new Header("Referer", "https://jmeter.apache.org/changes.html"));
    headerManager.add(new Header("JSESSIONID", "AZAZDZDAFEFZEVZEZEVZEVZEVZZ"));
    int numberOfReplacements = headerManager.replace("jmeter.apache.org", "${host}", true);
    assertEquals(1, numberOfReplacements);
    assertEquals("Referer", headerManager.getHeader(0).getName());
    assertEquals("JSESSIONID", headerManager.getHeader(1).getName());
    assertEquals("https://${host}/changes.html", headerManager.getHeader(0).getValue());
    assertEquals("AZAZDZDAFEFZEVZEZEVZEVZEVZZ", headerManager.getHeader(1).getValue());
    headerManager = new HeaderManager();
    headerManager.add(new Header("Referer", "https://JMeter.apache.org/changes.html"));
    headerManager.add(new Header("JSESSIONID", "AZAZDZDAFEFZEVZEZEVZEVZEVZZ"));
    numberOfReplacements = headerManager.replace("jmeter.apache.org", "${host}", false);
    assertEquals(1, numberOfReplacements);
    assertEquals("Referer", headerManager.getHeader(0).getName());
    assertEquals("JSESSIONID", headerManager.getHeader(1).getName());
    assertEquals("https://${host}/changes.html", headerManager.getHeader(0).getValue());
    assertEquals("AZAZDZDAFEFZEVZEZEVZEVZEVZZ", headerManager.getHeader(1).getValue());
}
Also used : Header(org.apache.jmeter.protocol.http.control.Header) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager) Test(org.junit.Test)

Example 8 with HeaderManager

use of org.apache.jmeter.protocol.http.control.HeaderManager 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 9 with HeaderManager

use of org.apache.jmeter.protocol.http.control.HeaderManager in project jmeter by apache.

the class AjpSampler method setConnectionHeaders.

private String setConnectionHeaders(URL url, String host, String method) throws IOException {
    HeaderManager headers = getHeaderManager();
    AuthManager auth = getAuthManager();
    StringBuilder hbuf = new StringBuilder();
    // Allow Headers to override Host setting
    //$NON-NLS-1$
    hbuf.append("Host").append(COLON_SPACE).append(host).append(NEWLINE);
    //Host
    setInt(0xA00b);
    setString(host);
    if (headers != null) {
        for (JMeterProperty jMeterProperty : headers.getHeaders()) {
            Header header = (Header) jMeterProperty.getObjectValue();
            String n = header.getName();
            String v = header.getValue();
            hbuf.append(n).append(COLON_SPACE).append(v).append(NEWLINE);
            int hc = translateHeader(n);
            if (hc > 0) {
                setInt(hc + AJP_HEADER_BASE);
            } else {
                setString(n);
            }
            setString(v);
        }
    }
    if (method.equals(HTTPConstants.POST)) {
        int cl = -1;
        HTTPFileArg[] hfa = getHTTPFiles();
        if (hfa.length > 0) {
            HTTPFileArg fa = hfa[0];
            String fn = fa.getPath();
            File input = new File(fn);
            cl = (int) input.length();
            if (body != null) {
                JOrphanUtils.closeQuietly(body);
                body = null;
            }
            body = new BufferedInputStream(new FileInputStream(input));
            setString(HTTPConstants.HEADER_CONTENT_DISPOSITION);
            setString("form-data; name=\"" + encode(fa.getParamName()) + "\"; filename=\"" + encode(fn) + //$NON-NLS-1$ //$NON-NLS-2$
            "\"");
            String mt = fa.getMimeType();
            hbuf.append(HTTPConstants.HEADER_CONTENT_TYPE).append(COLON_SPACE).append(mt).append(NEWLINE);
            // content-type
            setInt(0xA007);
            setString(mt);
        } else {
            hbuf.append(HTTPConstants.HEADER_CONTENT_TYPE).append(COLON_SPACE).append(HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED).append(NEWLINE);
            // content-type
            setInt(0xA007);
            setString(HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (JMeterProperty arg : getArguments()) {
                if (first) {
                    first = false;
                } else {
                    sb.append('&');
                }
                sb.append(arg.getStringValue());
            }
            stringBody = sb.toString();
            // TODO - charset?
            byte[] sbody = stringBody.getBytes();
            cl = sbody.length;
            body = new ByteArrayInputStream(sbody);
        }
        hbuf.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(COLON_SPACE).append(String.valueOf(cl)).append(NEWLINE);
        // Content-length
        setInt(0xA008);
        setString(String.valueOf(cl));
    }
    if (auth != null) {
        String authHeader = auth.getAuthHeaderForURL(url);
        if (authHeader != null) {
            // Authorization
            setInt(0xA005);
            setString(authHeader);
            hbuf.append(HTTPConstants.HEADER_AUTHORIZATION).append(COLON_SPACE).append(authHeader).append(NEWLINE);
        }
    }
    return hbuf.toString();
}
Also used : JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) FileInputStream(java.io.FileInputStream) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager) Header(org.apache.jmeter.protocol.http.control.Header) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File)

Example 10 with HeaderManager

use of org.apache.jmeter.protocol.http.control.HeaderManager in project jmeter by apache.

the class AjpSampler method getHeaderSize.

private int getHeaderSize(String method, URL url) {
    HeaderManager headers = getHeaderManager();
    CookieManager cookies = getCookieManager();
    AuthManager auth = getAuthManager();
    // Host always
    int hsz = 1;
    if (method.equals(HTTPConstants.POST)) {
        HTTPFileArg[] hfa = getHTTPFiles();
        if (hfa.length > 0) {
            hsz += 3;
        } else {
            hsz += 2;
        }
    }
    if (headers != null) {
        hsz += headers.size();
    }
    if (cookies != null) {
        hsz += cookies.getCookieCount();
    }
    if (auth != null) {
        String authHeader = auth.getAuthHeaderForURL(url);
        if (authHeader != null) {
            ++hsz;
        }
    }
    return hsz;
}
Also used : AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) CookieManager(org.apache.jmeter.protocol.http.control.CookieManager) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager)

Aggregations

HeaderManager (org.apache.jmeter.protocol.http.control.HeaderManager)10 Header (org.apache.jmeter.protocol.http.control.Header)7 Test (org.junit.Test)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 BufferedInputStream (java.io.BufferedInputStream)2 ArrayList (java.util.ArrayList)2 AuthManager (org.apache.jmeter.protocol.http.control.AuthManager)2 HTTPFileArg (org.apache.jmeter.protocol.http.util.HTTPFileArg)2 TestElement (org.apache.jmeter.testelement.TestElement)2 TestElementProperty (org.apache.jmeter.testelement.property.TestElementProperty)2 BufferedOutputStream (java.io.BufferedOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 UnknownHostException (java.net.UnknownHostException)1 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 KeyStoreException (java.security.KeyStoreException)1 HashMap (java.util.HashMap)1