Merge remote-tracking branch 'upstream/master'

This commit is contained in:
DOHA 2014-12-04 22:12:43 +02:00
commit cf935dc63f
10 changed files with 109 additions and 84 deletions

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId> <groupId>org.baeldung</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
@ -36,11 +35,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <!-- <dependency> -->
<groupId>org.apache.httpcomponents</groupId> <!-- <groupId>org.apache.httpcomponents</groupId> -->
<artifactId>httpcore</artifactId> <!-- <artifactId>httpcore</artifactId> -->
<version>${httpcore.version}</version> <!-- <version>${httpcore.version}</version> -->
</dependency> <!-- </dependency> -->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
@ -61,9 +60,9 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId> <artifactId>httpasyncclient</artifactId>
<version>4.1-beta1</version> <version>4.1-beta1</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
</dependency> </dependency>
<!-- logging --> <!-- logging -->
@ -179,7 +178,7 @@
<mockito.version>1.10.8</mockito.version> <mockito.version>1.10.8</mockito.version>
<httpcore.version>4.3.3</httpcore.version> <httpcore.version>4.3.3</httpcore.version>
<httpclient.version>4.3.6</httpclient.version> <httpclient.version>4.4-beta1</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<rest-assured.version>2.4.0</rest-assured.version> <rest-assured.version>2.4.0</rest-assured.version>

View File

@ -3,7 +3,9 @@ package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
@ -44,14 +46,17 @@ public class HttpAsyncClientTest {
private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com"; private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com";
private static final String COOKIE_NAME = "example"; // "JSESSIONID"; private static final String COOKIE_NAME = "example"; // "JSESSIONID";
// tests
@Test @Test
public void whenUseHttpAsyncClient_thenCorrect() throws Exception { public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start(); // client.start();
final HttpGet request = new HttpGet(HOST); final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null); final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get(); final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close(); client.close();
} }
@ -114,7 +119,6 @@ public class HttpAsyncClientTest {
client.close(); client.close();
} }
@Test @Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception { public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
@ -138,8 +142,8 @@ public class HttpAsyncClientTest {
@Test @Test
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception { public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final CredentialsProvider provider = new BasicCredentialsProvider(); final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, credentials); provider.setCredentials(AuthScope.ANY, creds);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
@ -175,4 +179,3 @@ public class HttpAsyncClientTest {
} }
} }

View File

@ -2,15 +2,12 @@ package org.baeldung.event.listener;
import java.util.UUID; import java.util.UUID;
import javax.mail.AuthenticationFailedException;
import org.baeldung.event.OnRegistrationCompleteEvent; import org.baeldung.event.OnRegistrationCompleteEvent;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService; import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -34,7 +31,8 @@ public class RegistrationListener implements ApplicationListener<OnRegistrationC
private void confirmRegistration(OnRegistrationCompleteEvent event) { private void confirmRegistration(OnRegistrationCompleteEvent event) {
User user = event.getUser(); User user = event.getUser();
String token = UUID.randomUUID().toString(); String token = UUID.randomUUID().toString();
service.addVerificationToken(user, token); service.createVerificationTokenForUser(user, token);
String recipientAddress = user.getEmail(); String recipientAddress = user.getEmail();
String subject = "Registration Confirmation"; String subject = "Registration Confirmation";
String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token; String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;

View File

@ -1,39 +1,30 @@
package org.baeldung.persistence.model; package org.baeldung.persistence.model;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity @Entity
@Table
public class User { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column(name = "firstName")
private String firstName; private String firstName;
@Column(name = "lastName")
private String lastName; private String lastName;
@Column(name = "email")
private String email; private String email;
@Column(name = "password")
private String password; private String password;
@Column(name = "enabled")
private boolean enabled; private boolean enabled;
@Column(name = "token_expired")
private boolean tokenExpired; private boolean tokenExpired;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ -44,6 +35,9 @@ public class User {
this.enabled = false; this.enabled = false;
this.tokenExpired = false; this.tokenExpired = false;
} }
//
public Long getId() { public Long getId() {
return id; return id;
} }
@ -108,6 +102,7 @@ public class User {
this.tokenExpired = expired; this.tokenExpired = expired;
} }
//
@Override @Override
public int hashCode() { public int hashCode() {
@ -137,4 +132,5 @@ public class User {
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
return builder.toString(); return builder.toString();
} }
} }

View File

@ -3,7 +3,7 @@ package org.baeldung.persistence.model;
import java.util.Calendar; import java.util.Calendar;
import java.sql.Date; import java.sql.Date;
import java.sql.Timestamp; import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -11,10 +11,8 @@ import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity @Entity
@Table
public class VerificationToken { public class VerificationToken {
private static final int EXPIRATION = 60 * 24; private static final int EXPIRATION = 60 * 24;
@ -23,14 +21,12 @@ public class VerificationToken {
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column(name = "token")
private String token; private String token;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, name = "user_id") @JoinColumn(nullable = false, name = "user_id")
private User user; private User user;
@Column(name = "expiry_date")
private Date expiryDate; private Date expiryDate;
public VerificationToken() { public VerificationToken() {
@ -39,17 +35,21 @@ public class VerificationToken {
public VerificationToken(String token) { public VerificationToken(String token) {
super(); super();
this.token = token; this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
public VerificationToken(String token, User user) { public VerificationToken(String token, User user) {
super(); super();
this.token = token; this.token = token;
this.user = user; this.user = user;
this.expiryDate = calculateExpiryDate(EXPIRATION); this.expiryDate = calculateExpiryDate(EXPIRATION);
} }
//
public String getToken() { public String getToken() {
return token; return token;
} }
@ -81,16 +81,41 @@ public class VerificationToken {
return new Date(cal.getTime().getTime()); return new Date(cal.getTime().getTime());
} }
//
@Override @Override
public boolean equals(final Object obj) { public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((expiryDate == null) ? 0 : expiryDate.hashCode());
result = prime * result + ((token == null) ? 0 : token.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
final VerificationToken verificationToken = (VerificationToken) obj; VerificationToken other = (VerificationToken) obj;
if (!token.equals(verificationToken.getToken())) if (expiryDate == null) {
if (other.expiryDate != null)
return false;
} else if (!expiryDate.equals(other.expiryDate))
return false;
if (token == null) {
if (other.token != null)
return false;
} else if (!token.equals(other.token))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false; return false;
return true; return true;
} }

View File

@ -6,15 +6,16 @@ import org.baeldung.validation.service.EmailExistsException;
public interface IUserService { public interface IUserService {
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
public User getUser(String verificationToken); User getUser(String verificationToken);
public void saveRegisteredUser(User user); void saveRegisteredUser(User user);
public void addVerificationToken(User user, String token); void deleteUser(User user);
public VerificationToken getVerificationToken(String VerificationToken); void createVerificationTokenForUser(User user, String token);
VerificationToken getVerificationToken(String VerificationToken);
public void deleteUser(User user);
} }

View File

@ -12,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
@Transactional
public class UserService implements IUserService { public class UserService implements IUserService {
@Autowired @Autowired
private UserRepository repository; private UserRepository repository;
@ -19,7 +20,8 @@ public class UserService implements IUserService {
@Autowired @Autowired
private VerificationTokenRepository tokenRepository; private VerificationTokenRepository tokenRepository;
@Transactional // API
@Override @Override
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException { public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
if (emailExist(accountDto.getEmail())) { if (emailExist(accountDto.getEmail())) {
@ -34,14 +36,6 @@ public class UserService implements IUserService {
return repository.save(user); return repository.save(user);
} }
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
@Override @Override
public User getUser(String verificationToken) { public User getUser(String verificationToken) {
User user = tokenRepository.findByToken(verificationToken).getUser(); User user = tokenRepository.findByToken(verificationToken).getUser();
@ -53,22 +47,30 @@ public class UserService implements IUserService {
return tokenRepository.findByToken(VerificationToken); return tokenRepository.findByToken(VerificationToken);
} }
@Transactional
@Override @Override
public void saveRegisteredUser(User user) { public void saveRegisteredUser(User user) {
repository.save(user); repository.save(user);
} }
@Transactional
@Override @Override
public void deleteUser(User user) { public void deleteUser(User user) {
repository.delete(user); repository.delete(user);
} }
@Transactional
@Override @Override
public void addVerificationToken(User user, String token) { public void createVerificationTokenForUser(User user, String token) {
VerificationToken myToken = new VerificationToken(token, user); VerificationToken myToken = new VerificationToken(token, user);
tokenRepository.save(myToken); tokenRepository.save(myToken);
} }
//
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
} }

View File

@ -47,16 +47,8 @@ public class MyUserDetailsService implements UserDetailsService {
if (user == null) { if (user == null) {
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1))); return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
} }
if (!user.isEnabled()) {
enabled = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
}
if (user.isTokenExpired()) {
accountNonExpired = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, accountNonExpired, true, true, getAuthorities(new Integer(1)));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword().toLowerCase(), user.isEnabled(), accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@ -1,7 +1,10 @@
package org.baeldung.web.controller; package org.baeldung.web.controller;
import java.util.Calendar; import java.util.Calendar;
import java.util.Locale;
import javax.validation.Valid; import javax.validation.Valid;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken; import org.baeldung.persistence.model.VerificationToken;
import org.baeldung.persistence.service.UserDto; import org.baeldung.persistence.service.UserDto;
@ -56,34 +59,40 @@ public class RegistrationController {
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET) @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) { public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) {
Locale locale = request.getLocale();
VerificationToken verificationToken = service.getVerificationToken(token); VerificationToken verificationToken = service.getVerificationToken(token);
if (verificationToken == null) { if (verificationToken == null) {
model.addAttribute("message", messages.getMessage("auth.message.invalidToken", null, request.getLocale())); String message = messages.getMessage("auth.message.invalidToken", null, locale);
return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage(); model.addAttribute("message", message);
return "redirect:/badUser.html?lang=" + locale.getLanguage();
} }
User user = verificationToken.getUser(); User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) { if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
user.setTokenExpired(true); model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
return "redirect:/badUser.html?lang=" + locale.getLanguage();
} }
user.setEnabled(true); user.setEnabled(true);
service.saveRegisteredUser(user); service.saveRegisteredUser(user);
return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); return "redirect:/login.html?lang=" + locale.getLanguage();
} }
@RequestMapping(value = "/user/registration", method = RequestMethod.POST) @RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) { public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) {
LOGGER.debug("Registering user account with information: {}", accountDto); LOGGER.debug("Registering user account with information: {}", accountDto);
User registered = new User();
String appUrl = request.getContextPath();
if (result.hasErrors()) { if (result.hasErrors()) {
return new ModelAndView("registration", "user", accountDto); return new ModelAndView("registration", "user", accountDto);
} }
registered = createUserAccount(accountDto);
User registered = createUserAccount(accountDto);
if (registered == null) { if (registered == null) {
result.rejectValue("email", "message.regError"); result.rejectValue("email", "message.regError");
} }
try { try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl)); eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
} catch (Exception me) { } catch (Exception me) {
return new ModelAndView("emailError", "user", accountDto); return new ModelAndView("emailError", "user", accountDto);

View File

@ -1,17 +1,17 @@
################### DataSource Configuration ########################## ################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/AUTHDATA jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_02?createDatabaseIfNotExist=true
jdbc.user=root jdbc.user=tutorialuser
###jdbc.pass=admin### jdbc.pass=tutorialmy5ql
init-db=false init-db=false
################### Hibernate Configuration ########################## ################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate hibernate.hbm2ddl.auto=create-drop
################### JavaMail Configuration ########################## ################### JavaMail Configuration ##########################
smtp.host=smtp.gmail.com smtp.host=smtp.gmail.com
smtp.port=465 smtp.port=465
smtp.protocol=smtps smtp.protocol=smtps
smtp.username=xxx@gmail.com smtp.username=xxx777@gmail.com
smtp.password= smtp.password=
support.email=xxx@gmail.com support.email=xxx777@gmail.com