how can i retrieve object properties from the object returned from api calls using rest template - spring-boot

i made an api call using spring rest template as a rest client. when the method that makes the api returns a string, postman is able to see the object and the associated object properties with its values. but when i change the return type to an object that models the api object returned, i get all null values. is there something wrong i'm doing?
#GetMapping(value="/verbvn/{xbvn}")
public Participant verBVN(#PathVariable String xbvn) {
System.out.println("bvn is "+xbvn);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setBearerAuth("sk_live_32a7ffd9cc47f");
HttpEntity <String> entity = new HttpEntity<String>(headers);
Participant r= restTemplate.exchange("https://api.stck.co/bnk/resolve_bvn/"+xbvn, HttpMethod.GET, entity, new ParameterizedTypeReference<Participant>() {}).getBody();
System.out.println("the participant firstname is "+r.getFirstName());
return r;
}
public class Participant {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private Long id;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id",referencedColumnName="id")
private Data data;
public Participant() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
#Entity
#Table
#Async
#JsonIgnoreProperties(ignoreUnknown=true)
public class Data {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private Long id;
#Column
#JsonProperty(value="first_name")
private String firstName;
#Column
#JsonProperty(value="last_name")
private String lastName;
#Column
#JsonProperty(value="phone")
private String phoneNumber;
#Column
#JsonProperty(value="email")
private String email;
public Data() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

Related

How to display error message if record exists

I am trying to validate that if the email exists in my database, the error message will come out instead of the White Error Page.
I tried using this link but it is not working for me. Below are my codes.
Codes for Model Class
public class Employee {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email", unique = true)
#Email
private String email;
#Column(name = "posit")
private String position;
#Column(name = "mobile")
private String phone_num;
public Employee() {}
public Employee(String firstName, String lastName, String email, String position, String phone_num) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone_num = phone_num;
this.position = position;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
Codes for EmployeeServiceInterface
public interface EmployeeService {
Employee save(Employee employee);
}
Codes for EmployeeServiceImplementation
#Service
public class EmployeeServiceImpl implements EmployeeService{
#Autowired
private EmployeeRepository employeeRepository;
#Override
public Employee save(Employee employee) {
this.employeeRepository.save(employee);
return employee;
}
public boolean exist(String email){
return employeeRepository.existsByEmail(email);
}
Controller
#Controller
public class EmployeeRegistrationController {
#Autowired
private EmployeeService employeeService;
private EmployeeServiceImpl employeeImpl;
#PostMapping("/saveEmployee")
public String saveEmployee(#ModelAttribute("employee") Employee employee) {
// save employee to database
employeeService.save(employee);
if(employeeService.exist==true){
return "User already exist";
}
return "success";
}
}

How should I Map foreign keys in entity classes to model class (pojo) objects

Model Class for User:
#Component
public class UserModel {
private Integer userId;
private Integer roleId;
private String firstName;
private String email;
private String password;
public Integer getUserId() {
return userId;
}
public Integer getRoleId() {
return roleId;
}
public String getFirstName() {
return firstName;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public void setName(String firstName) {
this.firstName = firstName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
}
Model Class for Role of the User:
#Component
public class RolesModel {
private Integer roleId;
private String roleName;
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
Entity Class for User:
#Entity
#Table(name = "userBloodBank")
public class User {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Integer userId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="roleId")
private Roles roles;
#NotNull
#Column
#Pattern(regexp="[A-Z][a-zA-Z]*",message="Only enter words starting with captital letter")
private String firstName;
#NotNull
#Column
#Email
#Pattern(regexp = "^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+$", message = "Enter a proper email ID")
private String email;
#NotNull
#Column
#Pattern(regexp= "^(?=.*[0-9])"
+ "(?=.*[a-z])(?=.*[A-Z])"
+ "(?=.*[##$%^&+=])"
+ "(?=\\S+$).{8,20}$", message="Enter minimum 8 characters and maximum 20 characters")
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Entity Class for Role:
#Entity
#Table(name="Roles")
public class Roles {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Integer roleId;
#NotNull
#Column
#Pattern(regexp="(Recipient|Donor|BloodBankAdmin|Admin)", message = "Choose among Recipient|Donor|BloodBankAdmin|Admin")
private String roleName;
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
In the above case Role Id has oneToOne relationship and how will I map this to model object of role and user? Help me with the code to create the function "convertModelToEntity()" and "convertEntityToModel".
You can add below code in your User-entity class to map entity with Model.
public static UserModel convertEntityToModel(User user) {
UserModel userModel = new UserModel();
userModel.setUserId(user.getUserId());
userModel.setRoleId(user.getRoles().getRoleId());
userModel.setFirstName(user.getFirstName());
userModel.setEmail(user.getEmail());
userModel.setPassword(user.getPassword());
return userModel;
}
This will return User-model.
I think you should add the Roles-model(or list of Roles-model) in User Model.

How to access object graph in javers

I have two entities Employee and Address.
Employee.java
public class Employee {
private Long id;
private String firstName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Address.java
public class Address {
public Address(Long addressId, String address, Long id) {
this.addressId = addressId;
this.address = address;
this.id = id;
}
public Address() {
}
#Id
private Long addressId;
private Long employeeId;
private String address;
public Long getAddressId() {
return addressId;
}
public void setAddressId(Long addressId) {
this.addressId = addressId;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId= employeeId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Useing Javers api i want all the changes made by Employee including Address.
suppose employeeId e1 with name e made some change in address a1 with address xyz and employeeId e1
Changes changes = javers.findChanges(QueryBuilder.byInstanceId(id,com.mybatis.emo.bean.Employee.class).withNewObjectChanges(true).build());
I want address changes also comes while querying employee.

Gson set SerializedName

I am using retrofit for making requests to my server. I am trying to use the same Model for multiple requests and I want to send different objects with different SerializedName.
My pojo looks like this:
public class BaseModel<T> implements Serializable {
#SerializedName("success")
#Expose
private boolean succcess;
#SerializedName("data")
#Expose private T data;
public boolean isSucccess() {
return succcess;
}
public void setSucccess(boolean succcess) {
this.succcess = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
How can I set my #SerializedName("data") in a dynamic way? Thank you all for your time!
Code sample:
public class BaseRequestModel<T> implements Serializable {
#SerializedName("success")
#Expose
private boolean success;
#Expose private T data;
public boolean isSucccess() {
return success;
}
public void setSucccess(boolean succcess) {
this.success = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
One of the objects that I am sending to BaseModel (as T data):
public class User implements Serializable {
transient String requestName = "user";
#SerializedName("id")
#Expose
private int id;
#SerializedName("owner_id")
#Expose private int ownerId;
#SerializedName("first_name")
#Expose private String firstName;
#SerializedName("middle_name")
#Expose private String middleName;
#SerializedName("last_name")
#Expose private String lastName;
#SerializedName("username")
#Expose private String username;
public String getRequestName() {
return requestName;
}
public void setRequestName(String requestName) {
this.requestName = requestName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
My custom serializer:
public class BaseRequestCustomSerializer<T> implements JsonSerializer<User> {
#Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
src.getRequestName();
return null;
}
}
I have to pass to the serializer instead of the specific object, since this is what my problem is all about. Any ideas? Thank you!
if you want to set #SerializedName("data") than you must be get same variable name from api response.

Retrieve data from a specific entity in an inheritance relationship in Spring Data Mongo

I have implemented an inheritance relationship using Spring Data MongoDB
I have an abstract entity that contains all the attributes common to all the others.
#Document(collection = PersonEntity.COLLECTION_NAME)
public abstract class PersonEntity {
public final static String COLLECTION_NAME = "persons";
#Id
private ObjectId id;
#Field("first_name")
private String firstName;
#Field("last_name")
private String lastName;
private Integer age;
public PersonEntity(){}
#PersistenceConstructor
public PersonEntity(String firstName, String lastName, Integer age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public ObjectId getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getFullName(){
return this.firstName + " - " + this.lastName;
}
}
This entity inherits the entities UserSystemEntity and SonEntity. These have specific #Field attributes and do not define the #Document annotation. So all documents are stored in the collection of "PERSONS".
To work with these entities I have created the corresponding repositories. Here I put the repository for the entity SonEntity.
#Repository
public interface SonRepository extends MongoRepository<SonEntity, ObjectId> {
Iterable<SonEntity> findByParentId(ObjectId id);
Long countByParentId(ObjectId id);
Long countByParentIdAndId(ObjectId parentId, ObjectId id);
}
The problem I have, is that when I use this repository to obtain a list of entities "SonEntity" by the following method:
#Override
public Page<SonDTO> findPaginated(Pageable pageable) {
Page<SonEntity> childrenPage = sonRepository.findAll(pageable);
return childrenPage.map(new Converter<SonEntity, SonDTO>(){
#Override
public SonDTO convert(SonEntity sonEntity) {
return sonEntityMapper.sonEntityToSonDTO(sonEntity);
}
});
It returns me documents of all entity types (UserSystemEntity, ParentEntity, SonEntity).
How can I configure this correctly to retrieve only the documents of the SonEntity entity?
Thanks in advance.
"SonEntity" Entity code:
public final class SonEntity extends PersonEntity {
#DBRef
private SchoolEntity school;
#DBRef
private ParentEntity parent;
public SonEntity() {
}
#PersistenceConstructor
public SonEntity(String firstName, String lastName, Integer age, SchoolEntity school, ParentEntity parent) {
super(firstName, lastName, age);
this.school = school;
this.parent = parent;
}
public SchoolEntity getSchool() {
return school;
}
public void setSchool(SchoolEntity school) {
this.school = school;
}
public ParentEntity getParent() {
return parent;
}
public void setParent(ParentEntity parent) {
this.parent = parent;
}
}
"UserSystemEntity" code:
public class UserSystemEntity extends PersonEntity {
#Field("email")
protected String email;
#Field("password")
protected String password;
#Field("is_locked")
protected Boolean locked = Boolean.FALSE;
#Field("last_login_access")
protected Date lastLoginAccess;
#DBRef
protected AuthorityEntity authority;
public UserSystemEntity() {
}
#PersistenceConstructor
public UserSystemEntity(String firstName, String lastName, Integer age, String email, String password, AuthorityEntity authority) {
super(firstName, lastName, age);
this.email = email;
this.password = password;
this.authority = authority;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean isLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public Date getLastLoginAccess() {
return lastLoginAccess;
}
public void setLastLoginAccess(Date lastLoginAccess) {
this.lastLoginAccess = lastLoginAccess;
}
public AuthorityEntity getAuthority() {
return authority;
}
public void setAuthority(AuthorityEntity authority) {
this.authority = authority;
}
#Override
public String toString() {
return "UserSystemEntity [email=" + email + ", password=" + password + ", locked=" + locked + ", authority="
+ authority + "]";
}
}
"ParentEntity" code:
public final class ParentEntity extends UserSystemEntity {
public ParentEntity() {
}
#PersistenceConstructor
public ParentEntity(String firstName, String lastName, Integer age, String email, String password,
AuthorityEntity authority) {
super(firstName, lastName, age, email, password, authority);
}
}
Here you can verify that when trying to list all entities of type "SonEntity" appear data of other entities. The user "admin" is stored in the DB as a document of type UserSystemEntity:
The information is stored in MongoDB as follows:

Resources