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.
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));
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.
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
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());
Related
I have an ArrayList
ArrayList<Integer> al=new ArrayList<>();
al.add(3);
al.add(8);
al.add(123);
al.add(41);
Not i want
String s="3812341";
Can this be done without a loop or by built in methods?
If you are using Java 8, this can be easily solved using Stream API.
String s = al.stream().map(String::valueOf).reduce((x, y) -> x + y).get();
We build a stream using stream() function and maps the Integer value to String value and finally reduces it to a String using reduce() function. This will return an Optional object which is why we are using get() function at the end to get the real value.
you can simply use below code
String s = al.toString().replaceAll("\\[|\\]|\\, ", "");
Hope this helps !!!
I am stuck in a problem where i have to allocate string objects in an array of strings But the problem is i don't know how many string objects i will be putting in this array.
CODE
static String[] decipheredMessage;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage[pointer] = new String();
decipheredMessage[pointer++] = word;
return true;
What i have done here is i have declared an array of strings and since i don't know how many strings my array is going to contain i dynamically create string objects and assign it to the array.
ERROR
$ java SentenceFormation
arms
Exception in thread "main" java.lang.NullPointerException
at SentenceFormation.makeSentence(SentenceFormation.java:48)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.main(SentenceFormation.java:16)
I don't know why i am getting this problem can anybody help me with this.
Thanks in advance.
Dynamic arrays do not work in Java. You need to use one of the fine examples of the collections framework. Import java.util.ArrayList.
static ArrayList<String> decipheredMessage=new ArrayList<>();;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage.add(new String());
decipheredMessage.add(word);
return true;
You can use a List implementation like ArrayList if you don't know how many elements your array will have.
static List<String> decipheredMessage = new ArrayList<>();
...
decipheredMessage.add("my new string");
Check out the List documentation (linked above) to see what APIs are available.
If you are using Java 5 or 6, you'll need to specify the type in the angled brackets above, i.e. new ArrayList<String>().
Try something like this, and read about List
List<String> decipheredMessage = new ArrayList<String>();
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage. add("string1");
decipheredMessage.add("string2");
return true;
I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated
Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,
From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.
I have a HashMap. The key will be a string and value can be anything ranging from a variable to a ArrayList.
The problem is I have an ArrayList. The values stored in the ArrayList are Region1,Region2,Region3,Region4.
So when I put this ArrayList in HashMap and print the HashMap I get the output as
[Region1,Region2,Region3,Region4].
Problem is I need to insert this whole comma separated String in Db and my procedure cannot recognize [] in this output.
How can I solve it..I cannot change anything at DB end.
Here's the code snippet:-
ArrayList<String> Region=new ArrayList<String>();
Region.add("Region1");
Region.add("Region2");
Region.add("Region3");
System.out.println(Region);
Output is [Region1, Region2, Region3]
I put this ArrayList in HashMap
HashMap<String,Object> regionHashMap=new HashMap<String,Object>();
regionHashMap.put("regionssss", Region);
System.out.println(regionHashMap);
Output is {regionssss=[Region1, Region2, Region3]}.
How can i Remove [] from the ArrayList...
I already succedded by using StringBuffer and Iterator but I cannot use it everytime Since I have huge number of ArrayList which will go inside the HashMap..
The String representation of a List automatically encloses with "[ ]" characters.
You could either create your own 'toString' method:
private String listToString(List<?> l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l.size(); i++) {
sb.append(l.get(i));
if (i != l.size() -1) sb.append(", ");
}
return sb.toString();
}
Or, you could use the substring function to remove the braces:
String s = list.toString();
s = s.substring(1, s.length()-1);
Don't use toString() at all. It is not meant to be used to create formatted UI strings. It is a developer tool, not a user presentation tool.
To do what you want is to just create a method to do your display and do the formatting in that method instead.
see this post to get more on this.
Try subclassing HashMap and override the toString() method
I am getting the checked items ids in ListView from List.getCheckedItemIds which returns long array, now how to convert this array to String array ?
long [] long_list = ProcessList.getCheckedItemIds();
String[] string_list = new String[long_list.length];
for(int i = 0; i < long_list.length; i++){
string_list[i] = String.valueOf(long_list[i]);
}
The question may be considered unwarranted a few years ago, but it's worth a new look now considering the recent progress in Java land with regards to the emerging Stream API.
Instead of relying on any third-party API, you can use the built-in Stream API for array operations in Java 1.8 and above.
You can now easily use
String[] yourStringArray = Arrays.stream(yourLongArray).mapToObj(String::valueOf).toArray();
And if your intention is to print yourStringArray, you can then convert it into a string using
String str = Arrays.toString(yourStringArray);
****
Lucky for us, Arrays.toString() operates on all types of arrays, so the whole thing can be simplified to just
String str = Arrays.toString(yourLongArray);
Isn't this cleaner?
You can use org.apache.commons.lang.StringUtils like this:
String[] string_list = StringUtils.join(long_list, ",").split(",");
You can leverage apache's BeanUtils to do Array conversion without doing iteration by yourself like below.
Long[] longArrays= (Long[]) ConvertUtils.convert(stringArrays, Long[].class);
Or with Java 8+,
Object[] array = ...; // or i.e. Long[] array
String[] s = Arrays.stream(array).map(String::valueOf).toArray(String[]::new);
You can make a new String array and pass the values of long array to the string array one by one:
String[] s=new String[long_list.length];
for(int i=0;i<long_list.length;i++)
{
s[i]=String.valueOF(long_list[i]);
}
Sorry for the mistakes. I've updated the code.