Create custom Java based extension in Gatling

45 Views Asked by At

See first answer to the same question 1.5 year ago Create custom Java based extension in Gatling (version 3.8.4)

With version 3.10.4, is it still impossible to create a Gatling extension in Java?

An it’s really impossible?

Since it seems to be possible to extends scala classes or implements scala interfaces in Java, What part is impossible to do?

Note that I don’t know Scala and have very limited knowledge of Gatling

1

There are 1 best solutions below

0
George Leung On

As much as Scala boasts its Java interoperability, using Scala code in Java can be hard or impossible if the Scala code isn't designed for use in Java (e.g. the Scala code will have to avoid certain Scala features).


To implement an extension of Gatling you'll have to implement the io.gatling.core.action.builder.ActionBuilder and io.gatling.core.action.RequestAction traits.

Consider the following trait extended by RequestAction

trait StrictLogging {

  protected val logger: Logger =
    Logger(LoggerFactory.getLogger(getClass.getName))
}

This trait is compiled down to a Java interface in the class file.

Pause and think.

Java interfaces do not allowing specifying a field, not to mention how that field gets initialized.

How does Scala do it?

It becomes 3 methods: a setter, a getter and an initializer static method.

void com$typesafe$scalalogging$StrictLogging$_setter_$logger_$eq(final Logger x$1);

Logger logger();

static void $init$(final StrictLogging $this) {
    $this.com$typesafe$scalalogging$StrictLogging$_setter_$logger_$eq(.MODULE$.apply(LoggerFactory.getLogger($this.getClass().getName())));
}

When you create a class that extends StrictLogging, the Scala compiler will implement/call those methods for you.


I hope this one example convinces you that, to implement a Scala trait in a Java class takes more Scala knowledge than implementing it in a Scala class.


The good news is that you don't have to worry about any of that if you just have some Java methods to call in Gatling. I have created a third party plugin that allows calling any generic code in Gatling.

https://github.com/phiSgr/gatling-ext/tree/master/gatling-kt-ext

The readme and the code is a bit out-of-date (ignore the mutable builder syntax bit), but they should be usable.