How do I pass in an object to a rest template? - java

How do I pass in an object to a RestTemplate? I currently have an object that I am trying to pass in to two different functions. In one way, I want to pass it in as a RequestBody, and in the other I want to pass it in as a RequestParam.
For example, I have the following code:
Student student = new Student("Allison");
Teacher response = restTemplate.getForObject("url for get student's teacher api/{schoolID}", Teacher.class, student);
The getStudentsTeacher takes in paramters (#PathVariable schoolID, #RequestBody Student student).
My code does not work, as I am not specifying the content type (json), so how would I do this? Also, how would this work with #RequestParam instead of #RequestBody?

According to the RestTemplate javadoc, the uri variables can be expanded. So, all you need to do, is to supply to value to expand the variable in the template
Teacher response = restTemplate.getForObject("domain.com/api/{schoolId}", Teacher.class, 123);
Now, it's really strange that you're sending a GET request with body.
If you really need to do so, then you'll have to use the RestTemplate#exchange method.
HttpEntity<Student> request = new HttpEntity<Student>(new Student("Allison"));
// 123 -> it's the schoolId that the exchange method will be using to expand the uri variable
ResponseEntity<Teacher> teacher = restTemplate.exchange("domain.com/api/{schoolId}", HttpMethod.GET, request, Teacher.class, 123);
log.info(teacher.getBody());

Related

How to update few fields using buildPut jersey method

I have the following code in java to update book using buildPut, it works fine, the book has mutiple fields like id, name, author, pages etc. Now if I want to update only 2 fields(name,author), what chages need to be done. Somebody told to use a small object containing fields smallBook(id,name,author) and pass to this code with Entity.entity(smallBook, MediaType.APPLICATION_JSON)) instead of book;
Will this work or any other method ? Can you give some example ?
Book book = getBook();
Invocation request = getClient()
.path("book")
.path(book.getId().toString())
.request(MediaType.APPLICATION_JSON)
.buildPut(Entity.entity(book, MediaType.APPLICATION_JSON));
`

Can I reference the Object I'm currently inside of

Newbie here. So I'm working with java persistence to make a crude wedding website that maps guests (invites) to weddings. As each invite can attend multiple weddings, I've made a method that maps over them (using Java streams) and returns weddings they are associated with like so:
#RequestMapping("/invites")
public List<Wedding> invitesList(HttpSession session) {
String email = (String) session.getAttribute("email");
return invites.findByEmail(email).stream()
.map(invite -> {
return invite.wedding;
}).collect(Collectors.toCollection(ArrayList<Wedding>::new));
}
This successfully returns a list of weddings. However, on the site you can select one wedding and choose to invite more people to said wedding. The next view on the site asks for the information present in the invite object (String username, String email address, etc.) However, I'm not sure how to reference the wedding I'm "inside" so as to make the association between the invite and the correct wedding. The subsequent route is currently written as so, and adds the invite to the database, and then critically makes the correct association between invite and wedding, then returns a list of wedding -specific invites in order to show everyone who's invited to the wedding:
#RequestMapping(path = "/create-guest", method = RequestMethod.POST)
public List <Invite> guestList(#RequestBody Invite invite){
Wedding wedding = weddings.findOne(Integer.valueOf(?));
//unsure how to get weddingid here...
wedding.invite = invite;
invites.save(invite);
return (List) wedding.invite;
}
How am I going to get the wedding id? I can't store it in the session. Is there a way I can reference the wedding I'm inside of currently? I can't set it in the previous page, so I can't pull it out in the later page. My front end colleague (using angular) says he can pass me the wedding id inside the invite object, but the fields within my object class won't allow it. My question is: How can I pass the weddingId of the chosen wedding to this subsequent invite page?
I'm assuming your using Spring MVC based on your annotations.
You can use a path variable. So instead of posting to /create-guest for wedding id 123 you post to /create-guest/123. You can then use the #PathVariable annotation to access that like so.
#RequestMapping(path = "/create-guest/{weddingId}", method = RequestMethod.POST)
public List <Invite> guestList(#PathVariable(value="weddingId") String weddingId, #RequestBody Invite invite){
Wedding wedding = weddings.findOne(Integer.valueOf(weddingId));
wedding.invite = invite;
invites.save(invite);
return (List) wedding.invite;
}
Just a suggestion if you are creating a RESTful web service. I'm no expert on REST convention but I would think it would be more "REST like" for you to have the url as follows:
/wedding/123/guest
If you post to that URL then it should create a guest for wedding id 123.
Obviously this is convention and not a requirement. It will functionally work either way, but other developers may find your api easier to use if you follow REST convention.

Swagger UI with Java Rest Service

I am new to using Swagger documentation. I am using Swagger's annotations on Java rest service class. Could you please provide some help on the below problem -
My rest method is as below:
public String testMethod3(#ApiParam(value = "Mailing address of the user", required = true) #FormParam("address") final String address) {}
As you see, I am passing a JSON String parameter - address to my rest method. On the Javascript side, I have the below code to set up the data -
var addressMap = {};
addressMap.city = 'SS';
addressMap.zipCode = '98877';
addressMap.state = 'CA';
I am now sending this to the rest method by calling JSON.stringify(addressMap).
In Swagger-UI, I am only getting one parameter option to enter. How can I let the user to know that this is a complex object and they need to pass city, zipcode and state values.
If you're passing data in a #FormParam, you'll need to add a value for each of the fields. For example, city, zipCode, and state.
But I believe what you really want to do is post the JSON as a HTTP POST method, which case you would remove the #FormParam and consume the values into a java object that has the fields in the payload.

how can i typecast Request body into desired entity in REST API Controller

my motive is to write one generic save method in REST API. User will send the entity in Request body such that depending upon Request Mapping String it should be converted to entity.
Why i am want this, because in my case there are as many as 50-60 entities and as per my understanding i have to write many controllers.
I am trying to achieve something like this.
#RequestMapping(value = "/{entity}", method = RequestMethod.POST)
#ResponseBody
public Object performSave(#PathVariable String entity
#RequestBody Object entity) {
switch(entity){
case "employee"
return employeeService.save((Employee)entity);
case "Boss"
return bossService.save((Boss)entity);
default:
return null;
}
but i am not able to do that because Spring cannot convert the JSON Request into java.lang.Object.
what possible solutions i have ?
If my question do not make sense to you, please let me know ,i will provide additional details.
Thanks in advance.
I don't think that is possible as the underlying mapper would need the concrete class which the json is parsed to. The parameter is simply a reference to the actual object.
Something to take note of is that when using REST and getting the benefit from it is not only having simple urls to call. One has to design APIs to be RESTfull. I would advice you to read up on that concept before going down this path you are heading.
It can be done with only one controller.
One possible implementation would be using JsonSubTypes and Java inheritance.
It is done by moddeling request body objects (entities, in the original question) that extend an abstract class. Request body parameter in the controller's method then has the type of the abstract class.

Spring MVC: Dynamic Param Name or Param Name using Regex?

I'm trying out this grid component called jQuery Bootgrid. In AJAX mode, it POSTs parameters to the server and the one related to sorting is sent like this:
sort[colname]=desc
The colname part changes depending on how you sort the grid.
Is there any way in Spring MVC using #RequestParam to capture that sort param?
For example, something like:
#RequestParam("sort[{\\*}]") Map<String, String> sort
That's just a wild guess and I doubt there is any clean way to do it. Any suggestions on how to handle it would be great.
Update: Also tried this simpler version which I actually thought might work
#RequestParam("sort") Map<String, String> sort
See on bootgrid forum: https://github.com/rstaib/jquery-bootgrid/issues/111
It is really silly but because cannot parse dynamic parameter on server side, you need to create new request parameters from the sort parameter by defining requestHandler in your bootgrid configuration in the following way:
requestHandler: function (request) {
if (request.sort) {
request.sortBy = Object.keys(request.sort)[0]; //this only gets first sort param
request.sortDir = request.sort[request.sortBy];
delete request.sort
}
return request;
}
And in Spring Controller:
#RequestParam(value = "sortBy", required = false) final String sortBy,
#RequestParam(value = "sortDir", required = false) final String sortDir
Do not forget to mark these parameters as not required because sort is not always posted to server side.

Categories

Resources