1
votes

I am new to using Beanshell/Java in my JMeter scripts. I have following code in my JMeter Beanshell Processor.

int count = Integer.parseInt(vars.get("student_id_RegEx_matchNr"));
String delimiter = ",";
StringBuffer sb = new StringBuffer();
for(int i=1;i<=25;i++) { 
sb.append(vars.get("student_id_RegEx_" + i));
if (i == count){
break; //to eliminate comma after the array
}else {
sb.append(delimiter);
}
}
vars.putObject("myUnsortedVar",sb.toString());

I get following as output when I run script:

myUnsortedVar=5,6,2,3,1,4

I want it to be sorted numerically like this and also stored in a new variable named "sortedVar".

1,2,3,4,5,6

What code can I use to sort this and also store in a new variable so I can use the sorted array in coming JMeter requests. Thanks for help.

4

4 Answers

1
votes

Taking sb.toString() = "5,6,2,3,1,4".

  • Use String::split() to convert from String to String[].
  • Use Arrays::sort() to sort the array
  • Use Arrays.toString() to convert from String[] to String

String[] sortedArray = Arrays.sort(sb.toString().split(","));
vars.putObject("mySortedVar", Arrays.toString(sortedArray));
0
votes

I suppose that in bean shell you may use the same as in Java. Once you fill StringBuffer, there is not easy way to sort the contents. Therefore I would store the contents first into an intermediate ArrayList<String> (or even better ArrayList<Integer> if you always get numbers), then sort it using Collections.sort, and then use another for cycle to put the list's contents into StringBuffer using the comma delimiter.

0
votes

You could do something like:

char [] responseCharArray = vars.get("myUnsortedVar").toCharArray();
Arrays.sort(responseCharArray);
String mySortedString = Arrays.toString(responseCharArray);    
vars.put("mySortedVar", mySortedString.replaceAll("\\,\\,","").replaceAll(" ",""));

See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter

-1
votes

As OndreJM suggested, you need to change your approach. Instead of storing values in StringBuffer, store them in ArrayList and then use Collections.sort to sort it. Following code should work for you.

// create an ArrayList
ArrayList strList = new ArrayList();
for (int i=0;i<25; i++){
strList.add(vars.get("student_id_RegEx_" + String.valueOf(i+1)));
}
// sort this ArrayList
Collections.sort(strList);
// use StringBuilder to build String from ArrayList
StringBuilder builder = new StringBuilder();
for (String id: strList){
builder.append(id);
builder.append(",");
}
builder.deleteCharAt(builder.length()-1);
// finally put in variable using JMeter built in 'vars.put'
// do not use vars.putObject, as you can not send object as request parameter
vars.put("sortedVar", builder.toString());