Writing the JMeter extension (1) Writing Sampler Code

Source: Internet
Author: User

Apache JMeter comes with a number of samplers for our use and is able to meet most of the testing needs. However, in the actual use of the process, it is inevitable that the characteristics of the project and the needs of the Apache JMeter to expand. Although the Java sampler can be written directly from Abstractjavasamplerclient, the GUI interface is not very friendly, or we want to write a sampler like HTTP request. For example, we need to write a TLS sampler, which allows the user to make a TLS request when sending a TLS version, as well as client certificates and other information. Please refer to the following code and comments:

package kg.apc.jmeter.samplers;import java.io.bufferedreader;import java.io.fileinputstream; Import java.io.inputstream;import java.io.inputstreamreader;import java.io.serializable;import  java.net.Socket;import java.security.KeyStore;import java.security.cert.CertificateException; import java.security.cert.x509certificate;import javax.net.ssl.keymanagerfactory;import  Javax.net.ssl.sslcontext;import javax.net.ssl.sslparameters;import javax.net.ssl.sslsocket;import  javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import  org.apache.jmeter.samplers.abstractsampler;import org.apache.jmeter.samplers.entry;import  org.apache.jmeter.samplers.interruptible;import org.apache.jmeter.samplers.sampleresult;import  org.apache.jorphan.logging.loggingmanager;import org.apache.log.logger;// fixme: actually  keep-alive does not work!/** * *  @author  undera */public class TLSRawSampler extends AbstractSampler  Implements serializable, cloneable, interruptible{    private static  final logger log = loggingmanager.getloggerforclass ();         //following static final string are property keys in  JMeter    private static final String HOST_NAME =  "TLS _hostname ";    private static final string port = " TLS_port " ;    private static final string tls_verson =  "TLS_ Tlsversion ";    private static final string cipher_list = " Tls_cipherlist ";    private static final string data = " TLS_ Data ";     private static final string client_cert =  "Tls_client_cert";     private static final String CLIENT_CERT_PASSWORD =  "Tls_client_cert_ Password ";      public tlsrawsampler ()  {    }         /**     * Process sample  here     */     @Override     public  Sampleresult sample (entry entry)  {       SampleResult  Sr = new sampleresult ();        sr.samplestart ();        sr.setsuccessful (True);        Sr.setsamplelabel (GetName ());        sr.setresponsecode ("$");               //do the sample here       try{        socket socket = gettlssocket ();        socket.getoutputstream (). Write (GetData (). GetBytes ());        stringbuilder headersb = new stringbuilder ();        stringbuilder contentsb = new stringbuilder ();        bufferedreader reader = new bufferedreader (New inputstreamreader ( Socket.getinputstream ()));       string line = null;        boolean header = true;        while ((Line = reader.readline ())  != null) {        if (Line.length ()  == 0) { &Nbsp;     header = false;       continue;        }       if (header) {        headersb.append (line);        headersb.append ( "\ n");       }       else{        contentsb.append (line);        Contentsb.append ("\ n");        }       }        sr.setresponseheaders (Headersb.tostring ());        sr.setresponsedata (contentsb.tostring (),  "");        Socket.close ();        }catch (exception e) {        sr.setsuccessful (FALSE);        sr.setresponsecode ("$");        sr.setresponsemessage (E.getmessage ());       }               sr.sampleend ();        RETURN SR;   &NBSP,} @Overridepublic  boolean interrupt ()  {// todo auto-generated method stubreturn false;} Following get and set methods are used for get and set  properties in JMeter        public String  GetHostName () {    return getpropertyasstring (tlsrawsampler.host_name);     }        public void sethostname (String  HostName) {    setproperty (Tlsrawsampler.host_namE, hostname);     }        public string  getport () {    return getpropertyasstring (tlsrawsampler.port);     }        public void setport (String port) {     setproperty (Tlsrawsampler.port, port);    }         public string gettlsversion () {    return  Getpropertyasstring (Tlsrawsampler.tls_verson);    }         public void settlsversion (string version) {    setproperty ( Tlsrawsampler.tls_verson, version);    }         public string getclientcert () {    return getpropertyasstring ( Tlsrawsampler.client_cert);   &nBsp; }        public void setclientcert (String  Clientcert) {    setproperty (Tlsrawsampler.client_cert, clientcert);     }        public string getcipherlist () {     return getpropertyasstring (tlsrawsampler.cipher_list);    }         public void setcipherlist (string list) {     setproperty (tlsrawsampler.cipher_list, list);    }         public string getdata () {    return  Getpropertyasstring (Tlsrawsampler.data);    }         public void setdata (string data) {    setproperty (TLSRawSampler.DATA,  data);     } &nBsp;      public string getclientcertpassword () {     return getpropertyasstring (Tlsrawsampler.client_cert_password);    }         public void setclientcertpassword (String password) {     setproperty (Tlsrawsampler.client_cert_password, password);     }        private socket gettlssocket ()  throws  exception{trustmanager[] alltrusted = {new x509trustmanager () {@Overridepublic   Void checkclienttrusted (X509certificate[] chain,string authtype)  throws  Certificateexception {// todo auto-generated method stub} @Overridepublic  void  checkservertrusted (X509certificate[] chain,string authtype)  throws  certificateexception {// todo auto-generated  method stub} @Overridepublic  x509certificate[] getacceptedissuers ()  {// TODO  auto-generated method stubreturn null;}}}; Sslcontext ctx = sslcontext.getinstance (Gettlsversion (),  "Sunjsse");//use 1.2//get  client certstring clientcert = getclientcert (); if (clientcert != null  && clientcert.length ()  > 0) {string clientcertpassword =  Getclientcertpassword (); Keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance ("SunX509"); Keystore keystore = keystore.getinstance ("PKCS12"); inputstream keyinput = new  fileinputstream (Clientcert); Keystore.load (Keyinput, clientcertpassword.tochararray ()); Keyinput.close (); Keymanagerfactory.init (Keystore, clientcertpassword.tochararray ()); Ctx.init ( Keymanagerfactory.getkeymanagers (),  alltrusted, null);} Else{ctx.init (null, alltrusted,&Nbsp;null);} Sslparameters parameters = ctx.getdefaultsslparameters (); String cipherlist = getcipherlist (); if (cipherlist != null &&  Cipherlist.length ()  > 0) {parameters.setciphersuites (Cipherlist.trim (). Split (","));} For (String cipher : parameters.getciphersuites ()) {log.info (cipher);} sslsocket socket =  (Sslsocket) ctx.getsocketfactory (). Createsocket (GetHostName (),  Integer.valueof (Getport ())); Socket.settcpnodelay (true); socket.setsslparameters (parameters); return socket;}}



Writing the JMeter extension (1) Writing Sampler Code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.