JMeter Create url dynamically based on a property - jmeter

I have a setUp Thread Group which hit an url and get a lot of products id.
/product/4564
/product/4534
/product/1234
....
I saved this in a property like this:
// Using jsr223
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import com.google.gson.Gson;
List<String> sendRequest(String url, String method, Map<String,Object> body) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(3000)
.build();
StringEntity entity = new StringEntity(new Gson().toJson(body), "UTF-8");
HttpUriRequest request = RequestBuilder.create(method)
.setConfig(requestConfig)
.setUri(url)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
.setEntity(entity)
.build();
HttpClientBuilder.create().build().withCloseable {httpClient ->
httpClient.execute(request).withCloseable {response ->
String res = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "";
return Arrays.asList("result", res);
}
}
}
Map<String,Object> map = new LinkedHashMap<>();
SampleResult.setIgnore();
def test1 = sendRequest("localhost:8080/product/list","GET", map);
ArrayList pathProduct = Arrays.toString(test1.get(1))
props.put("myProperty", pathProduct)
Then I have a throughtput controller inside another Thread group and that the reason to use a property instead of a variable. I read that if I use a variable won't be available on another thread.
Then I have a Http Request, and I set it like this:
protocol: http
server: localhost
path: ${__groovy(props.get("myProperty"))}
And it works partially because I'm getting only 1 url instead of N, the url I'm getting is:
http://localhost/product/4564/product/4534/product/1234
And I want to get:
http://localhost/product/4564
http://localhost/product/4534
http://localhost/product/1234
.....
Any idea? Thanks in advance

Finally, I created a file inside my script and I consumed it as a CSV Data Set Config and it worked. Thanks

Related

Trying to read a csv file in Jmeter using Beanshell Sampler

I am trying to read the cells in an xls file.This is the code I have.Please let me know where I am going wrong.I don't see any error in the logviewer but it isn't printing anything.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ApacheCommonsCSV {
public void readCSV() throws IOException {
String CSV_File_Path = "C:\\source\\Test.csv";
// read the file
Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
// parse the file into csv values
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for (CSVRecord csvRecord : csvParser) {
// Accessing Values by Column Index
String name = csvRecord.get(0);
String product = csvRecord.get(1);
// print the value to console
log.info("Record No - " + csvRecord.getRecordNumber());
log.info("---------------");
log.info("Name : " + name);
log.info("Product : " + product);
log.info("---------------");
}
}
}
You're declaring readCSV() function but not calling it anywhere, that's why your code doesn't even get executed.
You need to add this readCSV() function call and if you're lucky enough it will start working and if not - your will see an error in jmeter.log file.
For example like this:
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class ApacheCommonsCSV {
public void readCSV() throws IOException {
String CSV_File_Path = "C:\\source\\Test.csv";
// read the file
Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
// parse the file into csv values
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for (CSVRecord csvRecord : csvParser) {
// Accessing Values by Column Index
String name = csvRecord.get(0);
String product = csvRecord.get(1);
// print the value to console
log.info("Record No - " + csvRecord.getRecordNumber());
log.info("---------------");
log.info("Name : " + name);
log.info("Product : " + product);
log.info("---------------");
}
}
readCSV(); // here is the entry point
}
Just make sure to have commons-csv.jar in JMeter Classpath
Last 2 cents:
Any reason for not using CSV Data Set Config?
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting so consider migrating to Groovy right away. Check out Apache Groovy - Why and How You Should Use It for reasons, tips and tricks.

How to do I get the form values in Springboot sent from angular?

I am building a formData
const formulario = new FormData();
formulario.append('preco', this.formularioCasaVenda.get('preco').value);
formulario.append('foto_1', this.formularioCasaVenda.get('foto_1').value);
formulario.append('dormitorios', this.formularioCasaVenda.get('dormitorios').value);
I am sending it in a post request.
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'multipart/form-data'})
};
return this.http.post<Casa>("http://localhost:8080/api/casas-venda", formData1).pipe(
tap((product: Casa) => console.log(`added product w/ id=$`)),
catchError(this.handleError<Casa>('addProduct'))
);
How can I access dormitorios, foto_1, preco from the Spring boot controller, so I can populate a model?
My "desperate" atempt.
#CrossOrigin(origins = "http://localhost:4200")
#PostMapping("casas-venda")
public CasaVenda storeCasaVenda(#RequestParam("formulario") MultipartFile[] casaVenda){
CasaVenda casaVendaDB = new CasaVenda();
casaVendaDB.setDormitorios(1);
casaVendaDB.setPreco( Double.parseDouble(casaVenda[1].toString()));
casaVendaDB.setPreco(900.00);
return casaVendaDB;
// return this.casaVendaRepositorio.save(casaVenda);
}
This is one way of solving it:
#CrossOrigin(origins = "http://localhost:4200")
#PostMapping("/casas-venda")
public CasaVenda storeCasaVenda(#RequestParam("dormitorios") Integer dormitorios,
#RequestParam("preco") BigDecimal preco,
#RequestParam("foto_1") MultipartFile foto) {
CasaVenda casaVendaDB = new CasaVenda();
casaVendaDB.setDormitorios(dormitorios);
casaVendaDB.setPreco(preco.doubleValue());
// foto I am assuming is a file, so you receive it and you have to get the InputStream from it.
return casaVendaDB;
// return this.casaVendaRepositorio.save(casaVenda);
}
One hint:
Don't return in the endpoints #Entity classes, it is not a nice practice, instead you should create a DTO (Data Transfer Object) and only return to the Frontend what they need to know.
https://martinfowler.com/eaaCatalog/dataTransferObject.html
I hope I could help you.

How to convert from Java to Xamarin C#

Can someone help me convert the following from Java to C# (Xamarin)?
I tried a couple of different ways, but I cannot get it to work.
The code is:
HttpPost post = new HttpPost(url);
// Break out all extra HTTP header lines and add it to the HttpPost object
for (String line : contentType.replace("\r", "\n").split("\n")) {
if (line.length() > 0 && line.contains(":")) {
String[] parts = line.split(":", 2);
if (parts.length == 2) {
post.addHeader(parts[0].trim(), parts[1].trim());
}
}
}
// Create a byte array entity for the POST data, the content
// type here is only used for the postEntity object
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.setContentType("application/octet-stream");
post.setEntity(postEntity);
// Create a HttpClient and execute the HttpPost filled out above
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
// Get the response entity out of the response
HttpEntity entity = httpResponse.getEntity();
If you are stuck with
post.SetEntity(postEntity);
then it converts to:
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.SetContentType("application/octet-stream");
post.Entity = postEntity;
When converting to Java from C# you mostly have to change the property names to start with upperCase and then if you get stuck on certain objects I would look check out the Xamarin API Docs, HttpPost class linked here.

How can I write all values extracted via regex to a file?

I've got a piece of regex which I've tested in JMeter using the regexp tester and it returns multiple results (10), which is what I'm expecting.
I'm using the Regular Expression Extractor to retrieve the values and I would like to write ALL of them to a CSV file. I'm using the Beanshell Post Processor but I am only aware of a method to write 1 value to file.
My script in Beanshell so far:
temp = vars.get("VALUES"); // VALUES is the Reference Name in regex extractor
FileWriter fstream = new FileWriter("c:\\downloads\\results.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(temp);
out.close();
How can I write all the values found via the regex to file? Thanks.
If you'll look into Debug Sampler output, you'll see that VALUES will be a prefix.
Like
VALUES=...
VALUES_g=...
VALUES_g0=...
VALUES_g1=...
etc.
You can use ForEach Controller to iterate over them.
If you want to proceed with Beanshell - you'll need to iterate through all variables like:
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
FileOutputStream out = new FileOutputStream("c:\\downloads\\results.txt", true);
String newline = System.getProperty("line.separator");
Set variables = vars.entrySet();
for (Map.Entry entry : variables) {
if (entry.getKey().startsWith("VALUES")) {
out.write(entry.getValue().toString().getBytes("UTF-8"));
out.write(newline.getBytes("UTF-8"));
out.flush();
}
}
out.close();
To write the contents of your values array into the file, the following code should work (untested):
String[] values = vars.get("VALUES");
FileWriter fstream = new FileWriter("c:\\downloads\\results.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
for(int i = 0; i < values.length; i++)
{
out.write(values[i]);
out.newLine();
out.flush();
}
out.close();

How to filter a TreeGrid?

I currently have a TreeGrid which shows nodes with names. The data is coming from a manually populated DataSource.
When setting the filter on the nodeName field, The filter is not done recursevily and thus I can only filter the Root node.
How can I tell the filter to search for matches in child nodes?
PS: in the code below, I have 3 nodes Root > Run > Child1. If i try the filter and type "R", I get Root and Run. But if i Type "C", I get "no results found"
Code
DataSource:
package murex.otk.gwt.gui.client.ui.datasource;
import java.util.List;
import murex.otk.gwt.gui.client.ui.record.TreeRecord;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
public class ClassesDataSource extends DataSource {
private static ClassesDataSource instance = null;
public static ClassesDataSource getInstance() {
if (instance == null) {
instance = new ClassesDataSource("classesDataSource");
}
return instance;
}
private ClassesDataSource(String id) {
setID(id);
DataSourceTextField nodeNameField = new DataSourceTextField("nodeName");
nodeNameField.setCanFilter(true);
nodeNameField.setRequired(true);
DataSourceIntegerField nodeIdField = new DataSourceIntegerField("nodeId");
nodeIdField.setPrimaryKey(true);
nodeIdField.setRequired(true);
DataSourceIntegerField nodeParentField = new DataSourceIntegerField("nodeParent");
nodeParentField.setRequired(true);
nodeParentField.setForeignKey(id + ".nodeId");
nodeParentField.setRootValue(0);
setFields(nodeIdField, nodeNameField, nodeParentField);
setClientOnly(true);
}
public void populateDataSource(List<String> classNames) {
TreeRecord root = new TreeRecord("Root", 0);
addData(root);
TreeRecord child1 = new TreeRecord("Child1", root.getNodeId());
addData(child1);
TreeRecord child2 = new TreeRecord("Run", child1.getNodeId());
addData(child2);
}
}
Main
public void onModuleLoad() {
ClassesDataSource.getInstance().populateDataSource(new ArrayList<String>());
final TreeGrid employeeTree = new TreeGrid();
employeeTree.setHeight(350);
employeeTree.setDataSource(ClassesDataSource.getInstance());
employeeTree.setAutoFetchData(true);
TreeGridField field = new TreeGridField("nodeName");
field.setCanFilter(true);
employeeTree.setFields(field);
employeeTree.setShowFilterEditor(true);
employeeTree.setAutoFetchAsFilter(true);
employeeTree.setFilterOnKeypress(true);
employeeTree.draw();
}
I solved this.
The problem was that the filter was calling the server to fetch data whereas my datasource was set to Client Only. To fix this, the employeeTree must have employeeTree.setLoadDataOnDemand(false);
You may also use employeeTree.setKeepParentsOnFilter(true)
http://www.smartclient.com/smartgwtee/javadoc/com/smartgwt/client/widgets/tree/TreeGrid.html#setKeepParentsOnFilter(java.lang.Boolean)

Resources