From ea227f8a981e3758aab2213fb9574404766f2b1e Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 1 Aug 2015 13:57:52 +0300 Subject: [PATCH 01/34] formatting work and session fix --- .../dao/PasswordResetTokenRepository.java | 5 +- .../persistence/dao/PrivilegeRepository.java | 7 ++- .../persistence/dao/RoleRepository.java | 7 ++- .../persistence/dao/UserRepository.java | 7 +-- .../dao/VerificationTokenRepository.java | 5 +- .../persistence/model/PasswordResetToken.java | 49 ++++++++++++------- .../baeldung/persistence/model/Privilege.java | 23 ++++++--- .../org/baeldung/persistence/model/Role.java | 26 ++++++---- .../org/baeldung/persistence/model/User.java | 30 +++++++----- .../persistence/model/VerificationToken.java | 47 +++++++++++------- .../persistence/service/IUserService.java | 1 + .../OnRegistrationCompleteEvent.java | 5 +- .../listener/RegistrationListener.java | 8 +-- .../AuthenticationFailureListener.java | 6 ++- .../AuthenticationSuccessEventListener.java | 6 ++- .../security/LoginAttemptService.java | 15 +++--- ...SimpleUrlAuthenticationSuccessHandler.java | 23 ++++----- .../security/MyUserDetailsService.java | 12 ++--- .../java/org/baeldung/spring/AppConfig.java | 4 +- .../java/org/baeldung/spring/MvcConfig.java | 10 ++-- .../baeldung/spring/PersistenceJPAConfig.java | 2 + .../baeldung/spring/SecSecurityConfig.java | 4 +- .../validation/EmailExistsException.java | 3 +- .../baeldung/validation/EmailValidator.java | 6 +-- .../baeldung/validation/PasswordMatches.java | 12 +++-- .../validation/PasswordMatchesValidator.java | 8 +-- .../baeldung/validation/UserValidator.java | 4 +- .../org/baeldung/validation/ValidEmail.java | 14 +++--- .../controller/OldRegistrationController.java | 2 +- .../controller/RegistrationController.java | 2 +- .../baeldung/web/util/GenericResponse.java | 8 +-- .../src/main/webapp/WEB-INF/mvc-servlet.xml | 3 +- 32 files changed, 215 insertions(+), 149 deletions(-) diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PasswordResetTokenRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PasswordResetTokenRepository.java index 9ef80fe8b1..a1c22998de 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PasswordResetTokenRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PasswordResetTokenRepository.java @@ -6,7 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface PasswordResetTokenRepository extends JpaRepository { - public PasswordResetToken findByToken(String token); + PasswordResetToken findByToken(String token); + + PasswordResetToken findByUser(User user); - public PasswordResetToken findByUser(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java index 3f8016f314..f728e171df 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java @@ -4,7 +4,10 @@ import org.baeldung.persistence.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { - public Privilege findByName(String name); - public void delete(Privilege privilege); + Privilege findByName(String name); + + @Override + void delete(Privilege privilege); + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/RoleRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/RoleRepository.java index 90d6de60f2..3d6ba16d0f 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/RoleRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/RoleRepository.java @@ -4,7 +4,10 @@ import org.baeldung.persistence.model.Role; import org.springframework.data.jpa.repository.JpaRepository; public interface RoleRepository extends JpaRepository { - public Role findByName(String name); - public void delete(Role role); + Role findByName(String name); + + @Override + void delete(Role role); + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java index 12f07d8692..680b6973fa 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -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 { - public User findByEmail(String email); + User findByEmail(String email); - public void delete(User user); + @Override + void delete(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java index f9fc850d41..d40a843e88 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java @@ -6,7 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface VerificationTokenRepository extends JpaRepository { - public VerificationToken findByToken(String token); + VerificationToken findByToken(String token); + + VerificationToken findByUser(User user); - public VerificationToken findByUser(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/PasswordResetToken.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/PasswordResetToken.java index cfff0135da..fdf5473764 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/PasswordResetToken.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/PasswordResetToken.java @@ -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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java index c403ffb7a2..1331b1985d 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java @@ -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 roles) { + public void setRoles(final Collection 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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java index c7053fc56a..86680252d2 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java @@ -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 users) { + public void setUsers(final Collection users) { this.users = users; } @@ -63,7 +65,7 @@ public class Role { return privileges; } - public void setPrivileges(Collection privileges) { + public void setPrivileges(final Collection 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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java index 277ddef1dc..9640ba079b 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java @@ -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 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 roles) { + public void setRoles(final Collection 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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java index a25750d3d0..a8eb49f672 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java @@ -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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java index 7ec07e9488..9fa97395fa 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java @@ -34,4 +34,5 @@ public interface IUserService { void changeUserPassword(User user, String password); boolean checkIfValidOldPassword(User user, String password); + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/registration/OnRegistrationCompleteEvent.java b/spring-security-login-and-registration/src/main/java/org/baeldung/registration/OnRegistrationCompleteEvent.java index ede14537e8..75433f1286 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/registration/OnRegistrationCompleteEvent.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/registration/OnRegistrationCompleteEvent.java @@ -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; } + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/registration/listener/RegistrationListener.java b/spring-security-login-and-registration/src/main/java/org/baeldung/registration/listener/RegistrationListener.java index 16eb2177d5..0a3689f670 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/registration/listener/RegistrationListener.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/registration/listener/RegistrationListener.java @@ -30,13 +30,13 @@ public class RegistrationListener implements ApplicationListener() { - 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; } } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 09b22064b7..37703d9a09 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -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 authorities = authentication.getAuthorities(); - for (GrantedAuthority grantedAuthority : authorities) { + final Collection 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; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index 0de7fadd46..d9c3e586b1 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -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 getPrivileges(final Collection roles) { final List privileges = new ArrayList(); final List collection = new ArrayList(); - 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; } + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java index 219fcb729e..cba2b25285 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java @@ -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); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java index d5adf74992..56141d8f33 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java @@ -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"); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java index d2465af345..cb00353fe8 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java @@ -32,6 +32,8 @@ public class PersistenceJPAConfig { super(); } + // + @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index af75a6e73c..814ed92b33 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -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() diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailExistsException.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailExistsException.java index 952931bcff..554dfe7cbc 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailExistsException.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailExistsException.java @@ -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); } + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailValidator.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailValidator.java index bd69c7d550..ee2801eba0 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailValidator.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/EmailValidator.java @@ -12,15 +12,15 @@ public class EmailValidator implements ConstraintValidator { 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(); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java index 6a9b906b36..1e3193b7b5 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java @@ -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[]payload() default {}; + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatchesValidator.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatchesValidator.java index e8ec952fa8..a103b91e90 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatchesValidator.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatchesValidator.java @@ -8,12 +8,14 @@ import org.baeldung.persistence.service.UserDto; public class PasswordMatchesValidator implements ConstraintValidator { @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()); } + } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/UserValidator.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/UserValidator.java index cfd3a78f81..76348bee7e 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/UserValidator.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/UserValidator.java @@ -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."); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java index 1d5795ce16..b5dc4f0f46 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java @@ -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) diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/OldRegistrationController.java b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/OldRegistrationController.java index c4471f2642..dc14ad70a1 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/OldRegistrationController.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/OldRegistrationController.java @@ -61,7 +61,7 @@ public class OldRegistrationController { private Environment env; public OldRegistrationController() { - + super(); } // API diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java index f3520d052f..ca13d7f21e 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java @@ -61,7 +61,7 @@ public class RegistrationController { private Environment env; public RegistrationController() { - + super(); } // Registration diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/web/util/GenericResponse.java b/spring-security-login-and-registration/src/main/java/org/baeldung/web/util/GenericResponse.java index 384bb51589..076c481580 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/web/util/GenericResponse.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/web/util/GenericResponse.java @@ -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; } diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-login-and-registration/src/main/webapp/WEB-INF/mvc-servlet.xml index 7862ca24c0..fe527bd4e8 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -1,5 +1,6 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd" +> \ No newline at end of file From 4f97c2ccd0aa8fb070ea6508e7f191089eaa3097 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 10 Aug 2015 10:13:56 +0300 Subject: [PATCH 02/34] introducing cargo --- .../pom.xml | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index 9d344bcd37..19d0ae1a29 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -1,11 +1,13 @@ - + 4.0.0 + org.baeldung spring-security-login-and-registration + 1.0.1-SNAPSHOT + spring-security-login-and-registration war - 1.0.1-SNAPSHOT org.springframework.boot @@ -188,6 +190,27 @@ maven-war-plugin + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8081 + + + + + @@ -212,5 +235,9 @@ 18.0 + + 1.4.15 + + \ No newline at end of file From f76247aaa877368263f515b5ef590a920eb99e10 Mon Sep 17 00:00:00 2001 From: Vrajesh Jayswal Date: Thu, 13 Aug 2015 11:20:23 +0530 Subject: [PATCH 03/34] Java encode and decode test program --- .../encoding/ApacheCommonsEncodeDecode.java | 56 +++++++++++++ .../com/demo/encoding/Java8EncodeDecode.java | 84 +++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java create mode 100644 core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java diff --git a/core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java b/core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java new file mode 100644 index 0000000000..d15b1325dc --- /dev/null +++ b/core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java @@ -0,0 +1,56 @@ +package com.demo.encoding; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.UnsupportedEncodingException; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Test; + +public class ApacheCommonsEncodeDecode { + + @Test + public void whenStringIsEncoded() throws UnsupportedEncodingException { + String originalInput = "test input"; + Base64 base64 = new Base64(); + String encodedString = new String(base64.encode(originalInput.getBytes())); + + assertNotNull(encodedString); + assertNotEquals(originalInput, encodedString); + } + + @Test + public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException { + String originalInput = "test input"; + Base64 base64 = new Base64(); + String encodedString = new String(base64.encode(originalInput.getBytes())); + + String decodedString = new String(base64.decode(encodedString.getBytes())); + + assertNotNull(decodedString); + assertEquals(originalInput, decodedString); + } + + @Test + public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); + + assertNotNull(encodedString); + assertNotEquals(originalInput, encodedString); + } + + @Test + public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); + + String decodedString = new String(Base64.decodeBase64(encodedString.getBytes())); + + assertNotNull(decodedString); + assertEquals(originalInput, decodedString); + } + +} diff --git a/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java b/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java new file mode 100644 index 0000000000..cbbdca82a2 --- /dev/null +++ b/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java @@ -0,0 +1,84 @@ +package com.demo.encoding; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.util.Base64; +import java.util.UUID; + +import org.junit.Test; + +public class Java8EncodeDecode { + + @Test + public void whenStringIsEncoded() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); + assertNotNull(encodedString); + assertNotEquals(originalInput, encodedString); + } + + @Test + public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); + + byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + String decodedString = new String(decodedBytes); + + assertNotNull(decodedString); + assertEquals(originalInput, decodedString); + + } + + @Test + public void whenURLIsEncoded() throws UnsupportedEncodingException { + String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); + assertNotNull(encodedURL); + assertNotEquals(originalURL, encodedURL); + } + + @Test + public void whenURLIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException { + String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); + byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedURL.getBytes()); + String decodedURL = new String(decodedBytes); + assertNotNull(decodedURL); + assertEquals(originalURL, decodedURL); + } + + @Test + public void whenMIMEIsEncoded() throws UnsupportedEncodingException { + StringBuilder buffer = getMimeBuffer(); + + byte[] forEncode = buffer.toString().getBytes(); + String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); + + assertNotNull(encodedMime); + } + + @Test + public void whenMIMEIsEncoded_thenMIMECanBeDecoded() throws UnsupportedEncodingException { + StringBuilder buffer = getMimeBuffer(); + + byte[] forEncode = buffer.toString().getBytes(); + String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); + + byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime); + String decodedMime = new String(decodedBytes); + assertNotNull(decodedMime); + } + + private static StringBuilder getMimeBuffer() { + StringBuilder buffer = new StringBuilder(); + for (int count = 0; count < 10; ++count) { + buffer.append(UUID.randomUUID().toString()); + } + return buffer; + } + +} From a5ef06c93f2e24db1df9c51908d949584a3048e0 Mon Sep 17 00:00:00 2001 From: Vrajesh Jayswal Date: Sat, 15 Aug 2015 10:50:58 +0530 Subject: [PATCH 04/34] added method for basic encoding without padding --- .../com/demo/encoding/Java8EncodeDecode.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java b/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java index cbbdca82a2..241fee6ded 100644 --- a/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java +++ b/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java @@ -32,6 +32,28 @@ public class Java8EncodeDecode { assertEquals(originalInput, decodedString); } + + @Test + public void whenStringIsEncodedWithoutPadding() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); + assertNotNull(encodedString); + assertNotEquals(originalInput, encodedString); + } + + @Test + public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException { + String originalInput = "test input"; + String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); + + byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + String decodedString = new String(decodedBytes); + + assertNotNull(decodedString); + assertEquals(originalInput, decodedString); + + } + @Test public void whenURLIsEncoded() throws UnsupportedEncodingException { From 556b7ca8864917311a14ba5572cecdc3a1cf1b6a Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 15 Aug 2015 17:38:25 +0300 Subject: [PATCH 05/34] maven work --- spring-all/pom.xml | 14 +++--- spring-data-mongodb/.project | 43 ++++++++++++------- .../DocumentQueryIntegrationTest.java | 12 +++--- .../QueryMethodsIntegrationTest.java | 15 +++---- spring-exceptions/.classpath | 2 +- spring-exceptions/pom.xml | 14 +++--- spring-hibernate3/.classpath | 2 +- spring-hibernate3/pom.xml | 12 +++--- spring-hibernate4/.classpath | 2 +- spring-hibernate4/pom.xml | 14 +++--- spring-jpa/pom.xml | 14 +++--- spring-mvc-java/.classpath | 2 +- spring-mvc-java/pom.xml | 12 +++--- spring-mvc-no-xml/.classpath | 2 +- spring-mvc-no-xml/pom.xml | 4 +- spring-mvc-xml/.classpath | 2 +- spring-mvc-xml/pom.xml | 4 +- ....eclipse.wst.common.project.facet.core.xml | 6 ++- spring-rest/pom.xml | 12 +++--- spring-security-basic-auth/.classpath | 2 +- spring-security-basic-auth/pom.xml | 12 +++--- .../.classpath | 2 +- .../pom.xml | 2 +- spring-security-mvc-custom/.classpath | 2 +- spring-security-mvc-custom/pom.xml | 12 +++--- spring-security-mvc-digest-auth/.classpath | 2 +- spring-security-mvc-digest-auth/pom.xml | 12 +++--- spring-security-mvc-ldap/.classpath | 3 +- spring-security-mvc-ldap/pom.xml | 12 +++--- spring-security-mvc-login/.classpath | 2 +- spring-security-mvc-login/pom.xml | 12 +++--- spring-security-mvc-session/.classpath | 2 +- spring-security-mvc-session/pom.xml | 12 +++--- spring-security-rest-basic-auth/.classpath | 2 +- spring-security-rest-basic-auth/pom.xml | 12 +++--- spring-security-rest-custom/.classpath | 2 +- spring-security-rest-custom/pom.xml | 12 +++--- spring-security-rest-digest-auth/.classpath | 2 +- spring-security-rest-digest-auth/pom.xml | 10 ++--- spring-security-rest-full/pom.xml | 12 +++--- spring-security-rest/.classpath | 2 +- spring-security-rest/pom.xml | 12 +++--- 42 files changed, 177 insertions(+), 166 deletions(-) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 3fb515a0bd..3391846d97 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -210,21 +210,21 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE - 3.19.0-GA + 4.2.0.RELEASE + 4.0.2.RELEASE + 3.20.0-GA 1.2 - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -245,7 +245,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-data-mongodb/.project b/spring-data-mongodb/.project index 7a469b9f7a..bfe02478f5 100644 --- a/spring-data-mongodb/.project +++ b/spring-data-mongodb/.project @@ -1,18 +1,29 @@ - spring-data-mongodb - NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - org.eclipse.jdt.core.javabuilder - - - org.eclipse.m2e.core.maven2Builder - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - \ No newline at end of file + spring-data-mongodb + NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java index 83867dd423..75077c19cb 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java @@ -102,7 +102,7 @@ public class DocumentQueryIntegrationTest { query.addCriteria(Criteria.where("name").regex("^A")); List users = mongoTemplate.find(query, User.class); - + assertThat(users.size(), is(2)); } @@ -127,7 +127,7 @@ public class DocumentQueryIntegrationTest { query.addCriteria(Criteria.where("name").regex("c$")); List users = mongoTemplate.find(query, User.class); - + assertThat(users.size(), is(1)); } @@ -153,7 +153,7 @@ public class DocumentQueryIntegrationTest { query.with(pageableRequest); List users = mongoTemplate.find(query, User.class); - + assertThat(users.size(), is(2)); } @@ -178,11 +178,11 @@ public class DocumentQueryIntegrationTest { query.with(new Sort(Sort.Direction.ASC, "age")); List users = mongoTemplate.find(query, User.class); - + Iterator iter = users.iterator(); - assertThat(users.size(), is(3)); + assertThat(users.size(), is(3)); assertThat(iter.next().getName(), is("Antony")); assertThat(iter.next().getName(), is("Alice")); - assertThat(iter.next().getName(), is("Eric")); + assertThat(iter.next().getName(), is("Eric")); } } diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java index 5bbf779821..f7c35c8de2 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java @@ -3,7 +3,6 @@ package org.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; - import java.util.List; import org.baeldung.config.MongoConfig; @@ -13,7 +12,6 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { @@ -32,7 +30,7 @@ public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { List users = userRepository.findByName("Eric"); assertThat(users.size(), is(1)); } - + @Test public void givenUsersExist_whenFindingUsersWithAgeCreaterThanAndLessThan_thenUsersAreFound() { User user = new User(); @@ -53,7 +51,7 @@ public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { List users = userRepository.findByAgeBetween(26, 40); assertThat(users.size(), is(1)); } - + @Test public void givenUsersExist_whenFindingUserWithNameStartWithA_thenUsersAreFound() { User user = new User(); @@ -74,7 +72,7 @@ public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { List users = userRepository.findByNameStartingWith("A"); assertThat(users.size(), is(2)); } - + @Test public void givenUsersExist_whenFindingUserWithNameEndWithC_thenUsersAreFound() { User user = new User(); @@ -93,10 +91,10 @@ public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { mongoOps.insert(user); List users = userRepository.findByNameEndingWith("c"); - + assertThat(users.size(), is(1)); } - + @Test public void givenUsersExist_whenFindingUsersAndSortThem_thenUsersAreFoundAndSorted() { User user = new User(); @@ -115,8 +113,7 @@ public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { mongoOps.insert(user); List users = userRepository.findByNameLikeOrderByAgeAsc("A"); - + assertThat(users.size(), is(2)); } } - diff --git a/spring-exceptions/.classpath b/spring-exceptions/.classpath index c91caa1b09..6b533711d3 100644 --- a/spring-exceptions/.classpath +++ b/spring-exceptions/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index afd4abf4d8..46210f2fa7 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -203,14 +203,14 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE - 3.19.0-GA + 4.2.0.RELEASE + 4.0.2.RELEASE + 3.20.0-GA 1.2 - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 7.0.42 @@ -218,7 +218,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -240,7 +240,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-hibernate3/.classpath b/spring-hibernate3/.classpath index 8ebf6d9c31..5efa587d72 100644 --- a/spring-hibernate3/.classpath +++ b/spring-hibernate3/.classpath @@ -29,7 +29,7 @@ - + diff --git a/spring-hibernate3/pom.xml b/spring-hibernate3/pom.xml index eb6aae204c..653626bab0 100644 --- a/spring-hibernate3/pom.xml +++ b/spring-hibernate3/pom.xml @@ -162,13 +162,13 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE - 3.19.0-GA + 4.2.0.RELEASE + 4.0.2.RELEASE + 3.20.0-GA 3.6.10.Final - 5.1.35 + 5.1.36 7.0.47 @@ -176,7 +176,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -196,7 +196,7 @@ 3.3 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-hibernate4/.classpath b/spring-hibernate4/.classpath index 8b7cba482d..fa5dbd4c0e 100644 --- a/spring-hibernate4/.classpath +++ b/spring-hibernate4/.classpath @@ -29,7 +29,7 @@ - + diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 65ff14ce96..0f74e9603a 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -169,13 +169,13 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE - 3.19.0-GA + 4.2.0.RELEASE + 4.0.2.RELEASE + 3.20.0-GA - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 7.0.42 @@ -183,7 +183,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -203,7 +203,7 @@ 3.3 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index fd8ae12f00..b3b08167f1 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -174,13 +174,13 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE - 3.19.0-GA + 4.2.0.RELEASE + 4.0.2.RELEASE + 3.20.0-GA - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.2.RELEASE @@ -188,7 +188,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -208,7 +208,7 @@ 3.3 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-mvc-java/.classpath b/spring-mvc-java/.classpath index c91caa1b09..6b533711d3 100644 --- a/spring-mvc-java/.classpath +++ b/spring-mvc-java/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index a171e78dfd..20248107a3 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -140,19 +140,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -173,7 +173,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-mvc-no-xml/.classpath b/spring-mvc-no-xml/.classpath index c91caa1b09..6b533711d3 100644 --- a/spring-mvc-no-xml/.classpath +++ b/spring-mvc-no-xml/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-mvc-no-xml/pom.xml b/spring-mvc-no-xml/pom.xml index ac8d59dfda..fdaee3b133 100644 --- a/spring-mvc-no-xml/pom.xml +++ b/spring-mvc-no-xml/pom.xml @@ -144,7 +144,7 @@ - 4.1.6.RELEASE + 4.2.0.RELEASE 1.7.12 @@ -165,7 +165,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-mvc-xml/.classpath b/spring-mvc-xml/.classpath index c91caa1b09..6b533711d3 100644 --- a/spring-mvc-xml/.classpath +++ b/spring-mvc-xml/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 407c350700..6d62927d63 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -146,7 +146,7 @@ - 4.1.6.RELEASE + 4.2.0.RELEASE 1.7.12 @@ -167,7 +167,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml index 9ca0d1c1b7..b9386231e6 100644 --- a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,6 +1,8 @@ - - + + + + diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index f04d04e8ec..ceede90c2e 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -229,19 +229,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 2.5.1 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -265,7 +265,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-basic-auth/.classpath b/spring-security-basic-auth/.classpath index 135b02c3d7..5778c9435e 100644 --- a/spring-security-basic-auth/.classpath +++ b/spring-security-basic-auth/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml index d1152329f7..754a2c600b 100644 --- a/spring-security-basic-auth/pom.xml +++ b/spring-security-basic-auth/pom.xml @@ -225,19 +225,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -258,7 +258,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-security-login-and-registration/.classpath b/spring-security-login-and-registration/.classpath index 1151b0d257..91f27076be 100644 --- a/spring-security-login-and-registration/.classpath +++ b/spring-security-login-and-registration/.classpath @@ -25,7 +25,7 @@ - + diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index 19d0ae1a29..0bd539b68c 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -217,7 +217,7 @@ 1.7 4.1.6.RELEASE - 3.2.7.RELEASE + 4.0.2.RELEASE 1.7.12 diff --git a/spring-security-mvc-custom/.classpath b/spring-security-mvc-custom/.classpath index 78cd935a51..bbfdf4ade5 100644 --- a/spring-security-mvc-custom/.classpath +++ b/spring-security-mvc-custom/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 26d291427a..0e620d1d7a 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -230,19 +230,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -263,7 +263,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-security-mvc-digest-auth/.classpath b/spring-security-mvc-digest-auth/.classpath index 78cd935a51..bbfdf4ade5 100644 --- a/spring-security-mvc-digest-auth/.classpath +++ b/spring-security-mvc-digest-auth/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 9b132820ab..f01eccbe2a 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -225,19 +225,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -258,7 +258,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-security-mvc-ldap/.classpath b/spring-security-mvc-ldap/.classpath index efcf778ba0..6acf3eeeca 100644 --- a/spring-security-mvc-ldap/.classpath +++ b/spring-security-mvc-ldap/.classpath @@ -25,9 +25,10 @@ + - + diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 28e1f74bbd..f20ceef066 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -87,19 +87,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -119,7 +119,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-mvc-login/.classpath b/spring-security-mvc-login/.classpath index 78cd935a51..bbfdf4ade5 100644 --- a/spring-security-mvc-login/.classpath +++ b/spring-security-mvc-login/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index b181df8d60..17a4df513c 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -222,19 +222,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -255,7 +255,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-security-mvc-session/.classpath b/spring-security-mvc-session/.classpath index 78cd935a51..bbfdf4ade5 100644 --- a/spring-security-mvc-session/.classpath +++ b/spring-security-mvc-session/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 3239800743..be41375f49 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -230,19 +230,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -263,7 +263,7 @@ 2.6 2.18.1 2.7 - 1.4.14 + 1.4.15 diff --git a/spring-security-rest-basic-auth/.classpath b/spring-security-rest-basic-auth/.classpath index 135b02c3d7..5778c9435e 100644 --- a/spring-security-rest-basic-auth/.classpath +++ b/spring-security-rest-basic-auth/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 5ce1a622be..f59bf5156b 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -287,12 +287,12 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 4.4.1 @@ -303,7 +303,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -320,7 +320,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-rest-custom/.classpath b/spring-security-rest-custom/.classpath index 135b02c3d7..5778c9435e 100644 --- a/spring-security-rest-custom/.classpath +++ b/spring-security-rest-custom/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index c96deced6d..9f756ff09a 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -258,19 +258,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -290,7 +290,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-rest-digest-auth/.classpath b/spring-security-rest-digest-auth/.classpath index 135b02c3d7..5778c9435e 100644 --- a/spring-security-rest-digest-auth/.classpath +++ b/spring-security-rest-digest-auth/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index c4722c2c2e..bc5582b78c 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -275,11 +275,11 @@ 4.1.6.RELEASE - 3.2.7.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 4.4.1 @@ -293,7 +293,7 @@ 2.5.1 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -310,7 +310,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index f86f1a753d..daa0ed01af 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -413,12 +413,12 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.2.RELEASE @@ -430,7 +430,7 @@ 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -450,7 +450,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 diff --git a/spring-security-rest/.classpath b/spring-security-rest/.classpath index 135b02c3d7..5778c9435e 100644 --- a/spring-security-rest/.classpath +++ b/spring-security-rest/.classpath @@ -30,7 +30,7 @@ - + diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 0661697b22..1b1f2a23c5 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -237,19 +237,19 @@ - 4.1.6.RELEASE - 3.2.7.RELEASE + 4.2.0.RELEASE + 4.0.2.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.36 1.7.12 1.1.3 - 5.1.3.Final + 5.2.1.Final 18.0 @@ -269,7 +269,7 @@ 3.3 2.6 2.18.1 - 1.4.14 + 1.4.15 From 75b533efe982d040f1851f1d6760126efd3f8b65 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 15 Aug 2015 18:08:40 +0300 Subject: [PATCH 06/34] perperties work --- .../spring/PropertiesWithXmlConfigTwo.java | 14 -------------- ...tiesTwo.xml => basicConfigForPropertiesTwo.xml} | 0 .../src/main/resources/springScheduled-config.xml | 6 +++--- .../PropertiesWithMultipleXmlsIntegrationTest.java | 7 ++----- .../PropertiesWithXmlIntegrationTest.java | 6 ++---- .../ExternalPropertiesWithJavaIntegrationTest.java | 2 +- ...lPropertiesWithMultipleXmlsIntegrationTest.java | 2 +- .../ExternalPropertiesWithXmlIntegrationTest.java | 2 +- .../org/baeldung/test/IntegrationTestSuite.java | 10 +++++----- 9 files changed, 15 insertions(+), 34 deletions(-) delete mode 100644 spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java rename spring-all/src/main/resources/{configForPropertiesTwo.xml => basicConfigForPropertiesTwo.xml} (100%) rename spring-all/src/test/java/org/baeldung/properties/{core => basic}/PropertiesWithMultipleXmlsIntegrationTest.java (67%) rename spring-all/src/test/java/org/baeldung/properties/{core => basic}/PropertiesWithXmlIntegrationTest.java (73%) rename spring-all/src/test/java/org/baeldung/properties/{core => external}/ExternalPropertiesWithJavaIntegrationTest.java (97%) rename spring-all/src/test/java/org/baeldung/properties/{core => external}/ExternalPropertiesWithMultipleXmlsIntegrationTest.java (97%) rename spring-all/src/test/java/org/baeldung/properties/{core => external}/ExternalPropertiesWithXmlIntegrationTest.java (97%) diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java deleted file mode 100644 index e4365cbc8b..0000000000 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.properties.spring; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -@Configuration -@ImportResource("classpath:configForPropertiesTwo.xml") -public class PropertiesWithXmlConfigTwo { - - public PropertiesWithXmlConfigTwo() { - super(); - } - -} \ No newline at end of file diff --git a/spring-all/src/main/resources/configForPropertiesTwo.xml b/spring-all/src/main/resources/basicConfigForPropertiesTwo.xml similarity index 100% rename from spring-all/src/main/resources/configForPropertiesTwo.xml rename to spring-all/src/main/resources/basicConfigForPropertiesTwo.xml diff --git a/spring-all/src/main/resources/springScheduled-config.xml b/spring-all/src/main/resources/springScheduled-config.xml index 751b25470d..65566ee779 100644 --- a/spring-all/src/main/resources/springScheduled-config.xml +++ b/spring-all/src/main/resources/springScheduled-config.xml @@ -2,9 +2,9 @@ diff --git a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java similarity index 67% rename from spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java index 9fc793fc1b..eddadd2aeb 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java @@ -1,7 +1,5 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.basic; -import org.baeldung.properties.spring.PropertiesWithXmlConfigOne; -import org.baeldung.properties.spring.PropertiesWithXmlConfigTwo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,10 +7,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithXmlConfigOne.class, PropertiesWithXmlConfigTwo.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(locations = { "classpath:configForPropertiesOne.xml", "classpath:basicConfigForPropertiesTwo.xml" }) public class PropertiesWithMultipleXmlsIntegrationTest { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java similarity index 73% rename from spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java index ff5eaab910..5e7689a2d9 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.basic; -import org.baeldung.properties.spring.PropertiesWithXmlConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -8,10 +7,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(locations = "classpath:basicConfigForProperties.xml") public class PropertiesWithXmlIntegrationTest { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithJavaIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java index 1cf9c774f4..880f9d0c54 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithJavaIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.external; import org.baeldung.properties.spring.PropertiesWithJavaConfig; import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; diff --git a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithMultipleXmlsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithMultipleXmlsIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java index 98654ee4b6..660bd9bc4e 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.external; import org.baeldung.properties.spring.PropertiesWithXmlConfigOne; import org.baeldung.properties.spring.PropertiesWithXmlConfigTwo; diff --git a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithXmlIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java index b77aac63d8..4a111a04dd 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.external; import org.baeldung.properties.spring.PropertiesWithXmlConfig; import org.junit.Ignore; diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index 86ec917bd6..d574ad2356 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -1,11 +1,11 @@ package org.baeldung.test; -import org.baeldung.properties.core.ExternalPropertiesWithJavaIntegrationTest; -import org.baeldung.properties.core.ExternalPropertiesWithMultipleXmlsIntegrationTest; -import org.baeldung.properties.core.ExternalPropertiesWithXmlIntegrationTest; +import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; +import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; import org.baeldung.properties.core.PropertiesWithJavaIntegrationTest; -import org.baeldung.properties.core.PropertiesWithMultipleXmlsIntegrationTest; -import org.baeldung.properties.core.PropertiesWithXmlIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; From 3bc0b756ad927f39349f02c297528eaa582ec3b9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 15 Aug 2015 18:08:54 +0300 Subject: [PATCH 07/34] perperties work --- .../spring/PropertiesWithXmlConfigTwo.java | 14 ++++++++++++++ .../main/resources/basicConfigForProperties.xml | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java create mode 100644 spring-all/src/main/resources/basicConfigForProperties.xml diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java new file mode 100644 index 0000000000..87dbee3696 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java @@ -0,0 +1,14 @@ +package org.baeldung.properties.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource("classpath:basicConfigForPropertiesTwo.xml") +public class PropertiesWithXmlConfigTwo { + + public PropertiesWithXmlConfigTwo() { + super(); + } + +} \ No newline at end of file diff --git a/spring-all/src/main/resources/basicConfigForProperties.xml b/spring-all/src/main/resources/basicConfigForProperties.xml new file mode 100644 index 0000000000..b413e0cd94 --- /dev/null +++ b/spring-all/src/main/resources/basicConfigForProperties.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file From 7243b16d4926763a5feae5aeee6b7fb466b9cf4c Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 15 Aug 2015 18:14:55 +0300 Subject: [PATCH 08/34] work on properties --- .../PropertiesWithJavaConfig.java | 2 +- .../PropertiesWithXmlConfig.java | 2 +- .../PropertiesWithXmlConfigOne.java | 2 +- .../PropertiesWithXmlConfigTwo.java | 2 +- .../spring/BasicPropertiesWithJavaConfig.java | 23 +++++++++++++++++++ .../resources/basicConfigForPropertiesOne.xml | 12 ++++++++++ .../PropertiesWithJavaIntegrationTest.java | 6 ++--- ...ertiesWithMultipleXmlsIntegrationTest.java | 2 +- ...rnalPropertiesWithJavaIntegrationTest.java | 1 - ...ertiesWithMultipleXmlsIntegrationTest.java | 2 -- ...ernalPropertiesWithXmlIntegrationTest.java | 1 - .../baeldung/test/IntegrationTestSuite.java | 2 +- 12 files changed, 44 insertions(+), 13 deletions(-) rename spring-all/src/main/java/org/baeldung/properties/{spring => external}/PropertiesWithJavaConfig.java (94%) rename spring-all/src/main/java/org/baeldung/properties/{spring => external}/PropertiesWithXmlConfig.java (90%) rename spring-all/src/main/java/org/baeldung/properties/{spring => external}/PropertiesWithXmlConfigOne.java (90%) rename spring-all/src/main/java/org/baeldung/properties/{spring => external}/PropertiesWithXmlConfigTwo.java (87%) create mode 100644 spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java create mode 100644 spring-all/src/main/resources/basicConfigForPropertiesOne.xml rename spring-all/src/test/java/org/baeldung/properties/{core => basic}/PropertiesWithJavaIntegrationTest.java (78%) diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java similarity index 94% rename from spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java rename to spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java index 9b5d7ed047..1d6272315d 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package org.baeldung.properties.external; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java similarity index 90% rename from spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java rename to spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java index 9ad7febcb0..aa8017f98d 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package org.baeldung.properties.external; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java similarity index 90% rename from spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java rename to spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java index 9061cc10d4..474ee234ea 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package org.baeldung.properties.external; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java similarity index 87% rename from spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java rename to spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java index 87dbee3696..a8588a00b7 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package org.baeldung.properties.external; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java new file mode 100644 index 0000000000..1357d56090 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.properties.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; + +@Configuration +@PropertySource("classpath:foo.properties") +public class BasicPropertiesWithJavaConfig { + + public BasicPropertiesWithJavaConfig() { + super(); + } + + // beans + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + +} \ No newline at end of file diff --git a/spring-all/src/main/resources/basicConfigForPropertiesOne.xml b/spring-all/src/main/resources/basicConfigForPropertiesOne.xml new file mode 100644 index 0000000000..4301b1faf9 --- /dev/null +++ b/spring-all/src/main/resources/basicConfigForPropertiesOne.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java similarity index 78% rename from spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java index d6c99502d7..d7c4739951 100644 --- a/spring-all/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.properties.core; +package org.baeldung.properties.basic; -import org.baeldung.properties.spring.PropertiesWithJavaConfig; +import org.baeldung.properties.spring.BasicPropertiesWithJavaConfig; import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { BasicPropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) public class PropertiesWithJavaIntegrationTest { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java index eddadd2aeb..461f86f559 100644 --- a/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:configForPropertiesOne.xml", "classpath:basicConfigForPropertiesTwo.xml" }) +@ContextConfiguration(locations = { "classpath:basicConfigForPropertiesOne.xml", "classpath:basicConfigForPropertiesTwo.xml" }) public class PropertiesWithMultipleXmlsIntegrationTest { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java index 880f9d0c54..068198fce2 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java @@ -1,6 +1,5 @@ package org.baeldung.properties.external; -import org.baeldung.properties.spring.PropertiesWithJavaConfig; import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; import org.junit.Ignore; import org.junit.Test; diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java index 660bd9bc4e..0b41117386 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.properties.external; -import org.baeldung.properties.spring.PropertiesWithXmlConfigOne; -import org.baeldung.properties.spring.PropertiesWithXmlConfigTwo; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java index 4a111a04dd..679e8761c4 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java @@ -1,6 +1,5 @@ package org.baeldung.properties.external; -import org.baeldung.properties.spring.PropertiesWithXmlConfig; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index d574ad2356..d217dbf4ec 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -1,8 +1,8 @@ package org.baeldung.test; +import org.baeldung.properties.basic.PropertiesWithJavaIntegrationTest; import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; -import org.baeldung.properties.core.PropertiesWithJavaIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest; From 446bf7fbbd5a3b4a371d55515303d3f9f97abe18 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 16 Aug 2015 11:30:03 +0300 Subject: [PATCH 09/34] persistence work --- .../ExternalPropertiesWithJavaConfig.java | 25 ++++++++++++++++ ...a => ExternalPropertiesWithXmlConfig.java} | 4 +-- ...> ExternalPropertiesWithXmlConfigOne.java} | 4 +-- ...> ExternalPropertiesWithXmlConfigTwo.java} | 4 +-- .../spring/BasicPropertiesWithJavaConfig.java | 9 ------ .../PropertiesWithJavaConfig.java | 4 +-- ...asicPropertiesWithJavaIntegrationTest.java | 29 ++++++++++++++++++ ...ndedPropertiesWithJavaIntegrationTest.java | 30 +++++++++++++++++++ .../PropertiesWithJavaIntegrationTest.java | 5 ++-- ...rnalPropertiesWithJavaIntegrationTest.java | 2 +- ...ertiesWithMultipleXmlsIntegrationTest.java | 2 +- ...ernalPropertiesWithXmlIntegrationTest.java | 2 +- .../baeldung/test/IntegrationTestSuite.java | 4 +-- 13 files changed, 98 insertions(+), 26 deletions(-) create mode 100644 spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java rename spring-all/src/main/java/org/baeldung/properties/external/{PropertiesWithXmlConfig.java => ExternalPropertiesWithXmlConfig.java} (78%) rename spring-all/src/main/java/org/baeldung/properties/external/{PropertiesWithXmlConfigOne.java => ExternalPropertiesWithXmlConfigOne.java} (78%) rename spring-all/src/main/java/org/baeldung/properties/external/{PropertiesWithXmlConfigTwo.java => ExternalPropertiesWithXmlConfigTwo.java} (72%) rename spring-all/src/main/java/org/baeldung/properties/{external => spring}/PropertiesWithJavaConfig.java (80%) create mode 100644 spring-all/src/test/java/org/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java create mode 100644 spring-all/src/test/java/org/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java diff --git a/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java new file mode 100644 index 0000000000..216f905437 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java @@ -0,0 +1,25 @@ +package org.baeldung.properties.external; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; + +@Configuration +@ComponentScan("org.baeldung.properties.core") +@PropertySource("classpath:foo.properties") +public class ExternalPropertiesWithJavaConfig { + + public ExternalPropertiesWithJavaConfig() { + super(); + } + + // beans + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java similarity index 78% rename from spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java rename to spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java index aa8017f98d..ea5bbf1c4d 100644 --- a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java @@ -7,9 +7,9 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForProperties.xml") @ComponentScan("org.baeldung.core") -public class PropertiesWithXmlConfig { +public class ExternalPropertiesWithXmlConfig { - public PropertiesWithXmlConfig() { + public ExternalPropertiesWithXmlConfig() { super(); } diff --git a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java similarity index 78% rename from spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java rename to spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java index 474ee234ea..2698937e1e 100644 --- a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigOne.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java @@ -7,9 +7,9 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForPropertiesOne.xml") @ComponentScan("org.baeldung.core") -public class PropertiesWithXmlConfigOne { +public class ExternalPropertiesWithXmlConfigOne { - public PropertiesWithXmlConfigOne() { + public ExternalPropertiesWithXmlConfigOne() { super(); } diff --git a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java similarity index 72% rename from spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java rename to spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java index a8588a00b7..efbb995b73 100644 --- a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithXmlConfigTwo.java +++ b/spring-all/src/main/java/org/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java @@ -5,9 +5,9 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:basicConfigForPropertiesTwo.xml") -public class PropertiesWithXmlConfigTwo { +public class ExternalPropertiesWithXmlConfigTwo { - public PropertiesWithXmlConfigTwo() { + public ExternalPropertiesWithXmlConfigTwo() { super(); } diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java index 1357d56090..25bfaa20a9 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java @@ -1,9 +1,7 @@ package org.baeldung.properties.spring; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:foo.properties") @@ -13,11 +11,4 @@ public class BasicPropertiesWithJavaConfig { super(); } - // beans - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - } \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java similarity index 80% rename from spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java rename to spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java index 1d6272315d..08626bb4d2 100644 --- a/spring-all/src/main/java/org/baeldung/properties/external/PropertiesWithJavaConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java @@ -1,13 +1,11 @@ -package org.baeldung.properties.external; +package org.baeldung.properties.spring; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan("org.baeldung.properties.core") @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig { diff --git a/spring-all/src/test/java/org/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java new file mode 100644 index 0000000000..049b0d546a --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java @@ -0,0 +1,29 @@ +package org.baeldung.properties.basic; + +import org.baeldung.properties.spring.BasicPropertiesWithJavaConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { BasicPropertiesWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) +public class BasicPropertiesWithJavaIntegrationTest { + + @Autowired + private Environment env; + + @Value("${key.something}") + private String injectedProperty; + + @Test + public final void givenContextIsInitialized_thenNoException() { + System.out.println("in test via @Value: " + injectedProperty); + System.out.println("in test Environment: " + env.getProperty("key.something")); + } + +} diff --git a/spring-all/src/test/java/org/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java new file mode 100644 index 0000000000..28ef76e249 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java @@ -0,0 +1,30 @@ +package org.baeldung.properties.basic; + +import org.baeldung.properties.spring.BasicPropertiesWithJavaConfig; +import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { BasicPropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) +public class ExtendedPropertiesWithJavaIntegrationTest { + + @Autowired + private Environment env; + + @Value("${key.something}") + private String injectedProperty; + + @Test + public final void givenContextIsInitialized_thenNoException() { + System.out.println("in test via @Value: " + injectedProperty); + System.out.println("in test Environment: " + env.getProperty("key.something")); + } + +} diff --git a/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java index d7c4739951..c55c1ee783 100644 --- a/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java @@ -1,7 +1,6 @@ package org.baeldung.properties.basic; -import org.baeldung.properties.spring.BasicPropertiesWithJavaConfig; -import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; +import org.baeldung.properties.spring.PropertiesWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -12,7 +11,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { BasicPropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PropertiesWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) public class PropertiesWithJavaIntegrationTest { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java index 068198fce2..c38a4b5465 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ExternalPropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") public class ExternalPropertiesWithJavaIntegrationTest { diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java index 0b41117386..fe96ea8f7f 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithXmlConfigOne.class, PropertiesWithXmlConfigTwo.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfigOne.class, ExternalPropertiesWithXmlConfigTwo.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") public class ExternalPropertiesWithMultipleXmlsIntegrationTest { diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java index 679e8761c4..2ea2822b9a 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") public class ExternalPropertiesWithXmlIntegrationTest { diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index d217dbf4ec..f9845f42a7 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -1,6 +1,6 @@ package org.baeldung.test; -import org.baeldung.properties.basic.PropertiesWithJavaIntegrationTest; +import org.baeldung.properties.basic.ExtendedPropertiesWithJavaIntegrationTest; import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; @@ -16,7 +16,7 @@ import org.junit.runners.Suite.SuiteClasses; ExternalPropertiesWithJavaIntegrationTest.class, ExternalPropertiesWithMultipleXmlsIntegrationTest.class, ExternalPropertiesWithXmlIntegrationTest.class, - PropertiesWithJavaIntegrationTest.class, + ExtendedPropertiesWithJavaIntegrationTest.class, PropertiesWithMultipleXmlsIntegrationTest.class, })// @formatter:on public final class IntegrationTestSuite { From 6b10bee0a0d017d623d792301d3387ac8e5a8a7e Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 20 Aug 2015 11:36:19 +0300 Subject: [PATCH 10/34] cleanup work --- core-java-8/pom.xml | 6 ++++++ .../java8/base64/ApacheCommonsEncodeDecodeTest.java} | 4 ++-- .../org/baeldung/java8/base64/Java8EncodeDecodeTest.java} | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) rename core-java-8/src/{main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java => test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java} (95%) rename core-java-8/src/{main/java/com/demo/encoding/Java8EncodeDecode.java => test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java} (98%) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index b23e309696..9db2562fb4 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -28,6 +28,12 @@ 4.0 + + commons-codec + commons-codec + 1.10 + + org.apache.commons commons-lang3 diff --git a/core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java b/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java similarity index 95% rename from core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java rename to core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java index d15b1325dc..5e16df5a12 100644 --- a/core-java-8/src/main/java/com/demo/encoding/ApacheCommonsEncodeDecode.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java @@ -1,4 +1,4 @@ -package com.demo.encoding; +package org.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -9,7 +9,7 @@ import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; import org.junit.Test; -public class ApacheCommonsEncodeDecode { +public class ApacheCommonsEncodeDecodeTest { @Test public void whenStringIsEncoded() throws UnsupportedEncodingException { diff --git a/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java similarity index 98% rename from core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java rename to core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java index 241fee6ded..ae7bf0166d 100644 --- a/core-java-8/src/main/java/com/demo/encoding/Java8EncodeDecode.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -1,4 +1,4 @@ -package com.demo.encoding; +package org.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -10,7 +10,7 @@ import java.util.UUID; import org.junit.Test; -public class Java8EncodeDecode { +public class Java8EncodeDecodeTest { @Test public void whenStringIsEncoded() throws UnsupportedEncodingException { From ed2b7e4e2f01362d90f3e70f91fb1eb704c7e349 Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 20 Aug 2015 11:37:01 +0300 Subject: [PATCH 11/34] test cleanup --- .../base64/ApacheCommonsEncodeDecodeTest.java | 26 ++++---- .../java8/base64/Java8EncodeDecodeTest.java | 63 ++++++++++--------- 2 files changed, 47 insertions(+), 42 deletions(-) diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java index 5e16df5a12..9745655d8a 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java @@ -11,11 +11,13 @@ import org.junit.Test; public class ApacheCommonsEncodeDecodeTest { + // tests + @Test public void whenStringIsEncoded() throws UnsupportedEncodingException { - String originalInput = "test input"; - Base64 base64 = new Base64(); - String encodedString = new String(base64.encode(originalInput.getBytes())); + final String originalInput = "test input"; + final Base64 base64 = new Base64(); + final String encodedString = new String(base64.encode(originalInput.getBytes())); assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); @@ -23,11 +25,11 @@ public class ApacheCommonsEncodeDecodeTest { @Test public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException { - String originalInput = "test input"; - Base64 base64 = new Base64(); - String encodedString = new String(base64.encode(originalInput.getBytes())); + final String originalInput = "test input"; + final Base64 base64 = new Base64(); + final String encodedString = new String(base64.encode(originalInput.getBytes())); - String decodedString = new String(base64.decode(encodedString.getBytes())); + final String decodedString = new String(base64.decode(encodedString.getBytes())); assertNotNull(decodedString); assertEquals(originalInput, decodedString); @@ -35,8 +37,8 @@ public class ApacheCommonsEncodeDecodeTest { @Test public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); + final String originalInput = "test input"; + final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); @@ -44,10 +46,10 @@ public class ApacheCommonsEncodeDecodeTest { @Test public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); + final String originalInput = "test input"; + final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); - String decodedString = new String(Base64.decodeBase64(encodedString.getBytes())); + final String decodedString = new String(Base64.decodeBase64(encodedString.getBytes())); assertNotNull(decodedString); assertEquals(originalInput, decodedString); diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java index ae7bf0166d..c5027e0208 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -12,91 +12,94 @@ import org.junit.Test; public class Java8EncodeDecodeTest { + // tests + @Test public void whenStringIsEncoded() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); + final String originalInput = "test input"; + final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); } @Test public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); + final String originalInput = "test input"; + final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); - byte[] decodedBytes = Base64.getDecoder().decode(encodedString); - String decodedString = new String(decodedBytes); + final byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + final String decodedString = new String(decodedBytes); assertNotNull(decodedString); assertEquals(originalInput, decodedString); } - + @Test public void whenStringIsEncodedWithoutPadding() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); + final String originalInput = "test input"; + final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); } - + @Test public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException { - String originalInput = "test input"; - String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); + final String originalInput = "test input"; + final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); - byte[] decodedBytes = Base64.getDecoder().decode(encodedString); - String decodedString = new String(decodedBytes); + final byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + final String decodedString = new String(decodedBytes); assertNotNull(decodedString); assertEquals(originalInput, decodedString); } - @Test public void whenURLIsEncoded() throws UnsupportedEncodingException { - String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; - String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); + final String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + final String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); assertNotNull(encodedURL); assertNotEquals(originalURL, encodedURL); } @Test public void whenURLIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException { - String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; - String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); - byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedURL.getBytes()); - String decodedURL = new String(decodedBytes); + final String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + final String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); + final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedURL.getBytes()); + final String decodedURL = new String(decodedBytes); assertNotNull(decodedURL); assertEquals(originalURL, decodedURL); } @Test public void whenMIMEIsEncoded() throws UnsupportedEncodingException { - StringBuilder buffer = getMimeBuffer(); + final StringBuilder buffer = getMimeBuffer(); - byte[] forEncode = buffer.toString().getBytes(); - String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); + final byte[] forEncode = buffer.toString().getBytes(); + final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); assertNotNull(encodedMime); } @Test public void whenMIMEIsEncoded_thenMIMECanBeDecoded() throws UnsupportedEncodingException { - StringBuilder buffer = getMimeBuffer(); + final StringBuilder buffer = getMimeBuffer(); - byte[] forEncode = buffer.toString().getBytes(); - String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); + final byte[] forEncode = buffer.toString().getBytes(); + final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode); - byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime); - String decodedMime = new String(decodedBytes); + final byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime); + final String decodedMime = new String(decodedBytes); assertNotNull(decodedMime); } + // + private static StringBuilder getMimeBuffer() { - StringBuilder buffer = new StringBuilder(); + final StringBuilder buffer = new StringBuilder(); for (int count = 0; count < 10; ++count) { buffer.append(UUID.randomUUID().toString()); } From a9d376740e6222e620d34cbc12ec53581b2e7ee1 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 23 Aug 2015 00:41:11 +0300 Subject: [PATCH 12/34] Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 2da54bde1c..3d3d7b5da8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ + +The "REST with Spring" Classes +============================== +This is what I'm working on: +[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com) + + Spring Tutorials ================ From c8966e7792aa78adb5819e0fbebcbe4860dd57b2 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 23 Aug 2015 00:41:25 +0300 Subject: [PATCH 13/34] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d3d7b5da8..82c35f99a1 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ The "REST with Spring" Classes ============================== This is what I'm working on: -[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com) +[>> THE REST WITH SPRING CLASSES](http://www.restwithspring.com) Spring Tutorials From 4631f7e91586d5e73d7c223dc7f8d6338cde8b1e Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 23 Aug 2015 20:11:36 +0300 Subject: [PATCH 14/34] minor formatting work --- .../src/main/java/org/baeldung/event/CascadeCallback.java | 4 ++-- .../org/baeldung/event/CascadeSaveMongoEventListener.java | 4 ++-- .../mongotemplate/MongoTemplateQueryIntegrationTest.java | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java index 2f433b6b44..e56caad4cb 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java @@ -8,10 +8,10 @@ import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.util.ReflectionUtils; public class CascadeCallback implements ReflectionUtils.FieldCallback { - + private Object source; private MongoOperations mongoOperations; - + public CascadeCallback(final Object source, final MongoOperations mongoOperations) { this.source = source; this.setMongoOperations(mongoOperations); diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java index ae79c1d92e..79840fb570 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java @@ -6,10 +6,10 @@ import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventLis import org.springframework.util.ReflectionUtils; public class CascadeSaveMongoEventListener extends AbstractMongoEventListener { - + @Autowired private MongoOperations mongoOperations; - + @Override public void onBeforeConvert(final Object source) { ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations)); diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java index e1dc426cda..1701b9ac5a 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java @@ -26,7 +26,6 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class MongoTemplateQueryIntegrationTest { From 0b42f56f494d8ca8f53839bb135f27bd9c7bca47 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 23 Aug 2015 20:13:00 +0300 Subject: [PATCH 15/34] minor formatting work --- .../src/main/java/org/baeldung/config/MongoConfig.java | 4 ++-- .../java/org/baeldung/converter/UserWriterConverter.java | 8 ++++---- .../src/main/java/org/baeldung/event/CascadeCallback.java | 8 ++++---- .../src/main/java/org/baeldung/event/FieldCallback.java | 3 ++- .../src/main/java/org/baeldung/model/User.java | 4 ++-- .../main/java/org/baeldung/repository/UserRepository.java | 1 - 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java index 4b776af5b6..8fbe966074 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java @@ -7,9 +7,9 @@ import org.baeldung.converter.UserWriterConverter; import org.baeldung.event.CascadeSaveMongoEventListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.core.convert.CustomConversions; -import org.springframework.core.convert.converter.Converter; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.Mongo; @@ -19,7 +19,7 @@ import com.mongodb.MongoClient; @EnableMongoRepositories(basePackages = "org.baeldung.repository") public class MongoConfig extends AbstractMongoConfiguration { - private List> converters = new ArrayList>(); + private final List> converters = new ArrayList>(); @Override protected String getDatabaseName() { diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java index 18f2314c6b..54fa78e2d0 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java @@ -1,8 +1,8 @@ package org.baeldung.converter; -import org.springframework.stereotype.Component; import org.baeldung.model.User; import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; @@ -10,12 +10,12 @@ import com.mongodb.DBObject; @Component public class UserWriterConverter implements Converter { @Override - public DBObject convert(User user) { - DBObject dbObject = new BasicDBObject(); + public DBObject convert(final User user) { + final DBObject dbObject = new BasicDBObject(); dbObject.put("name", user.getName()); dbObject.put("age", user.getAge()); if (user.getEmailAddress() != null) { - DBObject emailDbObject = new BasicDBObject(); + final DBObject emailDbObject = new BasicDBObject(); emailDbObject.put("value", user.getEmailAddress().getValue()); dbObject.put("email", emailDbObject); } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java index e56caad4cb..e01a1bc8c0 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java @@ -18,14 +18,14 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { } @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) { final Object fieldValue = field.get(getSource()); if (fieldValue != null) { - FieldCallback callback = new FieldCallback(); + final FieldCallback callback = new FieldCallback(); ReflectionUtils.doWithFields(fieldValue.getClass(), callback); @@ -39,7 +39,7 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { return source; } - public void setSource(Object source) { + public void setSource(final Object source) { this.source = source; } @@ -47,7 +47,7 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { return mongoOperations; } - public void setMongoOperations(MongoOperations mongoOperations) { + public void setMongoOperations(final MongoOperations mongoOperations) { this.mongoOperations = mongoOperations; } } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java b/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java index 868bbc31f0..c6bd90d4f3 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java @@ -8,7 +8,8 @@ import org.springframework.util.ReflectionUtils; public class FieldCallback implements ReflectionUtils.FieldCallback { private boolean idFound; - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + @Override + public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (field.isAnnotationPresent(Id.class)) { diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java b/spring-data-mongodb/src/main/java/org/baeldung/model/User.java index 64fe404f5e..b67d632780 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/model/User.java @@ -73,7 +73,7 @@ public class User { return emailAddress; } - public void setEmailAddress(EmailAddress emailAddress) { + public void setEmailAddress(final EmailAddress emailAddress) { this.emailAddress = emailAddress; } @@ -81,7 +81,7 @@ public class User { return yearOfBirth; } - public void setYearOfBirth(Integer yearOfBirth) { + public void setYearOfBirth(final Integer yearOfBirth) { this.yearOfBirth = yearOfBirth; } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java index 72d9a4dba0..28b21ffb43 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java @@ -3,7 +3,6 @@ package org.baeldung.repository; import java.util.List; import org.baeldung.model.User; - import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; From ebcf6c8b7464af2baa433a275b06fff97568197c Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 23 Aug 2015 21:02:04 +0300 Subject: [PATCH 16/34] work on a cleanup bean --- spring-all/pom.xml | 27 +++++++++++++++++++ .../baeldung/spring/config/CleanupBean.java | 26 ++++++++++++++++++ .../baeldung/spring/config/CoreConfig.java | 17 ++++++++++++ spring-security-rest-full/pom.xml | 12 ++++----- 4 files changed, 76 insertions(+), 6 deletions(-) create mode 100644 spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 3391846d97..25db828613 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -7,6 +7,12 @@ spring-all war + + org.springframework.boot + spring-boot-starter-parent + 1.2.5.RELEASE + + @@ -101,6 +107,27 @@ guava ${guava.version} + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java b/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java new file mode 100644 index 0000000000..34e01bf15b --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java @@ -0,0 +1,26 @@ +package org.baeldung.spring.config; + +import java.util.concurrent.ExecutorService; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public final class CleanupBean implements DisposableBean { + + @Autowired + private ExecutorService setupExecutor; + + public CleanupBean() { + super(); + } + + // + + @Override + public void destroy() { + setupExecutor.shutdownNow(); + } + +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java index ff1742351b..21b67933ef 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java @@ -1,5 +1,11 @@ package org.baeldung.spring.config; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -12,4 +18,15 @@ public class CoreConfig extends WebMvcConfigurerAdapter { super(); } + // beans + + @Bean + public ExecutorService setupExecutor() { + final int coreThreads = 4; + final int maxThreads = 8; + final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreThreads, maxThreads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); + threadPoolExecutor.allowCoreThreadTimeOut(true); + return threadPoolExecutor; + } + } \ No newline at end of file diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index daa0ed01af..7a219288de 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -7,6 +7,12 @@ spring-security-rest-full war + + org.springframework.boot + spring-boot-starter-parent + 1.2.5.RELEASE + + @@ -454,10 +460,4 @@ - - org.springframework.boot - spring-boot-starter-parent - 1.2.4.RELEASE - - \ No newline at end of file From 6ef3de5c3df15cc3caed5b8ae68e85f92a856de3 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 23 Aug 2015 21:07:48 +0300 Subject: [PATCH 17/34] maven cleanup --- spring-all/pom.xml | 16 ---------------- .../org/baeldung/spring/config/CleanupBean.java | 7 +++++++ 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 25db828613..17226266fb 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -20,22 +20,18 @@ org.springframework spring-web - ${org.springframework.version} org.springframework spring-webmvc - ${org.springframework.version} org.springframework spring-orm - ${org.springframework.version} org.springframework spring-context - ${org.springframework.version} @@ -43,13 +39,11 @@ org.springframework spring-aspects - ${org.springframework.version} org.springframework spring-orm - ${org.springframework.version} @@ -62,18 +56,15 @@ org.javassist javassist - ${javassist.version} mysql mysql-connector-java - ${mysql-connector-java.version} runtime org.hsqldb hsqldb - 2.3.2 @@ -81,7 +72,6 @@ org.hibernate hibernate-validator - ${hibernate-validator.version} @@ -89,14 +79,12 @@ javax.servlet javax.servlet-api - 3.0.1 provided javax.servlet jstl - ${jstl.version} runtime @@ -134,7 +122,6 @@ org.springframework spring-test - ${org.springframework.version} test @@ -148,20 +135,17 @@ org.hamcrest hamcrest-core - ${org.hamcrest.version} test org.hamcrest hamcrest-library - ${org.hamcrest.version} test org.mockito mockito-core - ${mockito.version} test diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java b/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java index 34e01bf15b..ac90319745 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/CleanupBean.java @@ -2,12 +2,15 @@ package org.baeldung.spring.config; import java.util.concurrent.ExecutorService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public final class CleanupBean implements DisposableBean { + private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ExecutorService setupExecutor; @@ -20,7 +23,11 @@ public final class CleanupBean implements DisposableBean { @Override public void destroy() { + logger.info("Starting shutdown process - cleanup"); + setupExecutor.shutdownNow(); + + logger.info("Finishing shutdown process - cleanup"); } } \ No newline at end of file From b7822cc67831dd03fb4051e9dfd90244295a8b71 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 26 Aug 2015 12:05:55 +0300 Subject: [PATCH 18/34] minor cleanup work --- .../java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java index c5027e0208..c8d57d40b3 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -32,7 +32,6 @@ public class Java8EncodeDecodeTest { assertNotNull(decodedString); assertEquals(originalInput, decodedString); - } @Test @@ -53,7 +52,6 @@ public class Java8EncodeDecodeTest { assertNotNull(decodedString); assertEquals(originalInput, decodedString); - } @Test From 7a7ad7b368bcd7dcec6543c3467d1dfd69d7fb14 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 26 Aug 2015 12:10:06 +0300 Subject: [PATCH 19/34] testing work --- .../java8/base64/Java8EncodeDecodeTest.java | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java index c8d57d40b3..7b7a0be26a 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -15,9 +15,10 @@ public class Java8EncodeDecodeTest { // tests @Test - public void whenStringIsEncoded() throws UnsupportedEncodingException { + public void whenStringIsEncoded_thenOk() throws UnsupportedEncodingException { final String originalInput = "test input"; final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); + assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); } @@ -35,9 +36,10 @@ public class Java8EncodeDecodeTest { } @Test - public void whenStringIsEncodedWithoutPadding() throws UnsupportedEncodingException { + public void whenStringIsEncodedWithoutPadding_thenOk() throws UnsupportedEncodingException { final String originalInput = "test input"; final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes()); + assertNotNull(encodedString); assertNotEquals(originalInput, encodedString); } @@ -55,25 +57,27 @@ public class Java8EncodeDecodeTest { } @Test - public void whenURLIsEncoded() throws UnsupportedEncodingException { - final String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; - final String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); - assertNotNull(encodedURL); - assertNotEquals(originalURL, encodedURL); + public void whenUrlIsEncoded_thenOk() throws UnsupportedEncodingException { + final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes()); + assertNotNull(encodedUrl); + assertNotEquals(originalUrl, encodedUrl); } @Test - public void whenURLIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException { - final String originalURL = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; - final String encodedURL = Base64.getUrlEncoder().encodeToString(originalURL.getBytes()); - final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedURL.getBytes()); - final String decodedURL = new String(decodedBytes); - assertNotNull(decodedURL); - assertEquals(originalURL, decodedURL); + public void whenUrlIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException { + final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java"; + final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes()); + + final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl.getBytes()); + final String decodedUrl = new String(decodedBytes); + + assertNotNull(decodedUrl); + assertEquals(originalUrl, decodedUrl); } @Test - public void whenMIMEIsEncoded() throws UnsupportedEncodingException { + public void whenMimeIsEncoded_thenOk() throws UnsupportedEncodingException { final StringBuilder buffer = getMimeBuffer(); final byte[] forEncode = buffer.toString().getBytes(); @@ -83,7 +87,7 @@ public class Java8EncodeDecodeTest { } @Test - public void whenMIMEIsEncoded_thenMIMECanBeDecoded() throws UnsupportedEncodingException { + public void whenMimeIsEncoded_thenItCanBeDecoded() throws UnsupportedEncodingException { final StringBuilder buffer = getMimeBuffer(); final byte[] forEncode = buffer.toString().getBytes(); From 48e3cc3d382781cece8d4c457aea04a64a83dcae Mon Sep 17 00:00:00 2001 From: Eugen Date: Wed, 26 Aug 2015 15:12:34 +0300 Subject: [PATCH 20/34] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 82c35f99a1..161ca30fe0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ The "REST with Spring" Classes ============================== This is what I'm working on: -[>> THE REST WITH SPRING CLASSES](http://www.restwithspring.com) +[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=50off) Spring Tutorials From c3158b72f9c317a1df97ae8e65ed83fa68eb32da Mon Sep 17 00:00:00 2001 From: Eugen Date: Wed, 26 Aug 2015 15:13:50 +0300 Subject: [PATCH 21/34] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 161ca30fe0..408842855f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ The "REST with Spring" Classes ============================== -This is what I'm working on: -[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=50off) +This is what I'm working on:
+**[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=50off)** Spring Tutorials From 9c6cfa333feb6452ff8dac32cde13e488d6538a3 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Fri, 28 Aug 2015 09:26:25 +0300 Subject: [PATCH 22/34] [RestTemplate] Create unit tests for GET and POST methods --- .../org/baeldung/persistence/model/Owner.java | 25 ++++ .../persistence/model/Repository.java | 35 +++++ .../org/baeldung/persistence/model/User_.java | 2 + .../web/controller/FooController.java | 8 +- .../baeldung/client/RestTemplateLiveTest.java | 131 ++++++++++++++++++ 5 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java create mode 100644 spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java new file mode 100644 index 0000000000..cce00054de --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java @@ -0,0 +1,25 @@ +package org.baeldung.persistence.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Owner { + private String login; + private String url; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java new file mode 100644 index 0000000000..89372fa7a7 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java @@ -0,0 +1,35 @@ +package org.baeldung.persistence.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Repository { + private long id; + private String name; + + private Owner owner; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Owner getOwner() { + return owner; + } + + public void setOwner(Owner owner) { + this.owner = owner; + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java index c7b6ba2de8..b705c51ff8 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java @@ -5,7 +5,9 @@ import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(User.class) public class User_ { + public static volatile SingularAttribute id; public static volatile SingularAttribute firstName; public static volatile SingularAttribute lastName; public static volatile SingularAttribute age; + public static volatile SingularAttribute email; } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index fdf0157230..091c452731 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -85,11 +85,15 @@ public class FooController { @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final Foo resource, final HttpServletResponse response) { + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); - final Long idOfCreatedResource = service.create(resource).getId(); + Foo foo = service.create(resource); + final Long idOfCreatedResource = foo.getId(); eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); + + return foo; } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java new file mode 100644 index 0000000000..0265124ef3 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -0,0 +1,131 @@ +package org.baeldung.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.model.Repository; +import org.baeldung.spring.PersistenceConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }) +public class RestTemplateLiveTest { + + RestTemplate restTemplate; + private List> messageConverters; + private final String userReposUrl = "https://api.github.com/users/eugenp/repos"; + private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + + messageConverters = new ArrayList<>(); + MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); + jsonMessageConverter.setObjectMapper(new ObjectMapper()); + messageConverters.add(jsonMessageConverter); + } + + @Test + public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + ResponseEntity response = restTemplate.getForEntity(userReposUrl, String.class); + assertThat(response.getStatusCode(), is(HttpStatus.OK)); + } + + @Test + public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectRepoJson() throws IOException { + ResponseEntity response = restTemplate.getForEntity(repoUrl, String.class); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(response.getBody()); + + JsonNode name = root.path("name"); + assertThat(name.asText(), is("tutorials")); + + JsonNode owner = root.path("owner").path("login"); + assertThat(owner.asText(), is("eugenp")); + } + + @Test + public void givenRepoEndpoint_whenSendGetForObject_thenReturnsRepoObject() { + restTemplate.setMessageConverters(messageConverters); + String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; + Repository repository = restTemplate.getForObject(repoUrl, Repository.class); + + assertThat(repository.getName(), is("tutorials")); + assertThat(repository.getOwner().getLogin(), is("eugenp")); + } + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + String fooService = "http://localhost:8080/spring-security-rest-full/foos"; + + ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); + RestTemplate restTemplate = new RestTemplate(requestFactory); + + HttpEntity request = new HttpEntity<>(new Foo("bar")); + Foo foo = restTemplate.postForObject(fooService, request, Foo.class); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() { + String fooService = "http://localhost:8080/spring-security-rest-full/foos"; + + ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); + RestTemplate restTemplate = new RestTemplate(requestFactory); + + HttpEntity request = new HttpEntity<>(new Foo("bar")); + Foo firstInstance = restTemplate.postForObject(fooService, request, Foo.class); + Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class); + assertThat(firstInstance, notNullValue()); + assertThat(secondInstance, notNullValue()); + assertThat(firstInstance, not(secondInstance)); + } + + private ClientHttpRequestFactory getClientHttpRequestFactory() { + int timeout = 5; + RequestConfig config = RequestConfig.custom() + .setConnectTimeout(timeout * 1000) + .setConnectionRequestTimeout(timeout * 1000) + .setSocketTimeout(timeout * 1000).build(); + + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), + new UsernamePasswordCredentials("user1", "user1Pass")); + + CloseableHttpClient client = HttpClientBuilder.create() + .setDefaultRequestConfig(config) + .setDefaultCredentialsProvider(credentialsProvider).build(); + + return new HttpComponentsClientHttpRequestFactory(client); + } +} From 7dc0bafa12a3794757574c4eda8454da56bb688e Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Mon, 31 Aug 2015 09:24:33 +0300 Subject: [PATCH 23/34] [RestTemplate] Create unit tests for exchange() and execute() methods --- .../baeldung/client/RestTemplateLiveTest.java | 100 ++++++++++++++++-- 1 file changed, 92 insertions(+), 8 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index 0265124ef3..7e1081c4d3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -2,6 +2,7 @@ package org.baeldung.client; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.config.RequestConfig; @@ -14,26 +15,26 @@ import org.baeldung.spring.PersistenceConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.*; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import java.util.*; +import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; - +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }) public class RestTemplateLiveTest { @@ -42,6 +43,7 @@ public class RestTemplateLiveTest { private List> messageConverters; private final String userReposUrl = "https://api.github.com/users/eugenp/repos"; private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; + private final String fooService = "http://localhost:8080/spring-security-rest-full/foos"; @Before public void beforeTest() { @@ -108,7 +110,7 @@ public class RestTemplateLiveTest { Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class); assertThat(firstInstance, notNullValue()); assertThat(secondInstance, notNullValue()); - assertThat(firstInstance, not(secondInstance)); + assertThat(firstInstance.getId(), not(secondInstance.getId())); } private ClientHttpRequestFactory getClientHttpRequestFactory() { @@ -128,4 +130,86 @@ public class RestTemplateLiveTest { return new HttpComponentsClientHttpRequestFactory(client); } + + @Test + public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + String repoUrl = "https://api.github.com/repos/eugenp/{repoName}"; + RestTemplate template = new RestTemplate(); + + Map uriVariables = new HashMap<>(); + uriVariables.put("repoName", "tutorials"); + + HttpHeaders httpHeaders = template.headForHeaders(repoUrl, uriVariables); + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + assertThat(httpHeaders.get("X-RateLimit-Limit"), contains("60")); + } + + @Test + public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + RestTemplate template = new RestTemplate(getClientHttpRequestFactory()); + Set optionsForAllow = template.optionsForAllow(fooService); + HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE}; + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + @Test + public void givenRestService_whenPostResource_thenResourceIsCreated() { + RestTemplate restTemplate = new RestTemplate(); + + HttpHeaders headers = prepareBasicAuthHeaders(); + HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + ResponseEntity response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + Foo foo = response.getBody(); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + assertThat(foo.getId(), is(1L)); + } + + private HttpHeaders prepareBasicAuthHeaders() { + HttpHeaders headers = new HttpHeaders(); + String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + String logPass = "user1:user1Pass"; + byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + @Test + public void givenResource_whenPutExistingEntity_thenItIsUpdated() { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = prepareBasicAuthHeaders(); + HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + //Create entity + ResponseEntity response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + assertThat(response.getBody().getId(), is(1L)); + + //Update entity + Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(1); + String resourceUrl = fooService + "/1"; + restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + //Check that entity was updated + response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + Foo foo = response.getBody(); + assertThat(foo.getId(), is(1L)); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + private RequestCallback requestCallback(Foo updatedInstace) { + return clientHttpRequest -> { + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstace); + clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } } From f1254017a43d5a41c74a3436db0a994d13177330 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sat, 5 Sep 2015 18:23:09 +0300 Subject: [PATCH 24/34] Update README.md --- spring-rest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-rest/README.md b/spring-rest/README.md index 3231d65625..3b93b06d66 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -6,4 +6,4 @@ ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) -- [Redirect in Spring](http://www.baeldung.com/spring-redirect) +- [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) From 84950189c6ddbf00ca69e36a5e7e5a999452bbbc Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 7 Sep 2015 10:40:49 +0300 Subject: [PATCH 25/34] small version bump --- spring-boot/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 004d505fe5..57807ead74 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.2.5.RELEASE From ef60eda31cfb56e769e078fe0d377bd36077ac5c Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Fri, 11 Sep 2015 14:33:15 +0300 Subject: [PATCH 26/34] [RestTemplate] Create unit test for delete() method - Refactor RestTemplateClientTest --- .../org/baeldung/persistence/model/Owner.java | 25 --- .../persistence/model/Repository.java | 35 ---- .../web/controller/FooController.java | 24 +-- .../baeldung/client/RestTemplateLiveTest.java | 187 +++++++++--------- 4 files changed, 110 insertions(+), 161 deletions(-) delete mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java delete mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java deleted file mode 100644 index cce00054de..0000000000 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.persistence.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class Owner { - private String login; - private String url; - - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } -} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java deleted file mode 100644 index 89372fa7a7..0000000000 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.persistence.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class Repository { - private long id; - private String name; - - private Owner owner; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Owner getOwner() { - return owner; - } - - public void setOwner(Owner owner) { - this.owner = owner; - } -} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 091c452731..6b28a081d2 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -1,9 +1,6 @@ package org.baeldung.web.controller; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - +import com.google.common.base.Preconditions; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; import org.baeldung.web.exception.MyResourceNotFoundException; @@ -15,17 +12,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; -import com.google.common.base.Preconditions; +import javax.servlet.http.HttpServletResponse; +import java.util.List; @Controller @RequestMapping(value = "/foos") @@ -110,4 +103,11 @@ public class FooController { service.deleteById(id); } + @RequestMapping(method = RequestMethod.HEAD) + @ResponseStatus(HttpStatus.OK) + public void head(HttpServletResponse resp) { + resp.setContentType(MediaType.APPLICATION_JSON_VALUE); + resp.setHeader("bar", "baz"); + } + } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index 7e1081c4d3..d79ca52f5d 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -10,11 +10,12 @@ import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.model.Repository; +import org.baeldung.persistence.service.IFooService; import org.baeldung.spring.PersistenceConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -22,97 +23,165 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }) +@ContextConfiguration(classes = {PersistenceConfig.class}) public class RestTemplateLiveTest { RestTemplate restTemplate; private List> messageConverters; - private final String userReposUrl = "https://api.github.com/users/eugenp/repos"; - private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; - private final String fooService = "http://localhost:8080/spring-security-rest-full/foos"; + private static final String fooResourceUrl = "http://localhost:8080/spring-security-rest-full/foos"; + + @Autowired + private IFooService fooService; @Before public void beforeTest() { - restTemplate = new RestTemplate(); + restTemplate = new RestTemplate(getClientHttpRequestFactory()); messageConverters = new ArrayList<>(); MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); jsonMessageConverter.setObjectMapper(new ObjectMapper()); messageConverters.add(jsonMessageConverter); + + ensureOneEntityExists(); } @Test public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - ResponseEntity response = restTemplate.getForEntity(userReposUrl, String.class); + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); assertThat(response.getStatusCode(), is(HttpStatus.OK)); } @Test - public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectRepoJson() throws IOException { - ResponseEntity response = restTemplate.getForEntity(repoUrl, String.class); + public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.getBody()); JsonNode name = root.path("name"); - assertThat(name.asText(), is("tutorials")); + assertThat(name.asText(), is("bar")); - JsonNode owner = root.path("owner").path("login"); - assertThat(owner.asText(), is("eugenp")); + JsonNode owner = root.path("id"); + assertThat(owner.asText(), is("1")); } @Test public void givenRepoEndpoint_whenSendGetForObject_thenReturnsRepoObject() { restTemplate.setMessageConverters(messageConverters); - String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; - Repository repository = restTemplate.getForObject(repoUrl, Repository.class); - - assertThat(repository.getName(), is("tutorials")); - assertThat(repository.getOwner().getLogin(), is("eugenp")); + Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + assertThat(foo.getName(), is("bar")); + assertThat(foo.getId(), is(1L)); } @Test public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { - String fooService = "http://localhost:8080/spring-security-rest-full/foos"; - - ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); - RestTemplate restTemplate = new RestTemplate(requestFactory); - HttpEntity request = new HttpEntity<>(new Foo("bar")); - Foo foo = restTemplate.postForObject(fooService, request, Foo.class); + Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); assertThat(foo, notNullValue()); assertThat(foo.getName(), is("bar")); } @Test public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() { - String fooService = "http://localhost:8080/spring-security-rest-full/foos"; - ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); HttpEntity request = new HttpEntity<>(new Foo("bar")); - Foo firstInstance = restTemplate.postForObject(fooService, request, Foo.class); - Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class); + Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); assertThat(firstInstance, notNullValue()); assertThat(secondInstance, notNullValue()); assertThat(firstInstance.getId(), not(secondInstance.getId())); } + @Test + public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + assertTrue(httpHeaders.get("foo").contains("bar")); + } + + @Test + public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE}; + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + @Test + public void givenRestService_whenPostResource_thenResourceIsCreated() { + RestTemplate restTemplate = new RestTemplate(); + + HttpHeaders headers = prepareBasicAuthHeaders(); + HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + Foo foo = response.getBody(); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenResource_whenPutExistingEntity_thenItIsUpdated() { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = prepareBasicAuthHeaders(); + HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + //Create entity + ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + //Update entity + Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody().getId()); + String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); + restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + //Check that entity was updated + response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + Foo foo = response.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenRestService_whenCallDelete_thenEntityIsRemoved() { + String entityUrl = fooResourceUrl + "/1"; + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (HttpClientErrorException ex) { + assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + } + } + + private void ensureOneEntityExists() { + Foo instance = new Foo("bar"); + if (fooService.findOne(1L) == null) { + fooService.create(instance); + } + } + private ClientHttpRequestFactory getClientHttpRequestFactory() { int timeout = 5; RequestConfig config = RequestConfig.custom() @@ -131,42 +200,6 @@ public class RestTemplateLiveTest { return new HttpComponentsClientHttpRequestFactory(client); } - @Test - public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { - String repoUrl = "https://api.github.com/repos/eugenp/{repoName}"; - RestTemplate template = new RestTemplate(); - - Map uriVariables = new HashMap<>(); - uriVariables.put("repoName", "tutorials"); - - HttpHeaders httpHeaders = template.headForHeaders(repoUrl, uriVariables); - assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); - assertThat(httpHeaders.get("X-RateLimit-Limit"), contains("60")); - } - - @Test - public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { - RestTemplate template = new RestTemplate(getClientHttpRequestFactory()); - Set optionsForAllow = template.optionsForAllow(fooService); - HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE}; - assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); - } - - @Test - public void givenRestService_whenPostResource_thenResourceIsCreated() { - RestTemplate restTemplate = new RestTemplate(); - - HttpHeaders headers = prepareBasicAuthHeaders(); - HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); - - ResponseEntity response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class); - assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - Foo foo = response.getBody(); - assertThat(foo, notNullValue()); - assertThat(foo.getName(), is("bar")); - assertThat(foo.getId(), is(1L)); - } - private HttpHeaders prepareBasicAuthHeaders() { HttpHeaders headers = new HttpHeaders(); String encodedLogPass = getBase64EncodedLogPass(); @@ -180,30 +213,6 @@ public class RestTemplateLiveTest { return new String(authHeaderBytes, Charsets.US_ASCII); } - @Test - public void givenResource_whenPutExistingEntity_thenItIsUpdated() { - RestTemplate restTemplate = new RestTemplate(); - HttpHeaders headers = prepareBasicAuthHeaders(); - HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); - - //Create entity - ResponseEntity response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class); - assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - assertThat(response.getBody().getId(), is(1L)); - - //Update entity - Foo updatedInstance = new Foo("newName"); - updatedInstance.setId(1); - String resourceUrl = fooService + "/1"; - restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); - - //Check that entity was updated - response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); - Foo foo = response.getBody(); - assertThat(foo.getId(), is(1L)); - assertThat(foo.getName(), is(updatedInstance.getName())); - } - private RequestCallback requestCallback(Foo updatedInstace) { return clientHttpRequest -> { ObjectMapper mapper = new ObjectMapper(); From 7944711495f5e37700ca4129bb11435cae149933 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 11 Sep 2015 15:57:45 +0300 Subject: [PATCH 27/34] new java conversion --- .../java/io/JavaInputStreamToXUnitTest.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 982b84df36..53bbe8a8d3 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertThat; import java.io.BufferedReader; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -128,12 +129,27 @@ public class JavaInputStreamToXUnitTest { // tests - InputStream to byte[] @Test - public final void givenUsingPlainJava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); final byte[] targetArray = new byte[initialStream.available()]; initialStream.read(targetArray); } + @Test + public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int nRead; + final byte[] data = new byte[1024]; + while ((nRead = is.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); + } + + buffer.flush(); + final byte[] byteArray = buffer.toByteArray(); + } + @Test public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }).openStream(); From 1014588879d98727f665a25b58db75d1494ccc61 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Sat, 12 Sep 2015 00:04:31 +0300 Subject: [PATCH 28/34] [RestTemplate] Rename local RestTemplate instance so as not to shadow the field --- .../org/baeldung/client/RestTemplateLiveTest.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index d79ca52f5d..452eb614d4 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -102,9 +102,6 @@ public class RestTemplateLiveTest { @Test public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() { - ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); - RestTemplate restTemplate = new RestTemplate(requestFactory); - HttpEntity request = new HttpEntity<>(new Foo("bar")); Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); @@ -129,12 +126,12 @@ public class RestTemplateLiveTest { @Test public void givenRestService_whenPostResource_thenResourceIsCreated() { - RestTemplate restTemplate = new RestTemplate(); + RestTemplate template = new RestTemplate(); HttpHeaders headers = prepareBasicAuthHeaders(); HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); - ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); Foo foo = response.getBody(); assertThat(foo, notNullValue()); @@ -143,22 +140,22 @@ public class RestTemplateLiveTest { @Test public void givenResource_whenPutExistingEntity_thenItIsUpdated() { - RestTemplate restTemplate = new RestTemplate(); + RestTemplate template = new RestTemplate(); HttpHeaders headers = prepareBasicAuthHeaders(); HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); //Create entity - ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); //Update entity Foo updatedInstance = new Foo("newName"); updatedInstance.setId(response.getBody().getId()); String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); - restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); //Check that entity was updated - response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); Foo foo = response.getBody(); assertThat(foo.getName(), is(updatedInstance.getName())); } From baf956aa60134deb067e28a582f5a952528550f7 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Tue, 15 Sep 2015 21:39:01 +0300 Subject: [PATCH 29/34] [RestTemplate] Make it pure live test --- .../baeldung/client/RestTemplateLiveTest.java | 90 ++++++++++--------- 1 file changed, 48 insertions(+), 42 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index 452eb614d4..f771dfa306 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -1,38 +1,5 @@ package org.baeldung.client; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Charsets; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.baeldung.spring.PersistenceConfig; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.*; -import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RequestCallback; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @@ -41,17 +8,45 @@ import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class}) +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.persistence.model.Foo; +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; + public class RestTemplateLiveTest { RestTemplate restTemplate; private List> messageConverters; private static final String fooResourceUrl = "http://localhost:8080/spring-security-rest-full/foos"; - @Autowired - private IFooService fooService; - @Before public void beforeTest() { restTemplate = new RestTemplate(getClientHttpRequestFactory()); @@ -114,7 +109,7 @@ public class RestTemplateLiveTest { public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); - assertTrue(httpHeaders.get("foo").contains("bar")); + assertTrue(httpHeaders.get("bar").contains("baz")); } @Test @@ -162,7 +157,11 @@ public class RestTemplateLiveTest { @Test public void givenRestService_whenCallDelete_thenEntityIsRemoved() { - String entityUrl = fooResourceUrl + "/1"; + Foo foo = new Foo("remove me"); + ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); restTemplate.delete(entityUrl); try { restTemplate.getForEntity(entityUrl, Foo.class); @@ -174,9 +173,16 @@ public class RestTemplateLiveTest { private void ensureOneEntityExists() { Foo instance = new Foo("bar"); - if (fooService.findOne(1L) == null) { - fooService.create(instance); + instance.setId(1L); + + try { + restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); + } catch (HttpClientErrorException ex) { + if (ex.getStatusCode() == HttpStatus.NOT_FOUND) { + restTemplate.postForEntity(fooResourceUrl, instance, Foo.class); + } } + } private ClientHttpRequestFactory getClientHttpRequestFactory() { From b0c30e70ec9475ec2bac9d3359d8a248757d80a3 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Fri, 18 Sep 2015 14:48:56 +0300 Subject: [PATCH 30/34] [RestTemplate] Use constant for an application port value - Introduce consistent test names - Fix typo --- .../src/test/java/org/baeldung/Consts.java | 5 ++++ .../baeldung/client/RestTemplateLiveTest.java | 27 ++++++++++--------- .../baeldung/common/web/AbstractLiveTest.java | 13 ++++----- 3 files changed, 26 insertions(+), 19 deletions(-) create mode 100644 spring-security-rest-full/src/test/java/org/baeldung/Consts.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java new file mode 100644 index 0000000000..9c44d63c4d --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung; + +public interface Consts { + int APPLICATION_PORT = 8080; +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index f771dfa306..ac6825667d 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -1,6 +1,7 @@ package org.baeldung.client; import static org.apache.commons.codec.binary.Base64.encodeBase64; +import static org.baeldung.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -43,9 +44,9 @@ import com.google.common.base.Charsets; public class RestTemplateLiveTest { - RestTemplate restTemplate; + private RestTemplate restTemplate; private List> messageConverters; - private static final String fooResourceUrl = "http://localhost:8080/spring-security-rest-full/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/foos"; @Before public void beforeTest() { @@ -60,13 +61,13 @@ public class RestTemplateLiveTest { } @Test - public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); assertThat(response.getStatusCode(), is(HttpStatus.OK)); } @Test - public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException { + public void givenResourceUrl_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException { ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); ObjectMapper mapper = new ObjectMapper(); @@ -80,7 +81,7 @@ public class RestTemplateLiveTest { } @Test - public void givenRepoEndpoint_whenSendGetForObject_thenReturnsRepoObject() { + public void givenResourceUrl_whenSendGetForObject_thenReturnsRepoObject() { restTemplate.setMessageConverters(messageConverters); Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); assertThat(foo.getName(), is("bar")); @@ -106,21 +107,21 @@ public class RestTemplateLiveTest { } @Test - public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); assertTrue(httpHeaders.get("bar").contains("baz")); } @Test - public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE}; assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); } @Test - public void givenRestService_whenPostResource_thenResourceIsCreated() { + public void givenFooService_whenPostResource_thenResourceIsCreated() { RestTemplate template = new RestTemplate(); HttpHeaders headers = prepareBasicAuthHeaders(); @@ -134,7 +135,7 @@ public class RestTemplateLiveTest { } @Test - public void givenResource_whenPutExistingEntity_thenItIsUpdated() { + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { RestTemplate template = new RestTemplate(); HttpHeaders headers = prepareBasicAuthHeaders(); HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); @@ -156,7 +157,7 @@ public class RestTemplateLiveTest { } @Test - public void givenRestService_whenCallDelete_thenEntityIsRemoved() { + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { Foo foo = new Foo("remove me"); ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); @@ -193,7 +194,7 @@ public class RestTemplateLiveTest { .setSocketTimeout(timeout * 1000).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), + credentialsProvider.setCredentials(new AuthScope("localhost", APPLICATION_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); CloseableHttpClient client = HttpClientBuilder.create() @@ -216,10 +217,10 @@ public class RestTemplateLiveTest { return new String(authHeaderBytes, Charsets.US_ASCII); } - private RequestCallback requestCallback(Foo updatedInstace) { + private RequestCallback requestCallback(Foo updatedInstance) { return clientHttpRequest -> { ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(clientHttpRequest.getBody(), updatedInstace); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); }; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java index 862651266b..32a736b546 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java @@ -1,15 +1,16 @@ package org.baeldung.common.web; -import java.io.Serializable; - -import org.baeldung.test.IMarshaller; -import org.springframework.beans.factory.annotation.Autowired; - import com.google.common.base.Preconditions; import com.google.common.net.HttpHeaders; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; +import org.baeldung.test.IMarshaller; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.Serializable; + +import static org.baeldung.Consts.APPLICATION_PORT; public abstract class AbstractLiveTest { @@ -55,7 +56,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:8080/spring-security-rest-full/foos"; + return "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/foos"; } protected final RequestSpecification givenAuth() { From cd5d4527c536f34b8fbcc47713f171a93d3f3f0d Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Sep 2015 16:27:13 +0300 Subject: [PATCH 31/34] minor cleanup --- .../baeldung/client/RestTemplateLiveTest.java | 116 +++++++++--------- 1 file changed, 55 insertions(+), 61 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index ac6825667d..4e2066cb6f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -53,7 +53,7 @@ public class RestTemplateLiveTest { restTemplate = new RestTemplate(getClientHttpRequestFactory()); messageConverters = new ArrayList<>(); - MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); + final MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); jsonMessageConverter.setObjectMapper(new ObjectMapper()); messageConverters.add(jsonMessageConverter); @@ -62,45 +62,45 @@ public class RestTemplateLiveTest { @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); assertThat(response.getStatusCode(), is(HttpStatus.OK)); } @Test public void givenResourceUrl_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException { - ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); - ObjectMapper mapper = new ObjectMapper(); - JsonNode root = mapper.readTree(response.getBody()); + final ObjectMapper mapper = new ObjectMapper(); + final JsonNode root = mapper.readTree(response.getBody()); - JsonNode name = root.path("name"); + final JsonNode name = root.path("name"); assertThat(name.asText(), is("bar")); - JsonNode owner = root.path("id"); + final JsonNode owner = root.path("id"); assertThat(owner.asText(), is("1")); } @Test public void givenResourceUrl_whenSendGetForObject_thenReturnsRepoObject() { restTemplate.setMessageConverters(messageConverters); - Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); assertThat(foo.getName(), is("bar")); assertThat(foo.getId(), is(1L)); } @Test public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { - HttpEntity request = new HttpEntity<>(new Foo("bar")); - Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); assertThat(foo, notNullValue()); assertThat(foo.getName(), is("bar")); } @Test public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() { - HttpEntity request = new HttpEntity<>(new Foo("bar")); - Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); - Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + final Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class); assertThat(firstInstance, notNullValue()); assertThat(secondInstance, notNullValue()); assertThat(firstInstance.getId(), not(secondInstance.getId())); @@ -108,118 +108,112 @@ public class RestTemplateLiveTest { @Test public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { - HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); assertTrue(httpHeaders.get("bar").contains("baz")); } @Test public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { - Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); - HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE}; + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE }; assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); } @Test public void givenFooService_whenPostResource_thenResourceIsCreated() { - RestTemplate template = new RestTemplate(); + final RestTemplate template = new RestTemplate(); - HttpHeaders headers = prepareBasicAuthHeaders(); - HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); - ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + final ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - Foo foo = response.getBody(); + final Foo foo = response.getBody(); assertThat(foo, notNullValue()); assertThat(foo.getName(), is("bar")); } @Test public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { - RestTemplate template = new RestTemplate(); - HttpHeaders headers = prepareBasicAuthHeaders(); - HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); - //Create entity + // Create entity ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - //Update entity - Foo updatedInstance = new Foo("newName"); + // Update entity + final Foo updatedInstance = new Foo("newName"); updatedInstance.setId(response.getBody().getId()); - String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); + final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); - //Check that entity was updated + // Check that entity was updated response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); - Foo foo = response.getBody(); + final Foo foo = response.getBody(); assertThat(foo.getName(), is(updatedInstance.getName())); } @Test public void givenFooService_whenCallDelete_thenEntityIsRemoved() { - Foo foo = new Foo("remove me"); - ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); - assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - - String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + final String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); restTemplate.delete(entityUrl); try { restTemplate.getForEntity(entityUrl, Foo.class); fail(); - } catch (HttpClientErrorException ex) { + } catch (final HttpClientErrorException ex) { assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); } } private void ensureOneEntityExists() { - Foo instance = new Foo("bar"); + final Foo instance = new Foo("bar"); instance.setId(1L); - + try { - restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); - } catch (HttpClientErrorException ex) { - if (ex.getStatusCode() == HttpStatus.NOT_FOUND) { - restTemplate.postForEntity(fooResourceUrl, instance, Foo.class); - } + restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); + } catch (final HttpClientErrorException ex) { + if (ex.getStatusCode() == HttpStatus.NOT_FOUND) { + restTemplate.postForEntity(fooResourceUrl, instance, Foo.class); + } } - + } private ClientHttpRequestFactory getClientHttpRequestFactory() { - int timeout = 5; - RequestConfig config = RequestConfig.custom() - .setConnectTimeout(timeout * 1000) - .setConnectionRequestTimeout(timeout * 1000) - .setSocketTimeout(timeout * 1000).build(); + final int timeout = 5; + final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); - BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", APPLICATION_PORT, AuthScope.ANY_REALM), - new UsernamePasswordCredentials("user1", "user1Pass")); + final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope("localhost", APPLICATION_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - CloseableHttpClient client = HttpClientBuilder.create() - .setDefaultRequestConfig(config) - .setDefaultCredentialsProvider(credentialsProvider).build(); + final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); return new HttpComponentsClientHttpRequestFactory(client); } private HttpHeaders prepareBasicAuthHeaders() { - HttpHeaders headers = new HttpHeaders(); - String encodedLogPass = getBase64EncodedLogPass(); + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); return headers; } private String getBase64EncodedLogPass() { - String logPass = "user1:user1Pass"; - byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); return new String(authHeaderBytes, Charsets.US_ASCII); } - private RequestCallback requestCallback(Foo updatedInstance) { + private RequestCallback requestCallback(final Foo updatedInstance) { return clientHttpRequest -> { - ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); From 4f6b40fe6b49aac6879ab829362c4d75e0c22480 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Sat, 19 Sep 2015 11:37:47 +0300 Subject: [PATCH 32/34] [RestTemplate] Get rid of jsonMessageConverter --- .../org/baeldung/client/RestTemplateLiveTest.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index 4e2066cb6f..f8ca6358f7 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -10,9 +10,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.Set; import org.apache.http.auth.AuthScope; @@ -32,8 +30,6 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; @@ -45,18 +41,12 @@ import com.google.common.base.Charsets; public class RestTemplateLiveTest { private RestTemplate restTemplate; - private List> messageConverters; private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/foos"; @Before public void beforeTest() { restTemplate = new RestTemplate(getClientHttpRequestFactory()); - messageConverters = new ArrayList<>(); - final MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); - jsonMessageConverter.setObjectMapper(new ObjectMapper()); - messageConverters.add(jsonMessageConverter); - ensureOneEntityExists(); } @@ -82,7 +72,6 @@ public class RestTemplateLiveTest { @Test public void givenResourceUrl_whenSendGetForObject_thenReturnsRepoObject() { - restTemplate.setMessageConverters(messageConverters); final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); assertThat(foo.getName(), is("bar")); assertThat(foo.getId(), is(1L)); From 6da1ecf3d9f723a538cf6c56c526a4744a14180c Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 20 Sep 2015 20:51:11 +0300 Subject: [PATCH 33/34] testing work --- .../baeldung/client/RestTemplateLiveTest.java | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index f8ca6358f7..7c3449225a 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -50,6 +50,8 @@ public class RestTemplateLiveTest { ensureOneEntityExists(); } + // GET + @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); @@ -77,6 +79,8 @@ public class RestTemplateLiveTest { assertThat(foo.getId(), is(1L)); } + // POST + @Test public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { final HttpEntity request = new HttpEntity<>(new Foo("bar")); @@ -95,6 +99,8 @@ public class RestTemplateLiveTest { assertThat(firstInstance.getId(), not(secondInstance.getId())); } + // HEAD, OPTIONS + @Test public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); @@ -109,6 +115,8 @@ public class RestTemplateLiveTest { assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); } + // POST + @Test public void givenFooService_whenPostResource_thenResourceIsCreated() { final RestTemplate template = new RestTemplate(); @@ -123,12 +131,36 @@ public class RestTemplateLiveTest { assertThat(foo.getName(), is("bar")); } + // PUT + @Test public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { final RestTemplate template = new RestTemplate(); final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + // Create Resource + final ResponseEntity createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + // Create entity ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); @@ -145,6 +177,8 @@ public class RestTemplateLiveTest { assertThat(foo.getName(), is(updatedInstance.getName())); } + // DELETE + @Test public void givenFooService_whenCallDelete_thenEntityIsRemoved() { final Foo foo = new Foo("remove me"); @@ -161,6 +195,8 @@ public class RestTemplateLiveTest { } } + // + private void ensureOneEntityExists() { final Foo instance = new Foo("bar"); instance.setId(1L); @@ -172,7 +208,6 @@ public class RestTemplateLiveTest { restTemplate.postForEntity(fooResourceUrl, instance, Foo.class); } } - } private ClientHttpRequestFactory getClientHttpRequestFactory() { From a5375cb90cddc215b68c2bf489056148666a3d81 Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 22 Sep 2015 12:17:53 +0300 Subject: [PATCH 34/34] minor upgrades --- spring-all/pom.xml | 2 +- spring-boot/pom.xml | 2 +- .../pom.xml | 2 +- spring-security-rest-full/pom.xml | 2 +- .../web/controller/FooController.java | 20 +++++++++++++------ 5 files changed, 18 insertions(+), 10 deletions(-) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 17226266fb..e7184953ff 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.5.RELEASE + 1.2.6.RELEASE diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 57807ead74..3a116a2974 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.5.RELEASE + 1.2.6.RELEASE diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index 0bd539b68c..c1903177da 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.5.RELEASE + 1.2.6.RELEASE diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 7a219288de..596efb7569 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.5.RELEASE + 1.2.6.RELEASE diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 6b28a081d2..20307447b2 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -1,6 +1,9 @@ package org.baeldung.web.controller; -import com.google.common.base.Preconditions; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; import org.baeldung.web.exception.MyResourceNotFoundException; @@ -14,11 +17,16 @@ import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.util.UriComponentsBuilder; -import javax.servlet.http.HttpServletResponse; -import java.util.List; +import com.google.common.base.Preconditions; @Controller @RequestMapping(value = "/foos") @@ -81,7 +89,7 @@ public class FooController { @ResponseBody public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); - Foo foo = service.create(resource); + final Foo foo = service.create(resource); final Long idOfCreatedResource = foo.getId(); eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); @@ -105,7 +113,7 @@ public class FooController { @RequestMapping(method = RequestMethod.HEAD) @ResponseStatus(HttpStatus.OK) - public void head(HttpServletResponse resp) { + public void head(final HttpServletResponse resp) { resp.setContentType(MediaType.APPLICATION_JSON_VALUE); resp.setHeader("bar", "baz"); }