Jmeter Groovy Script to read and utilize header values - groovy

I was using jmeter to load test services
I need to use one of the response headers parameter value as input of next request.
For this I am using JSR223 Sampler and write Grrovy Script to read parameters.
I have used
**def headerList = prev.getResponseHeaders()
headerList.each(){
headersList.each{
log.info it;
if(it.equals("transactionRef"){
log.info"Required Header: "it
requiredHeader=it;
}**
The above code is not working
also it is traversing character by character.
Could someone help on this.
}

As per the JavaDoc SampleResult.getResponseHeaders() function returns response headers as a single String so if you want to get individual headers you need to split it by line separators first and then by colon to get name/value pairs.
Example code:
def headers = prev.getResponseHeaders().split('\n').inject([:]) { out, header ->
if (header.contains(':')) {
header.split(':').with {
out[it[0].trim()] = it[1].trim()
}
}
out
}
headers.each { header ->
if (header.getKey() == 'transactionRef') {
log.info('Required header value: ' + header.getValue())
}
}
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
P.S. Woudln't it be easier to go for Regular Expression Extractor? The relevant configuration would be something like:

Related

JScript Escape an ampersand in payload data for URL

I am attempting to launch a view using the following JS function:
$('#filterTop').click(function () {
var filterValue = $('#filterValueTop').val();
refreshView(`#Url.Action(Model.Action, Model.Controller)?pageSize=#Model.PageSize&pageNumber=#Model.PageNumber&sortDesc=#Model.SortDescending&filterType=#Model.FilterType&filterValue=${filterValue}&showAll=#Model.ShowAll` + `#Model.Payload`, '#Model.ResultView');
});
It worked great until I needed to append a static payload to the end of the URL. The relevant part is line 3 at the end:
&showAll=#Model.ShowAll` + `#Model.Payload`
I am assigning #Model.Payload a value of:
opts.Payload = "&batchID=" + batchID;
or "&batchID=25". The resulting URL is:
https://localhost:44303/Employee/Repaginate?pageSize=20&pageNumber=1&sortDesc=True&filterType=Name&filterValue=Jes&showAll=False&batchID=25
For some reason, it's translating the "&" to "&a.m.p;" (with no periods) which isn't a valid URL. I've tried various methods of escaping the character like using "%26", "/&", and several other garden varieties but alas, my attempts have been in vain. Any suggestions on what I am doing wrong?

nodejs skipping single quote from json key in output

I see a very weird problem when json when used in nodejs, it is skipping single quote from revision key . I want to pass this json as input to node request module and since single quote is missing from 'revision' key so it is not taking as valid json input. Could someone help how to retain it so that I can use it. I have tried multiple attempts but not able to get it correct.
What did I try ?
console.log(jsondata)
jsondata = {
'splits': {
'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
Expected :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
But in actual output single quote is missing from revision key :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
revision: 'master'
}
}
Run 2 :- Tried below code this also produce same thing.
data = JSON.stringify(jsondata)
result = JSON.parse(data)
console.log(result)
Run 3:- Used another way to achieve it
jsondata = {}
temp = {}
splits = []
temp['revision'] = 'master',
temp['os-name'] = 'ubuntu'
temp['platform-version'] = 'os'
temp['traffic-percent'] = 100
splits.push(temp)
jsondata['splits'] = splits
console.log(jsondata)
Run 4: tries replacing single quotes to double quotes
Run 5 : Change the order of revision line
This is what is supposed to happen. The quotes are kept only if the object key it’s not a valid JavaScript identifier. In your example, the 'splits' & 'revision' don't have a dash in their name, so they are the only ones with the quotes removed.
You shouldn't receive any error using this object - if you do, update this post mentioning the scenario and the error.
You should note that JSON and JavaScript are not the same things.
JSON is a format where all keys and values are surrounded by double quotes ("key" and "value"). A JSON string is produced by JSON.stringify, and is required by JSON.parse.
A JavaScript object has very similar syntax to the JSON file format, but is more flexible - the values can be surrounded by double quotes or single quotes, and the keys can have no quotes at all as long as they are valid JavaScript identifiers. If the keys have spaces, dashes, or other non-valid characters, then they need to be surrounded by single quotes or double quotes.
If you need your string to be valid JSON, generate it with JSON.stringify. If it's OK for it to be just valid JavaScript, then it's already fine - it does not matter whether the quotes are there or not.
If, for some reason, you need some imaginary third option (perhaps you are interacting with an API where someone has written their own custom string parser, and they are demanding that all keys are surrounded by single quotes?) you will probably need to write your own little string generator.

how to get the data in url using groovy code?

i want to get defect id from the url using groovy code (To build custom code in tasktop).
for example: I will have an dynamic url generated say www.xyz.com/abc/defect_123/ now I want to retrieve that letter that always starts from 17th position. and return the string
Please help..
Thanks in advance
Here are two possibilities. Please note that the "substring" option is very strict and will always start from the 16th position (what happens if the domain changes from www.xyz.com to www.xyzw.com?)
def str = 'www.xyz.com/abc/defect_123/';
def pieces = str.tokenize('/'); // prints defect_123
def from16 = str.substring(16); // prints defect_123/
println from16;
println pieces.last();
You should define this as dynamic url in UrlMappings.groovy file:
"www.xyz.com/abc/$defect_id" (controller: 'YourController', action: 'method_name')
and you can access the defect_id variable from YourController using params.defect_id

How to replace the Hexadecimal values to its original character string in C?

I have correlated the Token value taken from the following response snippet:
result.sessionToken = '7AFF3BA8\x2DD913\x2D4211\x2D990E\x2D7DF3AB5687B7';
Using the web_reg_save_param function as:
web_reg_save_param(
"TOKEN",
"LB=result.sessionToken = '",
"RB=';",
"ORD=1",LAST);
But in a later request I need to send the correlated value in the below format:
7AFF3BA8-DD913-4211-990E-7DF3AB5687B7
The value \x2D is to be substituted by -.
I am right now using the below 'C' and LR code for this:
strcat(pstr1,lr_eval_string("{RToken}"));
strcat(aSeparator,"\\");
for(a=0,b=0;pstr1[a]!=NULL;a++,b++)
{
if(pstr1[a]==aSeparator[0])
{
strcat(pstr2,"-");
pstr2[b+1]=pstr1[a+4];
a=a+5;
b=b+2;
}
pstr2[b]=pstr1[a];
}
lr_save_string(lr_eval_string(pstr2), "sessionToken");
I wanted a generic and another approach for this problem. I don't want to use web_convert_param function, but if there is a hidden trick to convert the string as desired I would like to know.
Thanks,
Ritika
Try This...lr_save_string(lr_eval_string("{TOKEN}"),"convertedtkn");

Is there standard method for managing camel cased strings in groovy?

For example groovy converts getSomeProperty() method to someProperty.
I need the same for my string. prefixMyString converted to myString.
Is there standard way to do so?
Groovy doesn't actually convert getSomeProperty() into someProperty. It only converts the other way, turning someProperty into getSomeProperty()
It does this using the capitalize(String property) method on org.codehaus.groovy.runtime.MetaClassHelper. You can run this in the console to see it work:
org.codehaus.groovy.runtime.MetaClassHelper.capitalize('fredFlinstone')
// outputs 'FredFlintstone'
The full conversion, including adding set, get, or is, can be found in the class groovy.lang.MetaProperty, under the methods getGetterName and getSetterName.
To convert the other way, you'll have to write your own code. However, that's relatively simple:
def convertName(String fullName) {
def out = fullName.replaceAll(/^prefix/, '')
out[0].toLowerCase() + out[1..-1]
}
println convertName('prefixMyString') // outputs: myString
println convertName('prefixMyOTHERString') // outputs: myOTHERString
Just change the prefix to meet your needs. Note that it's a regex, so you have to escape it.
EDIT: I made a mistake. There actually is a built-in Java method to decapitalize, so you can use this:
def convertName(String fullName) {
java.beans.Introspector.decapitalize(fullName.replaceAll(/^prefix/, ''))
}
It works nearly the same, but uses the built-in Java class for handling the decapitalization. This method handles uppercase characters a little differently, so that prefixUPPERCASETest returns UPPERCASETest.

Resources