I'm using Vertx 3, and I'm trying to find a good decoupled module that knows to turn query-string, headers and both content-type and body into a bean?
I know spring does that and various other frameworks as well, but I don't want to introduce a new framework i just want a super fast model binder that will either know to auto bind to a certain method or at least auto bind a certain class so i can invoke my rest method that currently accept one parameter, which is the model.
public ResponseBase query(QueryRequest model){ ... }
I don't mind adding annotations to the parameters etc.
Thanks!
Current my team use vertx Json.decodeValue to turn body (json string) to java class.
MyClass body = Json.decodeValue(rc.getBodyAsString(), MyClass.class);
to config Json to handle unknown properties, I setting
Json.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
for your query string, I think it is easy to write a class to convert it to a json string :)
I also catch DecodeException on Json.decodeValue to re throw a 400 Bad Request error.
Related
RPC in Internet transport layer, use dto is reasonable. Http controller? If all controller are used by front end, parameter defined as VO?
I guess you are asking whether the argument of the rest controller method can be a DTO.
Well it will depend on the framework you use. The http parameters are strings.
If the framework has an utility mechanism (probably an annotation) that lets you map the http params you receive into a DTO you supply as the rest controller method arg, there's no problem in the arg being a DTO.
If the framework doesn't have such utility (it just maps each http param into an string arg of the rest controller method), then you have to build manually the DTO in the rest controller method.
I don't know if Spring has such an utility annotation similar to #PathVariable but for gathering multiple request params into a DTO object.
UPDATE:
Spring #RequestBody annotation deserializes the JSON into the java object argument of the rest controller method. So, the arg annotated with #RequestBody is a DTO.
DDD says nothing about which type must be the params of a rest api. They can be either a DTO or Strings, it doesn't matter. If they where strings, you would have to construct the DTO by yourself. Using #RequestBody, Spring framework does it for you.
In java, an object that is carries between process is named following the camel case notation and having the DTO suffix.
e.g. ServiceMessageDTO
DTO stands for data transfer object.
This applies also to the request body parameters from the rest webmethods.
Newbie question...
I'm building my first Spring Boot restful service and want to support a GET call that returns a collection of entities. like:
/api/customers/
However, for certain consumers -like a list page in a web UI - they would only need a subset of the customer entity properties.
I'm thinking that I could add request parameters to my GET call to set the consumers specific field requirements, like
/api/customers/?fields=id,name,address
But what's the best way of implementing this inside the Java restful controller?
Currently in my rest controller the 'GET' is request mapped to a Java method, like
#RequestMapping(value="/", method= RequestMethod.GET)
public Customer[] getList() {
Customer[] anArray = new Customer[];
....
return anArray;
}
Is it possible to somehow intervene with the default Java to Json response body translation so that only the required properties are included?
TIA
Adding fields parameter is a good idea, best practice according to http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#limiting-fields
How to leave fields out?
1) Set them to null, possibly in a dedicated output class annotated with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Or
2) Use SimpleBeanPropertyFilter See a good step by step tutorial here 5. Ignore Fields Using Filters
i am trying to get json data and store data in db and send json object about status of operation i am able to store data in db but my return json object is not working fine i am not getting json object
my java code:
#RequestMapping(value = "/a",headers="Content-Type=application/json",method = RequestMethod.POST)
#ResponseBody
public JSONObject data(#RequestBody String load)
{
org.json.JSONObject obj = new org.json.JSONObject();
obj.put("Status", "Success");
obj.put("Details","DB updated");
return obj;
}
In your #RequestMapping annotation define produces = MediaTyp.APPLICATION_JSON_VALUE. Your method should then just return a simple Map.
What is returned is actually controlled by the accepts Header in the request. So as an alternativ you could always ensure that your request asks for the right typ. But setting produces in the annotation is in my opinion a good idea as Spring does some auto conversions based on libraries available on the classpath. This might cause security issues if you do not control the type by hand.
edit:
Instead of a simple Map you could also just return any Java Object as long as it can be serialized by Jackson. You can control serialization using annotation in the Object class in this case.
Also you need the Jaclson library on the classpath for this to work (should be the case if you use a basic Spring Boot Web App).
Here is the offical Spring guide on how to build sutch a service: http://spring.io/guides/gs/rest-service/
Suppose I need to write a Java client, which calls a REST API (with HTTP GET). I know it returns the data in JSON by default and I do not need to supply any headers.
Now I can use either Apache HttpClient to invoke the API or read the URL directly (get a stream from the URL with url.openStream and read the data). The second approach seems to me much simpler. Which one would you suggest and why ?
All the REST clients provide a wrapper over basic java URL based APIs. These clients are easy to use and provide all the necessary functionality. Your code will be much cleaner in case you use Apache HttpClient. And Apache's API are quite reliable.
I would use special libraries for that, like Jersey client or Apache CXF client.
https://jersey.java.net/documentation/latest/client.html
http://cxf.apache.org/docs/jax-rs.html
These ones are part of Java EE standard, a well defined specification which is widely used.
For JSON, consider https://github.com/FasterXML/jackson. Depending on what client you use, you will find information about how to make it work.
If you are not a big fan of JavaEE, and you look for neat and elegant API, and you are interested in working with a language on top of Java, Groovy HTTPBuilder is such a library that works like a charm!
twitter = new RESTClient( 'https://twitter.com/statuses/' )
resp = twitter.post( path : 'update.xml',
body : [ status:msg, source:'httpbuilder' ],
requestContentType : URLENC )
assert resp.status == 200
assert resp.data.user.screen_name == userName
You can use spring-data-rest and Spring's RestTemplate. No need to write a webapp as you can bootstrap Spring easily into a standalone java application putting AnnotationConfigApplicationContext in the Main(). It's quite simple.
For example, suppose you have a Restful URL, http://localhost:8080/croot/books/ that returns a list of books (deserialized into objects of type Book).
Using Spring's RestTemplate you can do the following:
public Resource<List<Resource<Book>>> findAll() {
return restTemplate
.exchange(
"http://localhost:8080/croot/books/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Resource<List<Resource<Book>>>>() {
}).getBody();
}
You can also process this using spring-data-hateoas allowing you to further decouple the client from the server and helps process what to do next, say in pagination.
This is a very simplified/contrived example but the REST support in Spring 3 combined with the spring-data framework is quite elegant.
Using Spring you also get the advantage of Jackson for JSON processing as the RestTemplate will have one of the flavors of Jackson's message converters (provided through MappingJackson2HttpMessageConverter for example) in it's list of default converters used for processing.
I have a Spring MVC controller which is servicing GET requests, to perform a search.
These requests have many optional parameters which may be passed on the query string.
For example:
#Data
public class SimpleSearchRequest implements SearchRequest {
private String term;
private List<Status> stati;
#JsonDeserialize(using=DateRangeDeserializer.class)
private Range<DateTime> dateRange;
}
If I were using a POST or PUT for this, I could nicely marshall the inbound request using a #RequestBody. However, because I'm using a GET, this doesn't seem to fit.
Instead, it seems I'm required to list all the possible parameters on the method signature as #RequestParam(required=false).
Aside from leading to ugly method signatures, I'm also losing out on all sorts of OO goodness by not using classes here.
Attempting to use #RequestBody fails (understandably so), and as discussed here and here, using an actual request body on a GET is not desirable.
Is there a way to get Spring MVC to support marshalling multiple #RequestParam's to a strongly typed object on GET requests?
It seems the answer was to simply remove the annotation.
This worked:
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody List<Result> search(SearchRequest request) {}