Java Webservice URL in JSF - java

I created a JSF application which also offers some Webservices. The webservices are created via annotations.
Now I want to create a webserviceInfo.xhtml Page , where I get all the needed webservice Information.
When I go to the address http://our.server.com/application/OurWebserviceName, I get all the information needed to access the webservice (this info page is generated automatically by Glassfish ).
To include this page, I did the following in the webserviceInfo.xhtml:
<iframe scrolling="automatic" width="971" height="1000" src="#{myBean.generateUrlToWebservice()}/OurWebserviceName"/>
Where:
public String generateUrlToWebservice(){
FacesContext fc = FacesContext.getCurrentInstance();
String servername = fc.getExternalContext().getRequestServerName();
String port = String.valueOf(fc.getExternalContext().getRequestServerPort());
String appname = fc.getExternalContext().getRequestContextPath();
return "http://"+servername+":"+port+appname;
}
Is there a more elegant solution to this?
BR, Rene

Use a page-relative URL.
<iframe src="OurWebserviceName"></iframe>
Or make use of <base> tag with little help of JSTL functions taglib.
<html xmlns:fn="http://java.sun.com/jsp/jstl/functions">
...
<base href="#{fn:replace(request.requestURL, request.requestURI, '')}#{request.contextPath}"></base>
This way any URL which doesn't start with scheme or / is always relative to this URL.
Or if you really need to do it in JSF the following gives less headache with scheme and port.
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
return request.getRequestURL().toString().replace(request.getRequestURI, "") + request.getContextPath();

Better will be if you gets all parameters dynamically like protocol (http,https..) and pages (after app name)
public String generateUrlToWebservice(){
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext exContext = fc.getExternalContext();
String servername = exContext.getRequestServerName();
String port = String.valueOf(exContext.getRequestServerPort());
String appname = exContext.getRequestContextPath();
String protocol = exContext.getRequestScheme();
String pagePath = exContext.getInitParameter("pagePath"); //read it from web.xml
return protocol +"://"+servername+":"+port+appname+pagePath;
}

Related

Best approach to create rest url to call external api in Java and SpringBoot

I'm working in a SpringBoot project where I'm developing a rest endpoint which will receive a few parameters and based on these parameters I will create a uri and I'll call another external endpoint to retrieve an image.
Right now I have a rest controller with the following endpoint:
#GetMapping(value = "/{param1}/{param2}/{param3}/{param4}", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getImageryBaseMap(#PathVariable("param1") Long param1, #PathVariable("param2") Long param2,
#PathVariable("param3") Long param3, #PathVariable("param4") Long param4)
throws IOException{
//calls my service
return myService.getMyMethod(param1, param2, param3, param4);
}
On myService class I make the call to an external endpoint.
public byte[] retrieveImageryBaseMap(Long param1, Long param2, Long param3, Long param4){
String url = "https://host-name:6443/external/Image/export?bbox="+ param1 +"%" + param2+ "+%"+ param3 + "%" + param4 +"&format=png&f=image";
// here I call the external api endpoint to retrieve an image
byte[] image = getImage(url);
return image;
}
My questions would be:
1) What is the best approach/practices to manage creating the url above? I basically hardcoded almost all the url above just replacing the values by the parameters coming from the method retrieveImageryBaseMap . Would like to know if there's a better approach for that or if it's ok.
2)I also hardcoded the host name and the port in the url String url = "https://host-name:6443/external/Image/export?bbox="+ param1 +"%" + param2+ "+%"+ param3 + "%" + param4 +"&format=png&f=image"; Right now I'm just testing this using the dev host-name, but in production the host name and port will be different. So also would like to ask the best approach/practice to manage the host name in the url? Should I hardcoded like that or use a different approach?
Guys much appreciate any help, I'm working by myself and unfortunately don't have a mentor to ask those sort of questions and got stuck here.
Cheers!
You can use UriComponentBuilder for such purposes it’s very flexible
Here is an example :
String URI = UriComponentsBuilder.newInstance()
      .scheme("https").host("host-name").port(6443).pathSegment("external”,”Image”,”export”)
      .queryParam(“paramName1”, value1)
.queryParam(“paramName2”,value2)
.build(). toUriString();
Here is url for documentation
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html

How does Spring MVC #PathVariable receive parameters with multiple '/'?

I was working on a file upload widget for managing images.
I wish that image paths can be received via #PathVariable in Spring MVC, such as http://localhost:8080/show/img/20181106/sample.jpg instead of http://localhost:8080/show?imagePath=/img/20181106/sample.jpg.
But / will be resolved Spring MVC, and it will always return 404 when accessing.
Is there any good way around this?
You can use like below.
#RequestMapping(value = "/show/{path:.+}", method = RequestMethod.GET)
public File getImage(#PathVariable String path) {
// logic goes here
}
Here .+ is a regexp match, it will not truncate .jpg in your path.
Sorry to say that, but I think the answer of #Alien does not the answer the question : it only handle the case of a dot . in the #PathVariable but not the case of slashes /.
I had the problem once and here is how I solved it, it's not very elegant but stil ok I think :
private AntPathMatcher antPathMatcher = new AntPathMatcher();
#GetMapping("/show/**")
public ... image(HttpServletRequest request) {
String uri = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String path = antPathMatcher.extractPathWithinPattern(pattern, uri);
...
}

messy code about java web application

Recently, I use idea with tomcat to start my first java web application (Servlet+JSP+MySql), After I finish all the code part, I try to query some data after I add them in the application, when I use English, it's fine, when I use Chinese, there are messy code in the console, I have done everything to change the
encoding become "utf-8", but I can't solve it, help me, please!
public String query(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
Product product = CommonUtils.toBean(request.getParameterMap(), Product.class);
product = encoding(product);
int pageCode = getPageCode(request);
int pageRecord = 10;
PageBean<Product> pageBean = productService.query(product, pageCode, pageRecord);
pageBean.setUrl(getUrl(request));
System.out.println(pageBean.getUrl());
request.setAttribute("pageBean",pageBean);
return "/content.jsp";
}
private Product encoding(Product product) throws UnsupportedEncodingException{
String name = product.getName();
if(name != null && name.trim().isEmpty()){
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
product.setName(name);
}
return product;
}
the result when I was query is this:
/ProductServlet?method=query&barcode=&name=%E5%B8%85&units=&purchasePrice=&salePrice=&inventory=&%E6%90%9C%E7%B4%A2=%E6%8F%90%E4%BA%A4
the name is Chinese, but it becomes messy code
First: name = new String(name.getBytes("ISO-8859-1"),"utf-8"); should not ever be done; then something else went wrong prior to that moment.
There are the following points where an encoding/charset can be set:
In the html <form accept-encoding="UTF-8"...> to indicate that the generated form field values should not be url-encoded as for instance %E5%B8%85.
On the request.setEncoding("UTF-8"); to tell that the request is in that encoding.
On the response.setEncoding("UTF-8"); for outgoing text.
There are many technologies that can be applied, and the settings above in reality can be done in numerous ways, as application settins, or in your case in the JSP as <%#page pageEncoding="UTF-8" %>.
If you are using a /WEB-INF/web.xml setting the pageEncoding for all JSPs would be:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>

Get the referrer's domain of the visitor for a website behind a load balancer

I have a Spring (Java) website that uses Kemp Technologies' LoadMaster as the balancer, which sits before my web servers.
I am able to get the right IP address of a visitor at any page via:
request.getRemoteAddr()
However, I am not able to get the correct domain of the referrer. Here is what I did:
I have the following code in a HandlerInterceptorAdapter, which is called for each web request. The code is to check whether a particular session variable exists. If yes, no action. If no, record the referrer's domain in session.
HttpSession session = request.getSession();
String value = (String) session.getAttribute("referrer");
if (value == null) {
String scheme = request.getScheme();
String serverName = request.getServerName();
int portNumber = request.getServerPort();
String url = scheme +"://"+serverName+ (portNumber == 80? "": portNumber);
session.setAttribute("referrer", url);
}
In other pages when I need the referrer's domain, I have the following:
String value = (String) request.getSession().getAttribute("referrer");
The problem is that the value I got is always my own domain (ex. http://www.example.com).
Where have I gone wrong?

Handling non-english URL with Spring and App Engine Task Queue

I have this problem where I need to queue a page link with TaskQueue:
Queue queue = QueueFactory.getDefaultQueue();
for (String href : hrefs){
href = baseUrl + href;
pageLinks = pageLinks + "\n" + href;
queue.add(TaskOptions.Builder
.withUrl("/crawler")
.param("url", href));
l("Added to queue url=["+href+"]");
}
The problem here is that, I think the URL that gets passed into the queue contains ?'s for Arabic characters. As it keeps on rescheduling.
The String pageLinks however is outputed in the browser through Spring MVC, and I can properly see the Arabic character being displayed. So I'm pretty the links are ok.
If I copy one of the links output on the browser, and paste it to the browser URL it works fine. So I'm pretty sure that the reason that the queue keeps on recheduling because it gets the wrong URL.
What could I be missing here? Do I need to convert the String href before passing it into the queue?
The crawl service looks like this:
#RequestMapping(method = RequestMethod.GET, value = "/crawl",
produces = "application/json; charset=iso-8859-6")
public #ResponseBody String crawl(HttpServletRequest req, HttpServletResponse res,
#RequestParam(value="url", required = false) String url) {
l("Processs url:" + url);
}
Also do I need to convert the #QueryParam String url here to Arabic or not?
You must Url-encode the parameters. See this question: Java URL encoding of query string parameters

Categories

Resources