formatting work and session fix

This commit is contained in:
eugenp 2015-08-01 13:57:52 +03:00
parent 73a63d007f
commit ea227f8a98
32 changed files with 215 additions and 149 deletions

View File

@ -6,7 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> { public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
public PasswordResetToken findByToken(String token); PasswordResetToken findByToken(String token);
PasswordResetToken findByUser(User user);
public PasswordResetToken findByUser(User user);
} }

View File

@ -4,7 +4,10 @@ import org.baeldung.persistence.model.Privilege;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> { public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {
public Privilege findByName(String name);
public void delete(Privilege privilege); Privilege findByName(String name);
@Override
void delete(Privilege privilege);
} }

View File

@ -4,7 +4,10 @@ import org.baeldung.persistence.model.Role;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> { public interface RoleRepository extends JpaRepository<Role, Long> {
public Role findByName(String name);
public void delete(Role role); Role findByName(String name);
@Override
void delete(Role role);
} }

View File

@ -1,11 +1,12 @@
package org.baeldung.persistence.dao; package org.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email); User findByEmail(String email);
public void delete(User user); @Override
void delete(User user);
} }

View File

@ -6,7 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> { public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {
public VerificationToken findByToken(String token); VerificationToken findByToken(String token);
VerificationToken findByUser(User user);
public VerificationToken findByUser(User user);
} }

View File

@ -32,14 +32,14 @@ public class PasswordResetToken {
super(); super();
} }
public PasswordResetToken(String token) { public PasswordResetToken(final String token) {
super(); super();
this.token = token; this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
public PasswordResetToken(String token, User user) { public PasswordResetToken(final String token, final User user) {
super(); super();
this.token = token; this.token = token;
@ -47,11 +47,13 @@ public class PasswordResetToken {
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
//
public String getToken() { public String getToken() {
return token; return token;
} }
public void setToken(String token) { public void setToken(final String token) {
this.token = token; this.token = token;
} }
@ -59,7 +61,7 @@ public class PasswordResetToken {
return user; return user;
} }
public void setUser(User user) { public void setUser(final User user) {
this.user = user; this.user = user;
} }
@ -67,18 +69,18 @@ public class PasswordResetToken {
return expiryDate; return expiryDate;
} }
public void setExpiryDate(Date expiryDate) { public void setExpiryDate(final Date expiryDate) {
this.expiryDate = expiryDate; this.expiryDate = expiryDate;
} }
private Date calculateExpiryDate(int expiryTimeInMinutes) { private Date calculateExpiryDate(final int expiryTimeInMinutes) {
Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime()); cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes); cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime()); return new Date(cal.getTime().getTime());
} }
public void updateToken(String token) { public void updateToken(final String token) {
this.token = token; this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
@ -96,29 +98,38 @@ public class PasswordResetToken {
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
PasswordResetToken other = (PasswordResetToken) obj; }
final PasswordResetToken other = (PasswordResetToken) obj;
if (expiryDate == null) { if (expiryDate == null) {
if (other.expiryDate != null) if (other.expiryDate != null) {
return false; return false;
} else if (!expiryDate.equals(other.expiryDate)) }
} else if (!expiryDate.equals(other.expiryDate)) {
return false; return false;
}
if (token == null) { if (token == null) {
if (other.token != null) if (other.token != null) {
return false; return false;
} else if (!token.equals(other.token)) }
} else if (!token.equals(other.token)) {
return false; return false;
}
if (user == null) { if (user == null) {
if (other.user != null) if (other.user != null) {
return false; return false;
} else if (!user.equals(other.user)) }
} else if (!user.equals(other.user)) {
return false; return false;
}
return true; return true;
} }

View File

@ -10,6 +10,7 @@ import javax.persistence.ManyToMany;
@Entity @Entity
public class Privilege { public class Privilege {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@ -23,16 +24,18 @@ public class Privilege {
super(); super();
} }
public Privilege(String name) { public Privilege(final String name) {
super(); super();
this.name = name; this.name = name;
} }
//
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(final Long id) {
this.id = id; this.id = id;
} }
@ -40,7 +43,7 @@ public class Privilege {
return name; return name;
} }
public void setName(String name) { public void setName(final String name) {
this.name = name; this.name = name;
} }
@ -48,7 +51,7 @@ public class Privilege {
return roles; return roles;
} }
public void setRoles(Collection<Role> roles) { public void setRoles(final Collection<Role> roles) {
this.roles = roles; this.roles = roles;
} }
@ -62,15 +65,19 @@ public class Privilege {
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
}
final Privilege privilege = (Privilege) obj; final Privilege privilege = (Privilege) obj;
if (!privilege.equals(privilege.name)) if (!privilege.equals(privilege.name)) {
return false; return false;
}
return true; return true;
} }

View File

@ -6,9 +6,9 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
@Entity @Entity
public class Role { public class Role {
@ -30,16 +30,18 @@ public class Role {
super(); super();
} }
public Role(String name) { public Role(final String name) {
super(); super();
this.name = name; this.name = name;
} }
//
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(final Long id) {
this.id = id; this.id = id;
} }
@ -47,7 +49,7 @@ public class Role {
return name; return name;
} }
public void setName(String name) { public void setName(final String name) {
this.name = name; this.name = name;
} }
@ -55,7 +57,7 @@ public class Role {
return users; return users;
} }
public void setUsers(Collection<User> users) { public void setUsers(final Collection<User> users) {
this.users = users; this.users = users;
} }
@ -63,7 +65,7 @@ public class Role {
return privileges; return privileges;
} }
public void setPrivileges(Collection<Privilege> privileges) { public void setPrivileges(final Collection<Privilege> privileges) {
this.privileges = privileges; this.privileges = privileges;
} }
@ -77,15 +79,19 @@ public class Role {
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
}
final Role role = (Role) obj; final Role role = (Role) obj;
if (!role.equals(role.name)) if (!role.equals(role.name)) {
return false; return false;
}
return true; return true;
} }

View File

@ -31,6 +31,8 @@ public class User {
private boolean tokenExpired; private boolean tokenExpired;
//
@ManyToMany @ManyToMany
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") )
private Collection<Role> roles; private Collection<Role> roles;
@ -45,7 +47,7 @@ public class User {
return id; return id;
} }
public void setId(Long id) { public void setId(final Long id) {
this.id = id; this.id = id;
} }
@ -53,7 +55,7 @@ public class User {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(final String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
@ -61,7 +63,7 @@ public class User {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(final String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
@ -69,7 +71,7 @@ public class User {
return email; return email;
} }
public void setEmail(String username) { public void setEmail(final String username) {
this.email = username; this.email = username;
} }
@ -77,7 +79,7 @@ public class User {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(final String password) {
this.password = password; this.password = password;
} }
@ -85,7 +87,7 @@ public class User {
return roles; return roles;
} }
public void setRoles(Collection<Role> roles) { public void setRoles(final Collection<Role> roles) {
this.roles = roles; this.roles = roles;
} }
@ -93,7 +95,7 @@ public class User {
return enabled; return enabled;
} }
public void setEnabled(boolean enabled) { public void setEnabled(final boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
@ -101,7 +103,7 @@ public class User {
return tokenExpired; return tokenExpired;
} }
public void setTokenExpired(boolean expired) { public void setTokenExpired(final boolean expired) {
this.tokenExpired = expired; this.tokenExpired = expired;
} }
@ -115,15 +117,19 @@ public class User {
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
}
final User user = (User) obj; final User user = (User) obj;
if (!email.equals(user.email)) if (!email.equals(user.email)) {
return false; return false;
}
return true; return true;
} }

View File

@ -32,14 +32,14 @@ public class VerificationToken {
super(); super();
} }
public VerificationToken(String token) { public VerificationToken(final String token) {
super(); super();
this.token = token; this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
public VerificationToken(String token, User user) { public VerificationToken(final String token, final User user) {
super(); super();
this.token = token; this.token = token;
@ -51,7 +51,7 @@ public class VerificationToken {
return token; return token;
} }
public void setToken(String token) { public void setToken(final String token) {
this.token = token; this.token = token;
} }
@ -59,7 +59,7 @@ public class VerificationToken {
return user; return user;
} }
public void setUser(User user) { public void setUser(final User user) {
this.user = user; this.user = user;
} }
@ -67,18 +67,18 @@ public class VerificationToken {
return expiryDate; return expiryDate;
} }
public void setExpiryDate(Date expiryDate) { public void setExpiryDate(final Date expiryDate) {
this.expiryDate = expiryDate; this.expiryDate = expiryDate;
} }
private Date calculateExpiryDate(int expiryTimeInMinutes) { private Date calculateExpiryDate(final int expiryTimeInMinutes) {
Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime()); cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes); cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime()); return new Date(cal.getTime().getTime());
} }
public void updateToken(String token) { public void updateToken(final String token) {
this.token = token; this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
@ -96,29 +96,38 @@ public class VerificationToken {
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
VerificationToken other = (VerificationToken) obj; }
final VerificationToken other = (VerificationToken) obj;
if (expiryDate == null) { if (expiryDate == null) {
if (other.expiryDate != null) if (other.expiryDate != null) {
return false; return false;
} else if (!expiryDate.equals(other.expiryDate)) }
} else if (!expiryDate.equals(other.expiryDate)) {
return false; return false;
}
if (token == null) { if (token == null) {
if (other.token != null) if (other.token != null) {
return false; return false;
} else if (!token.equals(other.token)) }
} else if (!token.equals(other.token)) {
return false; return false;
}
if (user == null) { if (user == null) {
if (other.user != null) if (other.user != null) {
return false; return false;
} else if (!user.equals(other.user)) }
} else if (!user.equals(other.user)) {
return false; return false;
}
return true; return true;
} }

View File

@ -34,4 +34,5 @@ public interface IUserService {
void changeUserPassword(User user, String password); void changeUserPassword(User user, String password);
boolean checkIfValidOldPassword(User user, String password); boolean checkIfValidOldPassword(User user, String password);
} }

View File

@ -12,13 +12,15 @@ public class OnRegistrationCompleteEvent extends ApplicationEvent {
private final Locale locale; private final Locale locale;
private final User user; private final User user;
public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) { public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) {
super(user); super(user);
this.user = user; this.user = user;
this.locale = locale; this.locale = locale;
this.appUrl = appUrl; this.appUrl = appUrl;
} }
//
public String getAppUrl() { public String getAppUrl() {
return appUrl; return appUrl;
} }
@ -30,4 +32,5 @@ public class OnRegistrationCompleteEvent extends ApplicationEvent {
public User getUser() { public User getUser() {
return user; return user;
} }
} }

View File

@ -30,13 +30,13 @@ public class RegistrationListener implements ApplicationListener<OnRegistrationC
// API // API
@Override @Override
public void onApplicationEvent(OnRegistrationCompleteEvent event) { public void onApplicationEvent(final OnRegistrationCompleteEvent event) {
this.confirmRegistration(event); this.confirmRegistration(event);
} }
private void confirmRegistration(OnRegistrationCompleteEvent event) { private void confirmRegistration(final OnRegistrationCompleteEvent event) {
User user = event.getUser(); final User user = event.getUser();
String token = UUID.randomUUID().toString(); final String token = UUID.randomUUID().toString();
service.createVerificationTokenForUser(user, token); service.createVerificationTokenForUser(user, token);
final SimpleMailMessage email = constructEmailMessage(event, user, token); final SimpleMailMessage email = constructEmailMessage(event, user, token);

View File

@ -12,10 +12,12 @@ public class AuthenticationFailureListener implements ApplicationListener<Authen
@Autowired @Autowired
private LoginAttemptService loginAttemptService; private LoginAttemptService loginAttemptService;
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) { @Override
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails(); public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent e) {
final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
if (auth != null) { if (auth != null) {
loginAttemptService.loginFailed(auth.getRemoteAddress()); loginAttemptService.loginFailed(auth.getRemoteAddress());
} }
} }
} }

View File

@ -12,10 +12,12 @@ public class AuthenticationSuccessEventListener implements ApplicationListener<A
@Autowired @Autowired
private LoginAttemptService loginAttemptService; private LoginAttemptService loginAttemptService;
public void onApplicationEvent(AuthenticationSuccessEvent e) { @Override
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails(); public void onApplicationEvent(final AuthenticationSuccessEvent e) {
final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
if (auth != null) { if (auth != null) {
loginAttemptService.loginSucceeded(auth.getRemoteAddress()); loginAttemptService.loginSucceeded(auth.getRemoteAddress());
} }
} }
} }

View File

@ -18,31 +18,34 @@ public class LoginAttemptService {
public LoginAttemptService() { public LoginAttemptService() {
super(); super();
attemptsCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() { attemptsCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() {
public Integer load(String key) { @Override
public Integer load(final String key) {
return 0; return 0;
} }
}); });
} }
public void loginSucceeded(String key) { //
public void loginSucceeded(final String key) {
attemptsCache.invalidate(key); attemptsCache.invalidate(key);
} }
public void loginFailed(String key) { public void loginFailed(final String key) {
int attempts = 0; int attempts = 0;
try { try {
attempts = attemptsCache.get(key); attempts = attemptsCache.get(key);
} catch (ExecutionException e) { } catch (final ExecutionException e) {
attempts = 0; attempts = 0;
} }
attempts++; attempts++;
attemptsCache.put(key, attempts); attemptsCache.put(key, attempts);
} }
public boolean isBlocked(String key) { public boolean isBlocked(final String key) {
try { try {
return attemptsCache.get(key) >= MAX_ATTEMPT; return attemptsCache.get(key) >= MAX_ATTEMPT;
} catch (ExecutionException e) { } catch (final ExecutionException e) {
return false; return false;
} }
} }

View File

@ -23,17 +23,18 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { @Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
handle(request, response, authentication); handle(request, response, authentication);
HttpSession session = request.getSession(false); final HttpSession session = request.getSession(false);
if (session != null) { if (session != null) {
session.setMaxInactiveInterval(30); session.setMaxInactiveInterval(30 * 60);
} }
clearAuthenticationAttributes(request); clearAuthenticationAttributes(request);
} }
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication); final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) { if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
@ -43,11 +44,11 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
redirectStrategy.sendRedirect(request, response, targetUrl); redirectStrategy.sendRedirect(request, response, targetUrl);
} }
protected String determineTargetUrl(Authentication authentication) { protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false; boolean isUser = false;
boolean isAdmin = false; boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) { for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("READ_PRIVILEGE")) { if (grantedAuthority.getAuthority().equals("READ_PRIVILEGE")) {
isUser = true; isUser = true;
} else if (grantedAuthority.getAuthority().equals("WRITE_PRIVILEGE")) { } else if (grantedAuthority.getAuthority().equals("WRITE_PRIVILEGE")) {
@ -65,15 +66,15 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
} }
} }
protected void clearAuthenticationAttributes(HttpServletRequest request) { protected void clearAuthenticationAttributes(final HttpServletRequest request) {
HttpSession session = request.getSession(false); final HttpSession session = request.getSession(false);
if (session == null) { if (session == null) {
return; return;
} }
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
} }
public void setRedirectStrategy(RedirectStrategy redirectStrategy) { public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy; this.redirectStrategy = redirectStrategy;
} }

View File

@ -12,9 +12,7 @@ import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.model.Privilege; import org.baeldung.persistence.model.Privilege;
import org.baeldung.persistence.model.Role; import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
@ -29,10 +27,7 @@ public class MyUserDetailsService implements UserDetailsService {
@Autowired @Autowired
private UserRepository userRepository; private UserRepository userRepository;
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired @Autowired
private RoleRepository roleRepository; private RoleRepository roleRepository;
@ -50,7 +45,7 @@ public class MyUserDetailsService implements UserDetailsService {
@Override @Override
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
String ip = request.getRemoteAddr(); final String ip = request.getRemoteAddr();
if (loginAttemptService.isBlocked(ip)) { if (loginAttemptService.isBlocked(ip)) {
throw new RuntimeException("blocked"); throw new RuntimeException("blocked");
} }
@ -76,7 +71,7 @@ public class MyUserDetailsService implements UserDetailsService {
private final List<String> getPrivileges(final Collection<Role> roles) { private final List<String> getPrivileges(final Collection<Role> roles) {
final List<String> privileges = new ArrayList<String>(); final List<String> privileges = new ArrayList<String>();
final List<Privilege> collection = new ArrayList<Privilege>(); final List<Privilege> collection = new ArrayList<Privilege>();
for (Role role : roles) { for (final Role role : roles) {
collection.addAll(role.getPrivileges()); collection.addAll(role.getPrivileges());
} }
for (final Privilege item : collection) { for (final Privilege item : collection) {
@ -92,4 +87,5 @@ public class MyUserDetailsService implements UserDetailsService {
} }
return authorities; return authorities;
} }
} }

View File

@ -28,13 +28,13 @@ public class AppConfig {
@Bean @Bean
public JavaMailSenderImpl javaMailSenderImpl() { public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); final JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getProperty("smtp.host")); mailSenderImpl.setHost(env.getProperty("smtp.host"));
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
mailSenderImpl.setUsername(env.getProperty("smtp.username")); mailSenderImpl.setUsername(env.getProperty("smtp.username"));
mailSenderImpl.setPassword(env.getProperty("smtp.password")); mailSenderImpl.setPassword(env.getProperty("smtp.password"));
Properties javaMailProps = new Properties(); final Properties javaMailProps = new Properties();
javaMailProps.put("mail.smtp.auth", true); javaMailProps.put("mail.smtp.auth", true);
javaMailProps.put("mail.smtp.starttls.enable", true); javaMailProps.put("mail.smtp.starttls.enable", true);
mailSenderImpl.setJavaMailProperties(javaMailProps); mailSenderImpl.setJavaMailProperties(javaMailProps);

View File

@ -53,13 +53,13 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
} }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/"); registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
} }
@Override @Override
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(final InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); final LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang"); localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor); registry.addInterceptor(localeChangeInterceptor);
} }
@ -77,14 +77,14 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean @Bean
public LocaleResolver localeResolver() { public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return cookieLocaleResolver; return cookieLocaleResolver;
} }
@Bean @Bean
public MessageSource messageSource() { public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages"); messageSource.setBasename("classpath:messages");
messageSource.setUseCodeAsDefaultMessage(true); messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8"); messageSource.setDefaultEncoding("UTF-8");

View File

@ -32,6 +32,8 @@ public class PersistenceJPAConfig {
super(); super();
} }
//
@Bean @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();

View File

@ -3,7 +3,8 @@ package org.baeldung.validation;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class EmailExistsException extends Throwable { public class EmailExistsException extends Throwable {
public EmailExistsException(String message) { public EmailExistsException(final String message) {
super(message); super(message);
} }
} }

View File

@ -12,15 +12,15 @@ public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
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 void initialize(ValidEmail constraintAnnotation) { public void initialize(final ValidEmail constraintAnnotation) {
} }
@Override @Override
public boolean isValid(String username, ConstraintValidatorContext context) { public boolean isValid(final String username, final ConstraintValidatorContext context) {
return (validateEmail(username)); return (validateEmail(username));
} }
private boolean validateEmail(String email) { private boolean validateEmail(final String email) {
pattern = Pattern.compile(EMAIL_PATTERN); pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email); matcher = pattern.matcher(email);
return matcher.matches(); return matcher.matches();

View File

@ -1,14 +1,15 @@
package org.baeldung.validation; package org.baeldung.validation;
import javax.validation.Constraint; import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import javax.validation.Payload; import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE; import javax.validation.Constraint;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import javax.validation.Payload;
@Target({ TYPE, ANNOTATION_TYPE }) @Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME) @Retention(RUNTIME)
@ -21,4 +22,5 @@ public @interface PasswordMatches {
Class<?>[]groups() default {}; Class<?>[]groups() default {};
Class<? extends Payload>[]payload() default {}; Class<? extends Payload>[]payload() default {};
} }

View File

@ -8,12 +8,14 @@ import org.baeldung.persistence.service.UserDto;
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {
@Override @Override
public void initialize(PasswordMatches constraintAnnotation) { public void initialize(final PasswordMatches constraintAnnotation) {
//
} }
@Override @Override
public boolean isValid(Object obj, ConstraintValidatorContext context) { public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
UserDto user = (UserDto) obj; final UserDto user = (UserDto) obj;
return user.getPassword().equals(user.getMatchingPassword()); return user.getPassword().equals(user.getMatchingPassword());
} }
} }

View File

@ -8,12 +8,12 @@ import org.springframework.validation.Validator;
public class UserValidator implements Validator { public class UserValidator implements Validator {
@Override @Override
public boolean supports(Class<?> clazz) { public boolean supports(final Class<?> clazz) {
return UserDto.class.isAssignableFrom(clazz); return UserDto.class.isAssignableFrom(clazz);
} }
@Override @Override
public void validate(Object obj, Errors errors) { public void validate(final Object obj, final 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.");

View File

@ -1,14 +1,16 @@
package org.baeldung.validation; package org.baeldung.validation;
import javax.validation.Constraint; import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import javax.validation.Payload; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import javax.validation.Constraint;
import static java.lang.annotation.ElementType.TYPE; import javax.validation.Payload;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ TYPE, FIELD, ANNOTATION_TYPE }) @Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME) @Retention(RUNTIME)

View File

@ -61,7 +61,7 @@ public class OldRegistrationController {
private Environment env; private Environment env;
public OldRegistrationController() { public OldRegistrationController() {
super();
} }
// API // API

View File

@ -61,7 +61,7 @@ public class RegistrationController {
private Environment env; private Environment env;
public RegistrationController() { public RegistrationController() {
super();
} }
// Registration // Registration

View File

@ -12,12 +12,12 @@ public class GenericResponse {
private String message; private String message;
private String error; private String error;
public GenericResponse(String message) { public GenericResponse(final String message) {
super(); super();
this.message = message; this.message = message;
} }
public GenericResponse(String message, String error) { public GenericResponse(final String message, final String error) {
super(); super();
this.message = message; this.message = message;
this.error = error; this.error = error;
@ -39,7 +39,7 @@ public class GenericResponse {
return message; return message;
} }
public void setMessage(String message) { public void setMessage(final String message) {
this.message = message; this.message = message;
} }
@ -47,7 +47,7 @@ public class GenericResponse {
return error; return error;
} }
public void setError(String error) { public void setError(final String error) {
this.error = error; this.error = error;
} }

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"> xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"
>
</beans> </beans>