unable to query findOne - SpringMVC MongoDB - spring

I am trying to login but unable to login because findOne query fails in DAOimplementation. I put series of system.out.println to see where does things go wrong.
and I get this
email: abcdef Password : 123123
email2: abcdef Password2: 123123
check 1
check 2
for some reason program wont reach to check 3, check 4 and inside if condition where user != null.
I tried mongoTemplate, mongoOperations, using addCriteria without criteria but no luck.
Code: UserDaoImplementation
import com.mthree.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
#Repository
#Service(value = "userDao")
public class UserDaoImpl implements UserDao {
#Autowired
MongoTemplate mongoTemplate;
private static final String COLLECTION_NAME = "user";
public List<User> listUser() {
return mongoTemplate.findAll(User.class, COLLECTION_NAME);
}
public void add(User user) {
if(!mongoTemplate.collectionExists(User.class)){
mongoTemplate.createCollection(User.class);
}
user.setId(UUID.randomUUID().toString());
mongoTemplate.insert(user, COLLECTION_NAME);
}
public void update(User user) {
mongoTemplate.save(user);
}
public void delete(User user) {
mongoTemplate.remove(user, COLLECTION_NAME);
}
public User findUserById(String id) {
return mongoTemplate.findById(id, User.class);
}
#Override
public User login(String Email, String Password) {
System.out.println("email2: "+ Email + " Password2: "+ Password);
try {
System.out.println("check 1");
Query query = new Query();
System.out.println("check 2");
// User user = mongoTemplate
// .findOne(query.addCriteria(Criteria.where("Email").is(Email)), User.class, COLLECTION_NAME);
User user = mongoTemplate.findOne(query(where("Email").is(Email)), User.class,COLLECTION_NAME);
System.out.println("check 3");
if(user != null){
//return user;
System.out.println("check 4");
System.out.println("password3: "+ Password + " Password4: "+ user.getPassword());
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//{} t y
if(bCryptPasswordEncoder.matches(Password, user.getPassword())) {
return user;
}
}
return null;
}catch (Exception e){
return null;
}
}
#Override
public void register(User user) {
mongoTemplate.insert(user);
}
#Override
public void changeProfile(User user) {
mongoTemplate.save(user);
}
}
Controller
#RequestMapping(value="/login", method= RequestMethod.POST)
public String login(#ModelAttribute("user") User user, HttpSession session, ModelMap modelMap){
//simply checking the values my password is not yet encrypted
System.out.println("email: "+ user.getEmail() + " Password : "+ user.getPassword());
User user2 = userService.login(user.getEmail(), user.getPassword());
if(user2 == null){
modelMap.put("error", "Invalid User");
return "account/login";
}else{
session.setAttribute("username", user.getFirstname());
return "account/welcome";
}
//BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
// userService.register(user);
//return "redirect:../login";
}
User - model
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class User {
#Id
private String id;
private long UserId;
private String Firstname;
private String Lastname;
private String Email;
private String Password;
private String Role;
private long CountryCode;
private long MobileNumber;
private String City;
private String Address;
public User(){
super();
}
public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address) {
super();
this.id = id;
this.UserId = userId;
this.Firstname = firstname;
this.Lastname = lastname;
this.Email = email;
this.Password = password;
this.Role = role;
this.CountryCode = countryCode;
this.MobileNumber = mobileNumber;
this.City = city;
this.Address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getUserId() {
return UserId;
}
public void setUserId(long userId) {
this.UserId = userId;
}
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 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 getRole() {
return Role;
}
public void setRole(String role) {
this.Role = role;
}
public long getCountryCode() {
return CountryCode;
}
public void setCountryCode(long countryCode) {
this.CountryCode = countryCode;
}
public long getMobileNumber() {
return MobileNumber;
}
public void setMobileNumber(long mobileNumber) {
this.MobileNumber = mobileNumber;
}
public String getCity() {
return City;
}
public void setCity(String city) {
this.City = city;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
this.Address = address;
}
}
Stack Trace
e: org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:257)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:230)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:205)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:867)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:758)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:735)
at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:231)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:129)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1760)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1750)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:624)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:589)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:581)
at com.mthree.dao.UserDaoImpl.login(UserDaoImpl.java:67)
at com.mthree.service.UserServiceImpl.login(UserServiceImpl.java:38)
at com.mthree.controller.HomeController.login(HomeController.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Use proper Java (Beans) naming conventions:
CamelCase with first letter lowercase:
public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address)
{
super();
this.id = id;
this.userId = userId;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.role = role;
this.countryCode = countryCode;
this.mobileNumber = mobileNumber;
this.city = city;
this.address = address;
}
Getter and Setter should be the field name with the first letter upper case and prefixed with get or set if present.
Properties referenced in queries/Strings are the same as the field name.
Note: There are some defiations from the actual Java Beans specification, e.g. the option to not have a default constructor.

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";
}
}

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!

Spring tool suite: not-null property references a null or transient value

could you help me with this question?
I built a project on sts4. I am trying to let users register an account on Postman. The primary method I am testing is Put(PutMapping), which I wrote on sts4. I got the project initialized completely, but when I click send from Postman, I got errors like below.
not-null property references a null or transient value: com.appsdeveloperblog.app.ws.io.entity.UserEntity.firstName
The following is part of my project.
UserDetailsRequestModel, (for processing incoming requestbody)
public class UserDetailsRequestModel {
private String firstName;
private String lastName;
private String email;
private String password;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}```
2. UserRest, (Class, which will be returned back to Postman)
```package com.appsdeveloperblog.app.ws.ui.model.response;
public class UserRest {
// public id, not auto increment key from database
private String userId;
private String firstName;
private String lastName;
private String email;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}```
3. UserDTO
```package com.appsdeveloperblog.app.ws.shared.dto;
import java.io.Serializable;
public class UserDTO implements Serializable {
private static final long serialVersionUID = -5607842248454975055L;
// auto increment key from database
private long id;
// public user id, which could be returned back to application
private String userId;
private String firstName;
private String lastName;
private String email;
// clear text password
private String password;
// password which is encrypted, stored,
private String encryptedPassword;
private String emailVerificationToken;
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 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 getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserEntity
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "users")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 5313493413859894403L;
// this Id is a primary key and auto incremented
// once a new record is inserted into database table
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 120)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserServiceImpl
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.appsdeveloperblog.app.ws.UserRepository;
import com.appsdeveloperblog.app.ws.io.entity.UserEntity;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepository;
#Override
public UserDTO createUser(UserDTO user) {
// (0) check whether the email already exist in database
if(userRepository.findByEmail(user.getEmail()) != null) {
throw new IllegalArgumentException("Email already exists.");
}
// 1. create an object UserEntity,
UserEntity userEntity = new UserEntity();
// 2. copy info from userDTO to userEntity
BeanUtils.copyProperties(user, userEntity);
// 3. encryptedPassword can't be got from user
// we have to assign value here for testing
userEntity.setEncryptedPassword("test");
// 4. the second data that is generated during this class is userID
userEntity.setUserId("testUserId");
// 5. now we can save userEntity into database,
// since it contains info from user, have to use userRepository
// after Auto-wired, we can use its methods
// use save method, we can save userEntity into database
UserEntity storedUserDetails = userRepository.save(userEntity);
// 6. we can return it back to RestController
// so we need an UserDTO object
UserDTO returnValue = new UserDTO();
BeanUtils.copyProperties(storedUserDetails, returnValue);
return returnValue;
}
}
UserController
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
import com.appsdeveloperblog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloperblog.app.ws.ui.model.response.UserRest;
#RestController // to make this class receive requests from HTTP
#RequestMapping("users") // http://localhost:8080/users + methods
public class UserController {
#Autowired
UserService userService;
#GetMapping
public String getUser() {
return "get user was called";
}
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails) {
// 1. instantiate a new object, which will be returned.
UserRest returnValue = new UserRest();
System.out.println(userDetails.getFirstname());
// 2. instantiate a new User Data transfer object,
// which could be shared across different layers
// we will populate this object with info we received from request body
UserDTO userDTO = new UserDTO();
// 3. use class BeanUtils class, which is from spring framework
// to copy properties from source object(userDetails) to our data transfer object
// so, we can populate info from request body into our data transfer object
// so, we have a data transfer object, which is populated info from request body
BeanUtils.copyProperties(userDetails, userDTO);
// 4.
// (1) userDTO, will be created at UI level, then be passed to service layer
// (2) service class will perform some additional business logic
// and generate some additional values, these values will be added to userDTO,
// (3) then userDTO will be used in business logic with a data layer
// to prepare an entity class, which will be stored in database
UserDTO createdUser = userService.createUser(userDTO);
// 5. populate returnValue object
// copy information from createdUser into returnValue
// other sensitive info, like password, should not be included
BeanUtils.copyProperties(createdUser, returnValue);
// 6. return, to mobile applications,or in here to Postman(HTTP client)
return returnValue;
}
#PutMapping
public String updateUser() {
return "update user was called";
}
#DeleteMapping
public String deleteUser() {
return "delete user was called";
}
}
Configuration on Postman
enter image description here
enter image description here
The Error I got
enter image description here
I spent a day on it. Help, please.
Try this:
#PutMapping
public String updateUser(#RequestBody) {
return "update user was called";
}

Spring Data JPA - findByAlias vs. findUserByAlias - error with both

I am using spring boot 2 with JPA and Spring Security.
I have a handler method that, depending upon a dropdown, will find all links either similar to a specific title or posted by a specific user. I know my database is set up properly.
I am getting a null pointer exception at this line:
Optional<User> user = userRepository.findUserByAlias("searchTerm");
I have tried changing the method to findByAlias(...) with the same result.
This is the code for my UserRepository:
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findUserByAlias(String alias);
Optional<User> findByAlias(String alias);
}
and this is my handler method wherein the error occurs at this line:
Optional<User> user = userRepository.findUserByAlias("searchTerm");
#GetMapping("/search")
public String showSearchResults(#RequestParam("searchTerm") String searchTerm, #RequestParam("searchBy") String searchBy, Model model) {
System.out.println("INSIDE showSearchResults + searchTerm =" + searchTerm);
List<Link> searchResults;
if(searchBy.equals("user")) {
System.out.println("INSIDE IF EQUALS 'user'");
// get the user by alias
Optional<User> user = userRepository.findUserByAlias("searchTerm");
// if the user is present the find all links by the user id
if (user.isPresent()) {
searchResults = linkRepository.findAllByUser_Id(user.get().getId());
} else {
searchResults = null;
}
}
if(searchBy.equals("title")){
searchResults = linkRepository.findAllByTitleLike("%" + searchTerm + "%");
} else {
searchResults = null;
}
model.addAttribute("searchTerm", new SearchTerm());
model.addAttribute("searchResults", searchResults);
return "search-results";
}
and this is my User class:
#Entity
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private Long id;
#Column
private String email;
#Column
private String password;
#Column
private boolean enabled;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id")
)
private Set<Role> roles = new HashSet<>();
#Column
private String firstName;
#Column
private String lastName;
#Column
private String fullName;
#Column
private String alias;
#Transient
private String confirmPassword;
public User(){
}
public User(String email, String password, boolean enabled,
String firstName, String lastName,
String fullName, String alias) {
this.email = email;
this.password = password;
this.enabled = enabled;
this.firstName = firstName;
this.lastName = lastName;
this.fullName = fullName;
this.alias = alias;
}
public void addRole(Role role){
roles.add(role);
}
public void addRoles(Set<Role> roles) {
roles.forEach(this::addRole);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
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 getFullName() {
return firstName + " " + lastName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for(Role role : roles){
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
#Override
public String getUsername() {
return null;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
}
So I have two questions:
1.) First and most importantly - why am I getting null pointer exception? I'm at a loss as to how to go about debugging this.
2.) What is the difference between findByAlias and findUserByAlias?
Any advice would be much appreciated.
Thank you for your help,
Marc
How is your userRepository injected into your controller? It seems that is the most likely reason for the null pointer.

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