JMeter Beanshell Postprocessor : Reading a file - jmeter

I am using the below script in a Beanshell Postprocessor
import java.io.*;
File f =new File ("C:\Users\xxxxx\Desktop\testresults.csv");
FileWriter fw=new FileWriter(f,true);
BufferedWriter bw=new BufferedWriter(fw);
var r=prev.getResponseCode();
if (r.equals("200"))
{
bw.write("Test Passed");
}
else
{
bw.write("Test failed");
}
bw.close();
fw.close();
But I am getting the below error
BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.io.*; File f =new File ("C:\Users\xxxxx\Desktop\testresults.csv") . . . '' Token Parsing Error: Lexical error at line 2, column 23. Encountered: "U" (85), after : ""C:\".
What could cause the above error.

You need to escape a backslash with a backslash like:
C:\\Users\\xxxxx\\Desktop\\testresults.csv
or use a forward slash instead:
C:/Users/xxxxx/Desktop/testresults.csv
A couple more hints:
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting
If you run your test with 2 or more concurrent threads they will be writing into the same file resulting in data corruption due to a race condition so maybe it worth considering switching to Flexible File Writer instead

Change to JSR223 Post Processor and write as one line (groovy default)
new File("C:\\Users\\xxxx\\Desktop\\\testresults.csv") << (prev.getResponseCode().equals("200") ? "Test Passed" : "Test failed")

Related

Jmeter BeanShellSampler error: Error invoking bsh method: eval import org.apache.commons.io.FileUtils

I use BeanShell code loading 100s of sql files in jmeter:
import org.apache.commons.io.FileUtils;
File folder = new File("D:\\sql99");
File[] sqlFiles = folder.listFiles();
for (int i = 0; i < sqlFiles.length; i++) {
File sqlFile = sqlFiles[i];
if (sqlFile.isFile()) {
vars.put("query_" + i,sqlFile.getName(),
FileUtils.readFileToString(sqlFiles[i]));
}
}
but get error info :
17:42:03,301 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.commons.io.FileUtils; File folder = new File("D:\sql99"); Fi . . . '' : Error in method invocation: Method put( java.lang.String, java.lang.String, java.lang.String ) not found in class'org.apache.jmeter.threads.JMeterVariables'
I want to get each sql execute time in jmeter results tree. How to fix code?
Thanks!
You're trying to call JMeterVariables.put() function which accepts 2 Strings as the parameters passing 3 Strings
The correct syntax is vars.put("variable-name", "variable-value"); so you need to decide how to amend this line:
vars.put("query_" + i, sqlFile.getName(), FileUtils.readFileToString(sqlFiles[i]));
so it would contain only 2 parameters instead of 3.
Also since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting mainly for performance reasons so it might be a good option for switching (the same code will work in Groovy without changes assuming you fix the issue with vars.put() function call)

Error on accessing Output Variable in beanshell preprocessor in Jmeter

I am unable to print 'Output Variable' value of foreach Controller in Beanshell Pre/Post-processor in Jmeter.
log.info("inside hash"+ ${current_file} ); //current_file is the Output variable name defined in foreach controller and has the value of current file path.
File file=new File(${current_file});
byte[] content = FileUtils.readFileToByteArray(file);
Whenever I execute the tests, I get this error:
2021-12-15 19:58:25,208 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``import org.apache.commons.io.FileUtils; import org.apache.jmeter.services.FileSe . . . '' Encountered "( "inside hash" + C :" at line 4, column 9.
Can anyone help me fix this error?
Don't inline JMeter functions or variables in form of ${current_file}, use vars shorthand for JMeterVariables class instance instead
Something like:
String current_file = vars.get("current_file");
log.info("inside hash"+ current_file );
File file=new File(current_file);
Don't use Beanshell, since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, there is a chance that your code will just start working after switching to Groovy or at least you will get more informative errors.

Beanshell Preprocessor in jmeter getting an error

For encrypting the input I am using the below code but facing the error
import java.util.Base64;
String plainPassword=vars.get("PW");
log.info(plainPassword);
String encodedPassword = new String(Base64.encodeBase64(plainPassword.getBytes()));
vars.put("encodedpassword", encodedPassword);
log.info("encodedpassword");
ctx.getCurrentSampler().getArguments().getArgument(0).setValue(encryptedpassword);
Error says:
Problem in BeanShell script. org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval
Sourced file: inline evaluation of: import java.util.Base64;
String plainPassword=vars.get("PW");
log.info(plainPa . . . : Typed variable dec
I fail to see encodeBase64() function in java.util.Base64 JavaDoc so double check the source from which you copied and pasted it.
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so you can change 2nd line of your "script" to something like:
String encodedPassword = plainPassword.bytes.encodeBase64().toString()
Full correct code just in case:
String plainPassword=vars.get("PW");
log.info(plainPassword);
String encodedPassword = plainPassword.bytes.encodeBase64().toString();
vars.put("encodedpassword", encodedPassword);
log.info(encodedPassword);
sampler.addNonEncodedArgument('', encodedPassword, '');
Demo:
More information: Apache Groovy - Why and How You Should Use It

Beanshell Script throws error while running from terminal but it runs perfectly in GUI mode in JMETER

I tried to run the following script:
import org.apache.commons.io.FileUtils; // necessary import
int lines = FileUtils.readLines(new File("${testPlanFileDir}/csv/test_smtp_save.csv")).size() - 1; // get lines count
vars.put("lines", String.valueOf(lines)); // store the count into "lines" variable
To get the number of lines in my csv, so that I can execute a loop according to the number of lines in the CSV file.
The script above runs perfectly if I run from GUI mode, but when I run from terminal then it throws following error.
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval
Sourced file: inline evaluation of:
``import org.apache.commons.io.FileUtils; // necessary import int lines = FileUtil . . . ''
: Typed variable declaration : Method Invocation FileUtils.readLines
How do you get this ${testPlanFileDir} variable value? Apart from it the code looks good.
If you want to have more relevant error message you can try putting your code into the try block:
import org.apache.commons.io.FileUtils;
try {
int lines = FileUtils.readLines(new File("${testPlanFileDir}/csv/test_smtp_save.csv")).size() - 1;
vars.put("lines", String.valueOf(lines));
}
catch (Throwable ex) {
log.error("Error in Beanshell", ex);
throw ex;
}
And look into jmeter.log file - it will contain the "usual" stacktrace.
Alternatively you can add debug() command to the very beginning of your Beanshell script - it will toggle debugging output to stdout
See How to Use BeanShell: JMeter's Favorite Built-in Component for more Beanshell-related tips and tricks
Replace ${testPlanFileDir} by:
vars.get("testPlanFileDir")
You should avoid using Beanshell in favor of JSR223+Groovy+Cache which is embedded in JMeter 3.0, see:
http://jmeter.apache.org/changes.html
https://www.ubik-ingenierie.com/blog/jmeter_performance_tuning_tips/
I used this to get the current directory of .jmx file.
Declared varaible TestPlanFileDir as;
${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}

JMeter / Beanshell "Error invoking bsh method: eval Sourced file:"

I'm having an issue in JMeter wherein I receive this error
2014/08/14 14:13:26 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String RequestUrl = vars.get("RequestUrl"); String[] params = RequestUrl.split(" . . . '' : Typed variable declaration
2014/08/14 14:13:26 WARN - jmeter.extractor.BeanShellPostProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String RequestUrl = vars.get("RequestUrl"); String[] params = RequestUrl.split(" . . . '' : Typed variable declaration
I have no clue whats wrong, and the code otherwise seems to be working. Can anyone give me some advice?
Here is the block of code in question:
String RequestUrl = vars.get("RequestUrl");
String[] params = RequestUrl.split("\\?");
String RequestTask = params[1].split("\\&")[1].split("=")[1];
System.out.println(RequestTask);
vars.put("RequestTask",RequestTask);
it should probably be mentioned that the code is in a post processor, which is paired with an Xpath extractor for "RequestUrl"
Edited to include entire error
I don't see your URL and what does XPath query return but in any case your URL parsing logic looks flaky as it strongly dependent on parameters order and presence and may bite you back in future in case of request URL change i.e. extra parameter or changed parameters order or something encoded, etc.
See below for reference:
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.net.URI;
import java.util.List;
String url = vars.get("RequestUrl");
List params = URLEncodedUtils.parse(new URI(url), "UTF-8");
for (NameValuePair param : params) {
if (param.getName().equals("put your actual param name here")) {
vars.put("RequestTask", param.getValue());
}
}
Also it worth checking out How to use BeanShell: JMeter's favorite built-in component for troubleshooting tips. In general to localize error logging should be used like:
log.info("something");
log.error("something else");
So if you don't see message in the log than Beanshell wasn't able to execute the line and failed somewhere above.
Also Beanshell error messages aren't very informative, I use the following construction in my scripts:
try {
//script logic here
}
catch (Throwable ex) {
log.error("Failed to do this or that", ex);
}
So error stracktrace could be read in jmeter.log file.
Hope this helps.
Could you show the whole error?
Try adding one statement after the other to see which one is root cause.
I suppose you may be making hypothesis on results (array access) which may be cause of issue.
if you are coverting a VuGen recorded JMS script to JMeter, then you have to look for the lr functions copied which WILL throw this/similar error.
For eg: int orderlinecount = Integer.parseInt(lr.eval_string("strInt"));
You have to make sure your script is free of all lr - related functions in order for the jmeter to successfully executed your script.

Resources