Package org.apache.jmeter.protocol.http.sampler

Examples of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase


    @Override
    public void process() {
        JMeterContext context = getThreadContext();
        Sampler sam = context.getCurrentSampler();
        SampleResult res = context.getPreviousResult();
        HTTPSamplerBase sampler = null;
        HTTPSampleResult result = null;
        if (res == null || !(sam instanceof HTTPSamplerBase) || !(res instanceof HTTPSampleResult)) {
            log.info("Can't apply HTML Link Parser when the previous" + " sampler run is not an HTTP Request.");
            return;
        } else {
            sampler = (HTTPSamplerBase) sam;
            result = (HTTPSampleResult) res;
        }
        List<HTTPSamplerBase> potentialLinks = new ArrayList<HTTPSamplerBase>();
        String responseText = ""; // $NON-NLS-1$
        responseText = result.getResponseDataAsString();
        Document html;
        int index = responseText.indexOf('<'); // $NON-NLS-1$
        if (index == -1) {
            index = 0;
        }
        if (log.isDebugEnabled()) {
            log.debug("Check for matches against: "+sampler.toString());
        }
        html = (Document) HtmlParsingUtils.getDOM(responseText.substring(index));
        addAnchorUrls(html, result, sampler, potentialLinks);
        addFormUrls(html, result, sampler, potentialLinks);
        addFramesetUrls(html, result, sampler, potentialLinks);
        if (potentialLinks.size() > 0) {
            HTTPSamplerBase url = potentialLinks.get(rand.nextInt(potentialLinks.size()));
            if (log.isDebugEnabled()) {
                log.debug("Selected: "+url.toString());
            }
            sampler.setDomain(url.getDomain());
            sampler.setPath(url.getPath());
            if (url.getMethod().equals(HTTPConstants.POST)) {
                PropertyIterator iter = sampler.getArguments().iterator();
                while (iter.hasNext()) {
                    Argument arg = (Argument) iter.next().getObjectValue();
                    modifyArgument(arg, url.getArguments());
                }
            } else {
                sampler.setArguments(url.getArguments());
                // config.parseArguments(url.getQueryString());
            }
            sampler.setProtocol(url.getProtocol());
            return;
        } else {
            log.debug("No matches found");
        }
        return;
View Full Code Here


            String hrefStr = namedItem.getNodeValue();
            if (hrefStr.startsWith("javascript:")) { // $NON-NLS-1$
                continue; // No point trying these
            }
            try {
                HTTPSamplerBase newUrl = HtmlParsingUtils.createUrlFromAnchor(hrefStr, ConversionUtils.makeRelativeURL(result.getURL(), base));
                newUrl.setMethod(HTTPConstants.GET);
                if (log.isDebugEnabled()) {
                    log.debug("Potential <a href> match: " + newUrl);
                }
                if (HtmlParsingUtils.isAnchorMatched(newUrl, config)) {
                    log.debug("Matched!");
View Full Code Here

           if (namedItem == null) {
               continue;
           }
           String hrefStr = namedItem.getNodeValue();
           try {
               HTTPSamplerBase newUrl = HtmlParsingUtils.createUrlFromAnchor(
                       hrefStr, ConversionUtils.makeRelativeURL(result.getURL(), base));
               newUrl.setMethod(HTTPConstants.GET);
               if (log.isDebugEnabled()) {
                   log.debug("Potential <frame src> match: " + newUrl);
               }
               if (HtmlParsingUtils.isAnchorMatched(newUrl, config)) {
                   log.debug("Matched!");
View Full Code Here

        if(paramMap == null || paramMap.isEmpty()){
            log.info("RegExUserParameters element:"+getName()+" => Referenced RegExp was not found, no parameter will be changed");
            return;
        }

        HTTPSamplerBase sampler = (HTTPSamplerBase) entry;
        PropertyIterator iter = sampler.getArguments().iterator();
        while (iter.hasNext()) {
            Argument arg = (Argument) iter.next().getObjectValue();
            String oldValue = arg.getValue();
            // if parameter name exists in http request
            // then change its value with value obtained with regular expression
View Full Code Here

        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 + "====================================================================");
        }
        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");
                }
                throw new JMeterException(); // hack to skip processing
            }
            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 reponse to browser, to engage SSL exchange
                outStreamClient.write(("HTTP/1.0 200 OK\r\n\r\n").getBytes(SampleResult.DEFAULT_HTTP_ENCODING)); // $NON-NLS-1$
                outStreamClient.flush();
               // With ssl request, url is host:port (without https:// or path)
                String[] param = request.getUrl().split(":")// $NON-NLS-1$
                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());
                    throw new JMeterException(); // hack to skip processing
                }
                // 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
                    final String url = param.length>0 " 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());
                    result = generateErrorResult(result, request, ioe, "\n**ensure browser is set to accept the JMeter proxy certificate**"); // Generate result (if nec.) and populate it
                    throw new JMeterException(); // hack to skip processing
                }
                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());
                    throw new JMeterException(); // hack to skip processing
                }
            }

            SamplerCreator 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);

            sampler.threadStarted(); // Needed for HTTPSampler2
            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());
            result = generateErrorResult(result, request, uhe); // Generate result (if nec.) and populate it
        } 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>"));
            result = generateErrorResult(result, request, e); // Generate result (if nec.) and populate it
        } catch (Exception e) {
            log.error(port + "Exception when processing sample", e);
            writeErrorToClient(HttpReplyHdr.formInternalError());
            result = generateErrorResult(result, request, e); // Generate result (if nec.) and populate it
        } 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) {
                headers.removeHeaderNamed(HTTPConstants.HEADER_COOKIE);// Always remove cookies
                headers.removeHeaderNamed(HTTPConstants.HEADER_AUTHORIZATION);// Always remove authorization
                // Remove additional headers
                for(String hdr : HEADERS_TO_REMOVE){
                    headers.removeHeaderNamed(hdr);
                }
            }
            if(result != null) // deliverSampler allows sampler to be null, but result must not be null
            {
                target.deliverSampler(sampler, new TestElement[] { captureHttpHeaders ? headers : null }, result);
            }
            try {
                clientSocket.close();
            } catch (Exception e) {
                log.error(port + "Failed to close client socket", e);
            }
            if(sampler != null) {
                sampler.threadFinished(); // Needed for HTTPSampler2
            }
        }
    }
View Full Code Here

     */
    @Override
    public HTTPSamplerBase createSampler(HttpRequestHdr request,
            Map<String, String> pageEncodings, Map<String, String> formEncodings) {
        // Instantiate the sampler
        HTTPSamplerBase sampler = HTTPSamplerFactory.newInstance(request.getHttpSamplerName());

        sampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

        // Defaults
        sampler.setFollowRedirects(false);
        sampler.setUseKeepAlive(true);

        if (log.isDebugEnabled()) {
            log.debug("getSampler: sampler path = " + sampler.getPath());
        }
        return sampler;
    }
View Full Code Here

     *
     */
    @Override
    public void process() {
        Sampler sam = getThreadContext().getCurrentSampler();
        HTTPSamplerBase sampler = null;
        if (!(sam instanceof HTTPSamplerBase)) {
            return;
        } else {
            sampler = (HTTPSamplerBase) sam;
        }
        boolean modified = false;
        PropertyIterator iter = sampler.getArguments().iterator();
        while (iter.hasNext()) {
            Argument arg = (Argument) iter.next().getObjectValue();
            modified = modifyArgument(arg);
            if (modified) {
                break;
View Full Code Here

     * @param testElement
     */
    public void modifyTestElement(TestElement testElement) {
        GuiUtils.stopTableEditing(table);
        if (testElement instanceof HTTPSamplerBase) {
            HTTPSamplerBase base = (HTTPSamplerBase) testElement;
            int rows = tableModel.getRowCount();
            @SuppressWarnings("unchecked") // we only put HTTPFileArgs in it
            Iterator<HTTPFileArg> modelData = (Iterator<HTTPFileArg>) tableModel.iterator();
            HTTPFileArg[] files = new HTTPFileArg[rows];
            int row=0;
            while (modelData.hasNext()) {
                HTTPFileArg file = modelData.next();
                files[row++]=file;
            }
            base.setHTTPFiles(files);
        }
    }
View Full Code Here

     *
     * @param testElement the HTTPSamplerBase to be used to configure the GUI
     */
    public void configure(TestElement testElement) {
        if (testElement instanceof HTTPSamplerBase) {
            HTTPSamplerBase base = (HTTPSamplerBase) testElement;
            tableModel.clearData();
            for(HTTPFileArg file : base.getHTTPFiles()){
                tableModel.addRow(file);
            }
            checkDeleteAndBrowseStatus();
        }
    }
View Full Code Here

    public static HTTPSamplerBase createUrlFromAnchor(String parsedUrlString, URL context) throws MalformedURLException {
        if (log.isDebugEnabled()) {
            log.debug("Creating URL from Anchor: " + parsedUrlString + ", base: " + context);
        }
        URL url = ConversionUtils.makeRelativeURL(context, parsedUrlString);
        HTTPSamplerBase sampler =HTTPSamplerFactory.newInstance();
        sampler.setDomain(url.getHost());
        sampler.setProtocol(url.getProtocol());
        sampler.setPort(url.getPort());
        sampler.setPath(url.getPath());
        sampler.parseArguments(url.getQuery());

        return sampler;
    }
View Full Code Here

TOP

Related Classes of org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.