Run massively scalable performance tests on web, mobile, and APIs

Request a Demo
Oct. 18th, 2018

Top 8 JMeter Java Classes You Should Be Using with Groovy

JSR223 (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 performance testing with JMeter. There is a whole family of JMeter JSR223 components: a sampler, an assertion, pre- and post- processors, a listener and a timer.

 

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.

 

What are Java Classes?

 

In object-oriented programming, classes are templates for creating objects, by describing the fields and methods of corresponding objects. JMeter is written in Java Language, so all the JMeter entities - like sampler, cache, listener, result - are described in the associated Java Class. Therefore,  you can use these classes In your JSR223 component to modify an entity behaviour 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” 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. 

 

1. Logger Class

 

Logger is actually not a JMeter class, rather it is 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:

  1. ERROR
  2. WARN
  3. INFO
  4. DEBUG
  5. TRACE

 

You can set the desirable level in Options-> Log Level to Debug.

 

debgging JMeter with Java classes

 

When a log level is set, all messages of that and 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 method

 

Use 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 method

 

Use 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 method

 

Use 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 method

 

The 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 method

 

The 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());

 

2. JMeterContext Class

 

The 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 Method

 

if (ctx.getThreadNum() == 5 && prev.isSuccessful() == true) {
	prev.setStopTest(true);
}

 

StartNextThreadLoop Method


ctx.setStartNextThreadLoop(boolean restartNextLoop) interrupts the current thread and starts a new JMeter 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);
}

 

3. SamplerResult Class

 

The 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.

 

You can find usage examples here and here

 

4. HTTPSamplerProxy Class

 

The HTTPSamplerProxy class is a proxy class for controlling HTTP Samplers. This is an extremely useful 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, for example: “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:

 

import org.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());

 

5-8. HeaderManager, CacheManager, CookieManager and AuthManager Classes

 

When you want to control the quantity 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 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:

 

import org.apache.jmeter.protocol.http.control.Header;
import org.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 any 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 you send requests to. By using methods of the AuthManager class you can control authorization to servers you make requests to:

 

import org.apache.jmeter.protocol.http.control.Authorization;
import org.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.

 

JMeter Java classes are written so that it is easy to access their methods through your scripts. With a little effort you can perform a fine tuning of your Test Plan to solve 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 in BlazeMeter. You will be able to share tests results, get advanced analytics and scale to multiple geo-locations. Start testing now by putting your URL in the box below.

     
arrow Please enter a valid URL

Interested in writing for our Blog? Send us a pitch!