cleanup work

This commit is contained in:
eugenp 2014-08-19 01:12:01 +03:00
parent 33b6d5c645
commit 1222077785
14 changed files with 121 additions and 117 deletions

View File

@ -3,7 +3,6 @@ package org.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
public interface UserRepository extends JpaRepository<User,Long>{
public User findByUsername(String username); public User findByUsername(String username);
} }

View File

@ -11,52 +11,58 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
@Entity(name = "role")
@Entity(name="role")
@Table(name = "role") @Table(name = "role")
public class Role { public class Role {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "user_id")
@JoinColumn(name = "user_id") private User user;
private User user;
@Column(name="role")
private Integer role;
public Role(){ @Column(name = "role")
super(); private Integer role;
} public Role() {
public Role(Integer role){ super();
super();
this.role = role; }
}
public Role(Integer role, User user){ public Role(Integer role) {
super(); super();
this.role = role; this.role = role;
this.user = user; }
}
public Long getId() { public Role(Integer role, User user) {
return id; super();
} this.role = role;
public void setId(Long id) { this.user = user;
this.id = id; }
}
public User getUser() { public Long getId() {
return user; return id;
} }
public void setUser(User user) {
this.user = user; public void setId(Long id) {
} this.id = id;
public Integer getRole() { }
return role;
} public User getUser() {
public void setRole(Integer role) { return user;
this.role = role; }
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
} }

View File

@ -17,17 +17,16 @@ public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column(name="firstName") @Column(name = "firstName")
private String firstName; private String firstName;
@Column(name="lastName") @Column(name = "lastName")
private String lastName; private String lastName;
@Column(name="username") @Column(name = "username")
private String username; private String username;
@Column(name="password") @Column(name = "password")
private String password; private String password;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToOne(mappedBy = "user",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Role role; private Role role;
public Long getId() { public Long getId() {
@ -77,8 +76,7 @@ public class User {
public void setRole(Role role) { public void setRole(Role role) {
this.role = role; this.role = role;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -100,11 +98,11 @@ public class User {
return false; return false;
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append("User [firstName=").append(firstName).append("]"). builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]");
append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]");
return builder.toString(); return builder.toString();
} }
} }

View File

@ -1,8 +1,8 @@
package org.baeldung.persistence.service; package org.baeldung.persistence.service;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class EmailExistsException extends Throwable{ public class EmailExistsException extends Throwable {
public EmailExistsException(String message) { public EmailExistsException(String message) {
super(message); super(message);
} }

View File

@ -10,33 +10,33 @@ import org.springframework.stereotype.Service;
@Service @Service
public class RepositoryService implements UserService { public class RepositoryService implements UserService {
@Autowired @Autowired
private UserRepository repository; private UserRepository repository;
@Autowired @Autowired
private Environment env; private Environment env;
@Autowired @Autowired
public RepositoryService( UserRepository repository) { public RepositoryService(UserRepository repository) {
this.repository = repository; this.repository = repository;
} }
@Transactional @Transactional
@Override @Override
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException { public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException {
if (emailExist(userAccountData.getUsername())) { if (emailExist(userAccountData.getUsername())) {
throw new EmailExistsException("There is an account with that email adress: " + userAccountData.getUsername()); throw new EmailExistsException("There is an account with that email adress: " + userAccountData.getUsername());
} }
User user = new User(); User user = new User();
user.setFirstName(userAccountData.getFirstName()); user.setFirstName(userAccountData.getFirstName());
user.setLastName(userAccountData.getLastName()); user.setLastName(userAccountData.getLastName());
user.setPassword(userAccountData.getPassword()); user.setPassword(userAccountData.getPassword());
user.setUsername(userAccountData.getUsername()); user.setUsername(userAccountData.getUsername());
user.setRole(new Role(userAccountData.getRole(), user)); user.setRole(new Role(userAccountData.getRole(), user));
return repository.save(user); return repository.save(user);
} }
private boolean emailExist(String email) { private boolean emailExist(String email) {
User user = repository.findByUsername(email); User user = repository.findByUsername(email);
if (user != null) { if (user != null) {

View File

@ -5,43 +5,52 @@ public class UserDto {
private String lastName; private String lastName;
private String password; private String password;
private String username; private String username;
private Integer role; private Integer role;
public Integer getRole() { public Integer getRole() {
return role; return role;
} }
public void setRole(Integer role) { public void setRole(Integer role) {
this.role = role; this.role = role;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append("User [firstName=").append(firstName).append("]"). builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]").append("[password").append(password).append("]");
append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]").append("[password").append(password).append("]");
return builder.toString(); return builder.toString();
} }
} }

View File

@ -1,8 +1,9 @@
package org.baeldung.persistence.service; package org.baeldung.persistence.service;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
public interface UserService { public interface UserService {
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException; public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException;
} }

View File

@ -10,18 +10,18 @@ public class UserValidator implements Validator {
private Pattern pattern; private Pattern pattern;
private Matcher matcher; private Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
@Override @Override
public boolean supports(Class<?> clazz) { public boolean supports(Class<?> clazz) {
return UserDto.class.isAssignableFrom(clazz); return UserDto.class.isAssignableFrom(clazz);
} }
@Override @Override
public void validate(Object obj, Errors errors) { public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required.");
} }
public boolean validateEmail(String email) { public boolean validateEmail(String email) {

View File

@ -22,33 +22,33 @@ import org.springframework.transaction.annotation.Transactional;
public class MyUserDetailsService implements UserDetailsService { public class MyUserDetailsService implements UserDetailsService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class); private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class);
private UserRepository userRepository; private UserRepository userRepository;
@Autowired @Autowired
public MyUserDetailsService(UserRepository repository) { public MyUserDetailsService(UserRepository repository) {
this.userRepository = repository; this.userRepository = repository;
} }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try { try {
LOGGER.debug("Loading user by username: {}", username); LOGGER.debug("Loading user by username: {}", username);
User user = userRepository.findByUsername(username); User user = userRepository.findByUsername(username);
LOGGER.debug("Found user: {}", user); LOGGER.debug("Found user: {}", user);
if (user == null) { if (user == null) {
//throw new UsernameNotFoundException("No user found with username: " + username); // throw new UsernameNotFoundException("No user found with username: " + username);
boolean enabled = false; boolean enabled = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1))); return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
} }
boolean enabled = true; boolean enabled = true;
boolean accountNonExpired = true; boolean accountNonExpired = true;
boolean credentialsNonExpired = true; boolean credentialsNonExpired = true;
boolean accountNonLocked = true; boolean accountNonLocked = true;
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole())); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) { public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
@ -60,7 +60,7 @@ public class MyUserDetailsService implements UserDetailsService {
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
if (role.intValue() == 2) { if (role.intValue() == 2) {
// roles.add("ROLE_USER"); // roles.add("ROLE_USER");
roles.add("ROLE_ADMIN"); roles.add("ROLE_ADMIN");
} else if (role.intValue() == 1) { } else if (role.intValue() == 1) {
@ -69,7 +69,7 @@ public class MyUserDetailsService implements UserDetailsService {
return roles; return roles;
} }
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) { public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) { for (String role : roles) {

View File

@ -12,7 +12,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class }) @Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
@PropertySource("classpath:application.properties") @PropertySource("classpath:application.properties")
public class AppConfig { public class AppConfig {
@Bean @Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer(); return new PropertySourcesPlaceholderConfigurer();

View File

@ -19,11 +19,8 @@ import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.JstlView;
@Configuration @Configuration
@ComponentScan(basePackages = { @ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
"org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao"
})
@EnableWebMvc @EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter { public class MvcConfig extends WebMvcConfigurerAdapter {
@ -44,9 +41,9 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
registry.addViewController("/console.html"); registry.addViewController("/console.html");
registry.addViewController("/admin.html"); registry.addViewController("/admin.html");
registry.addViewController("/registration.html"); registry.addViewController("/registration.html");
registry.addViewController("/successRegister.html"); registry.addViewController("/successRegister.html");
} }
@Bean @Bean
public ViewResolver viewResolver() { public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver(); final InternalResourceViewResolver bean = new InternalResourceViewResolver();
@ -55,11 +52,10 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
bean.setSuffix(".jsp"); bean.setSuffix(".jsp");
return bean; return bean;
} }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**") registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
.addResourceLocations("/","/resources/");
} }
@Override @Override
@ -85,11 +81,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
messageSource.setCacheSeconds(0); messageSource.setCacheSeconds(0);
return messageSource; return messageSource;
} }
@Bean @Bean
public UserValidator userValidator() { public UserValidator userValidator() {
UserValidator userValidator = new UserValidator(); UserValidator userValidator = new UserValidator();
return userValidator; return userValidator;
} }
} }

View File

@ -22,7 +22,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan({ "org.baeldung.persistence.model" }) @ComponentScan({ "org.baeldung.persistence.model" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig { public class PersistenceJPAConfig {
@Autowired @Autowired
private Environment env; private Environment env;
@ -69,5 +69,5 @@ public class PersistenceJPAConfig {
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties; return hibernateProperties;
} }
} }

View File

@ -10,5 +10,5 @@ public class SecSecurityConfig {
public SecSecurityConfig() { public SecSecurityConfig() {
super(); super();
} }
} }

View File

@ -9,8 +9,6 @@ import org.baeldung.persistence.service.UserValidator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -23,28 +21,25 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
public class RegistrationController { public class RegistrationController {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);
private UserService service; private UserService service;
@Autowired
private MessageSource messages;
@Autowired
private JavaMailSender mailSender;
@Autowired @Autowired
private UserValidator validator; private UserValidator validator;
@InitBinder @InitBinder
protected void initBinder(WebDataBinder binder) { protected void initBinder(WebDataBinder binder) {
binder.setValidator(this.validator); binder.setValidator(this.validator);
} }
@Autowired @Autowired
public RegistrationController(UserService service) { public RegistrationController(UserService service) {
this.service = service; this.service = service;
} }
@RequestMapping(value = "/user/registration", method = RequestMethod.GET) @RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) { public String showRegistrationForm(WebRequest request, Model model) {
LOGGER.debug("Rendering registration page."); LOGGER.debug("Rendering registration page.");
@ -52,7 +47,7 @@ public class RegistrationController {
model.addAttribute("user", userDto); model.addAttribute("user", userDto);
return "registration"; return "registration";
} }
@RequestMapping(value = "/user/registration", method = RequestMethod.POST) @RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) { public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername()); boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername());
@ -71,15 +66,15 @@ public class RegistrationController {
} }
} }
private User createUserAccount(UserDto userAccountData, BindingResult result) { private User createUserAccount(UserDto userAccountData, BindingResult result) {
User registered = null; User registered = null;
try { try {
registered = service.registerNewUserAccount(userAccountData); registered = service.registerNewUserAccount(userAccountData);
} catch (EmailExistsException e) { } catch (EmailExistsException e) {
return null; return null;
} }
return registered; return registered;
} }
}
}