Any hint to simplify this POST? (Java) - java

I implemented this POST operation in Jax-RS and it is working fine, however I am sure I can send the body in other way somehow. Any hint to simplify it? (By receiving an object for instance?)
Thanks!
#POST
#Path("updateUser/{name}/{surname}/{address}")
#Produces(MediaType.TEXT_PLAIN)
public Response updateUser(#FormParam("user") String name,
#FormParam("surname") String surname,
#FormParam("address") String address) throws UnknownHostException {
User user;
user = new CorporateUser(name, surname, address);
usersService.updateUser(user);
return Response.ok(user).build();
}

You can pass json string of object by using #consumes annotaion.
#POST
#Path("/updateUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public Response updateUser(User bean) {
usersService.updateUser(user);
return Response.ok(user).build();
}

Add a JSON provider like Jackson to your project.
#POST
#Path("updateUser")
#Consumes(value = { MediaType.APPLICATION_JSON })
#Produces(value = { MediaType.APPLICATION_JSON })
public Response updateUser(NewCorporateUserRequest req) throws UnknownHostException {
User user;
user = new CorporateUser(req.getName(), req.getSurname(), req.getAddress());
usersService.updateUser(user);
return Response.ok().entity(user).type(MediaType.APPLICATION_JSON).build();
}
public class NewCorporateUserRequest implements java.io.Serializable {
private String name;
private String surname;
private String address;
... Getters and Setters.
}

Related

POST request from Angular to SpringBoot API not sending parameters

I have this code, where I send an object to the API:
validateLogin(user:User):Observable<string>{
console.log(JSON.stringify(user));
return this.http.post<string>(`http://localhost:8080/login/login`, user).pipe(
map((resp)=>{
return this.repareString(JSON.stringify(resp));
})
)
}
I don't see anything wrong, but Spring Boot says "required request parameter 'user' for method parameter type String is not present". I've also tried sending it as a JSON object but it says the same. I believe that this is caused by the code in angular, that's why I post it here.
#RestController
#RequestMapping("/login")
public class LoginController {
#PostMapping("/login")
public static String login(#RequestParam String user) throws Exception{
System.out.println(user);
Login l = new ObjectMapper().readValue(user, Login.class);
if(l.checkUser().equals("ok")){
if(l.checkPassword().equals("ok")){
return "logged";
} else {
return l.checkPassword();
}
}
return l.checkUser();
}
}
And the Login class:
public class Login extends Database{
public String email;
public String pass;
public Statement stm;
public Login(String email, String pass) throws Exception{
this.email = email;
this.pass = pass;
this.stm = (Statement) this.con.createStatement();
}
I have tried sending it as a JSON string and I've also tried sending the object properties individually as various params.
Change your controller like this:
#RestController
#RequestMapping("/login")
public class LoginController {
#PostMapping("/login")
public static String login(#RequestBody Login login) throws Exception{
System.out.println(login);
if(login.checkUser().equals("ok")){
if(login.checkPassword().equals("ok")){
return "logged";
} else {
return login.checkPassword();
}
}
return login.checkUser();
}
}

Quarkus: #Valid doesn’t work with PanacheMongo

I have a problem with validation of my bean.
I'm using Quarkus with MongoDB and when I try to run a create REST API, with #Valid annotation before request bean, I expect an exception if I want to create a document with null field (obviously I use #NotNull in entity), but document is created without field.
Here is my code:
Car.java:
#MongoEntity(collection="cars")
public class Car extends PanacheMongoEntityBase {
#BsonId
private long id;
#NotNull
private String carName;
#NotNull
#Size(min = 1, max = 3)
private String code;
// get and set
}
CarResource.java:
#Path("/cars")
#Consumes("application/json")
#Produces("application/json")
public class CarResource {
#GET
public List<Car> list() {
return Car.listAll();
}
#GET
#Path("/{id}")
public Car get(long id) {
return Car.findById(id);
}
#POST
public Response create(#Valid Car car) {
car.persist();
return Response.status(201).build();
}
I have same problem with #Size annotation, because I can create a code field with more characters than 3.
UPDATE
Validation works with quarkus-hibernate-validator.
Now, I have to find a solution for unique field.
And besides from the main question: is there an annotation like #Indexed(unique = true)? I want an unique field for my app.
You need to use #Validated annotation on CarResource Class as shown below.
#Path("/cars")
#Consumes("application/json")
#Produces("application/json")
#Validated
public class CarResource {
#GET
public List<Car> list() {
return Car.listAll();
}
#GET
#Path("/{id}")
public Car get(long id) {
return Car.findById(id);
}
#POST
public Response create(#Valid Car car) {
car.persist();
return Response.status(201).build();
}
}

No suitable HttpMessageConverter found for response type and content type [application/json;charset=UTF-8] exception occurs

Im trying to hit Spring REST endpoint in my other module of the application. So im trying to use the REST Template to get a list of users as below :
The API request using REST Template :
public List<LeadUser> getUsersBySignUpType(String type, String id) {
String adminApiUrl = adminApiBaseUrl+"/crm/v1/users/?type="+type+"&id="+id;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<LeadUserList> response = restTemplate.exchange(
adminApiUrl, HttpMethod.GET, entity, LeadUserList.class);
return response.getBody().getUsersList();
}
LeadUserList class :
public class LeadUserList {
private List<LeadUser> usersList;
public List<LeadUser> getUsersList() {
return usersList;
}
}
LeadUser model class :
public class LeadUser {
#JsonProperty("id")
private String id;
#JsonProperty("email")
private String email;
#JsonProperty("name")
private String name;
#JsonProperty("businessName")
private String businessName;
#JsonProperty("phone")
private String phone;
#JsonProperty("address")
private String address;
#JsonProperty("createdTime")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
#JsonProperty("updatedTime")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date updatedTime;
#JsonProperty("bookletSignups")
private BookletSignUp bookletSignUp;
#JsonProperty("eventSignups")
private EventSignUp eventSignUp;
#JsonProperty("infoSignups")
private InfoSignUp infoSignUp;
#JsonProperty("webinarSignups")
private WebinarSignUp webinarSignUp;
public LeadUser() {
}
}
The API endpoint controller class :
#Controller
#Component
#RequestMapping(path = "/crm/v1")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value = "/users", method = GET,produces = "application/json")
#ResponseBody
public ResponseEntity<List<User>> getPartnersByDate(#RequestParam("type") String type,
#RequestParam("id") String id) throws ParseException {
List<User> usersList = userService.getUsersByType(type);
return new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
}
}
Although the return type is JSON from the API endpoint im getting the above exception. What have I done wrong here?
The exception :
Could not extract response: no suitable HttpMessageConverter found for response type [class admin.client.domain.LeadUserList] and content type [application/json]
Try additional settings as follows,
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
Also fix your exchange call,
ResponseEntity<List<LeadUser>> response = restTemplate.exchange(
adminApiUrl, HttpMethod.GET, entity, new ParameterizedTypeReference<List<LeadUser>>(){});

Error org.springframework.web.HttpMediaTypeNotSupportedException

i have a problem with rest and method post on my controler i have this 2 class the first is user in my class user i have my class with the getters and setter and a default contructor because for the finally I would like use Hibernate .:
#Entity
#Table(name="Utilisateur") // mapping with hibernate (but not using in this situation)
public class User {
#Id
private long id;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
#Column(name="admin")
private boolean admin;
#Column(name="actif")
private boolean actif;
#Column(name="logins")
private String logins;
#Column(name="email")
private String email;
#Column(name="naissance")
private String naissance;
#Column(name="pwd")
private String pwd;
#Column(name="compte")
private String compte;
public User(){
}
/*
with getter and setter.
*/
}
and my class controler (User controller) : is using for make the api principally post api .
#RestController
public class UserController {
#RequestMapping(
value="/api/greetings/post",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE
)
#ResponseBody
public ResponseEntity<User> getByEmail(#RequestBody User user){
if(user==null){
return new ResponseEntity<User>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
and i get this erreur I am using postman for make the query and in parameter of my query I send this Json query :
{"id":"3","nom":"Gille","prenom":"Laurent","admin":"1","actif":"0","logins":"gilaur","email":""toto#hotmail.com,"naissance":"1990/09/09","pwd":"gal","compte":"autre"}
And i get this error :
{"timestamp":1457906727481,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain;charset=UTF-8' not supported","path":"/api/greetings/post/"}
Thank you
you are change headers content-type application/json in Postman because you try set text/plain

Rest Api Post request

I cannot seem to get this to work for me ,I have seen this in other posts and was hoping someone may be able to spot what im doing wrong.I am trying to get the body of a request to this rest api but cannot seem to pull back what i need and just get null in the string below.
#POST
#Path("/SetFeeds")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String setFeed(#PathParam("name")String name2, #QueryParam("name") String name,#Context UriInfo uriInfo){
MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
String query = uriInfo.getRequestUri().getQuery();
String response = queryParams.getFirst("name");
return response;
}
A method parameter to accept the body of the request should not be annotated with anything (except in few cases like individual form params and multipart). So to get the raw JSON, you could simply add a String parameter
public String setFeed(#PathParam("name")String name2,
#QueryParam("name") String name,
#Context UriInfo uriInfo,
String jsonBody){
Or if you want to do the more common thing and use POJOs (so you don't need to parse the JSON yourself), you should look at this answer
Great answer, but I would like to add that you can use an object instead of a String and the Jackson of REST will take care the transformation without any further definition.
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String setFeed(#PathParam("name")String name2,
#QueryParam("name") String name,
MyJson json,
#Context UriInfo uriInfo){
MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
String query = uriInfo.getRequestUri().getQuery();
String response = queryParams.getFirst("name");
return response;
and a pojo as a json object:
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyJson{
private String name;
public MyJson(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

Categories