How to get deployed address programmatically? - java

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));
}

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.

Apache Http UrlBuilder stripping API version from URL

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);

RequestMapping with slashes and dot

I have to support following URL format
/service/country/city/addr1/addr2/xyz.atom
/service/country/city/addr1/addr2/addr3/xyz.atom
where country and city can be mapped to #PathVariable but after that the path can be dynamic with multiple slashes. The end part will have .atom or similar.
I tried following, but none of the options seem to be working
Wildcard
#RequestMapping(value="/service/{country}/{city}/**")
Regex
#RequestMapping(value="/service/{country}/{city}/{addr:.+}")
UseSuffixPatternMatch
Override method in Config class
#Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
Looks like combination of slash and dots don't work with above solutions.
I keep getting 406 for non-matching Accept header, or 404
The most dynamic approach would be to use MatrixVariable to manage the list of addresses but it is not applicable in your context since the paths cannot be modified as far as I understand from your question.
The best thing you can do to manage your dynamic path is to proceed in two steps:
Set a RequestMapping that extracts all the data except the addresses
Extract the addresses manually in the method
So for the first step you will have something like that:
#RequestMapping(value="/service/{country}/{city}/**/{file}.atom")
public String service(#PathVariable String country,
#PathVariable String city, #PathVariable String file,
HttpServletRequest request, Model model) {
This mapping matchs with all the required paths and allows to extract the country, the city and the file name.
In the second step we will use what has been extracted to get the addresses by doing something like this:
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
path = path.substring(String.format("/service/%s/%s/", country, city).length(),
path.length() - String.format("%s.atom", file).length());
String[] addrs = path.split("/");
First we extract from the request the full path
Then we remove what we have already extracted which are here the beginning and the end of the path
Then finally we use String.split to extract all the addresses
At this level you have everything you need.
Can you try this,
#RequestMapping(value="/service/{country}/{city}/{addr:[a-z]+\\\\.(atom|otherExtensions)}")
Just have to specify the complete regex format wherein you are expecting an extension at the end of the url such as atom, since this will be interpreted by default as MediaType by Spring.
another solution is specify the accepted MediaTypes
#RequestMapping(value="/service/{country}/{city}/{addr}", consumes = {MediaType.ATOM, MediaType...})
You can create custom MediaTypes if it is not predefined in Spring.

How can I get the URL paramter dynamically in Java?

A url is hit from browser now I want to get that url in my dataBean to extract its parameters for some checks.
How can I get that URL dynamically in that particular databean?
for instance :
someone hit
https://someAddress/AjaxForm?id=someid
I need to capture this url and get value of Id. How to do it?
you can do something likewise,
request.getRequestURL() // gives your current URL
where request is an instance of HttpServletRequest.
UPDATED :
If you are trying to find parameter which are comes along with URL, then
rather then do above mentioned my trick,
directly do likewise,
request.getParameter("id");
String url=request.getRequestURL()
String id=request.getParameter("id");
To get the parameter from url
request.getParameter("id");
And to insert it, in javascript add the parameter by attaching it to url
var url=baseurl+"?id="+id;
in the doGET method you write
String idValue=request.getParameter("id");
so the method will look like this
protected void doGET(HTTPServletRequest request,HTTPServletResponse response){
//some code here
String idValue=request.getParameter("id");//idValue will hold the value you passed in URL
//some more code here
}

Embed web liferay content within existing liferay web content

I'm trying to print a web content from inside another web content in Liferay 5.2.3. Following the issue How to embed WebContent in Liferay i've tried:
set ($group_id = $getterUtil.getLong($request.theme-display.scope-group-id))
set ($webcontent-id = "ROBAPAGINES-COL-ESQUERRA")
set ($webcontent=$journalContentUtil.getContent($group_id, $webcontent-id, "", "$locale", ""))
$webcontent
It works when the embedded web content has no structure and template but $webcontent is empty when I assign an structure-template to the same web content.
I'd greatly appreciate any help
It seems you are calling below method for getting web-content.
public static String getContent(
long groupId, String articleId, String viewMode, String languageId,
String xmlRequest)
But, you can use below mentioned method which accept templatedId.
public static String getContent(
long groupId, String articleId, String templateId, String viewMode,
String languageId, String xmlRequest)

Categories