Use Regular Expression for an URL - java

I have been banging my head for this issue but to no result.
I have a URL like this :
http://1.1.1.1:8080/Offers
Then I click on a Create button. It becomes :
http://1.1.1.1:8080/newaccount/Country/Region/State/2016/11/12/offer-111111.html
The 2016/11/12/offer-111111 portion of the URL keeps changing at each run.
Any ideas how I should use a regular expression from newaccount/Country/Region/State/2016/11/12/offer-111111, so that I could use this after 1.1.1.1:8080/, which would mean it would run irrespective of the changes in the URL?

As per your description:-
You are getting the second URL i.e.
http://1.1.1.1:8080/newaccount/Country/Region/State/2016/11/12/offer-111111.html
as a response of first URL hit.
So you can use below mentioned Regular Expression
newaccount/Country/Region/State/(.*?).html
and after that append the reference name in place of 2016/11/12/offer-111111 like this
http://1.1.1.1:8080/newaccount/Country/Region/State/${RegEX_RefrenceName}.html

Try this:
http://1.1.1.1:8080/newaccount/Country/Region/State/\d{4}/\d\d/\d\d/offer-\d+.html

Related

Rest assured : Illegal character in path

I am using response retrieved from one endpoint as path param in another endpoint.
However, when used in URI, it throws java.net.URISyntaxException: Illegal character in path.
//Post the endpoint
Response resp2 = RestAssured.given().
pathParam("id", build).
log().all().
when().urlEncodingEnabled(false).post("https://abc/{id}");
This is because the value of id used in uri is with double quotes like :-
https://abc/"id".
How can I get rid of these double quotes so as to use the value of id in uri , please advise.
First talk to the developer about this, because the nature of path param (/{id}) is to be replaced by a legitimate value (not enclosed in quotes); something like https://abc/23 or https://abc/param
I would not suggest any work-around for this as this is implemented in a wrong way from REST end point definition. You might go ahead and raise a defect against this.
Taking a shot in the dark here because I feel like the issue could possibly be coming from how you're getting the string from that response. If you're pulling it from a JSON using GSON or similar:
String name = myResponseJsonObject.get("member_name")
System.out.Println(name);
will print
"John"
whereas
String name = myResponseJsonObject.get("member_name").getAsString()
System.out.Println(name);
will give you
John
A small detail but this has tripped me up when using GSON and others when working with JSONs in java.
Thank you John and Mohan for your time , I really appreciate it.
I resolved this issue yesterday evening using Stringof function which removed the double quotes and provided me the String like value.

Match Url path with query string

I'm sending a request from SOAPUI to a wiremock server, and I'm attempting to match the url's.
This is the request that is being sent out: /user/test/?and=query
I've written the following regular expression:
stubFor(post(urlPathMatching("/user/test/\\?(and)\\=([a-z]*)"))
The problem is when I try to match the "?" when I use one backslash to capture the literal character, I get an error in Java saying:
"Illegal Escape Character"
What I tried to do to resolve the problem:
I know the solution is to use the second backslash to capture the "?" like this: "\?", but when I send the request I get an error saying the urls don't match because this is the request that is matched against the original one being sent from soap ui:
/user/test/\?(and)\=([a-z]*)
Can someone please help me on this?
EDIT: Second attempt
I've tried to use the dot notation to represent the "?" and "=" symbol. I've tested this on a regular expression tester and it checks out, but, It's still saying the url's dont match on soap ui.
Regular expression: stubFor(post(urlPathMatching("/user/test/.*(and).*([a-z]*)")).atPriority(1)
mismatched url: /user/test/.*(and).*([a-z]*)
When you are using urlPathMatching() you shouldn't put your query parameters in the url. That approach only works for urlEqualTo().
Instead you should specify the parameters separately using withQueryParam(), so your stub setup should be:
stubFor(post(urlPathMatching("/user/test/")).withQueryParam("and", matching("[a-z]*")));
\\ is just escapse the \, you should add one more \ before ? to escapse ?.
Just like this:
stubFor(post(urlPathMatching("/user/test/\\\?(and)\\=([a-z]*)"))

How to get an xsp value from URL link using Java

I am trying to retrieve the page name(.xsp)from the URL of the current page using Java. i have been able to accomplish the same thing with the Javascript below
context.getUrl().getSiteRelativeAddress(context).toString()
and it works but i want to get the same thing don using Java.
The best way to get SSJS variable names via Java is resolveVariable. This should work:
XSPContext context = (XSPContext) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "context");
String pageName = context.getUrl().getSiteRelativeAddress(context).toString();
(Updated with correct syntax for second line, thanks Knut)

Regex to Extract First Part of URL

I need a java regex to extract parts of a URL.
For example, take the following URLs:
http://localhost:81/example
https://test.com/test
http://test.com/
I would want my regex expression to return:
http://localhost:81
https://test.com
http://test.com
I will be using this in a Java patcher.
This is what I have so far, problem is it takes the whole URLs:
^https?:\/\/(?!.*:\/\/)\S+
import Java.net.URL
//snip
URL url = new URL(urlString);
return url.getProtocol() + "://" + url.getAuthority();
The right tool for the right job.
Building off your attempt, try this:
^https?://[^/]+
I'm assuming that you want to capture everything until the first / after http://? (That's what I was getting from your examples - if not, please post some more).
Are these URLs given as one input, or are each a different string?
Edit: It was pointed out that there were unnecessary escapes, so fixed to a more condensed version
Language independent answer:
For the whitespace: replace /^\s+/ with the empty string.
For removing the path information from the URL, if you can assume there aren't any slashes in the path (i.e. you're not dealing with http://localhost:81/foo/bar/baz), replace /\/[^\/]+$/ with the empty string. If there might be more slashes, you might try something like replacing /(^\s*.*:\/\/[^\/]+)\/.*/ with $1.
A simple one: ^(https?://[^/]+)

Velocity - How to avoid ParseErrorException when using jQuery?

I'm trying to add a jQuery post to some JavaScript on a web page. The entire page is built up of several Velocity templates. Everything has been fine until I've tried to add the jQuery post, now I get:
org.apache.velocity.exception.ParseErrorException: Encountered "," at line 282, column 24 of /WEB-INF/velocity/www/comments.vm
Was expecting one of:
"(" ...
<RPAREN> ...
<ESCAPE_DIRECTIVE> ...
~~~snip~~~
Line 282 is $.post(... and column 24 appears to be the first "," character. Initially I had the JSON on this line, but I moved it up (to the var myJSONObject ... line)as I thought the error related to invalid JSON (tabs at the start of the line gave a misleading column number).
var myJSONObject = {"body": "", "action": "postcomment", "submitted": "true", "ajax": "true"};
myJSONObject.body = $("body").val();
$.post("$!{articleurl}", myJSONObject, function(result){
btn.textContent='Comment sent successfully.';
});
Minor Update
I changed the following lines:
var url = "$articleurl";
$.post(url, myJSONObject, function(result){
~~~snip~~~
The parse exception still focuses on the first ",". I'm assuming the issue is that Velocity thinks it should be able to resolve $.post - when in fact, it's jQuery. I've used jQuery in other Velocity VM templates without any problem. Is there a way to get Velocity to ignore certain lines / statements when parsing?
Update 2
I found this link about escaping references in Velocity, but it does not resolve my issue. Adding a "\" before $.post gives me the exact same error, but the column is one extra, because of the character added at the start of the line.
You can wrap your javascript with #[[ ... ]]# which tells Velocity to not parse the enclosed block (new in Velocity 1.7)
#[[
<script>
...
</script>
]]#
Ok, there appears to be two solutions for this:
First, with jQuery we can just avoid using the global alias $ and instead use the jQuery object directly:
jQuery.post(url, myJSONObject, function(result){
~~~snip~~~
In my case, the above works great. But I suspect in other scenarios (non-jQuery) this may not be possible. In which case, we can 'hide' our character within a valid Velocity reference like this:
#set( $D = '$' )
${D}
Source: http://velocity.apache.org/engine/devel/user-guide.html#escapinginvalidvtlreferences
I'd still like to know why the backslash escape didn't work, but the above will at least get me moving again. :)
I think this is a bug in version 1.6.x, because it works fine in 1.7(If it did not, please tell me, I test it many times..), according to the reference, the $ takes effect only when it is followed by a-zA-Z. I want to try do debug what happened really, but the translation code is generated by Java CC tool, it is too hard to recognize the logic...
you must create a js file with your javascript code
and import your js file into your vm code
I couldn't get it to work with any of the other fixes like escaping "$" in velocity unfortunately. I got it working by loading an external js-file with the jQuery instead of writing jQuery directly in velocity. Worked out for me at least, hope it helps someone :)
/björn

Categories

Resources