Examples of SampleResult


Examples of org.apache.jmeter.samplers.SampleResult

     * reader will read, but do nothing with it. Essentially, the stream from
     * the server goes into the ether.
     */
    @Override
    public SampleResult sample() {
        SampleResult result = new SampleResult();
        result.setSuccessful(false); // Assume it will fail
        result.setResponseCode("000"); // ditto $NON-NLS-1$
        result.setSampleLabel(getName());
        try {
            result.setURL(this.getUrl());
            org.w3c.dom.Element rdoc = createDocument();
            if (rdoc == null) {
                throw new SOAPException("Could not create document", null);
            }
            // set the response defaults
            result.setDataEncoding(ENCODING);
            result.setContentType("text/xml"); // $NON-NLS-1$
            result.setDataType(SampleResult.TEXT);
            result.setSamplerData(fileContents);// WARNING - could be large

            Envelope msgEnv = Envelope.unmarshall(rdoc);
            // create a new message
            Message msg = new Message();
            result.sampleStart();
            SOAPHTTPConnection spconn = null;
            // if a blank HeaderManager exists, try to
            // get the SOAPHTTPConnection. After the first
            // request, there should be a connection object
            // stored with the cookie header info.
            if (this.getHeaderManager() != null && this.getHeaderManager().getSOAPHeader() != null) {
                spconn = (SOAPHTTPConnection) this.getHeaderManager().getSOAPHeader();
            } else {
                spconn = new SOAPHTTPConnection();
            }

            spconn.setTimeout(getTimeoutAsInt());

            // set the auth. thanks to KiYun Roe for contributing the patch
            // I cleaned up the patch slightly. 5-26-05
            if (getAuthManager() != null) {
                if (getAuthManager().getAuthForURL(getUrl()) != null) {
                    AuthManager authmanager = getAuthManager();
                    Authorization auth = authmanager.getAuthForURL(getUrl());
                    spconn.setUserName(auth.getUser());
                    spconn.setPassword(auth.getPass());
                } else {
                    log.warn("the URL for the auth was null." + " Username and password not set");
                }
            }
            // check the proxy
            String phost = "";
            int pport = 0;
            // if use proxy is set, we try to pick up the
            // proxy host and port from either the text
            // fields or from JMeterUtil if they were passed
            // from command line
            if (this.getUseProxy()) {
                if (this.getProxyHost().length() > 0 && this.getProxyPort() > 0) {
                    phost = this.getProxyHost();
                    pport = this.getProxyPort();
                } else {
                    if (System.getProperty("http.proxyHost") != null || System.getProperty("http.proxyPort") != null) {
                        phost = System.getProperty("http.proxyHost");
                        pport = Integer.parseInt(System.getProperty("http.proxyPort"));
                    }
                }
                // if for some reason the host is blank and the port is
                // zero, the sampler will fail silently
                if (phost.length() > 0 && pport > 0) {
                    spconn.setProxyHost(phost);
                    spconn.setProxyPort(pport);
                    if (PROXY_USER.length()>0 && PROXY_PASS.length()>0){
                        spconn.setProxyUserName(PROXY_USER);
                        spconn.setProxyPassword(PROXY_PASS);
                    }
                }
            }
            // by default we maintain the session.
            spconn.setMaintainSession(true);
            msg.setSOAPTransport(spconn);
            msg.send(this.getUrl(), this.getSoapAction(), msgEnv);
            @SuppressWarnings("unchecked") // API uses raw types
            final Map<String, String> headers = spconn.getHeaders();
            result.setResponseHeaders(convertSoapHeaders(headers));

            if (this.getHeaderManager() != null) {
                this.getHeaderManager().setSOAPHeader(spconn);
            }

            BufferedReader br = null;
            if (spconn.receive() != null) {
                br = spconn.receive();
                SOAPContext sc = spconn.getResponseSOAPContext();
                // Set details from the actual response
                // Needs to be done before response can be stored
                final String contentType = sc.getContentType();
                result.setContentType(contentType);
                result.setEncodingAndType(contentType);
                int length=0;
                if (getReadResponse()) {
                    StringWriter sw = new StringWriter();
                    length=IOUtils.copy(br, sw);
                    result.sampleEnd();
                    result.setResponseData(sw.toString().getBytes(result.getDataEncodingWithDefault()));
                } else {
                    // by not reading the response
                    // for real, it improves the
                    // performance on slow clients
                    length=br.read();
                    result.sampleEnd();
                    result.setResponseData(JMeterUtils.getResString("read_response_message"), null); //$NON-NLS-1$
                }
                // It is not possible to access the actual HTTP response code, so we assume no data means failure
                if (length > 0){
                    result.setSuccessful(true);
                    result.setResponseCodeOK();
                    result.setResponseMessageOK();
                } else {
                    result.setSuccessful(false);
                    result.setResponseCode("999");
                    result.setResponseMessage("Empty response");
                }
            } else {
                result.sampleEnd();
                result.setSuccessful(false);
                final String contentType = spconn.getResponseSOAPContext().getContentType();
                result.setContentType(contentType);
                result.setEncodingAndType(contentType);
                result.setResponseData(spconn.getResponseSOAPContext().toString().getBytes(result.getDataEncodingWithDefault()));
            }
            if (br != null) {
                br.close();
            }
            // reponse code doesn't really apply, since
            // the soap driver doesn't provide a
            // response code
        } catch (IllegalArgumentException exception){
            String message = exception.getMessage();
            log.warn(message);
            result.setResponseMessage(message);
        } catch (SAXException exception) {
            log.warn(exception.toString());
            result.setResponseMessage(exception.getMessage());
        } catch (SOAPException exception) {
            log.warn(exception.toString());
            result.setResponseMessage(exception.getMessage());
        } catch (MalformedURLException exception) {
            String message = exception.getMessage();
            log.warn(message);
            result.setResponseMessage(message);
        } catch (IOException exception) {
            String message = exception.getMessage();
            log.warn(message);
            result.setResponseMessage(message);
        } catch (NoClassDefFoundError error){
            log.error("Missing class: ",error);
            result.setResponseMessage(error.toString());
        } catch (Exception exception) {
            if ("javax.mail.MessagingException".equals(exception.getClass().getName())){
                log.warn(exception.toString());
                result.setResponseMessage(exception.getMessage());
            } else {
                log.error("Problem processing the SOAP request", exception);
                result.setResponseMessage(exception.toString());
            }
        } finally {
            // Make sure the sample start time and sample end time are recorded
            // in order not to confuse the statistics calculation methods: if
            //  an error occurs and an exception is thrown it is possible that
            // the result.sampleStart() or result.sampleEnd() won't be called
            if (result.getStartTime() == 0)
            {
                result.sampleStart();
            }
            if (result.getEndTime() == 0)
            {
                result.sampleEnd();
            }
        }
        return result;
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

        String httpSamplerName = target.getSamplerTypeName();
        // Instantiate the sampler
        HTTPSamplerBase sampler = HTTPSamplerFactory.newInstance(httpSamplerName);

        HttpRequestHdr request = new HttpRequestHdr(sampler);
        SampleResult result = null;
        HeaderManager headers = null;

        try {
            // Now, parse only first line
            request.parse(new BufferedInputStream(clientSocket.getInputStream()));
            outStreamClient = clientSocket.getOutputStream();

            if ((request.getMethod().startsWith(HTTPConstants.CONNECT)) && (outStreamClient != null)) {
                log.debug("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()); // $NON-NLS-1$ // TODO charset?
                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) {
                    log.debug("Start to negotiate SSL connection, host: " + param[0]);
                    clientSocket = startSSL(clientSocket, param[0]);
                } else {
                    log.warn("In SSL request, unable to find host and port in CONNECT request");
                }
                // Re-parse (now it's the http request over SSL)
                request.parse(new BufferedInputStream(clientSocket.getInputStream()));
            }

            // Populate the sampler. It is the same sampler as we sent into
            // the constructor of the HttpRequestHdr instance above
            request.getSampler(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);

            /*
             * If we are trying to spoof https, change the protocol
             */
            boolean forcedHTTPS = false; // so we know when to revert
            if (httpsSpoof) {
                if (httpsSpoofMatch.length() > 0){
                    String url = request.getUrl();
                    if (url.matches(httpsSpoofMatch)){
                        sampler.setProtocol(HTTPConstants.PROTOCOL_HTTPS);
                        forcedHTTPS = true;
                    }
                } else {
                    sampler.setProtocol(HTTPConstants.PROTOCOL_HTTPS);
                    forcedHTTPS = true;
                }
            }
            sampler.threadStarted(); // Needed for HTTPSampler2
            result = sampler.sample();

            /*
             * If we're dealing with text data, and if we're spoofing https,
             * replace all occurences of "https://" with "http://" for the client.
             * TODO - also check the match string to restrict the changes further?
             */
            if (httpsSpoof && SampleResult.TEXT.equals(result.getDataType()))
            {
                final String enc = result.getDataEncodingWithDefault();
                String noHttpsResult = new String(result.getResponseData(),enc);
                final String HTTPS_HOST = // match https://host[:port]/ and drop default port if present
                    "https://([^:/]+)(:"+HTTPConstants.DEFAULT_HTTPS_PORT_STRING+")?"; // $NON-NLS-1$ $NON-NLS-2$
                noHttpsResult = noHttpsResult.replaceAll(HTTPS_HOST, "http://$1"); // $NON-NLS-1$
                result.setResponseData(noHttpsResult.getBytes(enc));
            }

            // 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()), forcedHTTPS);
        } catch (UnknownHostException uhe) {
            log.warn("Server Not Found.", uhe);
            writeErrorToClient(HttpReplyHdr.formServerNotFound());
            result = generateErrorResult(result, uhe); // Generate result (if nec.) and populate it
        } catch (IllegalArgumentException e) {
            log.error("Not implemented (probably used https)", e);
            writeErrorToClient(HttpReplyHdr.formNotImplemented("Probably used https instead of http. " +
                    "To record https requests, see " +
                    "<a href=\"http://jakarta.apache.org/jmeter/usermanual/component_reference.html#HTTP_Proxy_Server\">HTTP Proxy Server documentation</a>"));
            result = generateErrorResult(result, e); // Generate result (if nec.) and populate it
        } catch (IOException ioe) {
            log.error("Problem with SSL certificate? Ensure browser is set to accept the JMeter proxy cert: "+ioe.getLocalizedMessage());
            // won't work: writeErrorToClient(HttpReplyHdr.formInternalError());
            if (result == null) {
                result = new SampleResult();
                result.setSampleLabel("Sample failed");
            }
            result.setResponseMessage(ioe.getMessage()+ "\n**ensure browser is set to accept the JMeter proxy certificate**");
        } catch (Exception e) {
            log.error("Exception when processing sample", e);
            writeErrorToClient(HttpReplyHdr.formInternalError());
            result = generateErrorResult(result, e); // Generate result (if nec.) and populate it
        } finally {
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

        return in;
    }

    private SampleResult generateErrorResult(SampleResult result, Exception e) {
        if (result == null) {
            result = new SampleResult();
            result.setSampleLabel("Sample failed");
        }
        result.setResponseMessage(e.getMessage());
        return result;
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

    /**
     * {@inheritDoc}
     */
    public SampleResult sample(Entry entry) {
        SampleResult res = new SampleResult();
        res.setSampleLabel(getName());
        res.setSamplerData(getContent());
        res.setSuccessful(false); // Assume failure
        res.setDataType(SampleResult.TEXT);
        res.sampleStart();

        try {
            TextMessage msg = createMessage();
            if (isOneway()) {
                producer.send(msg);
                res.setRequestHeaders(Utils.messageProperties(msg));
                res.setResponseOK();
                res.setResponseData("Oneway request has no response data", null);
            } else {
                if (!useTemporyQueue()) {
                    msg.setJMSReplyTo(receiveQueue);
                }

                Message replyMsg = executor.sendAndReceive(msg);
                res.setRequestHeaders(Utils.messageProperties(msg));
                if (replyMsg == null) {
                    res.setResponseMessage("No reply message received");
                } else {
                    if (replyMsg instanceof TextMessage) {
                        res.setResponseData(((TextMessage) replyMsg).getText(), null);
                    } else {
                        res.setResponseData(replyMsg.toString(), null);
                    }
                    res.setResponseHeaders(Utils.messageProperties(replyMsg));
                    res.setResponseOK();
                }
            }
        } catch (Exception e) {
            LOGGER.warn(e.getLocalizedMessage(), e);
            if (thrown != null){
                res.setResponseMessage(thrown.toString());
            } else {               
                res.setResponseMessage(e.getLocalizedMessage());
            }
        }
        res.sampleEnd();
        return res;
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

public class Example2 extends AbstractSampler implements TestBean {

    private static final long serialVersionUID = 240L;

    public SampleResult sample(Entry e) {
        SampleResult res = new SampleResult();
        res.setSampleLabel(getName());
        res.setSamplerData(myStringProperty);
        res.sampleStart();
        // Do something ...
        res.setResponseData(myStringProperty.toLowerCase(), null);
        res.setDataType(SampleResult.TEXT);
        res.sampleEnd();
        res.setSuccessful(true);
        return res;
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

            ldap.deleteTest(getPropertyAsString(ADD));
        }
    }

    public SampleResult sample(Entry e) {
        SampleResult res = new SampleResult();
        boolean isSuccessful = false;
        res.setSampleLabel(getName());
        res.setSamplerData(getPropertyAsString(TEST));// TODO improve this
        LdapClient ldap = new LdapClient();

        try {
            ldap.connect(getServername(), getPort(), getRootdn(), getUsername(), getPassword());

            if (getPropertyAsString(TEST).equals(ADD)) {
                addTest(ldap, res);
            } else if (getPropertyAsString(TEST).equals(DELETE)) {
                deleteTest(ldap, res);
            } else if (getPropertyAsString(TEST).equals(MODIFY)) {
                modifyTest(ldap, res);
            } else if (getPropertyAsString(TEST).equals(SEARCHBASE)) {
                searchTest(ldap, res);
            }

            // TODO - needs more work ...
            if (getPropertyAsString(TEST).equals(SEARCHBASE) && !searchFoundEntries) {
                res.setResponseCode("201");// TODO is this a sensible number? //$NON-NLS-1$
                res.setResponseMessage("OK - no results");
                res.setResponseData("successful - no results", null);
            } else {
                res.setResponseCodeOK();
                res.setResponseMessage("OK"); //$NON-NLS-1$
                res.setResponseData("successful", null);
            }
            res.setDataType(SampleResult.TEXT);
            isSuccessful = true;
        } catch (Exception ex) {
            log.error("Ldap client - ", ex);
            // Could time this
            // res.sampleEnd();
            // if sampleEnd() is not called, elapsed time will remain zero
            res.setResponseCode("500");// TODO distinguish errors better //$NON-NLS-1$
            res.setResponseMessage(ex.toString());
            isSuccessful = false;
        } finally {
            ldap.disconnect();
        }

        // Set if we were successful or not
        res.setSuccessful(isSuccessful);
        return res;
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

    private Sampler next2() {
        if (isFirst()) // must be the start of the subtree
        {
            calls = 0;
            noFailingSamples = 0;
            res = new SampleResult();
            res.setSampleLabel(getName());
            // Assume success
            res.setSuccessful(true);
            res.sampleStart();
            prevEndTime = res.getStartTime();//???
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

    public void sampleOccurred(SampleEvent se) {
        if (!isParent()) {
            // Check if we are still sampling our children
            if(res != null && !se.isTransactionSampleEvent()) {
                SampleResult sampleResult = se.getResult();
                res.setThreadName(sampleResult.getThreadName());
                res.setBytes(res.getBytes() + sampleResult.getBytes());
                if (!isIncludeTimers()) {// Accumulate waiting time for later
                    pauseTime += sampleResult.getEndTime() - sampleResult.getTime() - prevEndTime;
                    prevEndTime = sampleResult.getEndTime();
                }
                if(!sampleResult.isSuccessful()) {
                    res.setSuccessful(false);
                    noFailingSamples++;
                }
                res.setAllThreads(sampleResult.getAllThreads());
                res.setGroupThreads(sampleResult.getGroupThreads());
                res.setLatency(res.getLatency() + sampleResult.getLatency());
            }
        }
    }
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

     * totals, and the other for deltas.
     *
     * @see org.apache.jmeter.samplers.SampleListener#sampleOccurred(org.apache.jmeter.samplers.SampleEvent)
     */
    public void sampleOccurred(SampleEvent e) {
        SampleResult s = e.getResult();

        long now = System.currentTimeMillis() / 1000;// in seconds

        RunningSample myDelta = null;
        RunningSample myTotal = null;
View Full Code Here

Examples of org.apache.jmeter.samplers.SampleResult

    }

    public String execute() {
        if (isDynamic) {
            JMeterContext context = JMeterContextService.getContext();
            SampleResult previousResult = context.getPreviousResult();
            Sampler currentSampler = context.getCurrentSampler();
            return execute(previousResult, currentSampler);
        }
        return permanentResults; // $NON-NLS-1$
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.