Spring Rest Service GET with parentheses - spring

I have a Spring Rest Service like this:
#RequestMapping(value = "/banks", method = RequestMethod.GET)
public List<String> getBanks( #RequestParam(value="name" , required=true) String name) {
...
}
The name must allows special character like parentheses, but the problem is that when i put parentheses on the param, y receive the ASCCI code like #040# on the "name" parameter.
I thought in use #RequestBody with a wrap filter like a posible solution, but the method must change to POST to support the wrap in the Request Body and the api design going to be bad.
So, someone have a solition for support parentheses on the param of a GET Rest Service?

Related

Spring Rest Service Return Type

I have a rest service in spring which can return a string or a json. For this in my js code while sending the ajax request, i have specified datatype as "*". I wanted to know how can i handle this in spring service
All produces type are available in org.springframework.http.MediaType and for your requirement you can pass */*.
Constant for that is MediaType.ALL_VALUE in java code.
But if you know that your service always return JSON then I prefer to use MediaType.APPLICATION_JSON_UTF8_VALUE instead of MediaType.ALL_VALUE.
you can add attribute " produces" on your RequestMapping annotation:
#RequestMapping(value = "/yourPath", method = GET,
produces = { "application/json", "application/xml",....all what you want as type})

How to get Swagger UI to display similar Spring Boot REST endpoints?

I have a controller class with two endpoints
#RestController
#RequestMapping
public class TestController {
#RequestMapping(
value= "/test",
method = RequestMethod.GET)
#ResponseBody
public String getTest() {
return "test without params";
}
#RequestMapping(
value= "/test",
params = {"param"},
method = RequestMethod.GET)
#ResponseBody
public String getTest(#PathParam("param") int param) {
return "test with param";
}
}
One has a parameter, one doesn't, and the both work.
If I use curl or a web browser to hit the endpoints
http://localhost:8081/test
returns
test without params
and
http://localhost:8081/test?param=1
returns
test with param
but the swagger ui only shows the one without a parameter.
If I change the value in the request mapping for the request with a parameter to
#RequestMapping(
value= "/testbyparam",
params = {"param"},
method = RequestMethod.GET)
Swagger UI displays both endpoints correctly, but I'd rather not define my endpoints based on what swagger will or won't display.
Is there any way for me to get swagger ui to properly display endpoints with matching values, but different parameters?
Edit for Clarification:
The endpoints work perfectly fine; /test and /test?param=1 both work perfectly, the issue is that swagger-ui won't display them.
I would like for swagger ui to display the endpoints I have defined, but if it can't, then I'll just have to live with swagger-ui missing some of my endpoints.
Edit with reference:
The people answering here: Proper REST formatted URL with date ranges
explicitly say not to seperate the query string with a slash
They also said "There shouldn't be a slash before the query string."
The issue is in your Request Mapping, The second method declaration is overriding the first method. As Resource Mapping value is same.
Try changing the second method to below. As you want to give input in QueryParam rather than path variable, you should use #RequestParam not #PathParam.
Note that you have to give /test/, In order to tell Spring that your mapping is not ambiguous. Hope it helps.
#RequestMapping(
value= "/test/",
method = RequestMethod.GET)
#ResponseBody
public String getTest (#RequestParam("param") int param) {
return "test with param"+param;
}
Upon reading clarifications, the issue here is that swagger-ui is doing the correct thing.
You have two controller endpoints, but they are for the same RESOURCE /test that takes a set of optional query parameters.
Effectively, all mapped controller endpoints that have the same method (GET) and request mapping (/test) represent a single logical resource. GET operation on the test resource, and a set of optional parameters which may affect the results of invoking that operation.
The fact that you've implemented this as two separate controller endpoints is an implementation detail and does not change the fact that there is a single /test resource that can be operated upon.
What would be the benefit to consumers of your API by listing this as two separate endpoints in swagger UI vs a single endpoint with optional parameters? Perhaps it could constrain the set of allowed valid query parameters (if you set ?foo you MUST set &bar) but this can also be done in descriptive text, and is a much more standard approach. Personally, I am unfamiliar with any publicly documented api that distinguishes multiple operations for the same resource differentiated by query params.
As per Open API Specification 3
OpenAPI defines a unique operation as a combination of a path and an
HTTP method. This means that two GET or two POST methods for the same
path are not allowed – even if they have different parameters
(parameters have no effect on uniqueness).
Reference - https://swagger.io/docs/specification/paths-and-operations/
This was also raised as an issue but it was closed because OAS3 doesn't allow that -
https://github.com/springdoc/springdoc-openapi/issues/859
Try including the param in the path as below.
#GetMapping("/test/{param}")
public String getTest(#PathVariable final int param) {
return "test with param";
}
I'm unclear exactly what you're attempting to do, but I'll give two solutions:
If you want to have PATH parameters e.g. GET /test & GET /test/123 you can do:
#GetMapping("/test")
public String getTest() {
return "test without params";
}
#GetMapping("test/{param}")
public String getTest(#PathVariable("param") int param) {
return "test with param";
}
If you want query parameters (GET /test and GET /test?param=123) then you need a single endpoint that takes an optional parameter:
#GetMapping("test")
public String getTest(#RequestParam("param") Integer param) {
if(param == null) {
return "test without params";
} else {
return "test with param";
}
}

regexMatcher for URL with query parameters in Spring Security

How should I use parameters like this in regexMatcher in Spring Security? I have many URLs that start with /sUrl and have different parameters. This code doesn't work!
.regexMatchers("\\/sUrl\\?params=\\{url:\"reports\\/Manager\",subSystem:\"ABS\"\\}").access("hasRole('ROLE_ABS')")
Controller:
#RequestMapping(value = "sUrl", method = RequestMethod.GET)
public RedirectView sUrl(#RequestParam(name = "params") String params) {
RedirectView redirectView = new RedirectView();
.
.
.
return redirectView;
}
URL seen in network partition of browser inspector when I click on this link:
sUrl?params={url:%22reports/Manager%22,subSystem:%22ABS%22}
You have to use a regular expression with the URL-encoded query parameter, see RegexRequestMatcher:
Uses a regular expression to decide whether a supplied the URL of a supplied HttpServletRequest. Can also be configured to match a specific HTTP method. The match is performed against the servletPath + pathInfo + queryString of the request and is case-sensitive by default. Case-insensitive matching can be used by using the constructor which takes the caseInsensitive argument.
and HttpServletRequest:
Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
Returns:
a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.
Your modfified code:
.regexMatchers("\\/sUrl\\?params=\\{url:%22reports\\/Manager\%22,subSystem:%22ABS%22\\}").access("hasRole('ROLE_ABS')")

Spring RedirectAttributes

How can we use spring RedirectAttributes to add a attribute with same name and multiple values, like if I have HTTP request parameter say place=london&place=paris, and I want to redirect these "place" params in a redirectAttribute.
redirectAttribute.addAttribute("place",places??)
I don't want to use flash attributes.
Is it possible?
I'm really frustrated that there doesn't appear to be a cleaner solution, but I faced the same problem and ended up doing:
((HashMap<String, Object>) redirectAttrs).putIfAbsent("place",
Arrays.asList("london", "paris"));
This works because it bypasses the way that RedirectAttributes normally converts everything to a String when you add it, since they forgot to override the putIfAbsent method...
It works (for now), but I certainly don't recommend it.
You can use the mergeAttributes method:
String[] attrArray = {"london", "paris"};
Map<String, String[]> attrMap = new HashMap<>();
attrMap.put("place", attrArray);
redirectAttrs.mergeAttributes(attrMap);
This will create a URL with request parameters like this: place=london%2Cparis (where %2C is the ASCII keycode in hexadecimal for a comma), which is equivalent to place=london&place=paris.

How to pass url as rest service?

I am trying to build a rest service in spring boot to update my database..
#RequestMapping(value = "/setrepacking/{transaction_number}/{image_url}", method = RequestMethod.GET)
public String setRepackingDetails(#PathVariable String transaction_number,
#PathVariable String image_url) {
dao.setRepackingDetails(transaction_number, image_url);
return "Updated repacking details for "+transaction_number;
}
But my image_url is like below: And I want to pass below as part of rest component
http://xxxx.com/api/images/get?format=src&type=png
I am trying something like below:
`www.localhost:8080/setrepacking/3500574684/http://thecatapi.com/api/images`/get?format=src&type=png
It is not accepting...
How do I pass the parameter in my broswer??
Appricate any quick solution....
You have to URL encode your image URL path variable before passing it in the request, encoded URL looks like this:
http%3A%2F%2Fxxxx.com%2Fapi%2Fimages%2Fget%3Fformat%3Dsrc%26type%3Dpng
So you request has to look like this:
http://localhost:8080/setrepacking/3500574684/http%3A%2F%2Fxxxx.com%2Fapi%2Fimages%2Fget%3Fformat%3Dsrc%26type%3Dpng
This way you will get your image URL correctly. Also have a look at URLEncoder and URLDecoder

Resources