Skip to content

Build a Custom JMeter Plugin with Claude AI: Java Sampler and Function

JMeter covers HTTP, JDBC, JMS and a lot more out of the box. Sooner or later, though, you hit a system it does not speak: an in-house TCP protocol, a vendor SDK, a message format nobody else uses. That is when you need your own plugin.

Writing one used to mean digging through the JMeter source to find the right base class. Now you can ask Claude (or ChatGPT, or Gemini) to write the first version, and spend your own time on building and testing. Here we build a small Java Request sampler with Claude, package it with Maven, load it into JMeter and run it. A short custom function example comes at the end.

Pipeline: Claude writes the Java code, Maven builds a jar, the jar goes into JMeter lib/ext, and the sampler appears in Java RequestFrom a prompt to a sampler inside JMeterClaude writesthe codepaste intoMaven projectpom.xml + .javamvn packageplugin.jarcopy tolib/extrestart JMeterJavaRequestbuild error? paste it back
Every arrow is a step you can check on its own.

What you need

  • JMeter 5.6 or later.
  • A JDK and Maven installed. Run java -version in the same terminal you start JMeter from and note the version.
  • Claude, ChatGPT, Gemini or a similar AI tool.
  • A test system to point the sampler at.

Step 1: Tell the AI exactly what the sampler does

The more specific the prompt, the less you fix later. Say which base class to use, which parameters you want in the GUI, what counts as a failure, and which JMeter and Java versions you run.

Write a JMeter 5.6.3 Java Request sampler.
- Extend AbstractJavaSamplerClient
- Parameters (shown in the GUI): host, port, message, timeoutMs
- Open a TCP connection, send the message plus a newline,
  read one line back
- Time only the network work with sampleStart() / sampleEnd()
- Mark the sample failed on timeout, connection error or empty reply,
  and put the exception in the response message
- No dependencies outside the JDK and JMeter
Also give me a pom.xml that builds it as a jar for Java 11,
with the JMeter dependency as provided scope.

A TCP line check makes a good first plugin. It is small, and it uses every part of the sampler API once: parameters, timing, success and failure.

Step 2: Review the code before you build it

This is roughly what a good answer looks like. Read it before running anything. Check that the timer covers only the work you want to measure, and that every failure path marks the sample as failed.

package com.easyloadrunner.jmeter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

public class TcpLineSampler extends AbstractJavaSamplerClient {

    @Override
    public Arguments getDefaultParameters() {
        Arguments args = new Arguments();
        args.addArgument("host", "localhost");
        args.addArgument("port", "9000");
        args.addArgument("message", "PING");
        args.addArgument("timeoutMs", "5000");
        return args;
    }

    @Override
    public SampleResult runTest(JavaSamplerContext ctx) {
        String host = ctx.getParameter("host");
        int port = ctx.getIntParameter("port");
        int timeout = ctx.getIntParameter("timeoutMs");
        String message = ctx.getParameter("message");

        SampleResult result = new SampleResult();
        result.setSampleLabel("TCP " + host + ":" + port);
        result.setSamplerData(message);

        String reply = null;
        Exception error = null;
        result.sampleStart();
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), timeout);
            socket.setSoTimeout(timeout);
            OutputStream out = socket.getOutputStream();
            out.write((message + "\n").getBytes(StandardCharsets.UTF_8));
            out.flush();
            BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            reply = in.readLine();
        } catch (Exception e) {
            error = e;
        } finally {
            result.sampleEnd();
        }

        if (error == null && reply != null && !reply.isEmpty()) {
            result.setSuccessful(true);
            result.setResponseCodeOK();
            result.setResponseMessage("OK");
            result.setResponseData(reply, "UTF-8");
        } else {
            result.setSuccessful(false);
            result.setResponseCode("500");
            result.setResponseMessage(error != null
                ? error.getClass().getSimpleName() + ": " + error.getMessage()
                : "Empty reply");
        }
        return result;
    }
}

Notice that sampleEnd() sits in finally. It runs once whether the call works or fails, so failed samples still get a response time and JMeter never sees the timer stopped twice.

Lifecycle of a JMeter Java sampler: setupTest once per thread, runTest every iteration, teardownTest once per threadWhat JMeter calls, and whensetupTest()once per threadrunTest()every iterationteardownTest()once per threadsampleStart() ... your work ... sampleEnd()= the response time JMeter recordsopen connections hereclose them here
Only the code between sampleStart and sampleEnd counts as response time.

This example opens a new connection on every iteration, which is what a fresh client does. If your real clients keep a connection open, ask the AI to move the connect into setupTest() and the close into teardownTest(). Those run once per thread.

Step 3: Build the jar with Maven

The pom only needs one JMeter dependency, marked provided because JMeter already ships those classes:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.easyloadrunner</groupId>
  <artifactId>jmeter-tcp-line-sampler</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <maven.compiler.release>11</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.jmeter</groupId>
      <artifactId>ApacheJMeter_java</artifactId>
      <version>5.6.3</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>

Put the Java file under src/main/java/com/easyloadrunner/jmeter/ and run:

mvn clean package

The jar lands in target/jmeter-tcp-line-sampler-1.0.0.jar. Set maven.compiler.release to the Java version that runs your JMeter, not the newest one on your machine. A jar built for a newer Java than JMeter runs on will not load.

Fix loop: ask for the code, build with Maven, copy the exact error back to the AI, rebuild, then test with one threadThe fix loop with an AIAsk for code+ pom.xmlmvn packageCopy theexact errorPaste itback to Claude1 thread,1 loop testrepeat until it builds
It can take a few rounds.

If the build fails, copy the full error from the terminal, paste it to the AI and ask for a fix. Paste the exact text. "It doesn't compile" gives the AI nothing to work with.

Step 4: Load it into JMeter and test with one thread

  1. Copy the jar into JMETER_HOME/lib/ext.
  2. Restart JMeter. It only scans for plugins at startup.
  3. Add a Thread Group, then Add, Sampler, Java Request.
  4. Pick com.easyloadrunner.jmeter.TcpLineSampler from the class name dropdown. Your four parameters appear in the table below it.
  5. Add a View Results Tree, set 1 thread and 1 loop, and run it.

Run it once against a port where nothing is listening as well. You should see a failed sample with a ConnectException in the response message. That proves the failure path works, which matters more under load than the happy path.

If the class is missing from the dropdown, check jmeter.log first. If you see an UnsupportedClassVersionError, it is the Java version problem from Step 3. If the log is clean, some setups only pick the jar up from lib or through the user.classpath property, so try those next.

Bonus: a custom function in the same project

Sometimes you do not need a new sampler, just a new ${__something()} function to use inside requests. The pattern is short. Extend AbstractFunction and implement four methods:

package com.easyloadrunner.jmeter.functions;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

public class ReverseString extends AbstractFunction {

    private static final List<String> DESC =
        Collections.singletonList("Text to reverse");
    private CompoundVariable input;

    @Override
    public String getReferenceKey() {
        return "__reverse";
    }

    @Override
    public List<String> getArgumentDesc() {
        return DESC;
    }

    @Override
    public void setParameters(Collection<CompoundVariable> parameters)
            throws InvalidVariableException {
        checkParameterCount(parameters, 1);
        input = parameters.iterator().next();
    }

    @Override
    public String execute(SampleResult previousResult, Sampler currentSampler) {
        return new StringBuilder(input.execute()).reverse().toString();
    }
}

Save it as src/main/java/com/easyloadrunner/jmeter/functions/ReverseString.java. Then tell JMeter the function exists. Since JMeter 5.6, the official plugin tutorial recommends registering plugin classes in a service file. Create src/main/resources/META-INF/services/org.apache.jmeter.functions.Function containing one line:

com.easyloadrunner.jmeter.functions.ReverseString

Without that file, JMeter 5.6 still falls back to scanning the jars in lib/ext, and older versions only scan. That scan looks for function classes in packages whose name contains .functions. (the classfinder.functions.contain setting), which is why the package above ends in functions. Keep both and the function is found either way. An AI may skip the service file or put the class in your main package, so check these two yourself.

After a rebuild and restart, ${__reverse(abc)} returns cba, and the function appears in the Function Helper dialog.

Decision guide: Java Request sampler for a new protocol, custom function for values in expressions, JSR223 Groovy for one-off logicPlugin, function or JSR223?What do you need?A new protocolor client callJava Request samplerA value inside${...} expressionscustom functionA quick one-offin one test planJSR223 + Groovy
Pick the smallest thing that does the job.

Where the AI helps and where it does not

TaskAI is good atYou still check
Picking the base class and method namesUsually gets these right, saves API lookupsThat it matches your JMeter version
Writing the pom.xmlFast and usually rightThe Java release level
Fixing compile errorsVery good with the exact error textThat the fix did not change behaviour
Timing and failure handlingWrites it if you ask for itWhere sampleStart and sampleEnd sit
Behaviour under loadCannot tell youRun it with real threads

Frequently asked questions

Do I need to write a GUI for my sampler?
No. The Java Request sampler builds the parameter table from getDefaultParameters(). You only need your own GUI class if you want a custom screen.

Can I use the same plugin in non-GUI mode and in CI?
Yes. The jar just needs to be in lib/ext on every machine that runs the test, including load generators in a distributed setup.

Should I use JSR223 with Groovy instead?
For a quick one-off inside one test plan, often yes. A compiled plugin makes sense when several test plans or teams reuse the same logic.

Which AI tool is best for this?
Any of Claude, ChatGPT or Gemini can write this kind of Java. A precise prompt and the exact error text matter more than the tool.

Tomorrow in the AI in Performance Testing series: turning a JMeter results file (JTL) into a readable test report with ChatGPT or Claude, with percentiles, an error summary and an SLA pass/fail table.

RG

Raviteja Gorentla

Performance engineer writing since 2010 about LoadRunner, JMeter, NeoLoad, APM tools and the real problems that show up in load tests. Every fix here was tested on a live project.

Page views