BreadcrumbHomeResourcesBlog Top 8 JMeter Java Classes You Should Be Using With Groovy July 23, 2020 Top 8 JMeter Java Classes You Should Be Using with GroovyOpen Source AutomationBy Konstantin TonkovJSR223 (Java Specification Request 223) is a framework for embedding your scripts into Apache JMeter™’s Java source code. Since JSR223 components can be used to enhance your control over your Test Plan, they are one of the most useful tools for load testing with JMeter. While you can use a range of languages in JSR223 components, scripts written in the Groovy language can be significantly more efficient than BeanShell components or other languages. In this post, I will look at the top 8 JMeter Java classes that can be used with Groovy in JSR223 components, for customizing your scripts to suit any task.Table of ContentsWhat Are Java Classes?1. Logger Class2. JMeterContext Class3. SamplerResult Class4. HTTPSamplerProxy Class5-8. HeaderManager, CacheManager, CookieManager and AuthManager ClassesBottom LineTable of Contents1 - What Are Java Classes?2 - 1. Logger Class3 - 2. JMeterContext Class4 - 3. SamplerResult Class5 - 4. HTTPSamplerProxy Class6 - 5-8. HeaderManager, CacheManager, CookieManager and AuthManager Classes7 - Bottom LineBack to topWhat Are Java Classes?Classes are templates for creating objects, by describing the fields and methods of corresponding objects. JMeter is written in Java, so all the JMeter entities — like sampler, cache, listener, result — are described in the associated Java Classes.Therefore, you can use these classes In your JSR223 component to modify an entity's behavior as you wish.To invoke a class method you need the class object. Fortunately, most of the useful objects, like the current sampler or current result, already have a variable for them defined in the JSR223 components. For example, to access a Logger class object, you can simply write "log" and then invoke class methods. Same for the "sampler" variable, that points to the current sampler object of the HTTPSamplerProxy class.You can find descriptions and examples of some useful classes in posts like “How to Use BeanShell in JMeter” and “BeanShell for Beginners”. In my post I will try to look deeper into some classes mentioned in the posts above, as well as some other classes that I find worth mentioning. These classes were chosen because they allow you to easily write performance scripts for tasks of high complexity, invoking the full customization potential of JMeter. Back to top1. Logger ClassLogger is actually not a JMeter class, rather it is a Java class from a third-party library. You can access a Logger object for your component by using the log variable. The Logger class is very important for scripting because it lets you debug your scripts more easily. By letting you output any information to the JMeter log, you can check precisely if there are any issues with your scripts and where they occur.The log has five levels, which output custom messages to the JMeter log, printed by JMeter. They are:ERRORWARNINFODEBUGTRACEYou can set the desired level in Options-> Log Level to Debug.When a log level is set, all messages of that and the upper level are displayed. For example, if you set your log level to DEBUG, then all messages of levels DEBUG, INFO, WARN and ERROR will be displayed in the JMeter log. By default, the log level is set to INFO.Here are some examples of how you can use different methods of the Logger class to output custom messages on different log levels.debug methodUse the debug(String message) method to write debug messages to the JMeter’s log.log.debug(‘Current thread number:‘+ String.valueOf(ctx.getThreadNum()));The code above will output the current thread number in the JMeter log.info methodUse the info method to output messages that highlight the progress of the application at a basic level. For example, to output a name of a sampler that just started, in the JMeter log:log.info(‘Sampler ‘+ sampler.getName()+‘ started’);warn methodUse the warn method to output custom warnings about potentially harmful situations. Example of custom warning:log.warn(‘Could not convert string, using default encoding’);error methodThe Logger class supports stack-trace output - detailed information about an error. For example, when you catch the error e you may write the error in the JMeter log:log.error("Malformed URL detected:”, e);trace methodThe trace method is used for fine-grade debugging when you need to output very detailed information about your script:log.error("Response data:”+ prev.getResponseDataAsString());Back to top2. JMeterContext ClassThe JMeterContext class holds an object that describes the context of a thread. A context of a thread contains basic information about the thread, like the thread number, JMeter variables, and JMeter properties. You can access this object through the ctx variable. The JMeterContext class has a lot of useful methods. Some examples:GetThreadNumber Methodif(ctx.getThreadNum()==5&& prev.isSuccessful()==true){ prev.setStopTest(true);}StartNextThreadLoop Methodctx.setStartNextThreadLoop(boolean restartNextLoop) interrupts the current thread and starts a new JMeter testing thread when the ‘true’ value is passed as a parameter. This method can be used to handle error results in your script. For example, when the current thread encounters an error response to a crucial request you may proceed to a new thread:if(prev.getResponseCode()!=“200”){ ctx.setStartNextThreadLoop(true);} Back to top3. SamplerResult ClassThe SamplerResult class represents a sampler execution result as it is passed to listeners. This result contains data from the sampler’s execution, like response time and response data. In your JSR223 script you can access a SamplerResult object for a current sampler by the pointer prev.Back to top4. HTTPSamplerProxy ClassThe HTTPSamplerProxy class is a proxy class for controlling HTTP Samplers. This is an extremely useful Java class for accessing and setting data for your HTTP Samplers. A pointer to a current sampler is already set in a JSR223 component - its sampler. Using this pointer, you can establish full control over the current sampler through your script.You can change the HTTP method, arguments, headers, cookies and many, many more by invoking methods of an HTTPSamplerProxy object. All the available methods are listed on the JMeter API documentation site under HTTPSamplerBase class documentation. The HTTPSamplerProxy class offers you a great amount of control over your JMeter script.Sure, you can use your JSR223 script to set JMeter variables and then pass them to the sampler’s fields, such as a host, path, or even Header Manager’s headers in the JMeter GUI. But some parameters like: “Follow Redirects”, “Use KeepAlive”, or “Retrieve All Embedded Resources” can’t be controlled via variables. Nor can you set a variable quantity of arguments to pass. These need to be set directly in the JSR223 script, with the HTTPSamplerProxy.For example, adding a new argument to your sampler may look like this:sampler.addArgument(“name”,“data”);You may set a separator between the name and data values for your request manually:sampler.addArgument(“name”,“data”,“=”);If you need to pass an argument as a raw body of a POST request, you can either call the addArgument method and pass empty (not null) argument’s name as a parameter, or call a setPostBodyRaw(true) method beforehand. For example, both of the following scripts set the request body:sampler.addArgument(“”, requestBodyData);sampler.setPostBodyRaw(true); sampler.addArgument("name", requestBodyData);You can pass any string value as a request body. Some protocols, like OCSP and NTRIP, are communicated over HTTP, so you can encapsulate, for example, an OCSP request to the body data of your sampler to test other protocols.Setting “Follow Redirects” value:sampler.setFollowRedirects(false);You can control the list of files to send with the request. First, import the HTTPFileArgs class:importorg.apache.jmeter.protocol.http.util.HTTPFileArgs;Then create an HTTPFileArgs object and add it to your sampler:HTTPFileArgs filesToSend =new HTTPFileArgs(); filesToSend.addHTTPFileArg(“path/to/file1”,“filename1”,“mimitype1”); filesToSend.addHTTPFileArg(“path/to/file2”,“filename2”,“mimitype2”); sampler.setHTTPFiles(filesToSend.asArray()); Back to top5-8. HeaderManager, CacheManager, CookieManager and AuthManager ClassesWhen you want to control the number of headers passed through the script or the cookie policy, having the possibility to set configuration elements for your sampler manually can come in handy. These can be configured through the following JMeter Java classes: HeaderManager, CacheManager, CookieManager, and AuthManager.The HeaderManager class describes an object that controls headers for a request. By using methods of this class you can specify which headers will be passed to a request. For example, the following script:importorg.apache.jmeter.protocol.http.control.Header;importorg.apache.jmeter.protocol.http.control.HeaderManager; Header header =new Header("Accept","application/json"); HeaderManager headerManager =new HeaderManager(); headerManager.add(header); sampler.addTestElement(headerManager);adds a new header “Accept: application/json” to a current sampler.The CacheManager class describes an object that controls cache entries. Methods of this class allow you, for example, to check if a URL has an associated entry in the JMeter cache, and if it does - clear the cache:if(sampler.getCacheManager().inCache(sampler.getUrl())){ sampler.getCacheManager().clear();}An object of the CookieManager class controls cookies for requests. By invoking methods of this class you can, for example, manually specify where to clear cookies:if(sampler.getDomain()== vars.get(“ignoreCookieHost”)){ sampler.getCookieManager().setPolicy(“ignoreCookies”);}The AuthManager class represents an object that controls authorization for servers where you send requests. By using methods of the AuthManager class you can control authorization to servers you make requests to:importorg.apache.jmeter.protocol.http.control.Authorization;importorg.apache.jmeter.protocol.http.control.AuthManager; Authorization authorization =new Authorization(sampler.getUrl().toString,“admin”,“adminPa$$w0rd”,“”,“”, Mechanism.BASIC_DIGEST); sampler.getAuthManager().addAuth(authorization);It's literally impossible to describe all the use-cases of these “control” classes and all their methods. Therefore, I strongly recommend personal investigation, experimenting, and consulting with colleagues to learn the best ways to use them.Back to topBottom LineJMeter Java classes are written so that it is easy to access their methods through your scripts. With a little effort, you can fine-tune your Test Plan to solve the most sophisticated tasks. If you have any troubles, you can consult the exhaustive API documentation.When you’ve completed creating your script, run your JMX file.Start Testing NowBack to top
Konstantin Tonkov Konstantin Tonkov has been working in the software testing sphere for 7 years and is now at ISS Art. In addition to coding, Konstnatin likes playing board and video games.