cleanup work
This commit is contained in:
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>parent</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
</natures>
|
||||
</projectDescription>
|
||||
+71
-73
@@ -1,96 +1,94 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<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>com.baeldung</groupId>
|
||||
<artifactId>jpa-storedprocedure</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jpa-storedprocedure</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<jee.version>7.0</jee.version>
|
||||
<oracle.version>11.2.0.4</oracle.version>
|
||||
<hibernate.version>5.1.0.Final</hibernate.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<jee.version>7.0</jee.version>
|
||||
<oracle.version>11.2.0.4</oracle.version>
|
||||
<hibernate.version>5.1.0.Final</hibernate.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>JpaStoredProcedure</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<!--archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass>
|
||||
</manifest> </archive -->
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<finalName>JpaStoredProcedure</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<!--archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass> </manifest> </archive -->
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- core library -->
|
||||
<!-- core library -->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${jee.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${jee.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Oracle JDBC -->
|
||||
<dependency>
|
||||
<groupId>com.oracle</groupId>
|
||||
<artifactId>ojdbc6</artifactId>
|
||||
<version>${oracle.version}</version>
|
||||
</dependency>
|
||||
<!-- Oracle JDBC -->
|
||||
<dependency>
|
||||
<groupId>com.oracle</groupId>
|
||||
<artifactId>ojdbc6</artifactId>
|
||||
<version>${oracle.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Postgres JDBC -->
|
||||
<!-- Postgres JDBC -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>9.4.1208</version>
|
||||
</dependency>
|
||||
|
||||
<!-- MySql JDBC -->
|
||||
<!-- MySql JDBC -->
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.38</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.38</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Junit Library -->
|
||||
<!-- Junit Library -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -30,7 +30,7 @@ public class Car {
|
||||
@Id
|
||||
@SequenceGenerator(name = "CarIdSequence", sequenceName = "SEQ_CAR_ID", allocationSize = 1)
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CarIdSequence")
|
||||
//@GeneratedValue(strategy = GenerationType.IDENTITY) -- for MySQL
|
||||
// @GeneratedValue(strategy = GenerationType.IDENTITY) -- for MySQL
|
||||
@Column(name = "ID", unique = true, nullable = false, scale = 0)
|
||||
public long getId() {
|
||||
return id;
|
||||
|
||||
+5
-9
@@ -55,20 +55,16 @@ public class StoredProcedureTest {
|
||||
|
||||
@Test
|
||||
public void findCarsByYearNoNamedStored() {
|
||||
StoredProcedureQuery findByYearProcedure =
|
||||
entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
|
||||
.registerStoredProcedureParameter("data", Void.class, ParameterMode.REF_CURSOR)
|
||||
.registerStoredProcedureParameter("p_year", Integer.class, ParameterMode.IN)
|
||||
.setParameter("p_year", 2015);
|
||||
StoredProcedureQuery findByYearProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter("data", Void.class, ParameterMode.REF_CURSOR)
|
||||
.registerStoredProcedureParameter("p_year", Integer.class, ParameterMode.IN).setParameter("p_year", 2015);
|
||||
|
||||
findByYearProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
@Test
|
||||
@Ignore
|
||||
public void findCarsByYearMySql() {
|
||||
StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR",Car.class)
|
||||
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
|
||||
.setParameter(1, 2015);
|
||||
StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015);
|
||||
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>spring-security-login-and-registration</artifactId>
|
||||
<name>spring-security-login-and-registration</name>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0.0-BUILD-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.1.4.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Validation -->
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- @Inject -->
|
||||
<dependency>
|
||||
<groupId>javax.inject</groupId>
|
||||
<artifactId>javax.inject</artifactId>
|
||||
<version>${javax.inject.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Servlet -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet.jsp</groupId>
|
||||
<artifactId>javax.servlet.jsp-api</artifactId>
|
||||
<version>${javax.servlet.jsp-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Taglibs -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Test -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>spring-security-login-and-registration</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
<properties>
|
||||
<java-version>1.7</java-version>
|
||||
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
|
||||
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
|
||||
<org.aspectj-version>1.6.10</org.aspectj-version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.6</org.slf4j.version>
|
||||
<logback.version>1.1.1</logback.version>
|
||||
|
||||
<!-- javax jsp -->
|
||||
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
|
||||
|
||||
<!-- Inject -->
|
||||
<javax.inject.version>1</javax.inject.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+1
-1
@@ -59,7 +59,7 @@ public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigur
|
||||
.secret("secret")
|
||||
.authorizedGrantTypes("password","authorization_code", "refresh_token")
|
||||
.scopes("foo","read","write")
|
||||
.accessTokenValiditySeconds(3600) // 1 hour
|
||||
.accessTokenValiditySeconds(15) // 1 hour
|
||||
.refreshTokenValiditySeconds(2592000) // 30 days
|
||||
|
||||
.and()
|
||||
|
||||
+2
-1
@@ -66,7 +66,8 @@ app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,
|
||||
},function(){
|
||||
console.log("error");
|
||||
window.location.href = "login";
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package org.baeldung.event;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class OnRegistrationCompleteEvent extends ApplicationEvent {
|
||||
|
||||
private final String appUrl;
|
||||
private final Locale locale;
|
||||
private final User user;
|
||||
|
||||
public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
|
||||
super(user);
|
||||
this.user = user;
|
||||
this.locale = locale;
|
||||
this.appUrl = appUrl;
|
||||
}
|
||||
|
||||
public String getAppUrl() {
|
||||
return appUrl;
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return locale;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package org.baeldung.event.listener;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
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.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {
|
||||
@Autowired
|
||||
private IUserService service;
|
||||
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(OnRegistrationCompleteEvent event) {
|
||||
this.confirmRegistration(event);
|
||||
}
|
||||
|
||||
private void confirmRegistration(OnRegistrationCompleteEvent event) {
|
||||
User user = event.getUser();
|
||||
String token = UUID.randomUUID().toString();
|
||||
service.createVerificationTokenForUser(user, token);
|
||||
|
||||
String recipientAddress = user.getEmail();
|
||||
String subject = "Registration Confirmation";
|
||||
String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;
|
||||
String message = messages.getMessage("message.regSucc", null, event.getLocale());
|
||||
SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setTo(recipientAddress);
|
||||
email.setSubject(subject);
|
||||
email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl);
|
||||
mailSender.send(email);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package org.baeldung.hashing;
|
||||
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
|
||||
public class HashGenerator {
|
||||
|
||||
public String getHashedPassword(String password) {
|
||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
String hashedPassword = passwordEncoder.encode(password);
|
||||
return hashedPassword;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
public User findByEmail(String email);
|
||||
|
||||
public void delete(User user);
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {
|
||||
|
||||
public VerificationToken findByToken(String token);
|
||||
|
||||
public VerificationToken findByUser(User user);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table
|
||||
public class Role {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "user_id")
|
||||
private User user;
|
||||
|
||||
private Integer role;
|
||||
|
||||
public Role() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Role(Integer role) {
|
||||
super();
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Role(Integer role, User user) {
|
||||
super();
|
||||
this.role = role;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Integer getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Integer role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((role == null) ? 0 : role.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Role role = (Role) obj;
|
||||
if (!role.equals(role.role))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Role [role=").append(role).append("]").append("[id=").append(id).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
//ERASE
|
||||
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;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String email;
|
||||
|
||||
private String password;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
// ERASE
|
||||
@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;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String username) {
|
||||
this.email = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Role getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Role role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean isTokenExpired() {
|
||||
return tokenExpired;
|
||||
}
|
||||
|
||||
public void setTokenExpired(boolean expired) {
|
||||
this.tokenExpired = expired;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final User user = (User) obj;
|
||||
if (!email.equals(user.email))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
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;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class VerificationToken {
|
||||
|
||||
private static final int EXPIRATION = 60 * 24;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
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() {
|
||||
super();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getExpiryDate() {
|
||||
return expiryDate;
|
||||
}
|
||||
|
||||
public void setExpiryDate(Date expiryDate) {
|
||||
this.expiryDate = expiryDate;
|
||||
}
|
||||
|
||||
private Date calculateExpiryDate(int expiryTimeInMinutes) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(new Timestamp(cal.getTime().getTime()));
|
||||
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
|
||||
return new Date(cal.getTime().getTime());
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Token [String=").append(token).append("]").append("[Expires").append(expiryDate).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package org.baeldung.persistence.service;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.service.EmailExistsException;
|
||||
|
||||
public interface IUserService {
|
||||
|
||||
User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
|
||||
|
||||
User getUser(String verificationToken);
|
||||
|
||||
void saveRegisteredUser(User user);
|
||||
|
||||
void deleteUser(User user);
|
||||
|
||||
void createVerificationTokenForUser(User user, String token);
|
||||
|
||||
VerificationToken getVerificationToken(String VerificationToken);
|
||||
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package org.baeldung.persistence.service;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.baeldung.validation.service.PasswordMatches;
|
||||
import org.baeldung.validation.service.ValidEmail;
|
||||
import org.hibernate.validator.constraints.NotEmpty;
|
||||
|
||||
@PasswordMatches
|
||||
public class UserDto {
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private String firstName;
|
||||
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private String lastName;
|
||||
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private String password;
|
||||
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private String matchingPassword;
|
||||
|
||||
@ValidEmail
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private String email;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
private Integer role;
|
||||
|
||||
public Integer getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Integer role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getMatchingPassword() {
|
||||
return matchingPassword;
|
||||
}
|
||||
|
||||
public void setMatchingPassword(String matchingPassword) {
|
||||
this.matchingPassword = matchingPassword;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]").append("[password").append(password).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package org.baeldung.persistence.service;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.baeldung.hashing.HashGenerator;
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.dao.VerificationTokenRepository;
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.service.EmailExistsException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService implements IUserService {
|
||||
@Autowired
|
||||
private UserRepository repository;
|
||||
|
||||
@Autowired
|
||||
private VerificationTokenRepository tokenRepository;
|
||||
|
||||
@Autowired
|
||||
private HashGenerator hashGenerator;
|
||||
|
||||
@Override
|
||||
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
|
||||
if (emailExist(accountDto.getEmail())) {
|
||||
throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail());
|
||||
}
|
||||
User user = new User();
|
||||
user.setFirstName(accountDto.getFirstName());
|
||||
user.setLastName(accountDto.getLastName());
|
||||
String hashedPassword = hashGenerator.getHashedPassword(accountDto.getPassword());
|
||||
user.setPassword(hashedPassword);
|
||||
user.setEmail(accountDto.getEmail());
|
||||
user.setRole(new Role(Integer.valueOf(1), user));
|
||||
return repository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUser(String verificationToken) {
|
||||
User user = tokenRepository.findByToken(verificationToken).getUser();
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VerificationToken getVerificationToken(String VerificationToken) {
|
||||
return tokenRepository.findByToken(VerificationToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveRegisteredUser(User user) {
|
||||
repository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteUser(User user) {
|
||||
repository.delete(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.web.DefaultRedirectStrategy;
|
||||
import org.springframework.security.web.RedirectStrategy;
|
||||
import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
|
||||
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
|
||||
handle(request, response, authentication);
|
||||
HttpSession session = request.getSession(false);
|
||||
if (session != null) {
|
||||
session.setMaxInactiveInterval(30);
|
||||
}
|
||||
clearAuthenticationAttributes(request);
|
||||
}
|
||||
|
||||
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
|
||||
String targetUrl = determineTargetUrl(authentication);
|
||||
|
||||
if (response.isCommitted()) {
|
||||
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
redirectStrategy.sendRedirect(request, response, targetUrl);
|
||||
}
|
||||
|
||||
protected String determineTargetUrl(Authentication authentication) {
|
||||
boolean isUser = false;
|
||||
boolean isAdmin = false;
|
||||
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
|
||||
for (GrantedAuthority grantedAuthority : authorities) {
|
||||
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
|
||||
isUser = true;
|
||||
break;
|
||||
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
|
||||
isAdmin = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isUser) {
|
||||
return "/homepage.html?user=" + authentication.getName();
|
||||
} else if (isAdmin) {
|
||||
return "/console.html";
|
||||
} else {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
protected void clearAuthenticationAttributes(HttpServletRequest request) {
|
||||
HttpSession session = request.getSession(false);
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
|
||||
}
|
||||
|
||||
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
|
||||
this.redirectStrategy = redirectStrategy;
|
||||
}
|
||||
|
||||
protected RedirectStrategy getRedirectStrategy() {
|
||||
return redirectStrategy;
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
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.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class MyUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
@Autowired
|
||||
private IUserService service;
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
public MyUserDetailsService() {
|
||||
|
||||
}
|
||||
|
||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||
boolean enabled = true;
|
||||
boolean accountNonExpired = true;
|
||||
boolean credentialsNonExpired = true;
|
||||
boolean accountNonLocked = true;
|
||||
try {
|
||||
User user = userRepository.findByEmail(email);
|
||||
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(user.getEmail(), user.getPassword(), user.isEnabled(), accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
||||
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
|
||||
return authList;
|
||||
}
|
||||
|
||||
public List<String> getRoles(Integer role) {
|
||||
List<String> roles = new ArrayList<String>();
|
||||
if (role.intValue() == 2) {
|
||||
roles.add("ROLE_ADMIN");
|
||||
} else if (role.intValue() == 1) {
|
||||
roles.add("ROLE_USER");
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
private static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.event.service", "org.baeldung.event", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
||||
@PropertySource("classpath:application.properties")
|
||||
public class AppConfig {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JavaMailSenderImpl javaMailSenderImpl() {
|
||||
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();
|
||||
javaMailProps.put("mail.smtp.auth", true);
|
||||
javaMailProps.put("mail.smtp.starttls.enable", true);
|
||||
mailSenderImpl.setJavaMailProperties(javaMailProps);
|
||||
return mailSenderImpl;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.baeldung.hashing.HashGenerator;
|
||||
import org.baeldung.validation.service.EmailValidator;
|
||||
import org.baeldung.validation.service.PasswordMatchesValidator;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||
@EnableWebMvc
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public MvcConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/login.html");
|
||||
registry.addViewController("/logout.html");
|
||||
registry.addViewController("/homepage.html");
|
||||
registry.addViewController("/expiredAccount.html");
|
||||
registry.addViewController("/regitrationConfirm.html");
|
||||
registry.addViewController("/badUser.html");
|
||||
registry.addViewController("/emailError.html");
|
||||
registry.addViewController("/home.html");
|
||||
registry.addViewController("/invalidSession.html");
|
||||
registry.addViewController("/console.html");
|
||||
registry.addViewController("/admin.html");
|
||||
registry.addViewController("/registration.html");
|
||||
registry.addViewController("/successRegister.html");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setViewClass(JstlView.class);
|
||||
bean.setPrefix("/WEB-INF/view/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||
localeChangeInterceptor.setParamName("lang");
|
||||
registry.addInterceptor(localeChangeInterceptor);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
|
||||
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
|
||||
return cookieLocaleResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
|
||||
messageSource.setBasename("classpath:messages");
|
||||
messageSource.setUseCodeAsDefaultMessage(true);
|
||||
messageSource.setDefaultEncoding("UTF-8");
|
||||
messageSource.setCacheSeconds(0);
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EmailValidator usernameValidator() {
|
||||
EmailValidator userNameValidator = new EmailValidator();
|
||||
return userNameValidator;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordMatchesValidator passwordMatchesValidator() {
|
||||
PasswordMatchesValidator passwordMatchesValidator = new PasswordMatchesValidator();
|
||||
return passwordMatchesValidator;
|
||||
}
|
||||
|
||||
// DIC 7
|
||||
@Bean
|
||||
public HashGenerator hashGenerator() {
|
||||
HashGenerator hashGenerator = new HashGenerator();
|
||||
return hashGenerator;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Properties;
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:application.properties" })
|
||||
@ComponentScan({ "org.baeldung.persistence.model" })
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
|
||||
public class PersistenceJPAConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceJPAConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
|
||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||
dataSource.setUsername(env.getProperty("jdbc.user"));
|
||||
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JpaTransactionManager transactionManager() {
|
||||
JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
|
||||
@Configuration
|
||||
@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
public class SecSecurityConfig {
|
||||
|
||||
public SecSecurityConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class EmailExistsException extends Throwable {
|
||||
|
||||
public EmailExistsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
|
||||
private Pattern pattern;
|
||||
private Matcher matcher;
|
||||
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) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String username, ConstraintValidatorContext context) {
|
||||
return (validateEmail(username));
|
||||
}
|
||||
|
||||
private boolean validateEmail(String email) {
|
||||
pattern = Pattern.compile(EMAIL_PATTERN);
|
||||
matcher = pattern.matcher(email);
|
||||
return matcher.matches();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
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;
|
||||
|
||||
@Target({ TYPE, ANNOTATION_TYPE })
|
||||
@Retention(RUNTIME)
|
||||
@Constraint(validatedBy = PasswordMatchesValidator.class)
|
||||
@Documented
|
||||
public @interface PasswordMatches {
|
||||
|
||||
String message() default "Passwords don't match";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
import org.baeldung.persistence.service.UserDto;
|
||||
|
||||
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {
|
||||
|
||||
@Override
|
||||
public void initialize(PasswordMatches constraintAnnotation) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(Object obj, ConstraintValidatorContext context) {
|
||||
UserDto user = (UserDto) obj;
|
||||
return user.getPassword().equals(user.getMatchingPassword());
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
import org.baeldung.persistence.service.UserDto;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.ValidationUtils;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
public class UserValidator implements Validator {
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return UserDto.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object obj, 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.");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package org.baeldung.validation.service;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
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;
|
||||
|
||||
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
|
||||
@Retention(RUNTIME)
|
||||
@Constraint(validatedBy = EmailValidator.class)
|
||||
@Documented
|
||||
public @interface ValidEmail {
|
||||
|
||||
String message() default "Invalid Email";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user