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 log.info("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.

log.info("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");
log.info("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

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

Advanced samples

Ignore Http Status Code

Ignore globally

It is possible to ignore an error code (4xx OR 5xx code) by adding the following in a post processor script under any request, or at the top level (groovy):


And if you would like to ignore only a specific error code you can do it this way (groovy):

if(prev.getResponseCode() == "404") {

Activable through property

This script allows you to ignore certain errors based on HTTP Response Code:

final String prop = props.get("filterErrors");
final boolean isFilterErrors = prop == null ? true : Boolean.valueOf(prop);

if (isFilterErrors) {
  int responseCode = 200;

  try {
    responseCode = Integer.parseInt(prev.getResponseCode());
  } catch (final NumberFormatException e) {
    // Ignore

  if (responseCode >= 400 && responseCode < 500) {

This script can be enabled / disabled live during the test via JMeter property filterErrors. Set it to:

  • false to disable ignoring errors,
  • true to ignore certain errors again.

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:

import com.google.common.base.Stopwatch;

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

import com.google.common.base.Stopwatch;
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
log.info("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:

log.info("Thread Group name is: " + prev.getThreadName());

def end_time = prev.getEndTime()
log.info("End Time is: " + (new Date(end_time).toString()));
log.info("Response Time is: " + prev.getTime().toString());
log.info("Connect Time is: " + prev.getConnectTime().toString());
log.info("Latency is: " + prev.getLatency().toString());
log.info("Size in bytes is: " + prev.getBytesAsLong().toString());
log.info("URL is: " + prev.getURL());
log.info("The result is passed: " + prev.isSuccessful().toString());
log.info("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:

log.info("Current Sampler class is: " + ctx.getCurrentSampler());
log.info("JMeter Engine class is: " + ctx.getEngine());

log.info("Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage());
log.info("Previous Response Code is: " + ctx.getPreviousResult().getResponseCode());
log.info("Previous Response URL is: " + ctx.getPreviousResult().getURL());
log.info("Previous Response Time is: " + ctx.getPreviousResult().getTime());

log.info("Previous Domain is: " + ctx.getPreviousSampler().getDomain());
log.info("Previous Protocol is: " + ctx.getPreviousSampler().getProtocol());
log.info("Previous Port is: " + ctx.getPreviousSampler().getPort());
log.info("Previous Method is: " + ctx.getPreviousSampler().getMethod());

log.info("Thread Name is: " + ctx.getThread().getThreadName());
log.info("Thread Start Time is: " + ctx.getThread().getStartTime());
log.info("Thread End Time is: " + ctx.getThread().getEndTime());

log.info("Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop());
log.info("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 java.net.Authenticator;
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.

Write data to a local file

This script allows you to write data to a local file named file.csv. This can be useful if you want to prepare a dataset for a later test or just save information for later use.


The file will be cleaned automatically after the test when we destroy the load generator. But you can use an after test script to upload it to our report engine

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

BufferedWriter bw = null;
FileWriter fw = null;
String filename="file.csv";
String data="\n"+vars.get("token")+","+vars.get("login")+","+vars.get("password");
File file = new File(filename);

// if file does not exists, then create it
if (!file.exists()) {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);

Overwrite a header for all requests

This script allows to overwrite any header, even the user-agent that we normally change at runtime.

Place it as a pre-processor script at the root level or on the specific requests you want to override:

import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;

HeaderManager manager = ctx.getCurrentSampler().getHeaderManager();
manager.add(new Header("User-Agent","octoperf-jamg"));