Set Jersey to Default to JSON - jersey

I am using Jersey with Jackson. I want to default all endpoints (defined or not) to return JSON.
Let's say I have an /hello endpoint that produces application/json over GET. Now if I were to call /hello with POST, it is returning XML.
How does one configure this to default to JSON instead of XML?

I think I found an answer to this. I have not tested this yet, but am pretty sure this will work.
#Provider
public class CommonExceptionMapper implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception exception) {
return Response.status(statusCode).type(MediaType.APPLICATION_JSON).entity(restError).build();
}
}
I was missing the .type().

Related

Spring Boot - Is it possible to disable an end-point

Assuming I have a controller like:
public class MyController {
public String endpoint1() {...}
public String endpoint2() {...}
}
I want to disable endpoint1 for whatever reason in Spring. Simply, just disable it so that it cannot be accessed. So, I am not looking for how and what response to return in that case or how to secure that endpoint. Just looking to simply disable the endpoint, something like #Disabled annotation on it or so.
SOLUTION UPDATE:
Thanks all who contributed. I decided to go with #AdolinK suggestion . However, that solution will only disable access to the controller resulting into 404 Not Found. However, if you use OpenApi, your controller and all of its models such as request/response body will still show in swagger.
So, in addition to Adolin's suggestion and also added #Hidden OpenApi annotation to my controllers like:
In application.properties, set:
cars.controller.enabled=false
Then in your controller, use it. To hide controller from the OpenApi/Swagger as well, you can use #Hiden tag:
#Hidden
#ConditionalOnExpression("${cars.controller.enabled}")
#RestController
#RequestMapping("/cars")
public class Carontroller {
...
}
After this, every end point handled by this controller will return 404 Not Found and OpenApi/Swagger will not show the controllers nor any of its related schema objects such as CarRequestModel, CarResponseModel etc.
You can use #ConditionalOnExpression annotation.
public class MyController {
#ConditionalOnExpression("${my.controller.enabled:false}")
public String endpoint1() {...}
public String endpoint2() {...}
}
In application.properties, you indicates that controller is enabled by default
my.controller.enabled=true
ConditionalOnExpression sets false your property, and doesn't allow access to end-point
Why not remove the mapping annotation over that method?
Try this simple approach: You can define a property is.enable.enpoint1 to turn on/off your endpoint in a flexible way.
If you turn off the endpoint, then return a 404 or error page, which depends on your situation.
#Value("${is.enable.enpoint1}")
private String isEnableEnpoint1;
public String endpoint1() {
if (!"true".equals(isEnableEnpoint1)) {
return "404";
}
// code
}

GetMapping and PostMapping

#RestController
public class HelloWorldController {
#GetMapping(path="/helloWorld")
public String helloWorld() {
return "Hello-World";
}
}
I am new to RestFul WebServices. I tried to annotate the helloWorld() with PostMapping but it failed. Using GetMapping, it successfully gets executed.
Can somebody tell me why PostMapping was not allowed?
PostMapping for POST request.
GetMapping for GET request.
If you want call PostMapping success, you can use Postman or SoapUI, curl for testing HTTP POST request.
Reference document:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PostMapping.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html
In addition to #Do Nhu Vys answer. You will often encounter problems with CORS and CRFS while performing Post Requests.
References:
https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

#DenyAll ignored with Jersey (JAX-RS)

Here is my resource
#Path("test")
#DenyAll
public class TestResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public Response test() {
return Response.status(Response.Status.OK).entity("ok").build();
}
}
When I run the application and call GET /test the response is sent.
I am kind of confused, is there something else to do in addition to the annotation? Am I supposed to deny access myself in a filter?
When I use #RolesAllowed() I don't have to implement anything...
Thanks.
If you look at the source code for RolesAllowedDynamicFeature, you will see two two thing:
DenyAll is never checked for on classes.
There is a comment // DenyAll can't be attached to classes

Spring Data Rest Custom Method return String

I need a custom Method on Spring Data Rest that has some kind of input and returns a String.
#BasePathAwareController
#RequestMapping(value = "/businessActions")
public class BusinessActionController implements ResourceProcessor<RepositoryLinksResource> {
/**
* This BusinessAction's purpose is: Generiert für ein Modell das entsprechende Barrakuda-File.
* It returns one String.
*/
#RequestMapping(value = "/modellGenerieren", method = RequestMethod.GET)
public String modellGenerieren(#Param(value="project") String project) throws IOException {
// Get project by id from repository and map to string.
return "asdf\n";
}
}
By using #BasePathAwareController the endpoint will return "asdf\n", my desired output would be:
asdf
<new line>
Im able to produce this output by using only #Controller, but this breaks the awareness of the base path and i need the PersistentEntityResourceAssembler in other methods of this Controller - the assembler cannot be injected then.
The Bottom Line
It can be solved by using the following mapping and configuration:
// The OP's original controller with a small tweak
#BasePathAwareController
#RequestMapping("/businessActions")
public class MyCustomRestEndpoint {
// Let's specify the #produces type as text/plain (rather than the Spring Data REST JSON default)
#GetMapping(value = "/modellGenerieren", produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody ResponseEntity<String> modellGenerieren(#Param(value="project") String project) throws IOException {
// Get project by id from repository and map to string.
return ResponseEntity.ok("A String!");
}
}
#Configuration
public class PlainTextConfiguration implements RepositoryRestConfigurer {
// Allow for plain String responses from Spring via the `text/plain` content type
#Override
public void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters)
{
StringHttpMessageConverter converter = new StringHttpMessageConverter();
converter.setSupportedMediaTypes(configureMediaTypes());
messageConverters.add(converter);
}
private List<MediaType> configureMediaTypes() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.TEXT_PLAIN);
mediaTypes.add(MediaType.parseMediaType("text/plain;charset=iso-8859-1"));
mediaTypes.add(MediaType.parseMediaType("text/plain;charset=UTF-8"));
mediaTypes.add(MediaType.parseMediaType("text/plain;charset=UTF-16"));
return mediaTypes;
}
}
And by specifying the ACCEPT header when making the request (this is the key!):
GET http://localhost:8080/api/businessActions/modellGenerieren
Content-Type: text/plain
Accept: text/plain
This yields the following response:
GET http://localhost:8080/api/businessActions/modellGenerieren
HTTP/1.1 200 OK
Date: Mon, 24 Dec 2018 06:21:10 GMT
Content-Type: text/plain;charset=iso-8859-1
Accept-Charset: ... <large charset>
Content-Length: 9
A String!
Response code: 200 (OK); Time: 151ms; Content length: 9 bytes
The Reason
Upon investigation, it appears that the reason you can never seem to return the unquoted String is due to the behavior of the BasePathAwareHandlerMapping#lookupHandlerMethod function.
lookupHandlerMethod basically assumes that when making a request on a method, that the permissible media types are made with the HTTP request in the ACCEPT header. Otherwise it defaults to the default media type (configurable using RepositoryRestConfigurer#configureRepositoryRestConfiguration).
The default value for the default media type for Spring Data REST is either application/json or application/hal+json (depending on that default value, see here). That's why you are ONLY seeing application/json content types with the double quote, "", around your strings in the result. The String is being converted using the Jackson converter (which encloses Strings with quotes) and not a String converter.
After looking into it, I agree with you that this seems like a strange assumption. That is, the framework shouldn't assume that all requests are always explicitly specify the ACCEPT header with the desired media type (at least, I personally don't always expect to see it) and otherwise assume that all requests should be of the default media type only specifically because of a use case like yours.
Without looking too deeply into the documetation, the fact that #BasePathAwareController seems to imply that more than just the standard Spring Data Rest entities are fair game to use when leveraging Spring Data REST.
I'd personally return the produces type to the client even if the ACCEPT header wasn't specified -- and if I were to write some code to modify the BasePathAwareHandlerMapping, I'd add the following regarding my commented line:
#Override
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
...
if (!defaultFound) {
mediaTypes.add(configuration.getDefaultMediaType());
}
// Lookup the Handler Method for this request
// If no media types are specific in the ACCEPT header of this request...
// Then look and see if the method has a #produces specified and define that as the ACCEPT type
super.lookupHandlerMethod(lookupPath, new CustomAcceptHeaderHttpServletRequest(request, mediaTypes));
}
I have the same problem. And I have not solved it completely. But I hope this additional info at least helps:
There are 4 annotations in Spring and spring-data-rest that all are IMHO chaotically intermingeled. (See for example this Bug)
Spring Data Rest controllers: behaviour and usage of #BasePathAwareController, #RepositoryRestController, #Controller and #RestController
If you use #BasePathAwareController you get all the magic from Spring-data-rest (see SDR Doc) => But then you CANNOT return a simple String. (At least I did not found a way so far.)
If you use #RestController then your endpoint is completely indipendent from SDR.
If you want a #RestController to be exposed unser the same path prefix as the rest of your SDR API then you can use this:
#RestController
#RequestMapping("${spring.data.rest.base-path}")
public class MyCustomRestEndpoint { ... }
This reads the path prefix from application.properties
spring.data.rest.base-path=/api/v17
Then you can return a plain String.
But if you use #BasePathAwareController, as the OP said, because you need PersistentEntityResourceAssembler, then there is no way of returning a plain String.

Parsing JSON request body with Spring MVC

I am using Spring 4.1 framework for developing webservices. When I return a Java object as response, it is automatically converted to JSON and delivered to client, so I assume that JSON parser is in classpath and it is configured properly. However it fails to convert the request body from JSON into Java object and client is getting a HTTP response of 400.
Here is how the webservice looks like:
public class Details{
public Details(){
}
int code;
int area;
}
#RequestMapping(value = "/api/update/{phoneNumber}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> update(#PathVariable final String phoneNumber, #RequestBody Details details)
Here is how the request looks like:
Method: Post
Content-Type: application/json; charset=utf-8
Body: {"code":0,"area":12}
If I collect the request body as string and parse it manually then it works, so it gets the valid JSON but for some reason it is not parsing it automatically. I have no clue on how to fix it. Please help. Thanks in advance.
You have package-private properties in your Details class, so they are probably not recognised by json-converter.
You have several options:
define them as public (not recommended)
provide getters and setters
if you are using jackson, you can annotate them with #JsonProperty, leaving them package-private
Finally I got the reason for this. I was using inner classes which were not static. Making those static fixed the issue.

Resources