Group response from JMeter results - java

I am sending an HTTP request and its sending responses like 'abc' , 'cde' etc dynamically. How can I group and get the count of 'abc', 'cde' responses? I need to analyze the results based on the responses I am getting.
Please advice.

You can do it with the help of beanshell processor
example could be,
import org.springframework.util.StringUtils;
String Pattern1= "abc";
int countPattern1 = StringUtils.countOccurrencesOf(new String(data),Pattern1);
vars.put("Count_Pattern1", String.valueOf(countPattern1));
Here This is simple java code which is finding occurrences of string "abc" in Response of sampler (Which is present in data variable)
vars.put is finally returning the count of occurrences in Count_Pattern1 variable. You can write your logic in same beanshell or elsewhere like,
import org.springframework.util.StringUtils;
String Pattern1= "abc";
int countPattern1 = StringUtils.countOccurrencesOf(new String(data),Pattern1);
vars.put("Count_Pattern1", String.valueOf(countPattern1));
//Your logic

Add a Beanshell PostProcessor as a child of the request which returns these abc or cde bits.
Put the following code into the PostProcessor's "Script" area
String response = new String(data);
if (response.contains("abc")) {
prev.setSampleLabel("abc");
}
if (response.contains("cde")) {
prev.setSampleLabel("cde");
}
Explanation:
data is a shorthand to byte-array containing parent sampler response data.
prev stands for the parent sampler SampleResult instance
basing on whether response contains abc or cde parent sampler name will be changed accordingly (see image below for demo, "Dummy Sampler" becomes "abc" or "cde")
analyze results with the listener of your choice basing on sampler name
See How to use BeanShell: JMeter's favorite built-in component guide for comprehensive information on Beanshell scripting, pre-defined variables reference and kind of Beanshell cookbook.

Related

Redisearch query with "begin with" instead of "contains"

I am trying to understand on how to perform queries in Redisearch strictly with "begins with" and I keep getting "contains".
For example if I have fields with values like 'football', 'myfootball', 'greenfootball' and would provide a search term like this:
> FT.SEARCH myIdx #myfield:foot*
I want just to get 'football' but I keep getting other fields that contain the word instead of beginning with that word.
Is there a way to avoid this?
I was trying to use VERBATIM and things like #myfield:^foot* but nothing.
I am using JRedisearch as a client but eventually I had to enter the DB and perform these queries manually in order to figure out what's happening. That being said, is this possible to do with this client at the moment?
Thanks
EDIT
A sample of my index setup:
Client client = new Client(INDEX_NAME, url, PORT);
Schema sc = new Schema().addSortableTextField("url", 1.0); // using this field for query
client.dropIndex(true);
client.createIndex(sc, Client.IndexOptions.Default());
return client;
Sample document:
id: // random uuid
urlPath: myfootbal
application: web
market: Europe
After checking the RDB provided I see that when searching foot* you are not getting myfootbal. The replies look like this: /dot-com/plp/football/x/index.html. You are getting those replies because this url is tokenized, and '/' is one of the tokenize chars. If you do not want those urls to be tokenized you need to declare them as TAGS and not as TEXT. This way the entire url will be indexed as is and when search for foot* it will not appear in the results.
For more information about TAGS see the FT.CREATE documentation: https://oss.redislabs.com/redisearch/Commands.html

Groovy/Java - JSON - Update JSON through variable path

Anyone know how to efficiently set json in groovy with variable paths?
Context: I am working with soapui, a testing tool. Some tests are candidates to be data-driven. I have alot of variables. To make something sustainable that is easily implementable in similar circumstances, I would like a Groovy script that enables me to set variables.
I would name the variables 'parent.subParent.child'.
What I found:
http://groovy-lang.org/json.html
Referencing groovy variable as part of JSON path
I did find other things, but did not record them all.
The straight-forward thing I found was evaluation. With evaluation it was possible to get the values, but not the set them.
Eval.x(jsonbuilder, 'x.content.' + path) = 'newValue'
will return an error. But like I said, no problem retrieving the values in the json this way.
What I tried:
I have got an implementation which works for one level.
I can say:
jsonbuilder.content.parent.subParent[child] = 'newValue'
This will set the value of the requested entity.
Then I tried to expand this to an undefined number of levels.
//Assuming there is a jsonbuilder initialized
def jsonString = "{"parent":{"subParent":{"child":"oldValue"}}}"
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
def path = 'parent.subParent.child'
def listPath = path.split("\\.")
def element = jsonbuilder.content
for(int i = 0; i < listPath.size(); i++) {
element = element[listPath[i]]
}
element = 'newValue'
assert jsonbuilder.toString() == "{"parent":{"subParent":{"child":"newValue"}}}"
The issue: the value in the original json is not updated. Likely because I leave the jsonbuilder variable once I assign it to 'element' and continue with that entity.
That leaves me with two questions:
How do I get the element value in the original json?
More general: How do I update json with a variable path?
The rudimentary JSON assign function with jsonbuilder like this: jsonbuilder.content.parent.subParent.child = 'newValue' as given in one of the answers below is not what I am eyeing for. I am looking for a way to make the entire thing dynamic. I don't want to build a simple assignment, that already exists and works well. I am looking to build a machine that does the assignment for me, with the variable names parsed as the paths. Preferably within the groovy.json.* environment, but if I have to involve external libraries, so be it.
I was staring myself blind on a specific implementation of Eval. My solution was actually simple if I would have read the docs from the start.
You can find the docs for Eval here: http://docs.groovy-lang.org/2.4.7/html/api/groovy/util/Eval.html
Instead of trying to assign a value to an evaluated method/function, which is not logical now I think of if, you need to integrate everything into the evaluated expression. For what I find, you can have up to three variables you can use in you Eval function.
I only need two. I need the jsonbuilder object to be able to get the source of information. And I need to get the value to set. The path itself can be used as it exists because it is already what it needs to be with respect to the evaluation: a String.
The code:
import groovy.json.*
def jsonString = '{"parent":{"child":"oldValue"}}'
def newValue = 'newValue'
def stringPath = 'parent.child'
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
Eval.xy(jsonbuilder, newValue, 'x.content.' + stringPath + '= y')
System.out.println(jsonbuilder.toString()=='{"parent":{"child":"newValue"}}')
System.out.println(jsonbuilder.content.parent.child == 'newValue')​​​​​​​
By using Eval.xy(objectOne, objectTwo, StringExpression), I am telling that I am passing a string to be evaluated as an expression, in which x represents objectOne and y represents objectTwo.
The code can be viewed in an online groovy script engine here: https://groovyconsole.appspot.com/edit/5202721384693760
Small disclaimer: I can't imagine using an evaluated expression in a code base that lets variables be randomly manipulated by the outside world. This expression, if used, will sit comfortably inside the context of my SoapUI project.
Since you are willing to use library, json-path does that.
Credits to #kalle from here
Download the zip files from here
Extract the libraries and its dependencies from above zip
Copy them under SOAPUI_HOME/bin/ext directory
Restart SoapUI
Here you go:
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build()
//You need to prepend $. before the path which becomes valid jsonpath
def path = '$.parent.subParent.child'
def originalJson = """{
"parent": {
"subParent": {
"child": "oldValue"
}
}
}"""
def updatedJson = JsonPath.using(configuration).parse(originalJson).set(path, 'newValue').json()
println(updatedJson.toString())
Here you go:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
def jsonString = """{ "parent": {
"subParent": {
"child": "oldValue"
}
}
}"""
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
//Assign the value for child with new value
jsonbuilder.content.parent.subParent.child = 'newValue'
println jsonbuilder.toPrettyString()​​​​​​​​​​
You can try online Demo

How to encode decode between js and java?

I am working on a project in that java script as front-end and java as back-end are used, my problem is that I want to pass some string using restangular calls to my back-end resources. If passing parameter have space between the string then I got 500 (Server Error) before reaching to back-end resource side.
Lets take example :
At Java Script : RESTangular call
var myRestCall= Restangular.all('myRoot/myMethod/'+myLocalPath+'/'+folderName);
restPSTFolders.getList().then(function(listPSTFolders){
//my stuff
});
At Java Resource :
#ApiOperation(value = "My Method",
notes = "Returns My Method list",
responseContainer = "List",
response = List.class)
#Path("/myMethod/{myLocalPath}/{folderName}")
#GET
#Transactional
#Timed
public List myMethod(#PathParam("myLocalPath") String myLocalPath, #PathParam("folderName") String sFolderName) {
//my stuff
}
In my example myLocalPath parameter can have spaces and special characters in the string as it can be any :
C:\MY DRIVE\My Path One\My Path
D:\My favorite
To pass this to back-end class from RESTangular call, I need to replace all spaces with some character, it work for me, but I am not thinking its a good way to encode the special character and space with any character because the replacing character can also be a part of existing path then at back-end on again replacing the character, might change the path.
EDIT : If I passed the parameter as json object:
var parameterJsonPath = {};
parameterJsonPath={"myLocalPath": pathValue};
var myRestCall= Restangular.all('myRoot/myMethod/'+parameterJsonPath+'/'+folderName);
Does not make any sense as I got : ../myRoot/myMethod/%5Bobject%20Object%5D Failed to load resource: the server responded with a status of 500 (Server Error)
And making the parameterJsonPath to JSON.stringify(parameterJsonPath); will pass this as string that of no use for me.
Thus in all, is there any good way to encode the special character of string in js, so at back-end side I could decode that string using same key that were used while encoding?

Workaround on Scraping HTML by diving into js source code

I learn about jSoup recently and would like to dive more into it. However, I have met obstacle handling webpages with javascript (I have no knowledge in js, yet :/).
I have read that htmlunit would be the correct tool to perform webbrowser actions, but I figured out that I would need no knowledge in js if I can find out the JSON object obtained in the webpage using the javascript.
For example, this page:
among the source files, one of them is tooltips.js. In this file, variable rgNeededFeeds is generated and called in method LoadHeropediaData(), which is the method to generate the whole URL link for getting the json object.
URL = URL + 'jsfeed/heropediadata?feeds='+strFeeds+'&v=3633666222511362823&l=english';
I could not get my mind on what is actually strFeeds. I have tried various combinations but it doesn't work (it returned an empty array...). Or, my guess is totally off?
What I actually need is the data it displays on top when you click on one of the "items". The info in the "hover" would do too, but it lack the "recepi" info. And I'm presuming that by getting the json object from the full URL above, well, basically all data infos should be in that json.
Anyways, this is only based on what I understand from staring at those source files for hours. Do correct me if I'm wrong. (I'm in Java by the way)
**p/s: I would also like to take this opportunity to express my thanks to Balusc, he has been everywhere when I have doubts on jSoup. :>*
strFeeds is nothing but one of these two strings : itemdata or abilitydata
You can find this in tooltips.js at line 38-45
var rgNeededFeeds = [];
$.each( [ 'item', 'ability' ],
function( i, ttType ){
icons = GetIconCollection( ttType );
if ( icons.length ){
rgNeededFeeds.push( ttType+'data' );
//..............
}
}
)
ttType is the value of an iteration over the array [ 'item', 'ability' ] which concatenated with the string data is pushed into the array rgNeededFeeds
The function LoadHeropediaData is called at the end of the function above with rgNeededFeeds as parameter :
LoadHeropediaData( rgNeededFeeds );
Aside note : If you begin to start scraping websites, learning javascript will be MANDATORY.
NOTE : you're right, the JSON contains all the information needed...

Java - generating conditions from string

I'm trying to generate some conditions using string i get as input.
For example, i get as in put the string "length = 15" and i want to create from that the condition:
length == 15.
To be more specific, i have an int in my program called length and it is set to a specific value.
i want to get from the user a conditon as input ("length < 15" or "length = 15"....) and create an if statement that generates the condition and test it.
What is the best way of doing that?
Thanks a lot
Ben
Unless you're talking about code-generation (i.e. generating Java-code by input strings) you can't generate an if-statement based on a string.
You'll have to write a parser for your condition-language, and interpret the resulting parse trees.
In the end it would look something like this:
Condition cond = ConditionParser.parse("length = 15");
if (cond.eval()) {
// condition is true
}
Use a string tokenizer. The default method to distinguish between tokens (or the smallest parts of the input string) is white space, which is to your benefit.
check out javadocs for details:
http://docs.oracle.com/javase/1.3/docs/api/java/util/StringTokenizer.html
Depending on what restrictions you can place on your input format, you could consider using Rhino to embed Javascript. Your 'conditions' then just have to be valid JavaScript code. Something like this (disclaimer: haven't compiled it):
import javax.script.*;
public bool evalCondition (Object context, String javascript) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Object result = engine.eval(javascript);
Boolean condTrue = (Boolean)result;
return condTrue;
}
See the Embedding Rhino Tutorial for more details.

Categories

Resources