#JsonGetter doesn't work - spring

I want to make this method return {"valid":true/false}
#ResponseBody
#RequestMapping(value = "/checkUser", method = RequestMethod.POST)
Boolean checkUsersAvailable(#RequestParam("username") String username) {
return contentService.getUser(username) == null;
}
I add these annotations:
#JsonGetter("valid")
#JsonProperty("valid")
But it's still not working.

You can't return a primitive type and get JSON object as a response.
You can use a wrapper or something like that:
#ResponseBody
#RequestMapping(value = "/checkUser", method = RequestMethod.POST)
Map<String, Boolean> checkUsersAvailable(#RequestParam("username") String username) {
boolean result = contentService.getUser(username) == null;
return Collections.singletonMap("success", result);
}

Related

Getting HttpServerErrorException: 500 null when using #PathVariable

I am not getting this. I have a #RestController which is supposed to handle requests like /foo?latitude=15.12345. Of course there should be more parameters, but it's not even working for one.
This is the controller:
#RestController
public class GooglePlaceController {
private final static Logger LOGGER = LogManager.getLogger(GooglePlaceController.class);
#Autowired
private GooglePlaceService googlePlaceService;
#RequestMapping(value = "/foo", method = RequestMethod.GET)
public List<GooglePlaceEntity> doNearbySearch(#PathVariable Float latitude) {
LOGGER.trace("Searching for places nearby.");
return null;
}
}
and this is the request I am building:
public ResponseEntity<List<PlaceDto>> nearbySearch(Float lat, Float lng, Integer radius, Boolean googleSearch) {
String href = UriComponentsBuilder.fromHttpUrl("http://localhost:8081/foo")
.queryParam("latitude", lat)
.build().encode().toString();
ResponseEntity<Object> forEntity = this.oauthRestTemplate.getForEntity(href, null, Object.class);
return null;
}
However, I am getting this exception below, unless I remove #PathVariable Float latitude in which case the request gets handled correctly.
org.springframework.web.client.HttpServerErrorException: 500 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.security.oauth2.client.http.OAuth2ErrorHandler.handleError(OAuth2ErrorHandler.java:84)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:361)
at mz.api.client.Client.nearbySearch(Client.java:191)
But here is the thing:
In another controller I am having this:
#RequestMapping(value = "/groups/{groupId}/places", method = RequestMethod.GET)
public List<PlaceEntity> getGooglePlaces(#PathVariable Long groupId) {
return this.userGroupService.getPlaces(groupId);
}
#RequestMapping(value = "/groups/{groupId}/google-places", method = RequestMethod.POST)
public void addGooglePlace(#PathVariable Long groupId, #RequestParam String googlePlaceId) {
this.userGroupService.addGooglePlace(groupId, googlePlaceId);
}
and those requests are working without any problems.
#PathVariable is for parameters which are part of the URL like: /groups/{groupId}/google-places.
If parameter is after the ? you should use #RequestParam annotation.
#RequestMapping(value = "/foo", method = RequestMethod.GET)
public List<GooglePlaceEntity> doNearbySearch(#RequestParam Float latitude) {
LOGGER.trace("Searching for places nearby.");
return null;
}

ResponseEntity doesn't retrieve Integer

Want to return simple Integer in ResponseEntity:
#PreAuthorize("hasAnyAuthority('WORKER')")
#RequestMapping(value = "/countFiles", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Integer> countFiles(HttpServletRequest request){
Integer count = fileService.countFiles(request);
if(count == null){
return new ResponseEntity<Integer>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Integer>(count, HttpStatus.OK);
}
When I do it, at front end site I got without filed named 'count':
Before you answer:
At front end site everything works fine
The bug is at backend site
If you want a field named "count", you need to include the field name in an object or map result.
#PreAuthorize("hasAnyAuthority('WORKER')")
#RequestMapping(value = "/countFiles", method = RequestMethod.GET)
public ResponseEntity<Integer> countFiles(HttpServletRequest request)
{
Integer count = fileService.countFiles(request);
if (count == null) {
return ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(Collections.singletonMap("count", count));
}
FYI, it may be easier to use the static ResponseEntity.* methods to create new ResponseEntity instances. Also, you don't need #ResponseBody if the return value is ResponseEntity.

set #RequestMapping value to return spring controller

I have problem with mapping in spring 3 mvc. General I must "send" value (#RequestMapping(value = "/*") to my return statement. How it resolve? I was thinking about this:
#RequestMapping(value = "/*", method = RequestMethod.GET)
public String homeForm( Model model, HttpServletResponse response) throws IOException {
logger.info("Welcome ");
String url=response.getWriter().toString();
return url;
}
Is it good solutions, maybe someone has any advices?
Thaks
If you want to return the string that comes after the slash, you could do something like this:
#RequestMapping(value = "/{foo}", method = RequestMethod.GET)
public #ResponseBody String homeForm(#PathVariable("foo") String foo) {
return foo;
}

Influence on performance of using 'private static final' strings in Spring 3 REST controller

I'm working on REST API based on Spring 3 MVC. In each call I'm adding to JSON response two variables: 'description' and 'result'.
For example:
#RequestMapping(value = "entity.htm", method = RequestMethod.GET)
public ModelAndView get() {
ModelAndView mav = new ModelAndView(JSON_VIEW);
mav.addObject("description", "entity list");
mav.addObject("result", someService.getAll());
return mav;
}
Does it make sense for performance of the app to create a pool of private static final strings and use them every time I need?
I mean like this:
#Controller
public class MyController {
private static final String JSON_VIEW = "jsonView";
private static final String VAR_DESCRIPTION = "description";
private static final String VAR_RESULT = "result";
private static final String DESC_CREATED = "entity created";
private static final String DESC_ENTITY_LIST = "entity list";
private static final String DESC_ACCESS_DENIED = "forbidden";
#RequestMapping(value = "entity.htm", method = RequestMethod.PUT)
public ModelAndView put(HttpServletResponse response) {
ModelAndView mav = new ModelAndView(JSON_VIEW);
if (!entityService.someChecking()) {
mav.addObject(VAR_DESCRIPTION, DESC_ACCESS_DENIED);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
mav.addObject(VAR_DESCRIPTION, DESC_CREATED);
mav.addObject(VAR_RESULT, entityService.save(new Entity()));
response.setStatus(HttpServletResponse.SC_CREATED);
}
return mav;
}
#RequestMapping(value = "entity.htm", method = RequestMethod.GET)
public ModelAndView get(HttpServletResponse response) {
ModelAndView mav = new ModelAndView(JSON_VIEW);
if (!entityService.someChecking()) {
mav.addObject(VAR_DESCRIPTION, DESC_ACCESS_DENIED);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
mav.addObject(VAR_DESCRIPTION, DESC_ENTITY_LIST);
mav.addObject(VAR_RESULT, entityService.getAll());
}
return mav;
}
// and so on
}
Someone of these statuses I use only once, but DESC_ACCESS_DENIED I use up to 10 times in one REST controller.
Your get is not returning json, it returns a view.
I prefer using an enum instead of static final ints - easier to add functionality later.
Yes, it does make sense. It's a good pratice. It save's you time and effort if you ever need to change this values. It's quite insignificant in terms of memory use or process time, but it's better.
If you intend to use those strings more than once, then it is a good pratice to turn then into static final. But notice your methods aren't returning JSON responses. A JSON response is something like that:
#RequestMapping(value = "/porUF", method = RequestMethod.GET)
public #ResponseBody List<Municipio> municipios(
#RequestParam(value = "uf", required = true) String uf) {
if ( uf.length() != 2) {
return null;
}
return municipioBO.findByUf(uf);
}
The #ResponseBody annotation will transform the List into a JSON object, and the response of a HTTP GET for that is something like that:
[{"codigo":9701,"uf":{"uf":"DF","nome":"DISTRITO FEDERAL"},"nome":"BRASILIA "}]
This is a JSON response.

Expecting a request param with a "XOR" validation

I have a simple request call in a spring mvc controller
#ResponseBody
#RequestMapping(value = "/url", method = RequestMethod.GET)
public SomeDTO getSth(#RequestParam("paramA") Integer paramA, #RequestParam("paramB") Integer paramB) {
// ...
}
and I want to have either the paramA or the paramB otherwise a normal http response as it currently happens if I do not provide both parameters.
I know there is a required parameter available, but I do not see a way to connect both. Any idea?
I can't think of a very good solution, but the straightforward one seems to be normal, isn't it?
#ResponseBody
#RequestMapping(value = "/url", method = RequestMethod.GET)
public String getSth(#RequestParam(value = "paramA", required = false) Integer paramA,
#RequestParam(value = "paramB", required = false) Integer paramB) {
if (paramA == null ^ paramB == null) {
return "body";
} else {
throw new BadRequestException();
}
}
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public static class BadRequestException extends RuntimeException {
private static final long serialVersionUID = 1L;
}

Resources