Search in sources :

Example 1 with CacheManager

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

the class CacheManagerGui method configure.

@Override
public void configure(TestElement element) {
    super.configure(element);
    final CacheManager cacheManager = (CacheManager) element;
    useExpires.setSelected(cacheManager.getUseExpires());
    maxCacheSize.setText(Integer.toString(cacheManager.getMaxSize()));
    controlledByThreadGroup.setSelected(cacheManager.getControlledByThread());
    clearEachIteration.setSelected(cacheManager.getClearEachIteration());
}
Also used : CacheManager(org.apache.jmeter.protocol.http.control.CacheManager)

Example 2 with CacheManager

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

the class CacheManagerGui method createTestElement.

@Override
public TestElement createTestElement() {
    CacheManager element = new CacheManager();
    modifyTestElement(element);
    controlledByThreadGroup.setSelected(element.getControlledByThread());
    clearEachIteration.setEnabled(!element.getControlledByThread());
    return element;
}
Also used : CacheManager(org.apache.jmeter.protocol.http.control.CacheManager)

Example 3 with CacheManager

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

the class HTTPHC4Impl method sample.

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
    if (log.isDebugEnabled()) {
        log.debug("Start : sample {} method {} followingRedirect {} depth {}", url, method, areFollowingRedirect, frameDepth);
    }
    JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
    HTTPSampleResult res = createSampleResult(url, method);
    CloseableHttpClient httpClient = null;
    HttpRequestBase httpRequest = null;
    HttpContext localContext = new BasicHttpContext();
    HttpClientContext clientContext = HttpClientContext.adapt(localContext);
    clientContext.setAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER, getAuthManager());
    HttpClientKey key = createHttpClientKey(url);
    MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple;
    try {
        triple = setupClient(key, jMeterVariables, clientContext);
        httpClient = triple.getLeft();
        URI uri = url.toURI();
        httpRequest = createHttpRequest(uri, method, areFollowingRedirect);
        // can throw IOException
        setupRequest(url, httpRequest, res);
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }
    setupClientContextBeforeSample(jMeterVariables, localContext);
    res.sampleStart();
    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method) && cacheManager.inCache(url, httpRequest.getAllHeaders())) {
        return updateSampleResultForResourceInCache(res);
    }
    CloseableHttpResponse httpResponse = null;
    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(CONTEXT_ATTRIBUTE_SAMPLER_RESULT, res);
        // perform the sample
        httpResponse = executeRequest(httpClient, httpRequest, localContext, url);
        saveProxyAuth(triple, localContext);
        if (log.isDebugEnabled()) {
            log.debug("Headers in request before:{}", Arrays.asList(httpRequest.getAllHeaders()));
        }
        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if (log.isDebugEnabled()) {
            log.debug("Headers in request after:{}, in localContext#request:{}", Arrays.asList(httpRequest.getAllHeaders()), Arrays.asList(request.getAllHeaders()));
        }
        extractClientContextAfterSample(jMeterVariables, localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        if (localAddress != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString());
        }
        res.setRequestHeaders(getAllHeadersExceptCookie(request));
        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), entity.getContentLength()));
        }
        // Done with the sampling proper.
        res.sampleEnd();
        currentRequest = null;
        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));
        res.setResponseHeaders(getResponseHeaders(httpResponse));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) {
                // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }
        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        long headerBytes = // condensed length (without \r)
        (long) res.getResponseHeaders().length() + // Add \r for each header
        (long) httpResponse.getAllHeaders().length + // Add \r for initial header
        1L + // final \r\n before data
        2L;
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_ATTRIBUTE_METRICS);
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize(totalBytes - headerBytes);
        res.setSentBytes((Long) localContext.getAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES));
        if (log.isDebugEnabled()) {
            long total = res.getHeadersSize() + res.getBodySizeAsLong();
            log.debug("ResponseHeadersSize={} Content-Length={} Total={}", res.getHeadersSize(), res.getBodySizeAsLong(), total);
        }
        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }
        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());
        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }
        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);
        if (!isSuccessCode(statusCode)) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: {}", res.getRequestHeaders());
        }
        res.setRequestHeaders(getAllHeadersExceptCookie((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        JOrphanUtils.closeQuietly(httpResponse);
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE);
    }
    return res;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) URI(java.net.URI) URL(java.net.URL) HttpConnectionMetrics(org.apache.http.HttpConnectionMetrics) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager) HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpContext(org.apache.http.protocol.HttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.http.HttpException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) AuthState(org.apache.http.auth.AuthState)

Example 4 with CacheManager

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

the class HTTPSamplerBase method setCacheManager.

public void setCacheManager(CacheManager value) {
    CacheManager mgr = getCacheManager();
    if (mgr != null) {
        if (log.isWarnEnabled()) {
            log.warn("Existing CacheManager {} superseded by {}", mgr.getName(), value.getName());
        }
    }
    setCacheManagerProperty(value);
}
Also used : DNSCacheManager(org.apache.jmeter.protocol.http.control.DNSCacheManager) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager)

Example 5 with CacheManager

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

the class HTTPJavaImpl method sample.

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate.
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 *
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
    HttpURLConnection conn = null;
    String urlStr = url.toString();
    if (log.isDebugEnabled()) {
        log.debug("Start : sample {}, method {}, followingRedirect {}, depth {}", urlStr, method, areFollowingRedirect, frameDepth);
    }
    HTTPSampleResult res = new HTTPSampleResult();
    configureSampleLabel(res, url);
    res.setURL(url);
    res.setHTTPMethod(method);
    // Count the retries as well in the time
    res.sampleStart();
    // Check cache for an entry with an Expires header in the future
    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url, getHeaders(getHeaderManager()))) {
            return updateSampleResultForResourceInCache(res);
        }
    }
    try {
        // Sampling proper - establish the connection and read the response:
        // Repeatedly try to connect:
        int retry = -1;
        // Start with -1 so tries at least once, and retries at most MAX_CONN_RETRIES times
        for (; retry < MAX_CONN_RETRIES; retry++) {
            try {
                conn = setupConnection(url, method, res);
                // Attempt the connection:
                savedConn = conn;
                conn.connect();
                break;
            } catch (BindException e) {
                if (retry >= MAX_CONN_RETRIES) {
                    log.error("Can't connect after {} retries, message: {}", retry, e.toString());
                    throw e;
                }
                log.debug("Bind exception, try again");
                if (conn != null) {
                    // we don't want interrupt to try disconnection again
                    savedConn = null;
                    conn.disconnect();
                }
                setUseKeepAlive(false);
            } catch (IOException e) {
                log.debug("Connection failed, giving up");
                throw e;
            }
        }
        if (retry > MAX_CONN_RETRIES) {
            // This should never happen, but...
            throw new BindException();
        }
        // Nice, we've got a connection. Finish sending the request:
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData(conn);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT)) {
            String putBody = sendPutData(conn);
            res.setQueryString(putBody);
        }
        // Request sent. Now get the response:
        byte[] responseData = readResponse(conn, res);
        res.sampleEnd();
        // Done with the sampling proper.
        // Now collect the results into the HTTPSampleResult:
        res.setResponseData(responseData);
        int errorLevel = conn.getResponseCode();
        String respMsg = conn.getResponseMessage();
        String hdr = conn.getHeaderField(0);
        if (hdr == null) {
            // $NON-NLS-1$
            hdr = "(null)";
        }
        if (errorLevel == -1) {
            // Bug 38902 - sometimes -1 seems to be returned unnecessarily
            if (respMsg != null) {
                // Bug 41902 - NPE
                try {
                    errorLevel = Integer.parseInt(respMsg.substring(0, 3));
                    log.warn("ResponseCode==-1; parsed {} as {}", respMsg, errorLevel);
                } catch (NumberFormatException e) {
                    log.warn("ResponseCode==-1; could not parse {} hdr: {}", respMsg, hdr);
                }
            } else {
                // for result
                respMsg = hdr;
                log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= {} ", hdr);
            }
        }
        if (errorLevel == -1) {
            // $NON-NLS-1$
            res.setResponseCode("(null)");
        } else {
            res.setResponseCode(Integer.toString(errorLevel));
        }
        res.setSuccessful(isSuccessCode(errorLevel));
        if (respMsg == null) {
            // has been seen in a redirect
            // use header (if possible) if no message found
            respMsg = hdr;
        }
        res.setResponseMessage(respMsg);
        String ct = conn.getContentType();
        if (ct != null) {
            // e.g. text/html; charset=ISO-8859-1
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        String responseHeaders = getResponseHeaders(conn);
        res.setResponseHeaders(responseHeaders);
        if (res.isRedirect()) {
            res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION));
        }
        // record headers size to allow HTTPSampleResult.getBytes() with different options
        res.setHeadersSize(// $NON-NLS-1$ $NON-NLS-2$
        responseHeaders.replaceAll("\n", "\r\n").length() + // add 2 for a '\r\n' at end of headers (before data)
        2);
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize={}, bodySize={}, Total={}", res.getHeadersSize(), res.getBodySizeAsLong(), res.getHeadersSize() + res.getBodySizeAsLong());
        }
        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(conn.getURL());
        }
        // Store any cookies received in the cookie manager:
        saveConnectionCookies(conn, url, getCookieManager());
        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(conn, res);
        }
        res = resultProcessing(areFollowingRedirect, frameDepth, res);
        log.debug("End : sample");
        return res;
    } catch (IOException e) {
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // we don't want interrupt to try disconnection again
        savedConn = null;
        // We don't want to continue using this connection, even if KeepAlive is set
        if (conn != null) {
            // May not exist
            conn.disconnect();
        }
        // Don't process again
        conn = null;
        return errorResult(e, res);
    } finally {
        // calling disconnect doesn't close the connection immediately,
        // but indicates we're through with it. The JVM should close
        // it when necessary.
        // we don't want interrupt to try disconnection again
        savedConn = null;
        // Disconnect unless using KeepAlive
        disconnect(conn);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager) BindException(java.net.BindException) IOException(java.io.IOException)

Aggregations

CacheManager (org.apache.jmeter.protocol.http.control.CacheManager)6 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 BindException (java.net.BindException)1 HttpURLConnection (java.net.HttpURLConnection)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 GeneralSecurityException (java.security.GeneralSecurityException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 Header (org.apache.http.Header)1 HttpConnectionMetrics (org.apache.http.HttpConnectionMetrics)1 HttpEntity (org.apache.http.HttpEntity)1 HttpException (org.apache.http.HttpException)1 HttpHost (org.apache.http.HttpHost)1 HttpRequest (org.apache.http.HttpRequest)1 StatusLine (org.apache.http.StatusLine)1 AuthState (org.apache.http.auth.AuthState)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1