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"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>httpclient</artifactId>
@ -36,11 +35,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.apache.httpcomponents</groupId> -->
<!-- <artifactId>httpcore</artifactId> -->
<!-- <version>${httpcore.version}</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
@ -61,9 +60,9 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1-beta1</version>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1-beta1</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
</dependency>
<!-- logging -->
@ -179,7 +178,7 @@
<mockito.version>1.10.8</mockito.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>

View File

@ -3,7 +3,9 @@ package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
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_NAME = "example"; // "JSESSIONID";
// tests
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws Exception {
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
// client.start();
final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@ -114,7 +119,6 @@ public class HttpAsyncClientTest {
client.close();
}
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
@ -138,8 +142,8 @@ public class HttpAsyncClientTest {
@Test
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, credentials);
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, creds);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
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 javax.mail.AuthenticationFailedException;
import org.baeldung.event.OnRegistrationCompleteEvent;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@ -34,7 +31,8 @@ public class RegistrationListener implements ApplicationListener<OnRegistrationC
private void confirmRegistration(OnRegistrationCompleteEvent event) {
User user = event.getUser();
String token = UUID.randomUUID().toString();
service.addVerificationToken(user, token);
service.createVerificationTokenForUser(user, token);
String recipientAddress = user.getEmail();
String subject = "Registration Confirmation";
String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;

View File

@ -1,49 +1,43 @@
package org.baeldung.persistence.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "firstName")
private String firstName;
@Column(name = "lastName")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "enabled")
private boolean enabled;
@Column(name = "token_expired")
private boolean tokenExpired;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Role role;
public User() {
super();
this.enabled = false;
this.tokenExpired = false;
}
//
public Long getId() {
return id;
}
@ -99,7 +93,7 @@ public class User {
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTokenExpired() {
return tokenExpired;
}
@ -108,6 +102,7 @@ public class User {
this.tokenExpired = expired;
}
//
@Override
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("]");
return builder.toString();
}
}

View File

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

View File

@ -6,15 +6,16 @@ import org.baeldung.validation.service.EmailExistsException;
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;
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private UserRepository repository;
@ -19,7 +20,8 @@ public class UserService implements IUserService {
@Autowired
private VerificationTokenRepository tokenRepository;
@Transactional
// API
@Override
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
if (emailExist(accountDto.getEmail())) {
@ -34,14 +36,6 @@ public class UserService implements IUserService {
return repository.save(user);
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
@Override
public User getUser(String verificationToken) {
User user = tokenRepository.findByToken(verificationToken).getUser();
@ -53,22 +47,30 @@ public class UserService implements IUserService {
return tokenRepository.findByToken(VerificationToken);
}
@Transactional
@Override
public void saveRegisteredUser(User user) {
repository.save(user);
}
@Transactional
@Override
public void deleteUser(User user) {
repository.delete(user);
}
@Transactional
@Override
public void addVerificationToken(User user, String token) {
public void createVerificationTokenForUser(User user, String token) {
VerificationToken myToken = new VerificationToken(token, user);
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) {
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) {
throw new RuntimeException(e);
}

View File

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

View File

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