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 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;
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;
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;
import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
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 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();
}
public PasswordResetToken(String token) {
public PasswordResetToken(final String token) {
super();
this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
public PasswordResetToken(String token, User user) {
public PasswordResetToken(final String token, final User user) {
super();
this.token = token;
@ -47,11 +47,13 @@ public class PasswordResetToken {
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
//
public String getToken() {
return token;
}
public void setToken(String token) {
public void setToken(final String token) {
this.token = token;
}
@ -59,7 +61,7 @@ public class PasswordResetToken {
return user;
}
public void setUser(User user) {
public void setUser(final User user) {
this.user = user;
}
@ -67,18 +69,18 @@ public class PasswordResetToken {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
public void setExpiryDate(final Date expiryDate) {
this.expiryDate = expiryDate;
}
private Date calculateExpiryDate(int expiryTimeInMinutes) {
Calendar cal = Calendar.getInstance();
private Date calculateExpiryDate(final int expiryTimeInMinutes) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
public void updateToken(String token) {
public void updateToken(final String token) {
this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
@ -96,29 +98,38 @@ public class PasswordResetToken {
}
@Override
public boolean equals(Object obj) {
if (this == obj)
public boolean equals(final Object obj) {
if (this == obj) {
return true;
if (obj == null)
}
if (obj == null) {
return false;
if (getClass() != obj.getClass())
}
if (getClass() != obj.getClass()) {
return false;
PasswordResetToken other = (PasswordResetToken) obj;
}
final PasswordResetToken other = (PasswordResetToken) obj;
if (expiryDate == null) {
if (other.expiryDate != null)
if (other.expiryDate != null) {
return false;
} else if (!expiryDate.equals(other.expiryDate))
}
} else if (!expiryDate.equals(other.expiryDate)) {
return false;
}
if (token == null) {
if (other.token != null)
if (other.token != null) {
return false;
} else if (!token.equals(other.token))
}
} else if (!token.equals(other.token)) {
return false;
}
if (user == null) {
if (other.user != null)
if (other.user != null) {
return false;
} else if (!user.equals(other.user))
}
} else if (!user.equals(other.user)) {
return false;
}
return true;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -34,4 +34,5 @@ public interface IUserService {
void changeUserPassword(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 User user;
public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) {
super(user);
this.user = user;
this.locale = locale;
this.appUrl = appUrl;
}
//
public String getAppUrl() {
return appUrl;
}
@ -30,4 +32,5 @@ public class OnRegistrationCompleteEvent extends ApplicationEvent {
public User getUser() {
return user;
}
}

View File

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

View File

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

View File

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

View File

@ -18,31 +18,34 @@ public class LoginAttemptService {
public LoginAttemptService() {
super();
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;
}
});
}
public void loginSucceeded(String key) {
//
public void loginSucceeded(final String key) {
attemptsCache.invalidate(key);
}
public void loginFailed(String key) {
public void loginFailed(final String key) {
int attempts = 0;
try {
attempts = attemptsCache.get(key);
} catch (ExecutionException e) {
} catch (final ExecutionException e) {
attempts = 0;
}
attempts++;
attemptsCache.put(key, attempts);
}
public boolean isBlocked(String key) {
public boolean isBlocked(final String key) {
try {
return attemptsCache.get(key) >= MAX_ATTEMPT;
} catch (ExecutionException e) {
} catch (final ExecutionException e) {
return false;
}
}

View File

@ -23,17 +23,18 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
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);
HttpSession session = request.getSession(false);
final HttpSession session = request.getSession(false);
if (session != null) {
session.setMaxInactiveInterval(30);
session.setMaxInactiveInterval(30 * 60);
}
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
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);
}
protected String determineTargetUrl(Authentication authentication) {
protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("READ_PRIVILEGE")) {
isUser = true;
} else if (grantedAuthority.getAuthority().equals("WRITE_PRIVILEGE")) {
@ -65,15 +66,15 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
protected void clearAuthenticationAttributes(final HttpServletRequest request) {
final HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
public void setRedirectStrategy(final 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.Role;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@ -29,10 +27,7 @@ public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired
private RoleRepository roleRepository;
@ -50,7 +45,7 @@ public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
String ip = request.getRemoteAddr();
final String ip = request.getRemoteAddr();
if (loginAttemptService.isBlocked(ip)) {
throw new RuntimeException("blocked");
}
@ -76,7 +71,7 @@ public class MyUserDetailsService implements UserDetailsService {
private final List<String> getPrivileges(final Collection<Role> roles) {
final List<String> privileges = new ArrayList<String>();
final List<Privilege> collection = new ArrayList<Privilege>();
for (Role role : roles) {
for (final Role role : roles) {
collection.addAll(role.getPrivileges());
}
for (final Privilege item : collection) {
@ -92,4 +87,5 @@ public class MyUserDetailsService implements UserDetailsService {
}
return authorities;
}
}

View File

@ -28,13 +28,13 @@ public class AppConfig {
@Bean
public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
final JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getProperty("smtp.host"));
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
mailSenderImpl.setUsername(env.getProperty("smtp.username"));
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.starttls.enable", true);
mailSenderImpl.setJavaMailProperties(javaMailProps);

View File

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

View File

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

View File

@ -47,8 +47,8 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
.csrf().disable()
.authorizeRequests()
.antMatchers("/j_spring_security_check*","/login*", "/logout*", "/signin/**", "/signup/**",
"/user/registration*", "/regitrationConfirm*", "/expiredAccount*", "/registration*",
"/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*",
"/user/registration*", "/regitrationConfirm*", "/expiredAccount*", "/registration*",
"/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*",
"/user/changePassword*", "/emailError*", "/resources/**","/old/user/registration*","/successRegister*").permitAll()
.antMatchers("/invalidSession*").anonymous()
.anyRequest().authenticated()

View File

@ -3,7 +3,8 @@ package org.baeldung.validation;
@SuppressWarnings("serial")
public class EmailExistsException extends Throwable {
public EmailExistsException(String message) {
public EmailExistsException(final String 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,})$";
@Override
public void initialize(ValidEmail constraintAnnotation) {
public void initialize(final ValidEmail constraintAnnotation) {
}
@Override
public boolean isValid(String username, ConstraintValidatorContext context) {
public boolean isValid(final String username, final ConstraintValidatorContext context) {
return (validateEmail(username));
}
private boolean validateEmail(String email) {
private boolean validateEmail(final String email) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();

View File

@ -1,14 +1,15 @@
package org.baeldung.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@ -21,4 +22,5 @@ public @interface PasswordMatches {
Class<?>[]groups() 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> {
@Override
public void initialize(PasswordMatches constraintAnnotation) {
public void initialize(final PasswordMatches constraintAnnotation) {
//
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
UserDto user = (UserDto) obj;
public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
final UserDto user = (UserDto) obj;
return user.getPassword().equals(user.getMatchingPassword());
}
}

View File

@ -8,12 +8,12 @@ import org.springframework.validation.Validator;
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
public boolean supports(final Class<?> clazz) {
return UserDto.class.isAssignableFrom(clazz);
}
@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, "lastName", "message.lastName", "LastName is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required.");

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,6 @@
<?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"
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>