JMeter BeanShell Property Setting Across Thread Group - java

I'm trying to calculate the time between two events in JMeter using BeanShell PostProcessors.
In the first block, I get the time and store it as a property. This is in one Thread Group.
Then in another Thread Group, I have the second BeanShell block. I get an error which I cannot figure out. I have pasted the error here. Thank you very much for your hints and advice!
Here are the two pieces of BeanShell code:
FIRST POSTPROCESSOR:
//Set the current time to the time_upload variable
long time_upload = prev.getTime(); // get POST Time
props.put("time_upload",(String.valueof(time_upload)));
log.info("Time for Upload is: " + time_upload); // print difference to jmeter.log file
SECOND POSTPROCESSOR:
String no_saved_carts = vars.get("no_saved_carts");
String no_saved_carts_trimmed = no_saved_carts.trim();
String temp_description = vars.get("description");
String temp_description_no_space = temp_description.trim();
String time_upload_local = props.get("time_upload");
if(temp_description_no_space.equals("</") || no_saved_carts_trimmed.equals("No Saved Carts Found")){
vars.put("description","true");
} else{
vars.put("description","false");
//set the time to time_processing based on time_upload
long time_processing_done = prev.getTime(); // get time
long time_upload_long = Long.parseLong(time_upload_local); // get HTTP Sampler 1 execution time from variable
long delta = (time_processing_done - time_upload); // calculate difference
log.info("Time difference is: " + delta + " ms"); // print difference to jmeter.log file
}
The relevant part of the ERROR LOG:
2016/06/03 17:21:22 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``//Set the current time to the time_upload variable long time_upload = prev.getTi . . . '' : Error in method invocation: Static method valueof( long ) not found in class'java.lang.String'
2016/06/03 17:21:22 WARN - jmeter.extractor.BeanShellPostProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``//Set the current time to the time_upload variable long time_upload = prev.getTi . . . '' : Error in method invocation: Static method valueof( long ) not found in class'java.lang.String'
2016/06/03 17:21:22 INFO - jmeter.threads.JMeterThread: Thread is done: Upload Saved Cart Thread Group 1-1
2016/06/03 17:21:22 INFO - jmeter.threads.JMeterThread: Thread finished: Upload Saved Cart Thread Group 1-1
2016/06/03 17:21:22 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String temp_description = vars.get("description"); String no_saved_carts = vars. . . . '' : Typed variable declaration : Method Invocation Long.parseLong
2016/06/03 17:21:22 WARN - jmeter.extractor.BeanShellPostProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String temp_description = vars.get("description"); String no_saved_carts = vars. . . . '' : Typed variable declaration : Method Invocation Long.parseLong
2016/06/03 17:21:26 INFO - jmeter.threads.JMeterThread: Thread is done: Check Upload Status 2-1

You cannot convert long to String using String.valueOf() method, there are following options:
If you still want String just change the line to convert long to String to look like:
props.put("time_upload", Objects.toString(time_upload,null));
Get rid of long -> String and vice versa conversion, props is an usual java.util.Properties class instance so it stores Objects
In first PostProcessor:
long time_upload = prev.getTime();
props.put("time_upload", time_upload);
In second PostProcessor:
long time_upload_long = props.get("time_upload"); // no need to cast from String
You can use bsh.shared namespace to keep any Object - it will be accessible by all Thread Groups
In first PostProcessor:
bsh.shared.time_upload = prev.getTime();
In second PostProcessor:
long time_upload = bsh.shared.time_upload
You can get more informative error messages in jmeter.log file in case of Beanshell script error by surrounding your code with try/catch block like:
try {
//your code here
}
catch (Throwable ex) {
log.error("Something wrong", ex);
throw ex;
}
See How to Use BeanShell: JMeter's Favorite Built-in Component for more JMeter and Beanshell tips and tricks.

Related

JMeter JSR223 Listener for ExtentReports needs improvement

I wrote a new JSR223 Listener to write out test results into an extentreports html report. This is working nicely but could be improved. I'm just not sure the best way to improve it. One specific issue I am seeing is the dashboard's Time Taken value. It's showing the start/end time for the last sampler run. It should be showing the time of the first sampler as the start time and the time of the end sampler as the end time and should get the Time Taken value from those 2 datetimes. Can you please have a look at my listener script and share any advice you might have?
Test Plan setup: Inside a thread group, I have HTTP Request samplers that log in, doing one action and log out. At the root of the thread group, I have this code in a BeanShell Assertion with this code:
//request data
String requestData = new String(prev.SamplerData);
//String requestData = new String(requestData);
props.put("propRequestData", requestData);
//response data
String respData = new String(prev.ResponseData);
//String respData = new String(prev.getResponseDataAsString());
props.put("propResponse", respData);
//response code
String respCode = new String(prev.ResponseCode);
props.put("propRespCode",respCode);
//response message
String respMessage = new String(prev.ResponseMessage);
props.put("propRespMessage",respMessage);
At the root of my Test Plan, I have this JSR223 Listener code:
import com.aventstack.extentreports.*;
import com.aventstack.extentreports.reporter.*;
import com.aventstack.extentreports.markuputils.*;
ExtentHtmlReporter htmlReporter;
ExtentReports extent;
ExtentTest test;
// create the HtmlReporter
htmlReporter = new ExtentHtmlReporter("C:/AUTO_Results/Results_${testApp}_${reportDate}_${currentTime}_${testenv}.html");
//configure report
htmlReporter.config().setCreateOfflineReport(true);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("${testApp} Results");
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName("${testApp} Results ${reportDate}_${currentTime}_${testenv}");
htmlReporter.setAppendExisting(true);
// create ExtentReports
extent = new ExtentReports();
// attach reporter to ExtentReports
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
// Show Env section and set data on dashboard
extent.setSystemInfo("Tool","JMeter");
extent.setSystemInfo("Test Env","${testenv}");
extent.setSystemInfo("Test Date","${reportDate}");
extent.setSystemInfo("Test Time","${currentTime}");
//stringify test info
String threadName = sampler.getThreadName();
String samplerName = sampler.getName();
String requestData = props.get("propRequestData");
String respCode = props.get("propRespCode");
String respMessage = props.get("propRespMessage");
String responseData = props.get("propResponse");
// create test
test = extent.createTest(threadName+" - "+samplerName);
//test.assignCategory("API Testing");
// analyze sampler result
if (vars.get("JMeterThread.last_sample_ok") == "false") {
log.error("FAILED: "+samplerName);
print("FAILED: "+samplerName);
test.fail(MarkupHelper.createLabel("FAILED: "+sampler.getName(),ExtentColor.RED));
} else if (vars.get("JMeterThread.last_sample_ok") == "true") {
if(responseData.contains("#error")) {
log.info("FAILED: "+sampler.getName());
print("FAILED: "+sampler.getName());
test.fail(MarkupHelper.createLabel("FAILED: "+sampler.getName(),ExtentColor.RED));
} else if (responseData.contains("{")) {
log.info("Passed: "+sampler.getName());
print("Passed: "+sampler.getName());
test.pass(MarkupHelper.createLabel("Passed: "+sampler.getName(),ExtentColor.GREEN));
}
} else {
log.error("Something is really wonky");
print("Something is really wonky");
test.fatal("Something is really wonky");
}
//info messages
test.info("RequestData: "+requestData);
test.info("Response Code and Message: "+respCode+" "+respMessage);
test.info("ResponseData: "+responseData);
//playing around
//markupify json into code blocks
//Markup m = MarkupHelper.createCodeBlock(requestData);
//test.info(MarkupHelper.createModal("Modal text"));
//Markup mCard = MarkupHelper.createCard(requestData, ExtentColor.CYAN);
// test.info("Request "+m);
// test.info(mCard);
// test.info("Response Data: "+MarkupHelper.createCodeBlock(props.get("propResponse")));
// test.info("ASSERTION MESSAGE: "+props.get("propAssertion"));
// end the reporting and save the file
extent.flush();
The ${variables} you see listed in the JSR223 Listener are defined in a User Defined Variable element. I am using:
jmeter-3.2
extentreports-pro-3.0.5.jar in my lib folder
Here is a screenshot of the dashboard
Your end time is fine (end sampler), what you need is start of first sampler
I think you can use START predefined property:
START properties are also copied to variables with the same names.
START.MS - JMeter start time in milliseconds
START.YMD - JMeter start time as yyyyMMdd
START.HMS - JMeter start time as HHmmss
TESTSTART.MS - test start time in milliseconds
Another option to add JSR223 PostProcessor to first sampler and add to variable the start time:
log.info("start time is " + prev.getStartTime() );
vars.put("startTimeFirstSample", "" + prev.getStartTime() );
I ended up with the following workaround for the test duration.
1. in a setup Thread Group, I added a JSR223 Sampler with this code:
log.info("--------------Initialize");
import java.time.Duration;
import java.time.Instant;
Instant myStart = Instant.now();
props.put("varmyStart",myStart);
log.info("Test Start time: ---- "+props.get("varmyStart"));
//response
props.put("propResponse","Test Start time { "+props.get("varmyStart")+" }");
SampleResult.setResponseData(props.get("propResponse"));
in a teardown Thread group, I added a JSR223 Sampler with this code:
log.info("---------------End Test JSR223Sampler");
//props.put("varEndTest","Yes");
import java.time.Duration;
import java.time.Instant;
Instant myEnd = Instant.now();
props.put("varmyEnd",myEnd);
log.info("varmyEnd---- "+props.get("varmyEnd"));
Duration timeElapsed = Duration.between(props.get("varmyStart"),
props.get("varmyEnd"));
//millis
props.put("varTimeTakenMS",timeElapsed.toMillis().toString());
log.info("prop varTimeTaken(MS): --"+props.get("varTimeTakenMS"));
//seconds
props.put("varTimeTakenSEC",timeElapsed.getSeconds());
log.info("prop varTimeTaken(SEC): --"+props.get("varTimeTakenSEC"));
//minutes
props.put("varTimeTakenMINS",timeElapsed.toMinutes().toString());
log.info("prop varTimeTaken(MINS): --"+props.get("varTimeTakenMINS"));
//response
props.put("propResponse","Test End time { "+props.get("varmyEnd")+" }.
Test Duration: "+props.get("varTimeTakenMINS")+" Minutes");
SampleResult.setResponseData(props.get("propResponse"));
in the listener code, under the // Show Env section and set data on dashboard, I added these lines:
//extent.setSystemInfo("Actual Test Duration(ms)",props.get("varTimeTakenMS")+" milliseconds");
extent.setSystemInfo("Actual Test Duration(seconds)",props.get("varTimeTakenSEC")+" seconds");
extent.setSystemInfo("Actual Test Duration(mins)",props.get("varTimeTakenMINS")+" minutes");
It's not pretty but it's giving me what I need.

Having Java call an Applescript file with arguments

I have a Java program that calls an Applescript file to run, and returns information back to Java. However, I need to also pass some arguments to the Applescript file. The relevant portion of the Java file:
public static void scriptRunner(String[] args) {
// Connect to the database.
ConnectionManager.getInstance().setDBType(DBType.MYSQL);
// Prepare the AppleScript file to be executed.
String homeFolder = System.getenv("HOME");
File scriptFile = new File(homeFolder + "/Documents/Output--Test.applescript");
InputStream scriptStream = null;
try {
scriptStream = FileUtils.openInputStream(scriptFile);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not find the Output AppleScript file. Please notify Chris McGee", "File not found", JOptionPane.ERROR_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(scriptStream));
// These two lines prepare the scripting engine, ready to run the script.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
// Add the parameters to the engine so they will be passed to the script.
engine.put("javaOrderNum", args[0]);
engine.put("javaShipDate", args[1]);
engine.put("javaInitials", args[2]);
engine.put("javaOverruns", args[3]);
// Run the script and evaluate the result.
log.trace("Run the script and evaluate the result.");
Object result = null;
try {
result = engine.eval(bufferedReader); // Run the script and place the result into an abstract object.
} catch (ScriptException e) {
JOptionPane.showMessageDialog(null, "Either an error occurred with the Output script or the user cancelled it.", "Script error / cancel", JOptionPane.INFORMATION_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
log.debug(result); // Check that we received the correct information back from the script.
log.debug("");
.
.
.
Sadly, the engine.put lines, as suggested from a forum I read during my searches to get this problem solved, don't seem to work. The AppleScript file:
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
set jInitials to item 3 of arguments
set jOverruns to item 4 of arguments
-- Set the correct folder variable
if (folderExists(POSIX path of "/Volumes/Users/Scripts/")) then
set server_prefix to "/Volumes/Users/Scripts/"
else if (folderExists(POSIX path of "/centralserver/Users/Scripts/")) then
set server_prefix to "/centralserver/Users/Scripts/"
else
display alert "Please connect to the central server, then try again.
If you have already done so, please let Chris McGee know."
end if
with timeout of (30 * 60) seconds
tell application "Adobe InDesign CS6"
set myJavaScript to server_prefix & "sky-artdept/Test/Output.jsx"
set myResult to do script myJavaScript with arguments {jOrderNum, jShipDate, jInitials, jOverruns} language javascript
return myResult
end tell
end timeout
on folderExists(posixPath)
return ((do shell script "if test -e " & quoted form of posixPath & "; then
echo 1;
else
echo 0;
fi") as integer) as boolean
end folderExists
I am given an error that the variable arguments is not defined. What can I try next?
I can't help with the javascript running the applescript. But, you applescript code is missing a declaration. You're asking for "item 1 of arguments" but you never define the variable arguments.
When the script is not inside any handler, it is implicit that it is inside a run() handler. And, since you're needing to pass arguments on run, you should try wrapping your script, minus the on folderExists() handler, inside a run handler that includes the arguments declaration.
on run(arguments)
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
…
end timeout
end run
on folderExists(posixPath)
…
end folderExists

how to use property=value in CLI commons Library

I am trying to use the OptionBuilder.withArgName( "property=value" )
If my Option is called status and my command line was:
--status p=11 s=22
It only succeeds to identify the first argument which is 11 and it fails to identify the second argument...
Option status = OptionBuilder.withLongOpt("status")
.withArgName( "property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription("Get the status")
.create('s');
options.addOption(status);
Thanks for help in advance
You can access to passed properties using simple modification of passed command line options
--status p=11 --status s=22
or with your short syntax
-s p=11 -s s=22
In this case you can access to your properties simply with code
if (cmd.hasOption("status")) {
Properties props = cmd.getOptionProperties("status");
System.out.println(props.getProperty("p"));
System.out.println(props.getProperty("t"));
}
If you need to use your syntax strictly, you can manually parse your property=value pairs.
In this case you should remove .withValueSeparator() call, and then use
String [] propvalues = cmd.getOptionValues("status");
for (String propvalue : propvalues) {
String [] values = propvalue.split("=");
System.out.println(values[0] + " : " + values[1]);
}

Java ProgramCall.run hangs

Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe

bean validation- hibernate error

I am getting following exception when trying to run my command line application:
java.lang.ExceptionInInitializerError
at org.hibernate.validator.engine.ConfigurationImpl.<clinit>(ConfigurationImpl.java:52)
at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1937)
at org.hibernate.validator.util.Version.<clinit>(Version.java:39)
... 34 more
Am I doing anything wrong? Please suggest.
This is strange. I pasted the relevant parts of the static initialization block of o.h.v.u.Version in a class with a main and added some poor man's logging traces:
public class VersionTest {
public static void main(String[] args) {
Class clazz = org.hibernate.validator.util.Version.class;
String classFileName = clazz.getSimpleName() + ".class";
System.out.println(String.format("%-16s: %s", "classFileName", classFileName));
String classFilePath = clazz.getCanonicalName().replace('.', '/') + ".class";
System.out.println(String.format("%-16s: %s", "classFilePath", classFilePath));
String pathToThisClass = clazz.getResource(classFileName).toString();
System.out.println(String.format("%-16s: %s", "pathToThisClass", pathToThisClass));
// This is line 39 of `org.hibernate.validator.util.Version`
String pathToManifest = pathToThisClass.substring(0, pathToThisClass.indexOf(classFilePath) - 1)
+ "/META-INF/MANIFEST.MF";
System.out.println(String.format("%-16s: %s", "pathToManifest", pathToManifest));
}
}
And here the output I get when running it:
classFileName : Version.class
classFilePath : org/hibernate/validator/util/Version.class
pathToThisClass : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/org/hibernate/validator/util/Version.class
pathToManifest : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/META-INF/MANIFEST.MF
In your case, the StringIndexOutOfBoundsException: String index out of range: -2 suggests that:
pathToThisClass.indexOf( classFilePath )
is returning -1, making the pathToThisClass.substring(0, -2) call indeed erroneous.
And this means that org/hibernate/validator/util/Version.class is somehow not part of the pathToThisClass that you get. I don't have a full explanation but this must be related to the fact that you're using One-Jar.
Could you run the above test class and update your question with the output?
So, as you use One-JAR, the problem probably is in incompatibility between One-JAR and Hibernate Validator. However, in the latest version of One-JAR (0.97) it works fine, therefore use the latest version.

Categories