JSR223

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 BSF Sampler documentation.

Purpose

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.

vars.get("VARIABLE_NAME");
vars.put("VARIABLE_NAME","VALUE");

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

Note

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 "/"
vars.put("variable",vars.get("variable").replace("\\/","/"));

Random

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

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
  calendar.setTime(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.setTime(now);

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

Cookies

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();
manager.add(cookie);

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.

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

import com.google.common.base.Stopwatch;
vars.putObject("watch",Stopwatch.createStarted());

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;
    Thread.sleep(sleep);
}

Note

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 usefull 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.setResponseCode("201");
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.setSuccessful(false);
 prev.setResponseCode("500");
 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 usefull in specific situations since OctoPerf interface already allows editing requests:

sampler.setDomain("jmetervn.wordpress.com");
sampler.setProtocol("HTTPS");
sampler.setMethod("GET");
sampler.setPort(443);

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.get("PROPERTY_NAME");
props.put("PROPERTY_NAME", "VALUE");

//update the existing property
props.put("jmeter.version","3.1")

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");