Apache Http UrlBuilder stripping API version from URL - java

All,
I have my base url defined in a config like so
foobar.baseurl = https://api.foobar.com/v3/reporting/
This is passed as a constructor argument for my Spring bean
<bean id="foobarUriBuilder" class="org.apache.http.client.utils.URIBuilder">
<constructor-arg value="${foobar.baseurl}"/>
</bean>
This all works fine, however the URLBuilder strips the /v3/reporting part and then when I try to do something like this.
//Set URI path and query params
uriBuilder.setPath("/fooReports")
.setParameter("type_of_foo", FOO_TYPE);
So the request turns into this
https://api.foobar.com/fooReports?type_of_foo=bar
Which gives a HTTP 404 naturally.
So how do I stop URIBuilder stripping a part of my URL so I have the correct URL as below?
https://api.foobar.com/v3/reporting/fooReports?type_of_foo=bar

The /v3/reporting is part of the (original) path. When you set the path to something else, in this case /fooReports, it gets overridden.
You may try to compose the new path with
final String originalPath = uriBuilder.getPath();
uriBuilder.setPath(originalPath + "/fooReports")
.setParameter("type_of_foo", FOO_TYPE);

Related

Pass parameters to URL placeholders in java

I am getting the URL dynamically which has few placeholders. But i need to pass the parameters to the placeholders.
Below is the URL which i am getting dynamically
http://example.com/name/{name}/age/{age}
i need to pass parameters for name and age for the above url. How can we achieve that using java.
I guess you are looking Rest Client to call this URL and get response.
http://example.com/name/{name}/age/{age}
String resourceURL = "http://example.com/name";
ResponseEntity<String> response = restTemplate.getForEntity(resourceURL + "/swarit/age/20", String.class);
I would also suggest to do little research before posting question.

How to build a URI using URIbuilder without encoding hash

I have a URI like this:
java.net.URI location = UriBuilder.fromPath("../#/Login").queryParam("token", token).build();
and I am sending it as response: return Response.seeOther(location).build()
However, in the above URI, # is getting encoded to %23/. How do I create a URI with out encoding the hash #. According to official document, a fragment() method must be used to keep unencoded.
URI templates are allowed in most components of a URI but their value
is restricted to a particular component. E.g.
UriBuilder.fromPath("{arg1}").build("foo#bar"); would result in
encoding of the '#' such that the resulting URI is "foo%23bar". To
create a URI "foo#bar" use
UriBuilder.fromPath("{arg1}").fragment("{arg2}").build("foo", "bar") instead.
Looking at the example from docs, I am not sure how to apply it in my case.
The final URI should look like this:
http://localhost:7070/RTH_Sample14/#Login?token=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcnRoLmNvbSIsInN1YiI6IlJUSCIsInJvbGUiOiJVU0VSIiwiZXhwIjoxNDU2Mzk4MTk1LCJlbWFpbCI6Imtpcml0aS5rOTk5QGdtYWlsLmNvbSJ9.H3d-8sy1N-VwP5VvFl1q3nhltA-htPI4ilKXuuLhprxMfIx2AmZZqfVRUPR_tTovDEbD8Gd1alIXQBA-qxPBcxR9VHLsGmTIWUAbxbyrtHMzlU51nzuhb7-jXQUVIcL3OLu9Gcssr2oRq9jTHWV2YO7eRfPmHHmxzdERtgtp348
To construct the URI with fragment use
UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login").build()
This results in the URI string
http://localhost:7070/RTH_Sample14/#Login
But if you also add query parameters
UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login")
.queryParam("token", "t").build()
then the UriBuilder always inserts the query params before the fragment:
http://localhost:7070/RTH_Sample14/?token=t#Login
which simply complies to the URL syntax.
Instead of all the hassle of redirecting without encoding the hash value. I changed my code into the following:
java.net.URI location = new java.net.URI("../#/Login?token=" + token);
So the query param above is token appended to URI location. In front-end I am using angular's location.search().token to get capture the query param.
This worked for me. Looking for better answers though. Thanks

How to get deployed address programmatically?

I have following application URI structure:
ip:port/applicationName/someAction
How can I get following part of URI programmatically:
ip:port/applicationName/
I tryed
servletContext.getContext()
but it returns only applicationName.
P.S.
this works
String applicationBasePath = request.getRequestURL().substring(0,request.getRequestURL().indexOf("/",request.getRequestURL().indexOf("/")+2));
and this:
request.getRequestURL().substring(0, request.getRequestURL().indexOf(request.getRequestURI()))
But I don't like it.
I believe you need to get HttpServletRequest and there you can extract that information from getRequestURL().
The problem with servlet context only is that your application can be access e.g. via http://127.0.0.1/ or http://192.168.1.1/ and you don't know that without having actual request done. If you can define any "canonical" server name, you can do it e.g. like here: Getting server name during servlet initialization
ie. String serverName = getServletContext().getInitParameter("serverName"); with defined init parameter.
I couldn't write code better than:
public static String getApplicationBasePath(HttpServletRequest request) {
String absolutePath = request.getRequestURL().toString();
String contextPath = request.getRequestURI().toString();
return absolutePath.substring(0,absolutePath.indexOf(contextPath));
}

Jersey Path Param : Multiple backslash separated param

#Path("/assetViewCount/{path}")
above annotation can be used to retrive myValue into path for url like /assetViewCount/myValue.
How can I get myValue/nextValue from /assetViewCount/myValue/nextValue in path
Actually I found the solution to my problem, following annotation gives whatever there is after /assetViewCount/ into {path}
#Path("/assetViewCount/{path:.*}")
You can use an embedded parameter in Path like this:
#Path("/assetViewCount/{path}/nextValue")

Resteasy UriBuilder incorrectly encodes?

I am trying to create a URI from a string url using UriBuilder from RestEasy and I am getting some unexpected results. I am running the following piece of code.
UriBuilder uriBuilder = UriBuilder.fromPath("http://localhost:8190/items?pageNumber={pageNumber}&pageSize={pageSize}");
System.out.println(uriBuilder.build(1, 10));
Expected result:
http://localhost:8190/items?pageNumber=1&pageSize=10
Actual result:
http://localhost:8190/items%3FpageNumber=1&pageSize=10
When using UriBuilder.fromUri() instead of fromPath() it throws an exception while creating the URI
Illegal character in query at index 39: http://localhost:8190/items?pageNumber={pageNumber}&pageSize={pageSize}
the character at 39 is {.
I don't want to parse the complete string to create the URI part by part.
I looked at the RestEasy code and it is encoding the '?' character while creating the builder using org.jboss.resteasy.util.Encode#encode using the pathEncoding map from org.jboss.resteasy.util.Encode#pathEncoding.
Is my usage incorrect or the implementation incorrect?
Since RestEasy is a JAX-RS implementation, from the Oracle documentation of fromPath:
Create a new instance representing a relative URI initialized from a URI path.
I think it was not intended for absolute URLs, hence I'm afraid the answer is that your usage is incorrect.
You will need something like this (didn't test it though)
UriBuilder.fromUri("http://localhost:8190/").
path("{a}").
queryParam("pageNumber", "{pageNumber}").
queryParam("pageSize", "{pageSize}").
build("items", 1,10);

Categories