Jmeter JSR223 Sampler - Unable to Write Data To CSV File

纵然是瞬间 提交于 2021-02-08 08:54:24

问题


I'm using Jmeter v 4.0 r1823414. According to this answer, there is an advisory to use JSR223 PostProcessor, verbatim:

it is recommended to use Groovy for any form of scripting to consider migrating to JSR223 PostProcessor

Before this approach I tried to use BeanShell Sampler to simply write data to csv file. The code sample I took from the blazemeter tutorial page. However, I was getting error

Sourced file: inline evaluation of: ``import java.io.FileWriter; import java.util.Arrays; import java.io.Writer; impor . . . '' : Typed variable declaration : Attempt to access property on undefined variable or class name

Well, since it was suggested to move to JSR223 Sampler (or PostProcessor, not sure what's the difference between them in terms of functionality), I modified the code a little bit to be more Java based to be used in JSR223 Sampler:

import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;

public class Main {

    //Default separator
    private static char SEPARATOR = ',';

    //get path of csv file (creates new one if its not exists)
    private static String csvFile = "C:/TiredOfProgramming/Work/results.csv"; // for example '/User/Downloads/blabla.csv'

    private static String[] params = {"hello", "world", "jmeter"};

    //function write line in csv
    private static void writeLine(FileWriter writer, String[] parameters, char separator) throws IOException
    {
        boolean firstParameter = true;
        StringBuilder stringBuilder = new StringBuilder();
        String parameter = " ";

        for (int i = 0; i < parameters.length; i++)
        {
            //get param
            parameter = parameters[i];
            log.info(parameter);

            //if the first param in the line, separator is not needed
            if (!firstParameter)
            {
                stringBuilder.append(separator);
            }

            //Add param to line
            stringBuilder.append(parameter);

            firstParameter = false;
        }

        //prepare file to next line
        stringBuilder.append("\n");

        //add to file the line
        log.info(stringBuilder.toString());
        writer.append(stringBuilder.toString());
    }

        FileWriter fileWriter = new FileWriter(csvFile, true);
        writeLine(fileWriter, params, SEPARATOR);

        //proper close to file
        fileWriter.flush();
        fileWriter.close();
}

This particular script fails with the message:

Script8.groovy: 15: unexpected token: hello @ line 15, column 39. private static String[] params = {"hello", "world", "jmeter"};

If I test this in IntelliJ IDE with just wrapping writeLine method into the main method, everything works fine

package com.tiredofprogramming;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;

public class Main {

    //Default separator
    private static char SEPARATOR = ',';

    //get path of csv file (creates new one if its not exists)
    private static String csvFile = "C:\\TiredOfProgramming\\Work\\results.csv"; // for example '/User/Downloads/blabla.csv'

    private static String[] params = {"hello", "world", "jmeter"};

    public static void main(String[] args) throws IOException {
        FileWriter fileWriter = new FileWriter(csvFile, true);
        writeLine(fileWriter, params, SEPARATOR);
        //proper close to file
        fileWriter.flush();
        fileWriter.close();
    }


    //function write line in csv
    private static void writeLine(FileWriter writer, String[] parameters, char separator) throws IOException
    {
        boolean firstParameter = true;
        StringBuilder stringBuilder = new StringBuilder();
        String parameter = " ";

        for (int i = 0; i < parameters.length; i++)
        {
            //get param
            parameter = parameters[i];
            System.out.println(parameter);

            //if the first param in the line, separator is not needed
            if (!firstParameter)
            {
                stringBuilder.append(separator);
            }

            //Add param to line
            stringBuilder.append(parameter);

            firstParameter = false;
        }

        //prepare file to next line
        stringBuilder.append("\n");

        //add to file the line
        System.out.println(stringBuilder.toString());
        writer.append(stringBuilder.toString());

  }
}

My question is: does groovy sampler understand Java (in one of SO post I saw mention that Groovy understands 99% of the java syntax). Was anyone ever successful at writing data into the csv file using Jmeter?


回答1:


Try out this slight modification:

//Default separator
char SEPARATOR = ',';

//get path of csv file (creates new one if its not exists)
String csvFile = "C:\\TiredOfProgramming\\Work\\results.csv"; // for example '/User/Downloads/blabla.csv'

def params = ["hello", "world", "jmeter"];

//function write line in csv
def writeLine(FileWriter writer, List<String> parameters, char separator) throws IOException {
    boolean firstParameter = true;
    StringBuilder stringBuilder = new StringBuilder();
    String parameter = " ";

    for (int i = 0; i < parameters.size(); i++) {
        //get param
        parameter = parameters[i];
        log.info(parameter);

        //if the first param in the line, separator is not needed
        if (!firstParameter) {
            stringBuilder.append(separator);
        }

        //Add param to line
        stringBuilder.append(parameter);

        firstParameter = false;
    }

    //prepare file to next line
    stringBuilder.append("\n");

    //add to file the line
    log.info(stringBuilder.toString());
    writer.append(stringBuilder.toString());
}

FileWriter fileWriter = new FileWriter(csvFile, true);
writeLine(fileWriter, params, SEPARATOR);

//proper close to file
fileWriter.flush();
fileWriter.close();

However there are easier method to achieve the same in Groovy, check out:

  • Groovy Goodness: Working with Files
  • Apache Groovy - Why and How You Should Use It



回答2:


You can try out the code below. It is a simple code snippet but you can successfully write into csv file from Jmeter using JSR223 Postprocessor.

//get the JSON response from prev sampler

import com.eclipsesource.json.*;
import org.json.JSONArray;
import org.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

    String getResponse = prev.getResponseDataAsString();

    //parse the response and convert to string
    JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
    String parResponse = parser.parse(getResponse);

    String preResponse = parResponse.toString();
    //replace all commas with a semi-colon
    String csvResponse = preResponse.replaceAll(",", ";");

    //log response to file
    logFileName = "C:/apache-jmeter-5.1.1/Web_Service_Output.csv";
    BufferedWriter outLog = new BufferedWriter(new FileWriter(logFileName, true));
    outLog.write(csvResponse + "\n");
    outLog.close(); 


来源:https://stackoverflow.com/questions/51597623/jmeter-jsr223-sampler-unable-to-write-data-to-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!