Can't properly build HttpUrl which contains hash-bang - okhttp

I'm trying to build HttpUrl instance which contains hash-bang but can't properly do so. Final URL string value should look like this example: https://www.google.com/mobile/#!/id?platform=android
I've tried few solutions:
https://gist.github.com/novachevskyi/71529d8fdecf120e626af227193a9e0f
When adding hash-bang with HttpUrl.Builder::addEncodedPathSegment then final result would contain encoded hash symbol.
https://gist.github.com/novachevskyi/12b59e53d6162fb1cd4e6236b03fb504
After parsing base URL which contains hash-bang I'm getting next result:
https://www.google.com/mobile/?platform=android#!/id
Is there any way to build HttpUrl instance were string value would contain hash-bang in it?

You can do it with .parse() or with .fragment().
HttpUrl a = HttpUrl.parse("https://www.google.com/mobile/#!/id?platform=android");
HttpUrl b = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.encodedPath("/mobile/")
.fragment("!/id?platform=android")
.build();

Related

JMeter Array of variables to text file

I am running a query via JDBC request and I am able to get the data and place it in a variable array. The problem is I want the values of the variables to be saved to a text file. However, each variable is being given a unique number appended to it i.e. SCORED_1, SCORED_2,SCORED_3 etc. I am using a beanshell post processor to write to the text file. The problem is I unless I define A LINE Number. How can I get all results from a SQL query and dump them into a single variable without the variables separated by brackets and line separated on their own row.
import org.apache.jmeter.services.FileServer;
// get variables from regular expression extractor
ClaimId = vars.get("SCORED _9"); // I want to just use the
SCORED variable to contain all values from the array
without "{[" characters.
// pass true if want to append to existing file
// if want to overwrite, then don't pass the second
argument
FileWriter fstream = new FileWriter("C:/JMeter/apache-
jmeter-4.0/bin/FBCS_Verify_Final/Comp.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(ClaimId);
out.write(System.getProperty("line.separator"));
out.close();
fstream.close();
We are not telepathic enough to come up with the solution without seeing your query output and the result file format.
However I'm under impression that you're going into wrong direction. Given you're talking about {[ characters it appears that you're using Result Variable Name field
which returns an ArrayList which should be treated differently
However if you switch to Variable Names field
JMeter will generate a separate variable per each result set row and it should be much easier to work with and eventually concatenate
More information:
JDBC Request
Debugging JDBC Sampler Results in JMeter
JDBC request>Enter a Variable Name> Store as string>Add a Beanshell PostProcessor and add the following script.
import org.apache.jmeter.services.FileServer;
{
FileWriter fstream = new FileWriter("C:/JMeter/apache-jmeter-4.0/bin/FBCS_Verify_Final/Comp.txt", false);
BufferedWriter out = new BufferedWriter(fstream);
Count = vars.get("SCORED_#");
Counter=Integer.parseInt(vars.get("SCORED_#"));
for (int i=1;i<=Counter;i++)
{
ClaimId = vars.get("SCORED_"+i);
out.write(ClaimId);
out.write(System.getProperty("line.separator"));
}
out.flush();
out.close();
fstream.close();
}

UriComponentsBuilder query param and fragment

I want to generate the following path: '/app#/fragment1?test=toto' with spring library UriComponentsBuilder.
What I have tried so far:
UriComponentsBuilder ucb = UriComponentsBuilder.fromPath("/app").fragment("fragment1").queryParam("test","toto");
ucb.toUriString(); // -> gives me as result : '/app?test=toto#/fragment1'
Any idea how to achieve this in an elegant way?
I would simply do something like :
// first build fragment part
String fragmentWithQueryParams = UriComponentsBuilder.fromPath("/fragment1").queryParam("test","toto").toUriString();
// then generate full path
String fullPath = UriComponentsBuilder.fromPath("/app").fragment(fragmentWithQueryParams).toUriString());
System.out.println(fullPath); // -> "/app#/fragment1?test=toto"

How can we set the value to the header dynamically in SOAPUi?

I'm new to SoapUI. I wanted to know how can we add 2 property value into one Header value.
For instance, I got some response like in XML format:
<Response xmlns="Http://SomeUrl">
<access_token>abc</access_token>
<scope>scope1</scope>
<token_type>Bearer</token_type>
</Response>
I want to send both access_token & token type to a single header value like:
"Authorization":"Bearer abc"
I am not getting how to do this using property transfer step.
Can anyone please help me?
You can use XPath concat function to concatenate the both values in one variable in your property transfer steps, in your case you can use the follow XPath:
concat(//*:token_type," ",//*:access_token)
concat function concatenates two or more strings, //*:token_type gets the Bearer value and //*:access_token gets the abc.
Hope this helps,
Add a script step after the step returning what you describe above.
def tokenType = context.expand('${STEP RETURNING STUFF#Response#//Response/token_type}');
def token = context.expand('${STEP RETURNING STUFF#Response#//Response/access_token}');
//add header to all steps
for (def stepEntry : testRunner.testCase.testSteps) {
if (!(stepEntry.value instanceof com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep)) {
continue;
}
def headers = stepEntry.value.httpRequest.requestHeaders;
headers.remove("Authorization");
headers.put("Authorization", token_type + " " + token);
stepEntry.value.httpRequest.requestHeaders = headers;
}
Here is another way without using additional property transfer step, but uses script assertion
Add a script assertion for the request test step.
Use below code into that script, modify element XPath are required
def element1Xpath = '//*:token_type'
def element2Xpath = '//*:access_token'
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def response = groovyUtils.getXmlHolder(messageExchange.responseContentAsXml)
def field1 = response.getNodeValue(element1Xpath)
def field2 = response.getNodeValue(element2Xpath)
if (!field1) { throw new Error ("${element1Xpath} is either empty or null") }
if (!field1) { throw new Error ("${element2Xpath} is either empty or null") }
context.testCase.setPropertyValue('TEMP_PROPERTY', "${field1} ${field2}")
Now the expected value(merged) is available in a property 'TEMP_PROPERTY'. You may rename the property name as you wish in the last line of the code.
You may the new wherever it is needed within the test case.

How to use "Result Variable Name" in JDBC Request object of Jmeter

In JMeter I added the configuration for oracle server. Then I added a JDBC request object and put the ResultSet variable name to status.
The test executes fine and result is displayed in treeview listener.
I want to use the variable status and compare it with string but jmeter is throwing error about casting arraylist to string.
How to retrieve this variable and compare with string in While Controller?
Just used some time to figure this out and think the accepted answer is slightly incorrect as the JDBC request sampler has two types of result variables.
The ones you specify in the Variable names box map to individual columns returned by your query and these you can access by saying columnVariable_{index}.
The one you specify in the Result variable name contains the entire result set and in practice this is a list of maps to values. The above syntax will obviously not work in this case.
The ResultSet variable returned with JDBC request in JMeter are in the for of array. So if you want to use variable status, you will have to use it with index. If you want to use the first(or only) record user status_1. So you need to use it like status_{index}.
String host = vars.getObject("status").get(0).get("option_value");
print(host);
log.info("----- " + host);
Form complete infromation read the "yellow box" in this link:
http://jmeter.apache.org/usermanual/component_reference.html#JDBC_Request
Other util example:
http://jmeter.apache.org/usermanual/build-db-test-plan.html
You can use Beanshell/Groovy (same code works) in JSR233 PostProcessor to work with “Result Variable Name” from JDBC Request like this:
ArrayList results = vars.getObject("status");
for (HashMap row: results){
Iterator it = row.entrySet().iterator();
while (it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
log.info(pair.getKey() + "=" + pair.getValue());
}
}
Instead of output to log replace with adding to string with delimiters of your choice.

DisplayTool installation and usage

I am using Velocity 1.7 to format string and I had some trouble with default values. Velocity by itself has no special syntax for case when value is not set and we want to use some another, default value.
By the means of Velocity it looks like:
#if(!${name})Default John#else${name}#end
which is unconveniant for my case.
After googling I've found DisplayTool, according to documentation it will look like:
$display.alt($name,"Default John")
So I added maven dependency but not sure how to add DisplayTool to my method and it is hard to found instructions for this.
Maybe somebody can help with advice or give useful links?..
My method:
public String testVelocity(String url) throws Exception{
Velocity.init();
VelocityContext context = getVelocityContext();//gets simple VelocityContext object
Writer out = new StringWriter();
Velocity.evaluate(context, out, "testing", url);
logger.info("got first results "+out);
return out.toString();
}
When I send
String url = "http://www.test.com?withDefault=$display.alt(\"not null\",\"exampleDefaults\")&truncate=$display.truncate(\"This is a long string.\", 10)";
String result = testVelocity(url);
I get "http://www.test.com?withDefault=$display.alt(\"not null\",\"exampleDefaults\")&truncate=$display.truncate(\"This is a long string.\", 10)" without changes, but should get
"http://www.test.com?withDefault=not null&truncate=This is...
Please tell me what I am missing. Thanks.
The construction of the URL occurs in your Java code, before you invoke Velocity, so Velocity isn't going to evaluate $display.alt(\"not null\",\"exampleDefaults\"). That syntax will be valid only in a Velocity template (which typically have .vm extensions).
In the Java code, there's no need to use the $ notation, you can just call the DisplayTool methods directly. I've not worked with DisplayTool before, but it's probably something like this:
DisplayTool display = new DisplayTool();
String withDefault = display.alt("not null","exampleDefaults");
String truncate = display.truncate("This is a long string.", 10);
String url = "http://www.test.com?"
+ withDefault=" + withDefault
+ "&truncate=" + truncate;
It might be better, though, to call your DisplayTool methods directly from the Velocity template. That's what is shown in the example usage.

Resources