Quantcast
Channel: Apache Timeline
Viewing all articles
Browse latest Browse all 5648

How to read a zipped text file and iterate over all the lines

$
0
0
Hi All,

I'd like to create a script that would read a zipped text file, and for
example for each line (passed as variable) send a HTTP request.

So far, I've written a script that works partially :)
Partially, because sending a new line to log.info() prints out this new
line (which is good :) ), but when I set the value of a variable to newly
read line, then the value of that variable remains the same and is always
equal to the first line of that text file.

Please find the code below. To test it:
- create a simple text file with just few lines of random text,
- zip that text file
- Add a JSR223 preprocessor set the script language to Java
- configure the script accordingly
- add a HTTP sampler and add ${CONTEXT} to the "RAW Post Body" field
- check the msg value of the http request in "View Results Tree"

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.log.Logger;
import org.apache.jmeter.threads.JMeterVariables;

public class JmeterZipReader

private String zipFile;
private Logger log;
private String outputVariable;
private JMeterVariables vars;

JmeterZipReader(String zipFile, Logger log, String outputVariable,
JMeterVariables vars){
this.zipFile = zipFile;
this.log = log;
this.outputVariable = outputVariable;
this.vars = vars;

// textFile is the name of the text file inside the zip file
public void read(String textFile){
ZipFile zip;
ZipEntry ze;
InputStream input;
BufferedReader br;

try {
zip=new ZipFile(this.zipFile);
ze=zip.getEntry(textFile);
input = zip.getInputStream(ze);
br = new BufferedReader(new InputStreamReader(input,
"US-ASCII"));

String line;
int cnt = 0;
while((line = br.readLine()) != null & cnt <= 10) {
this.vars.put(this.outputVariable, line);
log.info(line);
cnt += 1;

br.close();
zip.close();

catch (Exception e) {
log.error("Unhandled exception:");
e.printStackTrace();

JmeterZipReader jzr = new JmeterZipReader("/path/to/a/test.zip", log,
"CONTEXT", ctx.getVariables());
jzr.read("test.csv");

Many thanks,
Janusz

Viewing all articles
Browse latest Browse all 5648

Trending Articles