Jmeter - jsr223 - Error with external library - jmeter

Jmeter - jsr223 - Error with external library
My java code with import org.web3j, run as expected, no error
package test;
import java.nio.charset.StandardCharsets;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.Sign;
import org.web3j.utils.Numeric;
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String privateAccountKey = "privateAccountKey ";
Credentials credentials = Credentials.create(privateAccountKey);
String message="messageABC";
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
Sign.SignatureData signature = Sign.signPrefixedMessage(messageBytes, credentials.getEcKeyPair());
byte[] value = new byte[65];
System.arraycopy(signature.getR(), 0, value, 0, 32);
System.arraycopy(signature.getS(), 0, value, 32, 32);
System.arraycopy(signature.getV(), 0, value, 64, 1);
System.out.println("signature: " + Numeric.toHexString(value));
}
}
In jmeter, I use JSR223 PostProcessor
I have added core-5.0.0.jar to folder apache-jmeter-5.5\lib\ext (Download from https://mvnrepository.com/artifact/org.web3j/core/5.0.0) and restart jmeter
After run, error is shown javax.script.ScriptException: Sourced file: inline evaluation of: import java.nio.charset.StandardCharsets; import org.web3j.crypto.Credentials; i . . . '' : Typed variable declaration : Class: Credentials not found in namespace : at Line: 7 : in file: inline evaluation of: import java.nio.charset.StandardCharsets; import org.web3j.crypto.Credentials; i . . . '' : Credentials
in inline evaluation of: ``import java.nio.charset.StandardCharsets; import org.web3j.crypto.Credentials; i . . . '' at line number 7
Please advise
Many thanks

You should place any 3rd-party .jar libraries to lib folder. lib/ext is for JMeter Plugins. See JMeter Classpath user manual entry for more details.
org.web3j.core library doesn't contain org.web3j.crypto.Credentials class, you will need to add this library to JMeter's lib folder
Since JMeter 3.1 you're supposed to be using Groovy language for scripting especially when it comes to resource intensive cryptographic operations, see Beanshell vs. JSR223 vs. Java For JMeter: Complete Showdown for more details so consider switching the language to groovy because java is not real Java, it's Beanshell interpreter

Related

Unable to achieve expected transaction in karate-gatling for load testing [duplicate]

I am trying to reuse karate scripts and perform load testing using gatling. The scenario defined is to load constant 50 users per second for 10 seconds. (To load test 500 users) However the number of requests per second does not exceed 20 requests per second in the gatling report. Please let me know if i am doing anything wrong.
ExampleTest.java code which executes Karate scripts
//package examples;
import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import org.apache.commons.io.FileUtils;
class ExamplesTest {
#Test
void testParallel() {
//System.setProperty("karate.env", "demo"); // ensure reset if other tests (e.g. mock) had set env in CI
Results results = Runner.path("classpath:examples").tags("~#ignore").parallel(10);
generateReport(results.getReportDir());
assertEquals(0, results.getFailCount(), results.getErrorMessages());
}
public static void generateReport(String karateOutputPath) {
Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList<String>(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File("target"), "demo");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
}
}
Scala Code to define load test scenarios.
package perf
import com.intuit.karate.gatling.PreDef._
import io.gatling.core.Predef._
import scala.concurrent.duration._
class KarateSimulate extends Simulation {
val protocol = karateProtocol(
"/v2/" -> Nil,
"/v2/" -> pauseFor("get" -> 0, "post" -> 25)
)
val userfeeder = csv("data/Token.csv").circular
val getScores = scenario("Get Scores for Students").feed(userfeeder).exec(karateFeature("classpath:examples/scores/student.feature"))
setUp(
getScores.inject(constantUsersPerSec(50) during (10 seconds)).protocols(protocol)
)
}
We updated the docs (in the develop branch) with tips on how to increase the thread-pool size if needed: https://github.com/intuit/karate/tree/develop/karate-gatling#increasing-thread-pool-size
Add a file called gatling-akka.conf to the root of the classpath (typically src/test/resources). Here is an example:
akka {
actor {
default-dispatcher {
type = Dispatcher
executor = "thread-pool-executor"
thread-pool-executor {
fixed-pool-size = 100
}
throughput = 1
}
}
}
Since we made some fixes recently, please try to build from source if the above does not work for 0.9.6.RC4, it is easy, here are the instructions: https://github.com/intuit/karate/wiki/Developer-Guide
If that does not work, it is important that you follow this process so that we can replicate: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
Please see these links below for good examples of how others have worked with the Karate project team to replicate issues so that they can be fixed:
https://github.com/intuit/karate/issues/1668
https://github.com/intuit/karate/issues/845

How to get the immediate parent name for a sampler in Jmeter

How to get the immediate parent name for a sampler in Jmeter. I have many transaction controllers. I am using Jmeter 5.3
I have a beanshell script for the same which is as below, but it always prints the very first controller name.
import org.apache.jmeter.control.GenericController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import java.lang.reflect.Field;
import java.util.Collection;
StandardJMeterEngine engine = ctx.getEngine();
Field test = engine.getClass().getDeclaredField("test");
test.setAccessible(true);
HashTree testPlanTree = (HashTree) test.get(engine);
SearchByClass simpleCtrlSearch= new SearchByClass(GenericController.class);
testPlanTree.traverse(simpleCtrlSearch);
Collection simpleControllers = simpleCtrlSearch.getSearchResults();
for (Object simpleController : simpleControllers) {
log.info(((GenericController) simpleController).getName());
}
In general this is either not possible or not too simple.
For particular your case if you need to determine the name of the Transaction Controller for the particular Sampler you can go for JSR223 Listener and the following code:
if (sampleEvent.isTransactionSampleEvent()) {
log.info("Transaction Controller name: " + sampleEvent.result.getSampleLabel())
}
Demo:
More information: Apache Groovy - Why and How You Should Use It

Maven plugin testing with Groovy: access to generated class?

I'm developping a Maven plugin and some of my tests are done through maven-invoker-plugin based on Groovy scripts (https://maven.apache.org/plugin-developers/plugin-testing.html).
This Maven plugin generates a Java class and I'd like to test this generated class behaviour with Groovy scripts.
I'm facing a problem with these Groovy scripts saying that it could not resolve the class:
Running post-build script: <blah>\verify.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 21: unable to resolve class com.mycompany.MyClass
# line 21, column 1.
import com.mycompany.MyClass
Here is the generated Java class from my plugin:
package com.mycompany;
public final class MyClass {
public static String getSomething() {
return "something";
}
}
Here is an extract of my Groovy test verify.groovy:
File generatedJavaFile = new File( basedir, "target/my-plugin/com/mycompany/MyClass.java" );
assert generatedJavaFile.exists()
assert generatedJavaFile.isFile()
File generatedClassFile = new File( basedir, "target/classes/com/mycompany/MyClass.class" );
assert generatedClassFile.exists()
assert generatedClassFile.isFile()
import com.mycompany.MyClass
assert MyClass.getSomething() == "the expected result"
I was wondering if something needs to be specified to the maven-invoker-plugin configuration to include the tested Maven project, or if it's just not possible and I need to find another way...
Thanks,
Benoît.

Beanshell PostProcessor Error: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.util.Arrays; import java.util.List;

I am getting error message
Error invoking bsh method: eval Sourced file: inline evaluation of:
``import java.util.Arrays; import java.util.List; import
java.util.concurrent.Time . . . '' : Typed variable declaration :
Error in method invocation: Static method create( java.lang.String )
not found in class'com.couchbase.client.java.CouchbaseCluster'
when I execute jmeter script with Beanshell Post Processor. Any thoughts on why I am seeing this error?
Here is the sample code:
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.Document;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
Cluster cluster = CouchbaseCluster.create("dev-int-couchbase1.aeg.cloud");
Bucket bucket = cluster.openBucket("source-image ",100, TimeUnit.MINUTES);
Document<JsonObject> loadedFromDoc = bucket.get("0292ofcfh4516");
if(loadedFromDoc == null)
return "Document Not found";
bucket.remove(“0292ofcfh4516");
log.info("In bean shell processor");
System.out.println("In bean shell processor");
cluster.disconnect();
return "Document Removed";
Instead of using create(String... varargs) method, suggest using create(List<String> nodes) method.
replace the following code
Cluster cluster = CouchbaseCluster.create("dev-int-couchbase1.aeg.cloud");
With:
nodes = new ArrayList();
nodes.add("dev-int-couchbase1.aeg.cloud");
Cluster cluster = CouchbaseCluster.create(nodes);
Note: I am not sure how to fix the issue related to varargs, so suggesting another one. I tried suggested method here, but did not work for varargs.
Reference:
http://docs.couchbase.com/sdk-api/couchbase-java-client-2.0.0/index.html?com/couchbase/client/java/CouchbaseCluster.html
I suggest use JSR223 Post Processor instead of BeanShell postprocessor. Just copy paste the code from BeanShell to JSR223 and select the language as Java under script language drop-down available in the JSR223 post processor.
This gives more flexibility in debugging (prints complete stack trace of the error/exception in the logs).
Coming to the error, it says that Static method create( java.lang.String ) not found in class'com.couchbase.client.java.CouchbaseCluster. I checked in the official docs here, which says there is a create method which takes String Varargs. I ma not sure whether that is causing the issue. so, try it out in JSR223 PostProcessor and debug the issue.
References:
https://www.blazemeter.com/blog/beanshell-vs-jsr223-vs-java-jmeter-scripting-its-performance

Groovy retrieve file version property (Windows)

Could you please help me to retrieve file version property from Groovy script (in Windows platform)?
I mean the Version property available in Windows (7) in Details tab of file Properties window opened by right-click on file name.
I found to do it with WSH only.
Thanks In Advance!
First I tried to find a solution with and "More New I/O APIs for the Java™ Platform" (NIO.2) but didn't succeed. When I looked closer at your WSH-example I realized it is COM scripting.
So there are 2 possiblities to solve this:
Com4j
Java Native Access (JNA)
An example for accessing Word from Java can be found here.
Update
I tried to solve your problem, but run into an exception within the Namespace-function:
#Grab(group='net.java.dev.jna', module='platform', version='3.5.2')
import com.sun.jna.platform.win32.COM.COMException
import com.sun.jna.platform.win32.COM.COMObject
import com.sun.jna.platform.win32.OleAuto;
import com.sun.jna.platform.win32.Variant;
import com.sun.jna.platform.win32.Variant.VARIANT;
import com.sun.jna.platform.win32.WTypes.BSTR;
import com.sun.jna.platform.win32.WinNT.HRESULT;
public class Shell extends COMObject {
public Shell() throws COMException {
super("Shell.Application", false);
}
public HRESULT Namespace(String dir) throws COMException
{
def bstrDir = OleAuto.INSTANCE.SysAllocString(dir)
def varDir = new VARIANT(bstrDir)
def result = new VARIANT.ByReference()
HRESULT hr = oleMethod(OleAuto.DISPATCH_METHOD, result, this.iDispatch, "Namespace", varDir);
}
}
def shell = new Shell()
shell.Namespace("C:\\Temp")

Resources