3

I am using Java with JSF and Beanshell script. I want to use fields and object of java class in beanshell. I have tried my best to get help from google but couldn't find any helpful information. For example

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import bsh.EvalError;
import bsh.Interpreter;

public class C {

static Map<String,Object> map = new HashMap<String,Object>();
static List<String> list = new ArrayList<String>();
static Map<String,Integer> integerMap = new HashMap<String,Integer>();

public static void main(String[] arg) throws EvalError{
    list.add("Hello");
    list.add("World");
    Interpreter i = new Interpreter();  // Construct an interpreter
    map.put("stringList", list);//in java
    i.eval("map.put(\"stringList\", list)");// gives error
    List list = (List) map.get("stringList");
    for(String str:(List<String>)list){
        System.out.println(str);
    }
  }
}

I want to perform all the operation which is available for collection in java to same object in beanshell.

Jmeter provide such facilities where user can update the variable in beanshell and based on the details given on link, it seems Jmeter is using string map and I want to do same things but it is with objects.

I would appreciate your inputs, if any technology in or framework which can be used to achieve my requirement would be good either java, beanshell, JSF or other available option in java.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Karim Narsindani
  • 434
  • 3
  • 14
  • 38

1 Answers1

1

In JMeter's Beanshell or better JSR223 Sampler (Java language) you can put objects in JMeter variables as put:

JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.putObject("stringList", stringList);

and get:

vars.getObject("stringList");

In Java general case you need to add variable to Beanshell Interpreter with set method:

    list.add("Hello");
    list.add("World");
    Interpreter i = new Interpreter();  // Construct an interpreter

    map.put("stringList", list);//in java
    try {
        i.set("map", map); 
        i.set("list", list); 
        System.out.println(i.eval("map.put(\"stringList\", list)"));
    } catch (EvalError e1) {
        e1.printStackTrace();
    }
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Jmeter is just an example which I gave but I am not looking for jmeter help, I want to achieve this in Java. I appreciate your input – Karim Narsindani Sep 17 '17 at 12:28
  • I accept your answer for this thread, is there any clean way to implement it. I want to avoid setting up variable in beanshell, is there any way to keep it clean like in Jmeter. Refer list link https://stackoverflow.com/questions/46267735/java-with-beanshell-to-access-fields-and-object-with-clean-code – Karim Narsindani Sep 17 '17 at 18:56