Monday, November 18, 2013

Beanshell Script Examples (Random string & logging to external file)

Beanshell script examples for generating random string & logging data to external file
Add the BeanShell Post Processor to the required request
Copy the below code to the Script window
Modify the script as per the requirement (assign the parameters to the variables)

Generate Random string:

// Generates a random string
import java.util.Random;

chars = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
int string_length = 32;
randomstring ="";
    for (int i=0; i<string_length; i++) {
        Random randomGenerator = new Random();
      int randomInt = randomGenerator.nextInt(chars.length());
        randomstring += chars.substring(randomInt,randomInt+1);               
    }
vars.put("uniqueStr",randomstring);

Logging JMeter data to external file:

//Assign to the variables
randomstr1 = vars.get("uniqueStr");
dtime11 = vars.get("dtime1");
rnd1 = vars.get("rnd");
regpass1 = vars.get("regpass");

//logs the information to jmeter.log
log.info(randomstr1);
log.info(dtime11);
log.info(rnd1);
log.info(regpass1);

//Creating an file object and writing to a csv file
FileWriter fstream = new FileWriter("C:\\apache-jmeter-2.9\\beanshell_log\\detail_log.csv",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(randomstr1+dtime11+rnd1+","+regpass1+"\n");
out.close();

2 comments: