Jmeter - Creating a new variable if variable already exists using Java - java

I'm using Jmeter and want to use Java to update variables,
I have a variable called XXVONO which stores values and adds a number suffix when executed in a loop. Example:
XXVONO_1 = value1
XXVONO_2 = value2
XXVONO_3 = value3
These variables contains values which are automatically stored when the loop is executed. However, I am trying to make a code which checks if the variable is empty or not, If true, it will save the new values, where if false, it will create a new variable (XXVONO_4) and save the value there without overwriting the existing variables.
How would I go about doing this? Do I use a while loop?
if (vars.get("VONO_2") != "") {
if (vars.get("XXVONO_" + vars.get("aps200_count_3")) == "") {
vars.put("XXVONO_" + vars.get("aps200_count_3"), vars.get("VONO_2"));
vars.put("XXJRNO_" + vars.get("aps200_count_3"), vars.get("JRNO_2"));
} else {
while (vars.get("XXVONO_" + vars.get("aps200_count_3")) != "") {
vars.put("new_count", vars.get("aps200_count_3"));
Integer temp = Integer.parseInt(vars.get("new_count")) + 1;
vars.put("new_count", temp.toString());
}
vars.put("XXVONO_" + vars.get("new_count"), vars.get("VONO_2"));
vars.put("XXJRNO_" + vars.get("new_count"), vars.get("JRNO_2"));
}
}

You can try using a map instead of creating a variables at runtime
Map<String,Object> map = new HashMap<>();
Inside the loop
if(map.get("DynamicVariableName")!=null){
map.put("DynamicVariableName"+autogeneratedNumberSuffix,ValueToBeStored)
}
else{
map.put("DynamicVariableName",ValueToBeStored)
}

What you could do is use an if/else statement:
if (XXVONO_1 == null)
{
XXYVONO_1 = //Insert data here
}
else if (XXVONO_2 == null)
{
XXVONO_2 = //Insert data here
}
else if (XXVONO_3 == null)
{
XXVONO_3 == //Insert data here
}
else
{
XXVONO_4 == //Insert data here
}
Of course, you can keep adding variables.
If there is no limit to the number of variables, try this:
HashMap<String, String> XXVONO = new HashMap<String, Integer>();
for (i = 1; i <= /*Number of variables*/; i += 1; i++) {
if (XXVONO["XXVONO_" + i] == null) {
XXVONO.put("XXVONO_" + i, /*insert data here*/);
}
}

Related

Is there a way to dynamically create a counter if such "month" exists?

I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?
CODE
public HashMap<String, Integer> getDataPoint() {
//My function code
HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
int janCounter = 0;
int febCounter = 0;
int marCounter = 0;
int aprCounter = 0;
int mayCounter = 0;
int juneCounter = 0;
int julyCounter = 0;
int augCounter = 0;
int septCounter = 0;
int octCounter = 0;
int novCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
OpenCsvReader reader = new OpenCsvReader();
ArrayList <STPost> STArray = reader.loadST("file_path");
Iterator STitr = STArray.iterator();
while (STitr.hasNext()) {
STPost St = (STPost) STitr.next();
Date retrievedate = St.getTime();
String strDate = sdf.format(retrievedate);
if(strDate.equals("Jan")) {
janCounter++;
}
else if (strDate.equals("Feb")) {
febCounter++;
}
else if (strDate.equals("Mar")) {
marCounter++;
}
else if (strDate.equals("Apr")) {
aprCounter++;
}
else if (strDate.equals("May")) {
mayCounter++;
}
else if (strDate.equals("June")) {
juneCounter++;
}
else if (strDate.equals("July")) {
julyCounter++;
}
else if (strDate.equals("Aug")) {
augCounter++;
}
else if (strDate.equals("Sept")) {
septCounter++;
}
else if (strDate.equals("Oct")) {
octCounter++;
}
else if (strDate.equals("Nov")) {
novCounter++;
}
else if (strDate.equals("Dec")) {
decCounter++;
}
numberOfPost.put("January", janCounter);
numberOfPost.put("Feburary", febCounter);
numberOfPost.put("March", marCounter);
numberOfPost.put("April", aprCounter);
numberOfPost.put("May", mayCounter);
numberOfPost.put("June", juneCounter);
numberOfPost.put("July", julyCounter);
numberOfPost.put("August", augCounter);
numberOfPost.put("September", septCounter);
numberOfPost.put("October", octCounter);
numberOfPost.put("November", novCounter);
numberOfPost.put("December", decCounter);
}
return numberOfPost
}
You can create an array of months and check if value exists there using indexOf method.
String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
Integer idx = months.indexOf(strDate);
Thereafter you can use SimpleDateFormat("MMMM") pattern to put and get it into your map.
if(idx > -1) {
String longDate = new SimpleDateFormat("MMMM").format(retrievedate);
Integer current = numberOfPost.get(longDate);
if (current == null) {
current = 1;
} else {
current += 1;
}
numberOfPost.put(longDate, current);
}
Thereafter, you can use map iterator to display content of map.
You already have a good start. Using a the hash map will make the code much tidier.
You can replace all those if statements and put statements with the code below:
if (!numberOfPosts.containsKey(strDate)) {
numberOfPosts.put(strDate, 0);
}
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1);
The if statement will create a dictionary entry if there is not one with the key of strDate. The value of the entry is set to 0.
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1)
The line above increments by 1 the dictionary entry with the key of strDate.

Observe livedata inside a for loop

I want to update a list in my activity that depends on the data of another list. Both the data list are being observed from the activity from the my viewmodel. After I get the data from my firstlist I need to run a for loop on this list to get the required ids and get the data for the second list.
But keeping the livedata observer in the for loop is causing a lot of problems. The for loop runs as expected but the livedata observer is getting called almost double the amount of the for loop. This happens only the first time when the list in being brought from the api. When I do the same operation a second time where the list is cached and is being brought from the database, the problem does not occur. Below is the source code for the problem,
for (int i = 0; i < firstList.size(); i++) {
final String uId = firstList.get(i).item.uid;
final long id = firstList.get(i).item.id;
viewModel.initAnotherItemRepository(uId, id);
viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
#Override
public void onChanged(Resource<List<SecondItem>> listResource) {
if (listResource.data != null) {
secondItemList.addAll(listResource.data);
if (count == firstList.size() - 1) {
//Do something
}
count = count + 1;
}
if (listResource.state == Resource.STATE_FAILURE) {
showLoadingSpinner(false);
}
}
}
);
}
Try to observe SecondItem outside the for loop. It gets data whenever update
viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
#Override
public void onChanged(Resource<List<SecondItem>> listResource) {
if (listResource.data != null) {
secondItemList.addAll(listResource.data);
if (count == firstList.size() - 1) {
//Do something
}
count = count + 1;
}
if (listResource.state == Resource.STATE_FAILURE) {
showLoadingSpinner(false);
}
}
}
);
for (int i = 0; i < firstList.size(); i++) {
final String uId = firstList.get(i).item.uid;
final long id = firstList.get(i).item.id;
viewModel.initAnotherItemRepository(uId, id);
}

Why list is replacing the old object with new object

I am trying to read the object through xml using JAXB and updating some info the saving back.
here is the read and update code-
dbf = DocumentBuilderFactory.newInstance();
dbuilder = dbf.newDocumentBuilder();
document = dbuilder.parse(file);
jc = JAXBContext.newInstance(OutletWisePlanningListContainer.class);
Binder<Node> binder = jc.createBinder();
owpLContainer = (OutletWisePlanningListContainer)
binder.unmarshal(document);
owpLContList = owpLContainer.getOwpList();
then - updating the objects
for (OutletWisePlanningList owpl1 : owpLContList) {
owpl = owpl1.getOwpList();
owpList = new OutletWisePlanningList();
owpList = owpl1;
skuList.add(owpl1.getSkuId());
for (i = 1; i < sku; i++) {
if (owpl1.getSkuId().trim().equals(request.getParameter("skuId" + i).trim())) {
owpl1.getSkuId();
ArrayList idList = new ArrayList();
int j = 1, cnt = 1;
al1.clear();
int perf = Integer.parseInt(request.getParameter("hdnPerf" + i));
for (OutletWisePlanning owps : owpl) {
owp = new OutletWisePlanning();
for (j = 1; j < perf; j++) { //used only when Planned outlets is changed
if (owp.getMarketIntId().trim().equals(request.getParameter("UID" + i + '-' + j).trim()) && !request.getParameter("txtTARGET_SETvolume" + i + '-' + j).trim().equals("0")) {
//some updation in owp object
al1.add(owp);
}
}
if (request.getParameter("selPlanUnplanned").equals("0")) { //used when Unplanned in selected
al1.add(owp);
}
}
owpList.setOwpList(al1);
owpList.setSkuId(owpl1.getSkuId());
}
}
owpList1.add(owpList);
Iterator itr = owpList1.iterator();
while (itr.hasNext()) {
OutletWisePlanningList op1 = (OutletWisePlanningList) itr.next();
for (OutletWisePlanning op2 : op1.getOwpList()) {
System.out.println("Party id in the owpList1" + op2.getPartyId());
}
}
}
al.addAll(owpList1);
And the xml from where i am reading data and updating the same-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OutletWisePlanningListContainer>
<OutletWisePlanningList skuId="4214">
<OutletWisePlanning partyId="14560">
<marketIntId>14002</marketIntId>
<perfAllocId>818</perfAllocId>
<relPartyName>Aangan (Indian North)</relPartyName>
<addrLine1>Bhikaji Cama Place</addrLine1>
<locationName>-NA-</locationName>
<planQty>30</planQty>
<planCpc>10</planCpc>
<agreedQty>0</agreedQty>
<agreedCpc>0</agreedCpc>
<executedQty>0</executedQty>
<executedCpc>0</executedCpc>
<actualQty>0</actualQty>
<actualCpc>0</actualCpc>
<claimedQty>0</claimedQty>
<claimedCpc>0</claimedCpc>
<genCpc>0</genCpc>
<eligibility></eligibility>
<eligibleItem>0</eligibleItem>
</OutletWisePlanning>
</OutletWisePlanningList>
<OutletWisePlanningList skuId="4215">
<OutletWisePlanning partyId="14554">
<marketIntId>14105</marketIntId>
<perfAllocId>819</perfAllocId>
<relPartyName>Dhaba (Indian North)</relPartyName>
<addrLine1>Aurangzeb Road</addrLine1>
<locationName>Aurangzeb Road</locationName>
<planQty>44</planQty>
<planCpc>10</planCpc>
<agreedQty>0</agreedQty>
<agreedCpc>0</agreedCpc>
<executedQty>0</executedQty>
<executedCpc>0</executedCpc>
<actualQty>0</actualQty>
<actualCpc>0</actualCpc>
<claimedQty>0</claimedQty>
<claimedCpc>0</claimedCpc>
<genCpc>0</genCpc>
<eligibility></eligibility>
<eligibleItem>0</eligibleItem>
</OutletWisePlanning>
</OutletWisePlanningList>
I am getting the xml with different skuId(i.e. ok) but partyId = 14560 is replacing by partyId = 14554 with its whole data.
Please help
This code has lot of unnecessary initializations and assignments. You should have to clear all those.
However to answer your question, my best guess is that the issue is with this for loop.
for (OutletWisePlanning owps : owpl) {
owp = new OutletWisePlanning();
for (j = 1; j < perf; j++) { //used only when Planned outlets is changed
if (owp.getMarketIntId().trim().equals(request.getParameter("UID" + i + '-' + j).trim()) && !request.getParameter("txtTARGET_SETvolume" + i + '-' + j).trim().equals("0")) {
//some updation in owp object
al1.add(owp);
}
}
if (request.getParameter("selPlanUnplanned").equals("0")) { //used when Unplanned in selected
al1.add(owp);
}
}
First you are initializing the owp inside the for-each loop. owp = new OutletWisePlanning(); This is never been assigned any values still you are using it on the if condition. Here either the code is incomplete or you might have some initializations inside the constructor. Anyway within the inner for loop the "SAME OBJECT REFERENCE" gets modified and added to the list al1 when the if conditions(both inside and outside the loop) satisfies. So no matter how many times you add the object to this list all will have the same value.

Variable might not have been initialized?

I have the following code for a conversion program:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
int type, value;
double conversion;
String output;
type = Integer.parseInt(conversionchoiceInput.getText());
value = Integer.parseInt(valueInput.getText());
if (type == 1)
{
conversion = inchesToCentimetres(value);
output = value + " inches = " + Math.round(conversion) + " centimetres";
}
else if (type == 2)
{
}
else if (type == 3)
{
}
else if (type == 4)
{
}
outputLabel.setText(output);
}
It says "variable output might not have been initiaized" when I already have?
Thanks!
The problem is that output needs to be initialised no matter what execution path the program takes. It is only initialised in the if path. Therefore, you need to give it a default value at the start (of empty string or something) or set it in all branches.
String output = "";
or
if (type == 1)
{
conversion = inchesToCentimetres(value);
output = value + " inches = " + Math.round(conversion) + " centimetres";
}
else if (type == 2)
{
output = "";
}
else if (type == 3)
{
output = "";
}
else if (type == 4)
{
output = "";
}
Naturally, the first option is the best.
If type != 1, then output isn't initialized. And even if you give output a value in each of the if branches (1, 2, 3, 4) output might not have been initialized, as if type < 1 or > 4 it still has no value.
You have just declared the variable there which is different from initializing it.

Converting Java code into Groovy

I am trying to convert a Java function into equivalent Groovy code, but I am not able to find anything which does && operation in loop. Can anyone guide me through..
So far this is what I got
public List getAlert(def searchParameters, def numOfResult) throws UnsupportedEncodingException
{
List respList=null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try
{
for(strIndex in searchStrings)
{
IQueryResult result = search(searchStrings[strIndex])
if(result!=null)
{
def count = 0
/*The below line gives me error*/
for(it in result.document && count < numOfResult)
{
}
}
}
}
catch(Exception e)
{
e.printStackTrace()
}
}
My Java code
public List getAlert(String searchParameters, int numOfResult) throws UnsupportedEncodingException
{
List respList = null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try {
for (int strIndex = 0; strIndex < searchStrings.length; strIndex++) {
IQueryResult result = search(searchStrings[strIndex])
if (result != null) {
ListIterator it = result.documents()
int count = 0
while ((it.hasNext()) && (count < numOfResult)) {
IDocumentSummary summary = (IDocumentSummary)it.next()
if (summary != null) {
String docid = summary.getSummaryField("infadocid").getStringValue()
int index = docid.indexOf("#")
docid = docid.substring(index + 1)
String url = summary.getSummaryField("url").getStringValue()
int i = url.indexOf("/", 8)
String endURL = url.substring(i + 1, url.length())
String body = summary.getSummaryField("infadocumenttitle").getStringValue()
String frontURL = produrl + endURL
String strURL
strURL = frontURL
strURL = body
String strDocId
strDocId = frontURL
strDocId = docid
count++
}
}
}
result = null
}
} catch (Exception e) {
e.printStackTrace()
return respList
}
return respList
}
It seems to me like
def summary = result.documents.first()
if (summary) {
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
is all you really need, because the for loop actually doesn't make much sense when all you want is to process the first record.
If there is a possibility that result.documents contains nulls, then replace first() with find()
Edit: To process more than one result:
def summaries = result.documents.take(numOfResult)
// above code assumes result.documents contains no nulls; otherwise:
// def count=0
// def summaries = result.documents.findAll { it && count++<numOfResult }
summaries.each { summary ->
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
In idiomatic Groovy code, many loops are replace by iterating methods like each()
You know the while statement also exists in Groovy ?
As a consequence, there is no reason to transform it into a for loop.
/*The below line gives me error*/
for(it in result.document && count < 1)
{
}
This line is giving you an error, because result.document will try to call result.getDocument() which doesn't exist.
Also, you should avoid using it as a variable name in Groovy, because within the scope of a closure it is the default name of the first closure parameter.
I haven't looked at the code thoroughly (or as the kids say, "tl;dr"), but I suspect if you just rename the file from .java to .groovy, it will probably work.

Categories

Resources