Skip to content


There are two types of JSR223:

  • Actions: can be dropped anywhere,
  • Pre/Post processors: can be dropped under HTTP Request Actions.

JSR223 Pre/Post processors

These are like JSR223 actions but executed right before or after the enclosing HTTP action.

JSR223 Action

The JSR223 allows you to execute a script, written in various languages: JSR223 Language

More information is available in the JMeter documentation.

Parameter name Description Required
Name Descriptive name for this script. No
Language All languages supported by JMeter out of the box are also currently supported by OctoPerf. Yes
Script The script executed each time the Virtual User comes to ths action. Yes

JSR223 Action

The following table described some of most importable global script variables already defined:

name Description Example
ctx Execution context ctx.isSamplingStarted();
vars Variables in the scope vars.get("counter");
props System properties props.get("START.HMS");
log Log messages in the log file"Hello World!");
SampleResult Points to the current SampleResult SampleResult.getLatency();
OUT Console output OUT.println("Hello World!");

If you need more information about the existing global variables, see the Beanshell Sampler documentation.


As OctoPerf is a GUI driven tool, you might encounter some limitation. The JSR223 component opens a new world of possibilities by giving you control of everything through a script. Of course the prupose of OctoPerf is still to use the graphical interface for most of your scenario. But JSR223 will let you do anything that your application may require: Concatenate values Find the next working day * Manipulate variables

Basic samples

This section lists various samples for JSR223 action scripts that you may need for complex Virtual Users. Note that all of them are written in Java, so make sure you select this language in your script action.

Log a Message

This script is an example of how to log a message and the logging levels available. Note that the resulting message will be visible in the JMeter log file after the test only."This is the log for INFOR level");
log.warn("This is the log for WARNING level");
log.error("This is the log for ERROR level");

Manipulate a Variable

This script shows how to get and put variables from the variable screen in and out of your script.


String my_var = vars.get("MY_VARIABLE");"The value of my_var is " + my_var);


Although vars.put will create the variable if it does not exists, it will not be available in the autocompletion unless you also create it in the variable screen.

Increment an Integer

A simple script to add a value to an integer. This one is useful since by default vars.get and vars.put work with strings.

int my_number = vars.get("MY_NUMBER").toInteger();
int new_number = 3;

int add = my_number + new_number;

vars.put("MY_NUMBER", add.toString());

Replace String in a Variable

This quick script will replace a set of chars by another:

// Replaces "\/" by "/"


This script puts a random value between 5 and 10 in the variable ${random}

var random = new java.util.Random().nextInt(6) + 5;
vars.put("random", random.toString());

Log Sampler Info "The Sample Label is : " + SampleResult.getSampleLabel() ); "The Start Time in miliseconds is : " + SampleResult.getStartTime() ); "The Response Code is : " + SampleResult.getResponseCode() ); "The Response Message is : " + SampleResult.getResponseMessage() );

Advanced samples

Timestamp or current date

This script puts a timestamp in the variable "${timestamp}". Optional sections allow to add time to the current date or format it differently.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

Date now = new Date(); // get current time
Calendar c = Calendar.getInstance(); // get Java Calendar instance
c.setTime(now); // set Calendar time to now

//Add 5 minutes to current time
//c.add(Calendar.MINUTE, 5); 

//Get a timestamp
Date now = c.getTimeInMillis(); // get Date value for amended time
String mydate = now.toString();

//OR Create a formatter for date
//Date now = c.getTime();
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
//String mydate = sdf.format(now); // format date as string

vars.put("timestamp",mydate); // save date to JMeter variable named "timestamp"

Next Working Day

This one is a bit more complex. It will create a new date and then proceed to compute the next working day and store it into the nextworkingday variable. This can be usefull when you have to enter an attendance or any work related date in a calendar.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public boolean isWorkingDay(Date date, Calendar calendar) {
  // set calendar time with given date
  int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
  // check if it is Saturday(day=7) or Sunday(day=1)
  if ((dayOfWeek ==  7) || (dayOfWeek == 1)) {
    return false;
  return true;  

Calendar c = Calendar.getInstance();
Date now = new Date();

c.add(Calendar.DAY_OF_WEEK, 1);
while(!isWorkingDay(c.getTime(), c)) {
  c.add(Calendar.DAY_OF_WEEK, 1);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
vars.put("nextworkingday", df.format(c.getTime()));


This script adds a cookie named "foo" with the value " bar" for the server "my server". Because of references to the current sampler, this script only works as a Pre-processor.

import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;

Cookie cookie = new Cookie("foo","bar","my server","/",false,-1);
CookieManager manager = ctx.getCurrentSampler().getProperty("HTTPSampler.cookie_manager").getObjectValue();

Do not store large response contents

Very large response content can have a negative impact on JMeter memory. To minimize it, you can activate the storage of a particular response as a MD5 Hash. Just put a PreProcessor under your request with this script:


Iteration pacing

Iteration pacing is a good way to make sure every iteration will have the same duration whatever the response time. To implement it, we will use two scripts and a constant variable named "pacing" that contains the duration of the pacing in milliseconds.


The following scripts need to be run as Java scripts, not Groovy.

Put a first script at the very beginning of your Virtual user profile:


Then the last action in your user profile should be a script with:

import java.util.Map;

Map env = System.getenv();

Stopwatch watch = vars.getObject("watch");
long elapsed = watch.elapsed(java.util.concurrent.TimeUnit.MILLISECONDS);
long pacing = Long.parseLong(vars.get("pacing"));

//We do not replay pacing for VU validation
if (elapsed <= pacing && "STANDARD".equals(env.get("TEST_MODE"))) {
    long sleep = pacing-elapsed;


We use TEST_MODE to ensure the pacing is only used during a real test and not a during a validation.

Modifying Current SampleResult

Modifying the current sample result is actually quite simple. It can be useful when you want to programmatically control the response content.

SampleResult.setSampleLabel("This test is modified by JSR223 script");

def start = System.currentTimeMillis(); //return current time in milliseconds
SampleResult.setStartTime(start); // set StartTime"Start Time should be: " + (new Date(start)).toString()); //print the start time in Date format

SampleResult.setResponseMessage("This is message returned from JSR223 script");
SampleResult.setResponseData("You will see this sentence in Response Data tab", "UTF-8");

Read Previous SampleResult

Using the prev variable you can also check the content of the previous sample result:"Thread Group name is: " + prev.getThreadName());

def end_time = prev.getEndTime()"End Time is: " + (new Date(end_time).toString()));"Response Time is: " + prev.getTime().toString());"Connect Time is: " + prev.getConnectTime().toString());"Latency is: " + prev.getLatency().toString());"Size in bytes is: " + prev.getBytesAsLong().toString());"URL is: " + prev.getURL());"The result is passed: " + prev.isSuccessful().toString());"Headers are: " + prev.getResponseHeaders());

Modify Previous SampleResult

And of course you can also edit the previous sample result. Here is an example overriding response times that are over a certain value:

def response_time = prev.getTime().toInteger();

def expected_response_time = 500;

if (response_time > expected_response_time) {
 prev.setSampleLabel("The response time is too long");
 prev.setResponseMessage("The expected response time is : " + expected_response_time + "ms but it took: " + response_time + "ms");

Modify HTTP Request

JSR scripts also allow you to edit requests. This is only useful in specific situations since OctoPerf interface already allows editing requests:


JMeter Context

This script provides examples of what you can achieve through the ctx variable:"Current Sampler class is: " + ctx.getCurrentSampler());"JMeter Engine class is: " + ctx.getEngine());"Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage());"Previous Response Code is: " + ctx.getPreviousResult().getResponseCode());"Previous Response URL is: " + ctx.getPreviousResult().getURL());"Previous Response Time is: " + ctx.getPreviousResult().getTime());"Previous Domain is: " + ctx.getPreviousSampler().getDomain());"Previous Protocol is: " + ctx.getPreviousSampler().getProtocol());"Previous Port is: " + ctx.getPreviousSampler().getPort());"Previous Method is: " + ctx.getPreviousSampler().getMethod());"Thread Name is: " + ctx.getThread().getThreadName());"Thread Start Time is: " + ctx.getThread().getStartTime());"Thread End Time is: " + ctx.getThread().getEndTime());"Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop());"Stop Test on Error: " + ctx.getThreadGroup().getOnErrorStopTest());

Read Write JMeter Properties

JMeter properties can be edited this way:

props.put("PROPERTY_NAME", "VALUE");

//update the existing property

JVM configuration change

As we take care of installing and maintaining the JVM for you, not all the usual settings are available. But some settings can be edited after the JVM is started using this script:

System.setProperty("jsse.enableSNIExtension", "false");

Set a proxy for all requests

While the proxy option is not available in OctoPerf, it is still possible to add a proxy to every HTTP request using the following code:

import org.apache.jmeter.ProxyAuthenticator;

System.setProperty("http.proxyHost", "XXX.XXX.XXX.XXX");
System.setProperty("http.proxyPort", "XXXX");
System.setProperty("http.nonProxyHosts", "XXX.XXX.XXX.XXX,XXX.XXX.XXX.XXX");

Note that we do not recommend load testing through a proxy since you will be limited by the proxy capacity. If you proceed with load testing through a proxy, make sure to monitor the proxy server as well.