How to get Summarizer output in file - jmeter

I'm new to JMeter. I want to get Summarizer output to get test progress not in stdout.
(summary = 4 in 3,5s = 1,2/s Avg: 1012 Min: 999 Max: 1044 Err: 4 (100,00%))
for example a list contains these values
............
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault(
"summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// String TestResut=Summariser.format(null,null,null);
String csvFile = "filePath";
MyResultCollector csvlogger = new MyResultCollector(summer);
csvlogger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], csvlogger);
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();

First initialize the list with 3 variables like below
vars.put("a","NA");
vars.put("b","NA");
vars.put("c","NA");
when you get values for those variables, put into variables like below.
vars.put("a","1/2S");
Finally write the values into the file like below:
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(vars.get("summaryReportFile.csv"),true);
out = new BufferedWriter(fstream);
String summary = "+vars.get("a")+","+vars.get("b")+","+vars.get("c")+"\n";
out.write(summary);
out.close();
fstream.close();

Related

How to replace the value inside a file that was located in local using javascript?

I have a scenario where after reading the file, it needs the value inside that file to be replaced.
We have this script from our JMeter where we based our script from. (Please refer to the code below)
def file = new File('C:/Peak2020/China/${__time(YMMdd)}-085644-336_000101-plant 8956.xml')
def newConfig = file.text.replace('596791365558876095', '000101')
file.text = newConfig
def newConfig2 = file.text.replace('C6D-CN-NBB2829A', 'C7D-CN-NBB$4568792B')
file.text = newConfig2
def sku = file.text.replace('323094-01', '45903-01')
file.text = sku
I tried doing it in the Neoload, using the replace() but it's not working. It does copy the file from sourcefolder to destinationfolder but the value was not changed. (Please refer to the code below)
var file = new java.io.BufferedReader(new java.io.FileReader("C:\\Peak2020\\China\\testSource1.xml"));
var line = file.readLine();
var id = line.replace(new RegExp("596791365558876095", "12345678"), "");
var destFile = line;
var writer = new java.io.FileWriter("C:\\Peak2020\\Teemp\\TestDestination3.xml",true);
writer.write(destFile);
writer.close();
Does anyone knows what right javascript code to use? Thank you.
String is immutable in Javascript and Java you are replacing it in
var id = line.replace(new RegExp("596791365558876095", "12345678"), "");
but then you use the var line again for the new variable.
var destFile = line;
it should be
var destFile = id;
because replace will return a new string with the replaced value.

Is it possible to generate UUID v1 with JMeter?

I read JMeter's manual and saw that there is __uuid() function for JMeter. It allows to generate UUID type 4 for JMeter tests. Is it possible to generate UUIDv1 in JMeter or maybe some plugin exists.
I would recommend taking the following steps:
Download Jug library (for example from here) and drop the .jar somewhere to JMeter Classpath
Restart JMeter to pick the .jar up
Once done you should be able to generate UUIDv1 using JSR223 Test Elements and Groovy language like:
import com.fasterxml.uuid.EthernetAddress
import com.fasterxml.uuid.Generators
import com.fasterxml.uuid.impl.TimeBasedGenerator
def addr = EthernetAddress.fromInterface()
def gen = Generators.timeBasedGenerator(addr)
def v1uuid = gen.generate()
log.info(v1uuid.toString())
Demo:
References:
Generating version 1 UUIDs
Groovy is the New Black
In jmeter you can add JSR 223 Sampler choose Java language and execute java code for UUID version 1:
String timeuuid = com.datastax.driver.core.utils.UUIDs.timeBased().toString();
And then add it to Jmeter variable:
vars.put("myUUID", timeuuid);
First, we'll generate the 64 least and most significant bits as long values:
private static long get64LeastSignificantBitsForVersion1() {
Random random = new Random();
long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long variant3BitFlag = 0x8000000000000000L;
return random63BitLong + variant3BitFlag;
}
private static long get64MostSignificantBitsForVersion1() {
LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
Duration duration = Duration.between(start, LocalDateTime.now());
long seconds = duration.getSeconds();
long nanos = duration.getNano();
long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
long version = 1 << 12;
return
(timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
}
We can then pass these two values to the constructor of the UUID:
public static UUID generateType1UUID() {
long most64SigBits = get64MostSignificantBitsForVersion1();
long least64SigBits = get64LeastSignificantBitsForVersion1();
return new UUID(most64SigBits, least64SigBits);
}

JDBC ResultSet to ArrayList, ArrayList to .txt file

I got the following piece of code that retrieves all rows in a table:
String MakeTXT = "USE SRO_VT_SHARD Select * from _RefTeleLink";
pst = conn.prepareStatement(MakeTXT);
rs = pst.executeQuery();
ArrayList<String> links = new ArrayList<>();
int i = 1;
String rows = "";
while (rs.next()) {
for (i = 1; i <= 22; i++) {
links.add(rs.getString(i));
if (i == 22) {
links.add("\n");
}
}
}
rows = String.join("\t", links);
System.out.println(rows);
}
}
What I want to do is:
Select all rows from the table. See result: prnt.sc/egbh4o
Write all selected rows to a .txt file
.txt file has to look something like this (literally copy pasted the rows): http://prntscr.com/egbhn4
What my code currently outputs:
output
It does this because there are 22 columns, and when the loop reaches 22, it adds an enter to the ArrayList.
What I'm actually looking for is a way to copy an entire row using ResultSet, instead of using a for loop to loop 22 times, and make a row of the 22 results.
Have looked everywhere but couldn't find anything.. :(
You do not need an ArrayList to hold the column values as they are read. I'd better use a StringBuilder as show below, concatenating tabs inside the loop and then replacing the last one with a line feed.
String MakeTXT = "USE SRO_VT_SHARD Select * from _RefTeleLink";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(MakeTXT);
List<String> rows = new ArrayList<>();
StringBuilder row = new StringBuilder();
ResultSetMetaData meta = rs.getMetaData();
final int colCount = meta.getColumnCount();
while (rs.next()) {
row.setLength(0);
for (int c=0; c<=colCount; c++)
row.append(rs.getString(c)).append("\t");
row.setCharAt(row.length()-1, '\n');
rows.add(row.toString());
}
rs.close();
stm.close();

Jmeter error when trying to create file using beanshell

This is my beanshell code to create a file and append one line to it:
FileName = vars.get("fileName");
f = new FileOutputStream(FileName,true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print("Test Set: " + FileName);
f.close();
I get fileName from a regex extractor in a previous sampler. I have checked debug postprocessor and confirmed this is set correctly. However I get this error in sampler result:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``FileName = vars.get("fileName"); f = new FileOutputStream(FileNam . . . '' : Object constructor
The problem is: if FileName is null, the constructor for FileOutputStream will throw an exception, and BeanShell is not great in showing underlying exceptions. So what you need is to handle the case where file name is null:
String fileName = vars.get("fileName");
if( fileName == null )
{
fileName = "mydefaultname"; // assign some default name
}
f = new FileOutputStream(fileName, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print("Test Set: " + fileName);
f.close();
If you don't want to have some default name, you can also quit the script at that point:
if( fileName == null )
{
return;
}

Concatenate variables and create MD5

Using JMeter, I would like to take values from CSV file, concatenate the values and do a MD5 hash on them and then send the value as part of HTTP request using HTTP Request Sampler.
I tried the following but did not get the correct result:
created CSV Data Set Config and added the variables csvVal1,csvVal2,csvVal3;
in the jp#gc-Dummy Sampler i added the following:
${__MD5(${csvval1}+${csvval2}+${csvval3})}
This did not work, what is the right way?
I ended up using BeanShell Preporcessor and used the following script
import java.security.MessageDigest;
String val1 = vars.get("csv_val1");
String val2 = vars.get("csv_val2");
String val3 = vars.get("csv_val3");
String totalString = val1+val2+val3;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(totalString.getBytes("utf-8"), 0, totalString.length());
md5hash = md.digest();
StringBuffer sb = new StringBuffer();
for (int i=0;i<md5hash.length;i++) {
String sval = Integer.toHexString((int) md5hash[i] & 0xFF);
if(sval.length()== 1)
{
sval = "0"+sval;
}
sb.append(sval);
}
log.info("tktest: "+ sb);
vars.putObject("MD5Signature", sb.toString());
There's a new function __digest, currently in nightly builds
In your case to save in MD5Signature variable the result of 3 variable use the following:
${__digest(MD5,${csv_val1}${csv_val2}${csv_val3},,,MD5Signature)}

Resources