How to use cell values of .csv file in jmeter? - java

I have a .csv file which contains the multiple entries of employee names.Now i want to read that .csv file in my jmx script in jmeter. It should be in a way that each thread of my jmx script reads the different value from the .csv file. And then i want to use those cell values in the HTTP Request.
I am using Bean Shell pre processor for it. But it is of no help for me.The below is code which i have written for it
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
CSVReader reader = new CSVReader(new FileReader(C:/Users/manoj/Downloads/View_All_names.csv));
String[] row;
String name;
while ((row = reader.readNext()) != null)
{
name = row[1];
}
The value "name" i want to use it in my HTTP Request then.DO i have to mention this attribute "name" in Test Plan??
Any help is appreciated.

First of all, are you aware of __CSVRead() function? You should be able to use it directly in the place where you need the value from CSV file without having to write a single line of code.
Just in case you still want Beanshell for any reason.
You need to surround the path to CSV file with quotation marks
You need to write the resulting value into JMeter Variables for later reuse.
Where did you get the above code? If CSVReader stands for com.helger.commons.csv.CSVReader from ph-commons-6.2.4.jar - you need to use it a little bit differently, like use List instead of array of strings to wit:
import com.helger.commons.csv.CSVReader;
CSVReader reader = new CSVReader(new FileReader("C:/Users/manoj/Downloads/View_All_names.csv"));
List row;
String name;
int counter = 1;
while ((row = reader.readNext()) != null) {
name = row.get(1).toString();
vars.put("name_" + counter, name);
counter++;
}
After Beanshell PreProcessor finishes its work you will be able to access variables values like:
${name_1}
${name_2}
${name_3}
etc.
vars stands for an instance of JMeterVariables class which provides read/write access to the JMeter Variables in scope. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter tests.

All you need is to put one CSV Data Set Config component, and it will read entries for you. Each line for each thread (user). In the component you need to specify variable name which you will later use in your test plan, as well as the path to your .csv file.
If you put variable name like "name" (w/out quotes) you will use ${name} in requests/samplers where you want to use it.

A simple way to capture the column values from excel in jMeter
Just insert data in excel column wise i.e. horizontally insert all the data and use
${__CSVRead(filePath,ColNum)}

Related

Read specific information from an .xlsx file using java

The xlsx file has contents in the below format enter image description here
I want to capture the information highlighted into different fields that go into the database as a string
Final date would be in the 3rd row highlighted and that would be stored in string finaldate;
Row no :6 that has final status as Fail would go into string Status;
And then,Row 24:DATAID the value before . has to be retrieved like 3ABC36812 has to be stored using string.split(".")[0] into string dataid;
Since these columns might be varying in different rows within the excel sheet,how do i capture these values specifically and accurately using BufferedReader component
String line;
try (BufferedReader br = new BufferedReader(new FileReader(str)))
{
for (int i = 0; i < n; i++)
br.readLine();
line = br.readLine();
System.out.println(line);
if (line.startsWith("FINAL DATE:"))
{
string [] split=line.split(":").[1]
//not sure coz even HH:MM has the colon in it,so how to extract the date value alone
finaldate=split; ///????
}
//so i am checking if the column dataid exists using starts with and then fetch the row below that having the dataid into string data column
if (line.startsWith("DATAID"))
{
needcat=true;
System.out.println( "bye "+needcat);
}
I dont want to use the apache poi since my version of java does not support that and i would prefer to explore using the bufferedreader/filestream components in java
I really don't think you're going to get what you want the way you're trying to do it. Take a look at this page:
https://docs.fileformat.com/spreadsheet/xlsx/
It looks like they're suggesting that .xlsx files are zip files.
If that's true, you're not going to have success the way you're reading it.
I don't understand why you can't use POI. If you need Java prior to 11, maybe you can grab an older copy from 10 years ago or something.
Otherwise, you'll want to use a Zip library to unpack it first.

Using I/O stream to parse CSV file

I have a CSV file of US population data for every county in the US. I need to get each population from the 8th column of the file. I'm using a fileReader() and bufferedStream() and not sure how to use the split method to accomplish this. I know this isn't much information but I know that I'll be using my args[0] as the destination in my class.
I'm at a loss to where to being to be honest.
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
BufferedReader() buff = new BufferedReader(new FileReader(args[0]));
String
}
try {
}
}
The output should be an integer of the total US population. Any help with pointing me in the right direction would be great.
Don't reinvent the wheel, don't parse CSV yourself: use a library. Even such a simple format as CSV has nuances: fields can be escaped with quotes or unescaped, the file can have or have not a header and so on. Besides that you have to test and maintain the code you've wrote. So writing less code and reusing libraries is good.
There are a plenty of libraries for CSV in Java:
Apache Commons CSV
OpenCSV
Super CSV
Univocity
flatpack
IMHO, the first two are the most popular.
Here is an example for Apache Commons CSV:
final Reader in = new FileReader("counties.csv");
final Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for (final CSVRecord record : records) { // Simply iterate over the records via foreach loop. All the parsing is handler for you
String populationString = record.get(7); // Indexes are zero-based
String populationString = record.get("population"); // Or, if your file has headers, you can just use them
… // Do whatever you want with the population
}
Look how easy it is! And it will be similar with other parsers.

Univocity - Detect missing column when parsing CSV

I'm using Univocity library to parse CSV and it works perfectly, but I need a way to detect if the file being parsed has less columns than required
For example, if I'm expecting a 3 columns file, with columns mapped to [H1,H2,H3] then I received a file (which has no headers) that looks like
V1_H1,V1_H2
V2_H1,V2_H2
When using
record.getString("H3");
this would return null, instead, I need this file to either fail to be parsed or I can check if it misses a column and stop processing it
Is there any way to achieve this?
So since my main issue here is to make sure that the headers count is the same as the number of columns provided in the CSV file, and since I'm using an iterator to iterate over records, I've added a check like:
CsvParser parser = new CsvParser(settings);
ResultIterator<Record, ParsingContext> iterator = parser.iterateRecords(inputStream).iterator();
if(iterator.getContext().parsedHeaders().length != settings.getHeaders().length){
throw new Exception("Invalid file");
}
It's working for me, not sure if there is a better way to do it.
I've watched Univocity documentation and I've found here that there is a way to add annotations to the destination objects you are going to generate from the CSV input
#Parsed
#Validate
public String notNulNotBlank; //This should fail if the field is null or blank
#Parsed
#Validate(nullable = true)
public String nullButNotBlank;
#Parsed
#Validate(allowBlanks = true)
public String notNullButBlank;
This will also help you to use the objects instead of having to work with fields.
Hope that helps :-)

How to read external JSON file from JMeter

Is there a way (any jmeter plugin) by which we can have the JMeter script read all the contents(String) from external text file ?
I have a utility in java which uses Jackson ObjectMapper to convert a arraylist to string and puts it to a text file in the desktop. The file has the JSON info that i need to send in the jmeter Post Body.
I tried using ${__FileToString()} but it was unable to deserialize the instance of java.util.ArrayList. It was also not reading all the values properly.
I am looking for something like csv reader where i just give the file location. I need all the json info present in the file. Need to extract it and assign to the post body.
Thanks for your help !!!
If your question is about how to deserialize ArrayList in JMeter and dynamically build request body, you can use i.e. Beanshell PreProcessor for it.
Add a Beanshell PreProcessor as a child of your request
Put the following code into the PreProcessor's "Script" area:
FileInputStream in = new FileInputStream("/path/to/your/serialized/file.ser");
ObjectInput oin = new ObjectInputStream(in);
ArrayList list = (ArrayList) oin.readObject();
oin.close();
in.close();
for (int i = 0; i < list.size(); i++) {
sampler.addArgument("param" + i, list.get(i).toString());
}
The code will read file as ArrayList, iterate through it and add request parameter like:
param1=foo
param2=bar
etc.
This is the closest answer I'm able to provide, if you need more exact advice - please elaborate your question. In the meantime I recommend you to get familiarized with How to use BeanShell: JMeter's favorite built-in component guide to learn about scripting in JMeter and what do pre-defined variables like "sampler" in above code snippet mean.

Load txt's file into Java application and save it to XML's file

I read the next answer about load file into java application.
I need to write a program that load .txt, which contains a list of records. After I parse it, I need to match the records (with conditions that I will check), and save the result to XML's file.
I am stuck on this issue, and I will happy for answer to next questions:
How I load the .txt file into Java?
After I load the file, how I can acsses to the information into it? for example, How I can asked if the first line of one of the records is equal to "1";
How I export the result to XML's file.
one: you need a sample-code for reading a file line by line
two: the split-method of a string might be helpful. For instance getting the number of the first element if information is seperated by a space
String myLine;
String[] components = myLine.split(" ");
if(components != null && components.length >= 1) {
int num = Integer.parseInt(components[0]);
....
}
three: you can just write it like any text-file, or use any XML-Writer you want
Basic I/O
Integer.parseInt(1stLine)
There are a plethora of choices.
Create POJO's to represent the records and write them using XMLEncoder
SAX
DOM..

Categories