JMeter Beanshell - save file as pdf - jmeter

Currently I am saving variable values in ".txt" file using beanshell post-processor, I want to save variable value into a pdf file , is there any way I can achieve it?
To save variable value in a text file, i am using below code:
var1= vars.get("myVariableValue");
f = new FileOutputStream("D:/myTextFile.txt",true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(var1);
f.close();

You need an external library like PdfBox for this
You will need to have PDFBox in JMeter Classpath
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting
Assuming all above:
Download pdfbox-2.0.24.jar and fontbox-2.0.24.jar files and put them to "lib" folder of your JMeter installation
Restart JMeter to pick up the "jar"
Add an appropriate JSR223 Test Element to your Test Plan
Put the following code into "Script" area:
import org.apache.jmeter.threads.JMeterVariables
JMeterVariables vars = new JMeterVariables()
vars.put('myVariableValue','hello')
def document = new org.apache.pdfbox.pdmodel.PDDocument()
def page = new org.apache.pdfbox.pdmodel.PDPage()
document.addPage(page)
def contentStream = new org.apache.pdfbox.pdmodel.PDPageContentStream(document, page)
contentStream.setFont(org.apache.pdfbox.pdmodel.font.PDType1Font.COURIER, 12)
contentStream.beginText()
contentStream.showText(vars.get('myVariableValue'))
contentStream.endText()
contentStream.close()
document.save('myPDFFile.pdf')
document.close()
That's it, you should see myPDFFile.pdf file in JMeter's working directory

Related

How to calculate average response of 100 threads in bean shell sampler from a .csv file and write it to a .html file

I have Response data of each thread in a .csv file. Now once all the threads run and saved response result in a .csv file or .jtl how to calculate the average of all the thread response and how to calculate min and max of those responses in beanshell and write the average , min and max result in a .html file through beanshell sampler
The easiest option would be going for JMeterPluginsCMD Command Line Tool which can export Aggregate Report in CSV format. The relevant command line would be something like:
JMeterPluginsCMD--generate-csv test.csv --input-jtl results.jtl --plugin-type AggregateReport
You can install JMeter Plugins Command Line Tool using JMeter Plugins Manager
If you still want to go for scripting make sure to choose the most performing scripting option which is JSR223 Sampler and Groovy language. Example Groovy code to calculate min, max and avg values from the CSV file would be something like:
def csvFile = new File('test.csv')
log.info('--- CSV File contents ---')
log.info(csvFile.text)
log.info('-------------------------')
def responseTimes = csvFile.readLines().each {}.collect {responseTime -> responseTime as long}
log.info('Avg:' + responseTimes.sum() / responseTimes.size())
log.info('Max: ' + responseTimes.max())
log.info('Min: ' + responseTimes.min())
Demo:

Write JDBC query results to CSV file?

I would like to setup a test plan to execute a query and write the results to a csv file.
Following the advice from this question:
https://sqa.stackexchange.com/questions/26456/write-jdbc-request-results-to-csv-file
I have setup my test plan. It runs without issue, but a foo.csv file is not created.
this is the code in the JSR223 preprocessor:
resultSet = vars.getObject("resultSet");
StringBuilder result = new StringBuilder();
for (Object row : resultSet ) {
iter = row.entrySet().iterator();
while (iter.hasNext()) {
pair = iter.next();
result.append(pair.getValue());
result.append(",");
}
result.append(System.getProperty("line.separator"));
}
org.apache.commons.io.FileUtils.writeStringToFile(new File("foo.csv"), result.toString(), "UTF-8");
The file is being written in current working directory, you can locate where JMeter written it by running the following command in the Terminal application:
find / -type f -name 'foo.csv'
You can also amend the last line of code in order to explicitly specify full path to the CSV file like:
org.apache.commons.io.FileUtils.writeStringToFile(new File("/Users/aoppenheim/Desktop/foo.csv"), result.toString(), "UTF-8");
Also I would suggest switching "Language" to groovy as java assumes using Beanshell interpreter and it might become a performance bottleneck in case of high loads. See Apache Groovy - Why and How You Should Use It guide for more details.
This was actually working, the csv file was just not being written where I expected. I added this to find the file:
log.info(System.getProperty("user.dir"));

Getting/using output of CMD window of Jmeter

I,m running a Java file from BeanShell Sampler in jmeter, I'm getting the output successful in cmd windows of jmeter. The output comprises of series of logger files,I need to extract only a specified string from the cmd window and use it for another sample
Given you run your program using i.e. ProcessBuilder you should be able to access its output via Process.getInputStream() method
Process process = new ProcessBuilder('c:\\apps\\jmeter\\bin\\jmeter.bat', '-v').start()
String output = org.apache.commons.io.IOUtils.toString(process.getInputStream(),'UTF-8')
log.info('My program output is:')
log.info(output)
Also I would recommend considering switching to JSR223 Sampler and Groovy language as this way it will be much faster and easier:
def output = "jmeter.bat -v".execute().text
log.info('My program output is:')
log.info(output)
Demo:
This java bean shell Command made the console out by j meter that is std out to be written in a file
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("D:\\dir1\\dir2\\abc.out")),true));
Make sure your path to file should have double backward slash

Running a jmeter test via Blazemeter Taurus and Jenkins

I am having issues with my jmeter test.
I am using Blazemeter Taurus (bzt command) to run it, and I run it as a Jenkins job.
My issue is:
I created user defined values, which I set as Jmeter properties so I can pass them params from the command line:
example for a property I set
The issue occurs when I pass a number:
bzt -o modules.jmeter.properties.profileId=413 -o modules.jmeter.properties.lab=8050
these are parsed as 8050.0 and 413.0
Because the "lab" param is embeded in a url, it breaks the url.
When running this via command line with the jmeter command, this works fine.
I tried working around this with a bean shell sampler that does the following:
int a = Integer.parseInt(vars.get(${lab}));
String raw = String.ValueOf(a);
String processed = raw.substring(0,5);
vars.putObject("lab" ,new String(processed));
props.put("lab", lab);
log.info("this is the new " + ${lab});
but this fails.
any help would be appreciated.
In regards to Taurus issue - report it via Taurus support forum
In regards to Beanshell workaround - your code is not very correct, you need to amend it as follows:
int lab = (int)Double.parseDouble(props.get("lab"));
int profileId = (int)Double.parseDouble(props.get("profileId"));
props.put("lab", String.valueOf(lab));
props.put("profileId", String.valueOf("profileId"));
log.info("lab=" + lab);
log.info("profileId=" + profileId);
as stuff passed via -o modules.jmeter.properties should be accessed via props shorthand, not vars
Demo:
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using JMeter and Java API from Beanshell test elements in your JMeter test.

run sh script in jmeter

For load testing I want to randomize my testvalues before I run the test in jmeter. To do so, I want to use this bash script:
#! /bin/bash
cat data.dsv | shuf > randomdata.dsv
This should be executed in jmeter. I tried using a BeanShell Sampler with this command (I am using this command to always find the correct paht to the file no matter on which machine I want to execute it):
execute(${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}random.sh)
but I always get this error message:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``execute(/home/user/git/path/'' Encountered "( /" at line 1, column 8.
Any Ideas what to do or is there some best practice I just di not found yet?
I would suggest going for OS Process Sampler instead, it should be easier to use, something like:
In regards to Beanshell approach, there is no need to us __Beanshell function in the Beanshell sampler, besides an instance of Beanshell interpreter is created each time you call the function causing performance overhead. You can just put the code into sampler's "Script" area as
import org.apache.jmeter.services.FileServer;
StringBuilder command = new StringBuilder();
FileServer fileServer = FileServer.getFileServer();
command.append(fileServer.getBaseDir());
command.append(System.getProperty("file.separator"));
command.append("random.sh");
Process process = Runtime.getRuntime().exec(command.toString());
int returnValue = process.waitFor();
return String.valueOf(returnValue);
See How to use BeanShell: JMeter's favorite built-in component guide for information on Beanshell scripting in JMeter.

Resources