Search code examples
javajmeterbeanshell

Pass an output of stdout(jmeter) and pass it as variable string to another sampler


This is my scenario I'm running a java program in bean shell sampler in j meter and getting the required string in STD OUT console. Even i have successfully wrote the required string to a output file. I need to extract the string from the file or console and pass it to other samples(the required string is present along with lot of information in the output so i need to extract string like "Required String:following Character" Thanks in advance


Solution

  • When ever You need to direct a output Use this following code

    System.setOut(new PrintStream(new BufferedOutputStream(new
    FileOutputStream("path/to/file/output.txt")), true));
    

    Say I'm Calling a external java file which is included in test plan (as some jar file)

    Write This code in Beanshell Sampler

    import userdir.UserClass;
    
    UserClass obj1 =new UserClass(); obj1.method1();
    
    System.setOut(new PrintStream(new BufferedOutputStream(new
    FileOutputStream("path/to/file/output.txt")), true));
    

    Now whatever ouput is produced by Userclass in STD OUT will be directed to the ouput.txt

    Code to Extract the required string in Beanshell Post Processor from the file ouput.txt

    import java.io.FileNotFoundException;   
    import java.util.Scanner;   
    import org.apache.jmeter.samplers.SampleResult;
    
    File file = new File("path/to/file/output.txt");  
    String word = "Req String1";  
    String word2 = "Req String2";  
    Scanner scanner = null;  
    String line;   
    String s1;  
    String s2;     
    try {
       scanner = new Scanner(file); }    
      catch(FileNotFoundException e) {     //handle this }
    
     //now read the file line by line     
    
     while (scanner.hasNextLine()) {  
    line = scanner.nextLine();
    
    if(line.contains(word)) {   
       log.info(line);  
       s1=line;    
      //now the entire line along with Req String1 will be stored in s1
    }
    
    if(line.contains(word2)) { 
      log.info(line);
       s2=line;
    }
     }
    
    log.info("The value in Encrypt str  ="+s1);  
    log.info("The value in Signatr str  ="+s2);  
    String[] s1 = s1.split(":");  
    String[] s2 =s2.split(":");  
    //since my value in the line is Req String1:needed data
    
    props.put("s1",s1[1]);  
    props.put("s2",s2[1]);
    
    log.info("The value in ORIGINAL Req String1  ="+props.get("s1"));
    log.info("The value in ORIGINAL Req String2  ="+props.get("s2"));
    scanner.close();
    

    Hope this is useful to all