Error: No string encryptor registered for hibernate with name "hibernateStringEncryptor" in with jasypt - spring

I have a problem with Jasyt with Spring Boot and Hibernate.
When i try to write encrypted password into database i got an error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'receptionistController': Invocation of init method failed; nested exception is org.jasypt.exceptions.EncryptionInitializationException: No string encryptor registered for hibernate with name "hibernateStringEncryptor"
hibernateStringEncryptor is registred in Configuration class
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = "medical.center")
public class HibernateConfig {
#Bean
public void Test(){
System.out.println("Test");
}
public EnvironmentStringPBEConfig encryptorConfiguration(){
EnvironmentStringPBEConfig encryptor = new EnvironmentStringPBEConfig();
encryptor.setAlgorithm("PBEWithMD5AndDES");
encryptor.setPasswordSysPropertyName("beaver.encryption.password");
return encryptor;
}
public StandardPBEStringEncryptor standardStringEncryptor(){
StandardPBEStringEncryptor stringEncryptor = new StandardPBEStringEncryptor();
stringEncryptor.setConfig(encryptorConfiguration());
return stringEncryptor;
}
#Bean
#Autowired
public HibernatePBEStringEncryptor hibernateStringEncryptor(){
HibernatePBEStringEncryptor stringEncryptor = new HibernatePBEStringEncryptor();
stringEncryptor.setEncryptor(standardStringEncryptor());
stringEncryptor.setRegisteredName("hibernateStringEncryptor");
return stringEncryptor;
}
And User Class:
#Entity
#TypeDef(
name="encryptedString",
typeClass=EncryptedStringType.class,
parameters={#Parameter(name="encryptorRegisteredName",
value="hibernateStringEncryptor")}
public class User {
#Id
#GeneratedValue
private Long id;
private String login;
#Autowired
#Type(type="encryptedString")
private String password;
private String firstName;
private String lastName;
#Column(nullable=true)
private String email;
#Column(nullable=true)
private String phone;
#Column(nullable=true)
private LocalDate bornDate;
#CreatedDate
private LocalDateTime createTime;
#LastModifiedDate
private LocalDateTime modDate;
#Transient
private final static String[] rolesArray = { "Admin", "Doctor", "Patient", "Receptionist" };
private int role;
#Autowired(required=false)
#OneToMany(cascade = CascadeType.ALL)
#Column(nullable = true)
private List<UserMessage> userMessagesRecive;
#Autowired(required=false)
#OneToMany(cascade = CascadeType.ALL)
#Column(nullable = true)
private List<UserMessage> userMessagesSend;
public static String[] getRolesArray() {
return rolesArray;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public void setModDate(LocalDateTime modDate) {
this.modDate = modDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstMame) {
this.firstName = firstMame;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBornDate() {
return bornDate;
}
public void setBornDate(LocalDate bornDate) {
this.bornDate = bornDate;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public String[] getRoles() {
return rolesArray;
}
public List<UserMessage> getUserMessagesRecive() {
return userMessagesRecive;
}
public void setUserMessagesRecive(List<UserMessage> userMessagesRecive) {
this.userMessagesRecive = userMessagesRecive;
}
public List<UserMessage> getUserMessagesSend() {
return userMessagesSend;
}
public void setUserMessagesSend(List<UserMessage> userMessagesSend) {
this.userMessagesSend = userMessagesSend;
}
public String getRoleByName(int role) {
return rolesArray[role];
}
}
And main method:
#SpringBootApplication
#EnableJpaRepositories("medical.center")
#ComponentScan(basePackages = "medical.center")
#EntityScan("medical.center")
#EnableTransactionManagement
public class MedicalCenterApplication {
public static void main(String[] args) {
SpringApplication.run(MedicalCenterApplication.class, args);
and Receptionist Class:
#RestController
public class ReceptionistController {
#Autowired
private final ReceptionistRepository receptionistRepository;
private final ReceptionistGenerator receptionistGenerator;
private static final Logger logger = Logger.getLogger(ReceptionistController.class);
public ReceptionistController(ReceptionistRepository receptionistRepository,
ReceptionistGenerator receptionistGenerator) {
this.receptionistRepository = receptionistRepository;
this.receptionistGenerator = receptionistGenerator;
}
#PostConstruct
public void runAtStart() {
receptionistRepository.save(receptionistGenerator.generate());
}
#GetMapping("/getRecepcionist")
public Receptionist getReceptionist() {
logger.info("Get Receptionist");
return receptionistRepository.getOne(1L);
}
}
Please help.
Lukasz

Related

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.

Spring Boot; passing user's First Name to welcome.jsp after logging in

A lot of the articles online for Spring Boot deals with Spring Security and it does not help me in the slightest. I am trying to implement a registration and login page and once the user successfully logins, it will take them to a welcome page where it should display their first name, something like "Welcome first name or Welcome username". I have tried passing the first name through a
model.addAttribute("firstName", accountInstance.getFirstName());
but that doesn't seem to work. Any hints to achieve this would be much appreciated
Login Controller
#Controller
public class LoginController {
#Autowired
private AccountRepository accountRepo;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model) {
model.addAttribute("login", new AccountEntity());
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public Object submitLoginIn(#ModelAttribute("login") AccountEntity accountForm, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(accountForm.getEmail().toLowerCase());
// Password Verifier using Argon2
Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder();
boolean passwordMatch = argon2PasswordEncoder.matches(accountForm.getPassword(), accountInstance.getPassword());
// issue where if i use caps email, throws null pointer exception
if (accountInstance == null || !passwordMatch) {
System.out.println("Invalid Email or Password");
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
return "login";
} else if (accountInstance.isEnabled() == false) {
System.out.println("Cant login cause not verified");
return "login";
} else {
System.out.println("account exist");
model.addAttribute("firstName", accountInstance.getFirstName());
return "redirect:welcome"; // Change later
}
}
}
Account Repository
public interface AccountRepository extends CrudRepository<AccountEntity, Long> {
// Optional<AccountEntity> findById(Long Id);
AccountEntity findByUserName(String userName);
AccountEntity findByPassword(String password);
AccountEntity findByEmail(String email);
AccountEntity findByVerificationCode(String verificationCode);
}
Account Entity
#Entity(name = "user")
public class AccountEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String userName;
private String email;
private String password;
// private String gender;
private Integer age;
private Date createdDate;
private boolean enabled;
#Column(updatable = false)
private String verificationCode;
// Getters and Setters
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
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 String getGender() { return gender; }
*
* public void setGender(String gender) { this.gender = gender; }
*/
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Welcome.jsp
<p> Welcome, ${firstName.firstName} </p>
<!-- <p> Welcome, ${firstName} </p> -->
SO #Bollywood was correct with the redirecting:welcome. Doing so didn't pass the value I wanted to the jsp. Changing it to return "welcome" instead of return "redirect:welcome" worked!

Can't save many-to-many relations by form in JSP

The Context
I have a simple workshop application with three entities - Job, Employee and Customer. I am trying to create web interface which will add new Job in this case. Job has many to many relations with Employee and Customer. In Job entity there are lists of Employee and Customer as well.
The Problem
When I try to post my request with new Job through HTTP I get Bad Request 400 with description:
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
I don't know where excactly is bug.
Forms for adding Customer and Employee work fine.
The Code
Entities:
Employee
#Component
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String employeeName;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String employeeSurname;
#ManyToMany(mappedBy = "employeeList")
private List<Job> jobList;
public Employee() {
}
public Employee(int id, String employeeName, String employeeSurname) {
this.id = id;
this.employeeName = employeeName;
this.employeeSurname = employeeSurname;
}
public Employee(String employeeName, String employeeSurname) {
this.employeeName = employeeName;
this.employeeSurname = employeeSurname;
}
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeSurname() {
return employeeSurname;
}
public void setEmployeeSurname(String employeeSurname) {
this.employeeSurname = employeeSurname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}}
Customer
#Component
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Pattern(regexp="[a-zA-Z]+")
#NotEmpty
private String CustomerName;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String CustomerSurname;
#Pattern (regexp = "\\w+")
#NotEmpty
private String car;
private int phonenumber;
#ManyToMany(mappedBy = "customerList")
private List<Job> jobList;
public Customer(String customerName, String customerSurname, String car, int phonenumber) {
CustomerName = customerName;
CustomerSurname = customerSurname;
this.car = car;
this.phonenumber = phonenumber;
}
public Customer(int id, String customerName, String customerSurname, String car, int phonenumber) {
this.id=id;
CustomerName = customerName;
CustomerSurname = customerSurname;
this.car = car;
this.phonenumber = phonenumber;
}
public Customer() {
}
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
public String getCustomerName() {
return CustomerName;
}
public void setCustomerName(String customerName) {
CustomerName = customerName;
}
public String getCustomerSurname() {
return CustomerSurname;
}
public void setCustomerSurname(String customerSurname) {
CustomerSurname = customerSurname;
}
public int getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(int phonenumber) {
this.phonenumber = phonenumber;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}}
Job
#Component
#Entity
public class Job {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotEmpty
#Pattern(regexp="[a-zA-Z]+")
private String jobName;
#ManyToMany(fetch = FetchType.EAGER)
private List<Employee> employeeList;
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany
private List<Customer> customerList;
public Job() {
}
public Job(String jobName, List<Employee> employeeList, List<Customer> customerList) {
this.jobName = jobName;
this.employeeList = employeeList;
this.customerList = customerList;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public List<Customer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}}
DaoImpl
JobDaoImpl
#Repository
public class JobDaoImpl implements JobDao {
#PersistenceContext
EntityManager entityManager;
#Override
public List<Job> findAllJobs() {
return entityManager.createQuery("select j from Job j order by j.id", Job.class)
.getResultList();
}
#Override
public Job addJob(Job job) {
entityManager.persist(job);
entityManager.flush();
entityManager.refresh(job);
return job;
}}
Service
JobService
#Service
#Transactional
public class JobService {
private JobDao jobDao;
public List<Job> findAllJobs(){
return jobDao.findAllJobs();
}
public Job addNewJob(Job job){return jobDao.addJob(job);}
public JobService(JobDao jobDao) {
this.jobDao = jobDao;
}
}
Controller
JobController
#Controller
public class JobController {
JobService jobService;
EmployeeService employeeService;
CustomerService customerService;
public JobController(JobService jobService, EmployeeService employeeService, CustomerService customerService) {
this.jobService = jobService;
this.employeeService = employeeService;
this.customerService = customerService;
}
//JOB INDEX
#RequestMapping("job-index.html")
public ModelAndView getJobIndex() {
ModelAndView modelAndView = new ModelAndView("jobViews/jobIndex");
return modelAndView;
}
//SHOW EMPLOYEES
#RequestMapping("show-jobs.html")
public ModelAndView getAllJobs() {
ModelAndView modelAndView = new ModelAndView("jobViews/jobs");
modelAndView.addObject("jobs", jobService.findAllJobs());
return modelAndView;
}
//ADD NEW JOB GET METHOD
#GetMapping(value = "add-job.html")
public ModelAndView addNewJob(){
return new ModelAndView("jobViews/addJob","job", new Job());
}
//ADD NEW JOB POST METHOD
#PostMapping(value = "add-job.html")
public ModelAndView addNewJob(#ModelAttribute Job job){
return new ModelAndView("jobViews/addJobConfirmation","job",job);
}
#ModelAttribute("employeeInit")
public List<Employee> initializeEmployees() {
return employeeService.findAllEmployee();
}
#ModelAttribute("customerInit")
public List<Customer> initializeCustomer(){ return customerService.findAllCustomer();}}
JSP Views
addJob.jsp
<f:form method="post" modelAttribute="job">
<p>Job name:<f:input path="jobName"/></p>
<f:hidden path="id"/>
<f:select path="employeeList" multiple="true">
<f:options items="${employeeInit}" itemLabel="employeeSurname" itemValue="id"></f:options>
</f:select>
<f:select path="customerList" multiple="true">
<f:options items="${customerInit}" itemLabel="customerSurname" itemValue="id"></f:options>
</f:select>
<button type="submit">Add</button>

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.

[org.hibernate.mapping.Column(authorities)]

I have follow Hibernate error:
"Could not determine type for: java.util.List, at table: user, for columns: [org.hibernate.mapping.Column(authorities)]"
What can cause a problem?
Also, is it possible use it without model role, and set return getAuthority role "USER" by default?
User model:
#Entity
#Table(name = "user")
public class User implements UserDetails {
private int id;
private String username;
private String password;
private List<Role> roles;
#Id
#GeneratedValue
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String getUsername() {
return this.username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public List<Role> getAuthorities() {
return this.roles;
}
#OneToMany(mappedBy = "user")
public List<Role> getRoles() {
return this.roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Role model:
#Entity
#Table(name = "role")
public class Role implements GrantedAuthority {
private int id;
private User user;
private String role;
public Role() {
}
public Role(String role){
this.role = role;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name="user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String getAuthority() {
return this.role;
}
#Basic
#Column(name="role")
public String getRole(){
return this.role;
}
public void setRole(String role){
this.role = role;
}
}
I found solution myself. I set #Transient annotation to all method, which i don't want that it shouldn't be column in table.
You must replace all annotations for the attributes not to the getter methods.

Resources