I am trying to read an xls file in jmeter using beanshell postprocessor. The error i get in the logs is: "Typed variable declaration : Class: Workbook not found in namespace"
Following is my code.
import java.io.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
FileInputStream(vars.get("jmeterScriptPath")+"\\"+vars.get("VIN")+".xls", true);
Workbook wb = Workbook.getWorkbook(new java.io.File("C:\\datasheet\\RIGUD000000000051.xls"));
Sheet sh = wb.getSheet("RIGUD000000000051");
// To get the number of rows present in sheet
int totalNoOfRows = sh.getRows();
// To get the number of columns present in sheet
int totalNoOfCols = sh.getColumns();
for (int row = 0; row < totalNoOfRows; row++) {
for (int col = 0; col < totalNoOfCols; col++) {
System.out.print(sh.getCell(col, row).getContents() + "\t");
vars.put("responseContent",sh.getCell(col, row).getContents());
}
System.out.println();
}
In order to get it working follow next two steps:
Copy jxl.jar to JMeter's "lib" folder
Restart JMeter - it's required to pick the jxl.jar up.
You should be good to do with your code.
P.S. I would recommend to switch to Apache POI as JExcelApi supports only Excel 2003 documents and now is almost 2016. If you download tika-app.jar it will enable preview of all supported formats in View Results Tree listener and you also will get read/write access to them all from scripting test elements.
See How to Extract Data From Files With JMeter guide for more information on working with binary files in JMeter.
Related
I'm getting error when trying to create a workbook in the Jmeter.
I'm using "tika-app.jar"
After workbook creation is done I want to write data in excel xlx file.
Below is my JSR223 sampler:
Error response which I'm getting is as below:
Can someone help
Copy tika-app-xxx.jar to "lib" folder of your JMeter installation
Restart JMeter to pick the .jar up
Switch to groovy language
Your code should start working without "Class not found" errors
If you're looking for "recipes" with regards to how to fill the Excel file check out Busy Developers' Guide to HSSF and XSSF Features
Just in case a piece of code from the above guide:
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
We tried with the below code and cannot able to open in Microsoft Excel. Is this the right way to generate the .xlsb file using NPOI? Please advise
using (var exportdata = new MemoryStream())
{
var name = output.xlsb;
System.Web.HttpContext.Current.Response.Clear();
workbook.Write(exportdata);
System.Web.HttpContext.Current.Response.ContentType = "application / vnd.ms - excel.sheet.binary.macroEnabled.12";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + name + ";"));
System.Web.HttpContext.Current.Response.BinaryWrite(exportdata.ToArray());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
I am facing one problem during uploading multiple files on server. I implemented some logic and fetched files one by one from a folder . But in HTTP request my URL is something like {Container name} followed by {Filename}.
My problem is in filename parameter value what should i passed so that every files will be uploaded on server .
My code is as below:-
File folder = new File("c:\\Test1\\Test");
File[] files = folder.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
for (int i=0; i < files.length; i++) {
vars.put("file_" + i, files[i].getAbsolutePath());
}
In file path i am passing this ${filesToUpload} ,parameter name and mimetype
I don't think your way is correct (unless you want to build the full raw body), you should rather invoke HTTPSamplerBase.setHTTPFiles() function using the following example steps:
Add JSR223 PreProcessor as a child of the HTTP Request sampler to which you want to add files
Put the following code into "Script" area:
import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.TrueFileFilter
import org.apache.jmeter.protocol.http.util.HTTPFileArg
import java.nio.file.Files
def files = FileUtils.listFiles(new File("c:/Test1/Test"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)
def arguments = []
files.eachWithIndex { file, index ->
arguments.add(new HTTPFileArg(file.getAbsolutePath(), "your_parameter_name", Files.probeContentType(file.toPath())))
}
sampler.setHTTPFiles(arguments as HTTPFileArg[])
That's it, the code will dynamically read the files from folder and add the files from it to the request, just make sure to amend your_parameter_name to the real respective value
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
I have written below code under beanshall post-processor. But when I am running 1000 threads the files are overwriting existing content instated of appending. It is working for 1-5 threads. Can anyone help me on this?
import org.apache.commons.io.FileUtils;
import java.util.ArrayList;
import java.util.Collections;
File fExceptionLog = new File("${logPath}/ExceptionLog.txt");
String extExceptionData= FileUtils.readFileToString(fExceptionLog);
id=vars.get("id");
try{
String cDatestamp="${__time(yyyyMMddHHmmssSSS)}";
String cResponce = prev.getResponseDataAsString();
String cRequest = prev.getQueryString();
String cResponceCode=prev.getResponseCode();
cTransactionName = prev.getSampleLabel();
cResponseTime = prev.getTime();
cSize = prev.getBytesAsLong();
cIsSuccessful =prev.isSuccessful();
File fRequestLog = new File("${logPath}/RequestLog.txt");
File fHitLog = new File("${logPath}/HitLog.txt");
File fResponceLog = new File("${logPath}/ResponceLog.txt");
File fErrorLog = new File("${logPath}/ErrorLog.txt");
String extHitData = FileUtils.readFileToString(fHitLog);
String extRequestData = FileUtils.readFileToString(fRequestLog);
String extResponceData = FileUtils.readFileToString(fResponceLog);
String extErrorData = FileUtils.readFileToString(fErrorLog);
log.info("cResponceCode"+cResponceCode);
FileUtils.writeStringToFile(fHitLog,extHitData+id+"~"+cDatestamp+"~"+cTransactionName+"~"+cResponceCode+"~"+cResponseTime+"~"+cSize+"~"+cIsSuccessful+"\n");
if(cResponceCode.equals("200")){
FileUtils.writeStringToFile(fRequestLog,extRequestData+id+"~"+cDatestamp+"~"+cTransactionName+"~"+cResponce+"\n");
FileUtils.writeStringToFile(fResponceLog,extResponceData+id+"~"+cDatestamp+"~"+cResponceCode+"~"+cResponce+"\n");
}else{
FileUtils.writeStringToFile(fErrorLog,extErrorData+id+"~"+cDatestamp+"~"+cTransactionName+"~"+cResponce+"\n"+id+"~"+cDatestamp+"~"+cResponceCode+"~"+cResponce+"\n");
}
}catch(Exception e){
FileUtils.writeStringToFile(fExceptionLog,extExceptionData+id+"~"+cDatestamp+"~"+cTransactionName+"~"+e+"\n");
}
You're violating at least 3 JMeter Best Practices
You're referring JMeter Variables like ${logPath} while you should be using vars shorthand instead like vars.get("logPath")
You're using Beanshell while starting from JMeter 3.1 you should be using JSR223 and Groovy
And last but not the least, you yourself introduced a race condition so when several threads will be concurrently writing the same file it will result in data loss. You can put this Beanshell test element (along with the parent Sampler(s)) under the Critical Section Controller, but it will reduce concurrency of the parent sampler(s) to only one at a time
If you need to write some some metrics into a custom file in your own format I would rather recommend consider migrating to the Flexible File Writer which is extremely "flexible" with regards to what values is to store and it accumulates multiple entries in memory and flushes them periodically in batch manner so all the data will be stored without collisions.
You can install Flexible File Writer using JMeter Plugins Manager
How to measure size of response data of multiple http samplers in JMeter. I need to find the overall size of all the responses not for individual responses. I am trying to fetch it through a Beanshell code but it displays the size of the last sample executed:-
import java.util.io.*;
import java.lang.io.*;
int totalsize;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
totalsize = totalsize + test;
log.info("totalsize is = "+totalsize);
Thank you.
Use JSR223 code with props and set JMeter property totalsize with 0 at start
props.put("totalsize", Integer.parseInt(prop.get("totalsize")) + test);
Following solution also worked for me on a beanshell post processor:-
import java.util.io.*;
import java.lang.io.*;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
text = ctx.getCurrentSampler().getName();
log.info("Sampler name is " +text);
if(text.equalsIgnoreCase("Test Sampler")){
props.put("totalsize",Integer.parseInt("0"));
}else{
props.put("totalsize", (props.get("totalsize")!=null?props.get("totalsize"):0) + test);
}
log.info("totalsize is = "+props.get("totalsize"));
"test" captures the size of each of the sample requests and keeps adding it to the "totalsize". At the end of the execution I am initializing totalsize back to 0.
it's more appropriate to use prev.getBytesAsLong() to get each sampler response size. Take a look at JMeter API
To have combined size of multiple responses you could try grouping needed requests in transaction via Transaction Controller.