Spring Boot "Failed to execute CommandLineRunner Error" - java

I tried to add One To Many Annotation to my spring boot project, but when I run my project I get "Failed to execute CommandLineRunner " error.
I wanted users in the user's table to have more than one city. So, I tried to add OneToMany Annotation.
You can see the error at the attachment.
User Class
package io.javabrains.springsecurity.jpa.models;
import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="app_user")
public class User {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String userName;
private String password;
private boolean active;
private String role;
private String city;
#OneToMany(targetEntity = UserCity.class,cascade = CascadeType.ALL)
#JoinTable(name="USER_CITY",joinColumns=#JoinColumn(name="m_user_id"),
inverseJoinColumns=#JoinColumn(name="cityId"))
private List<UserCity> usercity;
public User() {
super();
// TODO Auto-generated constructor stub
}
public List<UserCity> getUsercity() {
return usercity;
}
public void setUsercity(List<UserCity> usercity) {
this.usercity = usercity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
User City Class
package io.javabrains.springsecurity.jpa.models;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="user_city")
public class UserCity {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int cityId;
private String cityName;
public UserCity() {
super();
// TODO Auto-generated constructor stub
}
public UserCity(int cityId, String cityName, User mUser) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.mUser = mUser;
}
#ManyToOne
private User mUser;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public User getmUser() {
return mUser;
}
public void setmUser(User mUser) {
this.mUser = mUser;
}
}
User Repository
package io.javabrains.springsecurity.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByUserName(String userName);
}
User City Repository
package io.javabrains.springsecurity.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
public interface CityRepository extends JpaRepository<UserCity,id>{
}
Spring Application Class
package io.javabrains.springsecurity.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
#SpringBootApplication
#EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{
#Bean
public WeatherService ws() {
return new WeatherService ();
}
#Autowired
UserRepository userRepository;
CityRepository cityRepository;
public static void main(String[] args) {
SpringApplication.run(SpringsecurityApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Application Running.");
User adminUser= new User();
UserCity ucity=new UserCity();
UserCity ucity2=new UserCity();
ucity.setCityName("amsterdam");
adminUser.setUserName("Admin");
adminUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
adminUser.setRole("ROLE_ADMIN");
adminUser.setActive(true);
adminUser.setCity("bologna");
ucity.setmUser(adminUser);
userRepository.save(adminUser);
cityRepository.save(ucity);
User newUser= new User();
newUser.setUserName("User");
newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
newUser.setRole("ROLE_USER");
newUser.setActive(true);
newUser.setCity("maribor");
ucity2.setmUser(newUser);
userRepository.save(newUser);
cityRepository.save(ucity2);
}
}

The problem you are encountering, more specifically the NullPointerException at line 54 of your main application, is caused by the fact that the cityRepository is not
instantiated.
Looking through your configuration, I see that you only register the UserRepository with the #EnableJpaRepositories annotation.
Try adding also the CityRepository to the #EnableJpaRepositories, and also specify this bean as a candidate for autowiring( also add #Autowired to this bean, as you did for UserRepository)
For a good practice, following the MVC structure, it would be nice is all your spring repositories, the beans responsible for all CRUD operations with the database to be under the same package

Related

SpringBoot #Service annotation issue

Hi people I am working on one application .I have created a model but after giving all annotation and configuring all properties it is showing below error. Can anyone please look into below issue?
application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/expenses
spring.datasource.username =dante
spring.datasource.password =jboss
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.format_sql=true
server.port=9191
Main Class
package com.expenses.demo;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.expenses.demo.modal.Role;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.service.UserService;
#SpringBootApplication
public class ExpenseApplication implements CommandLineRunner {
#Autowired
private UserService userService;
public static void main(String[] args) {
SpringApplication.run(ExpenseApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting code");
User user = new User();
user.setFirstname("Aniket");
user.setLastname("Turiley");
user.setEmail("abc#gmail.com");
user.setPassword("abc");
user.setPhone("99220289");
Role role1=new Role();
role1.setRoleId(44L);
role1.setRoleName("ADMIN");
Set<UserRole> userRoleSet = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setRole(role1);
userRole.setUser(user);
userRoleSet.add(userRole);
User user1= this.userService.createUser(user,userRoleSet);
System.out.println(user1.getUsername());
}
}
Model Class
Role.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="roleinformation")
public class Role {
#Id
private long roleId;
private String roleName;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "role")
private Set<UserRole> userRoles = new HashSet<>();
public Role() {
}
public Role(int roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long l) {
this.roleId = l;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
User.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usersinfo")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String username;
private String password;
private String email;
private String phone;
private boolean enable=true;
// user has many roles
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "user")
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public User() {
}
public User(Long id, String firstname, String lastname, String username, String password, String email,
String phone, boolean enable) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.enable = enable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
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 getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Repository Interfaces
RoleRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.Role;
public interface RoleRepository extends JpaRepository<Role, Long>{
}
UserRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
Service Class
Service.java
package com.expenses.service;
import java.util.Set;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
public interface UserService {
//creating user
public User createUser(User user,Set<UserRole> userRoles) throws Exception;
}
Service Implementation class
ServiceImplementation.java
package com.expenses.service;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.repository.RoleRepository;
import com.expenses.repository.UserRepository;
import com.expenses.service.UserService;
#Service
public class UserServiceImplementation implements UserService{
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
User local= this.userRepository.findByUsername(user.getUsername());
if(local!=null) {
System.out.println("User Already Exist");
throw new Exception("User Already Exist");
}else {
// user create
for(UserRole ur:userRoles) {
roleRepository.save(ur.getRole());
}
user.getUserRoles().addAll(userRoles);
local = this.userRepository.save(user);
}
return local;
}
}
ERROR
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-07-28 18:16:59.304[0;39m [31mERROR[0;39m [35m8492[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.expenses.demo.ExpenseApplication required a bean of type 'com.expenses.service.UserService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.expenses.service.UserService' in your configuration.
Spring Boot will do the component scan (search for Classes with #Service, #Repository, #Controller, #Component) annotation only classes that are located in the same package as the main class (#SpringBootApplication annoteted class), and its subpackages.
So you need eighter to
move ExpenseApplication one package up, to com.expenses,
move all classes that needs to be found by the component scan to to com.expenses.demo or a subpackage, or
configure the component scan (and Spring Data too), for example, by #SpringBootApplication(scanBasePackages = "com.expenses")
BTW: Najeeb Arif is right too, in addition you need to add #Autowired to UserServiceImplementation.userRepository but I think you do not need to add the #Repository annotation to the Spring-Data-JPA repository interfaces.
Add this to your main class
#SpringBootApplication(scanBasePackages = "com.expenses")
This will help the component scan will find your classes.
First mark both of your Repositories with
#Repository
In your user service, you are missing the Autowired annotation.
I personally like the constructor injection.
Role Repository
#Repository
public interface RoleRepository extends JpaRepository<Role, Long>{
}
Same for the user repo.
in your User Service Impl
#Service
public class UserServiceImplementation implements UserService{
private final UserRepository userRepository;
private final RoleRepository roleRepository;
/* when using constructor injection #Autowired is not required */
public UserServiceImplementation(UserRepository userRepository, RoleRepository roleRepository){
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
//...
}
}

Spring-Data Project is not receiving my Get/Post "404 not found"

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:
D:\>curl -G localhost:8080/demo/first?=Biagio
{"timestamp":"2020-10-04T22:46:35.996+00:00","status":404,"error":"Not Found","message":"","path":"/demo/first"}
And to each of my POST / Add requests like this ERROR:
D:\>curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni#gmail.com -d surname=Jackie
{"timestamp":"2020-10-04T22:40:51.928+00:00","status":404,"error":"Not Found","message":"","path":"/demo/add"}
Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now
AccessingDataMysqlApplication.java
package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}
MainController.java
package com.example.accessingdatamysql.rest;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;
#RestController
#RequestMapping("/demo")
public class MainController {
#Autowired
private UserService userService;
#Transactional
//#RequestMapping(value = "/add/", method = RequestMethod.POST)
#PostMapping(path="/demo/add")
public String addNewUser(#PathVariable("name") String name, #PathVariable("email") String email,
#PathVariable("surname") String surname) {
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "User Saved in DB";
}
#SuppressWarnings({ "rawtypes", "unchecked" })
//#RequestMapping(value = "/fetchUser/{name}", method = RequestMethod.GET)
#GetMapping("/demo/first")
public ResponseEntity<UserDto> fetchUser(#PathVariable("name") String name) {
System.out.println(name);
try {
UserDto namefound = userService.findFirstByName(name);
System.out.println("Name found");
ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println("User not found");
return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
}
}
}
UserService.java
package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
#Service
public interface UserService {
UserDto findFirstByName(String name);
void create(UserDto user);
}
UserServiceImpl.java
package com.example.accessingdatamysql.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
UserMapper mapper;
#Override
public UserDto findFirstByName(String name) {
UserEntity entity = userRepository.findFirstByName(name);
return mapper.toDtoMapper(entity);
}
#Override
public void create(UserDto user) {
UserEntity entity = mapper.toEntityMapper(user);
userRepository.create(entity);
}
}
UserMapper.java
package com.example.accessingdatamysql.util;
import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
#Mapper(componentModel = "spring")
public interface UserMapper {
public UserEntity toEntityMapper (UserDto user);
public UserDto toDtoMapper (UserEntity userEntity);
}
UserRepository.java
package com.example.accessingdatamysql.repo;
import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;
#Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);
}
UserRepositoryImpl.java
package com.example.accessingdatamysql.service;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
#Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public UserEntity findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteria = builder.createQuery(UserEntity.class);
Root<UserEntity> root = criteria.from(UserEntity.class);
criteria.select(root).where(builder.equal(root.get("name"), name));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<UserEntity> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
#Override
// per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}
}
UserDto.java
package com.example.accessingdatamysql.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class UserDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7621330660870602403L;
/**
*
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
private Timestamp timestamp;
private String email;
private String surname;
}
If you need I can also insert User.java and the pom, but the pom has no problems as the dependencies are all correct.
You have an additional demo in your path descriptions for GET and POST methods, you should remove it:
#GetMapping("/demo/first")
#PostMapping(path = "/demo/first")
It should be :
#GetMapping("/first")
#PostMapping(path = "/first")
This because you have already defined demo in the RequestMapping annotation in the class level.

How to write a unit test for OneToMany connection (testing Rest endpoint)?

I'm a beginner in programming, so please forgive me if I'm asking a trivial question.
My question is, how can I make my testing method be able to check the UserModel's OneToMany connection related to the CalendarModel. I want to check, that the list contains the proper Entity, so all the 4 fields of the UserModel were tested.
My UserModel:
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class UserModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#OneToMany(mappedBy = "id")
#JsonIgnore
private List<CalendarModel> calendarModels;
private String username;
private String password;
public UserModel(long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public UserModel() {
}
public long getId() {
return id;
}
//Other Getters and Setters
My CalendarModel:
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class CalendarModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(cascade = CascadeType.MERGE)
private UserModel userModel;
private String googleId;
private String summary;
public CalendarModel() {
}
public CalendarModel(UserModel userModel, String googleId, String summary) {
this.userModel = userModel;
this.googleId = googleId;
this.summary = summary;
}
public Long getId() {
return id;
}
//Other Getters and Setters
My RestController with the endpoint:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class UserController {
private UserServiceImpl service;
#Autowired
public UserController(UserServiceImpl service) {
this.service = service;
}
#GetMapping("/api/users")
public ResponseEntity<Object> allUser() {
List<UserModel> userModelList = service.listUsers();
if (!userModelList.isEmpty() && userModelList != null) {
return new ResponseEntity<>(userModelList, HttpStatus.OK);
}
return new ResponseEntity<>("Error: users not found!", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
My UserModelBuilder class for testing purposes:
public class UserModelBuilder {
long id = 1;
String userName = "user";
String password = "password";
public UserModelBuilder() {
}
public UserModelBuilder withId(long id) {
this.id = id;
return this;
}
public UserModelBuilder withUsername(String userName) {
this.userName = userName;
return this;
}
public UserModelBuilder withPassword(String password) {
this.password = password;
return this;
}
public UserModel build() {
return new UserModel(id, userName, password);
}
}
My test (currently working properly):
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserServiceImpl service;
#Test
public void listAllUserTest() throws Exception {
UserModel firstUser = new UserModelBuilder()
.withId(1)
.withPassword("password")
.withUsername("firstuser")
.build();
UserModel secondUser = new UserModelBuilder()
.withId(2)
.withPassword("otherpass")
.withUsername("seconduser")
.build();
Mockito.when(service.listUsers()).thenReturn(Arrays.asList(firstUser, secondUser));
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/api/users")
.accept(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].password", is("password")))
.andExpect(jsonPath("$[0].username", is("firstuser")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].password", is("otherpass")))
.andExpect(jsonPath("$[1].username", is("seconduser")))
.andExpect(status().isOk())
.andDo(print())
.andReturn();
Mockito.verify(service).listUsers();
}
}
Thank you in advance! :)

#AuthenticationPrincipal Throws Exception

This test project becouse of I don't know how I inject #AuthenticationPrincipal annotation in method ,I have some problem,#AuthenticationPrincipal UserDetails throws exception
UserDetails userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal()
is working not problem but I want to inject this annotation in method how can I do ?
When I added annotation in method this exception is thrown
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface org.springframework.security.core.userdetails.UserDetails
How can I inject #AuthenticationPrincipal to index method in MainControll class ?
How can I solve this situation ?
MainControll.class
package com.sencerseven.springsecurityauth.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MainController {
#RequestMapping(value = {"/"})
public ModelAndView index(#AuthenticationPrincipal UserDetails userDetails) {
ModelAndView mv = new ModelAndView("index");
mv.addObject("user", userDetails);
return mv;
}
#RequestMapping(value = {"/login"})
public ModelAndView loginPage(#RequestParam(name="error",required = false)String error,
#RequestParam(name="logout",required = false)String logout) {
ModelAndView mv = new ModelAndView("login");
mv.addObject("userClickLoginPage",true);
return mv;
}
#RequestMapping("/perform-logout")
public String logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
new SecurityContextLogoutHandler().logout(httpServletRequest, httpServletResponse, authentication);
}
return "redirect:/";
}
}
This class is my main controller
WebSecurityConfig.class
package com.sencerseven.springsecurityauth.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
#Bean
public static BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Configuration
public static class HomeConfigLogin extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll().and()
.formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("/", true).loginProcessingUrl("/login").and().logout().and().exceptionHandling()
.accessDeniedPage("/").and().csrf();
}
}
}
MyUserDetailService
package com.sencerseven.springsecurityauth.security;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.sencerseven.springsecurityauth.dao.UserDAO;
import com.sencerseven.springsecurityauth.dto.Role;
#Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
#Transactional
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
com.sencerseven.springsecurityauth.dto.User user = userDAO.findByUserName(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getRole());
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(com.sencerseven.springsecurityauth.dto.User user,
List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (Role userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
}
User.class
package com.sencerseven.springsecurityauth.dto;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private boolean enabled;
private String email;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> role;
public User() {
}
public User(String username, String password, boolean enabled, String email, Set<Role> role) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.email = email;
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<Role> getRole() {
return role;
}
public void setRole(Set<Role> role) {
this.role = role;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled
+ ", email=" + email + ", role=" + role + "]";
}
}
Role.class
package com.sencerseven.springsecurityauth.dto;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name = "Role")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String role;
#ManyToMany(mappedBy = "role", fetch = FetchType.LAZY)
private Set<User> user;
public Role() {
}
public Role(String role, Set<User> user) {
this.role = role;
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
#Override
public String toString() {
return "Role [id=" + id + ", role=" + role + ", user=" + user + "]";
}
}
if you use WebMvcConfigurationSupport and #AuthenticationPrincipal than you must add a AuthenticationPrincipalArgumentResolver:
public class WebMvcConfig extends WebMvcConfigurationSupport {
...
#Override
protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
}

Get SessionScoped Bean's field through FacesContext

I have the following classes:
ClassA
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import timereport.db.UserBean;
import timereport.utils.JPAUtil;
#Named("classA")
#SessionScoped
public class ClassA implements Serializable {
#Inject
protected UserBean userBean;
public void logout() {
userBean = null;
}
public void login() {
EntityManager em = JPAUtil.getEntityManagerFactory().createEntityManager();
userBean = em.find(UserBean.class, userBean.getUsername());
}
//setter and getter for userBean
}
Here in login() I am doing
EntityManager em = JPAUtil.getEntityManagerFactory().createEntityManager();
userBean = em.find(UserBean.class, userBean.getUsername());
to get the entire UserBean object and this is right. Here comes the problem...
ClassB
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.sql.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import timereport.db.UserBean;
import timereport.ClassB;
import timereport.utils.JPAUtil;
#Named("classB")
#SessionScoped
public class ClassB implements Serializable {
#Inject private UserBean userBean;
String throughUserBean = userBean.getUsername();
...
}
Here, I don't know why, but I expected to get the username set when the user logs in. And when I call #Inject UserBean or #Inject ClassB I expect they to be from the same session scope and hold the UserBean object that is initialized on login. But both (classB and userBean) return NULL when I refer to them. Am I wrong in my expectations for having these objects set and is there another way to do this?
Here is part of the UserBean class:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.proxiad.timereport.utils.AESEncryptDecryptUtil;
#Named("user")
#SessionScoped
#Entity
#Table(name="t_user")
public class UserBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = -56986575421886097L;
#Id
#Column(name="username")
private String username;
#Column(name="fullname")
private String fullname;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn (name="department", referencedColumnName="value")
private ReferenceDataBean department;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="role", referencedColumnName="value")
private ReferenceDataBean role;
public UserBean() {}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
try {
this.password = AESEncryptDecryptUtil.encrypt(password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public ReferenceDataBean getDepartment() {
return department;
}
public void setDepartment(ReferenceDataBean department) {
this.department = department;
}
public ReferenceDataBean getRole() {
return role;
}
public void setRole(ReferenceDataBean role) {
this.role = role;
}
#Override
public int hashCode() {
return getUsername().hashCode() + 17 * getEmail().hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof UserBean) {
UserBean user = (UserBean) obj;
if (getUsername().equals(user.getUsername()) && getEmail().equals(user.getEmail())) {
return true;
}
}
return false;
}
#Override
public String toString() {
return String.format("Username: %s\nEmail: %s\nDepartment:\n%s\nRole:\n%s\n",
getUsername(), getEmail(), getDepartment(), getRole());
}
}
Injection takes place after construction. Injected properties are not available during construction. The earliest point to access injected properties is a #PostConstruct method.
So, replace
#Inject private UserBean userBean;
String throughUserBean = userBean.getUsername();
by
#Inject private UserBean userBean;
String username;
#PostConstruct
public void init() {
username = userBean.getUsername();
}
That #Inject ClassB makes no sense, so I removed it.

Categories