I need the originId and description fields to be optional if the status is 'CREATED' and mandatory if it's 'UPDATED'.
#PutMapping("{id}")
#ResponseStatus(HttpStatus.OK)
public Mono<Void> update(#PathVariable (value = "id") String id,
#RequestBody #Valid PackageDTO request) {
return update.execute(id, request);
}
public class PackageDTO {
private Long originId;
private String description;
private PackageStatus status;
}
public enum PackageStatus {
CREATED, UPDATED;
}
I tried to use 'required' in Requestbody but i did not succeed
Related
I have the below response modal generated from swagger2.0.
Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2022-08-17T22:02:01.513781100-05:00[America/Chicago]")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("city")
private String city ;
#JsonProperty("dateOfBirth")
private String dateOfBirth;
}
when the get User returns the response I would like to skip/Ignore the name and city and wants to return only id and dateOfBirth, how to use JsonIgnoreProperties while converting the response to bodyToMono.
public Mono<User> getUser(String userid) {
return this.webClientConfig
.getWebClient()
.get()
.uri(uriBuilder -> uriBuilder.path("/users/").path(userid).build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(User.class)
}
used Jackson2ObjectMapperBuilder
https://www.baeldung.com/jackson-deserialize-json-unknown-properties
In my current implementation Validation for the two fields of SpecialTransactionDTO (transactionMetric and transactionRank) works in all cases. Now its parent class TransactionDTO that I receive as a #RequestBody contains a boolean field shouldValidate that indicates whether to validate the two fields of SpecialTransactionDTO or not.
How should I configure (turn off) validation for the cases when the value of shouldValidate flag is false?
#PostMapping("{id}/transaction/")
#ApiOperation(value = "Create transaction", httpMethod = "POST", response = TransactionDTO.class)
public ResponseEntity<Object> createTransaction(#PathVariable("id") Long accountId,
#Validated({TransactionNumber.class})
#RequestBody TransactionDTO transaction)
throws NotFoundException, URISyntaxException {
TransactionDTO result = transactionService.createTransaction(accountId, transaction);
return ResponseEntity.created(new URI("api/userAccount/" + accountId)).body(result);
}
#JsonSubTypes({
#JsonSubTypes.Type(value = SpecialTransactionDTO.class, name = SpecialTransactionDTO.TYPE),
#JsonSubTypes.Type(value = TransactionDTO.class, name = TransactionDTO.TYPE)
})
public class TransactionDTO {
#NotNull
private Long id;
#NotNull
private String transactionInitiator;
private Boolean shouldValidate;
private String transactionCode;
}
public class SpecialTransactionDTO extends TransactionDTO {
#NotNull
private Long userId;
#Pattern(regexp = "0|\\d{8,11}")
private String transactionMetric;
#Pattern(regexp = "\\d{1,3}")
private String transactionRank;
}
You could eliminate #Validated annotation altogether and imitate Spring's behaviour as follows:
#PostMapping("{id}/transaction/")
#ApiOperation(value = "Create transaction", httpMethod = "POST", response = TransactionDTO.class)
public ResponseEntity<Object> createTransaction(#PathVariable("id") Long accountId,
#RequestBody TransactionDTO transaction)
throws NotFoundException, URISyntaxException, MethodArgumentNotValidException {
// Check if we should validate here. Spring will convert your MethodArgumentNotValidException into HTTP 400
if(transaction.shouldValidate) {
SpringValidatorAdapter adapter = new SpringValidatorAdapter(validator);
BeanPropertyBindingResult result = new BeanPropertyBindingResult(transaction, transaction.getClass().getName());
adapter.validate(transaction, result, TransactionNumber.class);
if (result.hasErrors()) {
throw new MethodArgumentNotValidException(null, result);
}
}
TransactionDTO result = transactionService.createTransaction(accountId, transaction);
return ResponseEntity.created(new URI("api/userAccount/" + accountId)).body(result);
}
I have an object like this.
public class Profile {
private String email;
private String phone;
#SerializedName("userCode")
private String user_code;
public String getEmail() {
return email;
}
public String getPhone() {
return phone;
}
public String getUser_code() {
return user_code;
}
}
This is what I got when I return that object in Rest API
{
"email": "abc#gmail.com",
"phone": 12345678,
"user_code": "742aeaefac"
}
Apparently annotation #SerializedName here did not work, I can understand that it get the object properties name base on its getter name, not in the annotation. If I change the getter name into getUserCode(), it will work as I expected.
I also try to use #JsonProperty but didn't help too.
Can someone explain what is the work here to solve this?
Update the code for serialization process in the controller.
#PostMapping(path = "/login", produces = "application/json")
#ResponseBody
public ClientRepresentation login(#RequestBody LoginRequest login) {
Map<String, Object> resObj = new HashMap<String, Object>();
ProfileResponse profileResponse = userService.findUserProfileByUserCode(login.getUserCode());
//Code logic to process object data...
resObj.put("profile", profileResponse);
return ClientRepresentationBuilder.buildClientRep(HttpStatus.OK.value(), "Success", resObj);
}
ClientRepresentation class
public class ClientRepresentation implements Serializable {
private Integer code;
private String message;
private Object data;
}
I have a Java (uses JPA) project that looks like below.
On the DB side:
TableName - Userdetails
Stores ID, no of items ordered and status.
The status is taken from another table called status.
On the Java side:
UserRepository is the JPA which has 2 methods to store user data into
the DB, and to retrieve user data based on the status.
An enum called Status equivalent to the DB table status.
Question:
If I want to store the user data into the DB, how should I pass the status field in?
E.g. should I do userRepository.storeToUserDetails("1", "John", Status.CREATED)
If I want to retrieve the user data based on status, how do I pass the status field?
E.g. userRepository.findUserDetailsByStatusIn(Status.CREATED)
1.You may add into logic of project Service class and use him from main code. in its turn, class Service should use interface Reposytory
Add to Status enum values of code
public enum Status {
CREATED(200), ACTIVE(207), SUSPENDET(400), FINDED(500);
private long code;
public long getCode() {
return code;
}
StatusEnum(long code){
this.code = code;
}
}
public class UserService{
#Autovired
private UserRepository userRepository;
public storeToUserDetails(long id, String name, Status status){
User user = userRepository.getOne(id);
user.setName(name);
user.setStatus(status);
userRepository.update(user);
}
}
3. Create class StatusCode
#Entity(name = "status")
public class StatusCode {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "status")
private long status;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getStatusCode() {
return status;
}
public void setStatusCode(String statusCode) {
this.status = statusCode;
}
}
In entity User use setter and getter for Status:
#OneToOne(cascade = CascadeType.ALL)
private StatusCode statusCode;
public void setStatus(Status status){
StatusCode temp = new StatusCode();
temp.setStatusName(status.name());
temp.setId(status.getCode());
this.setStatus(temp);
}
public Status getStatus(){
if statusCode != null{
return Satus.valueOf(statusCode.getName())}
return null;
}
Repository:
public interface UserRepository extends JpaRepository<User, Long> {
}
methods getOne() and update() extends from JpaReposytory interfase
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