Skip to content

Commit 710c25f

Browse files
authored
Ocheja fix (eugenp#3572)
* Define beans for handling different message types in a lean chat app * Add class based spring beans configuration * Define spring configuration in XML for constructor based bean injection * Refactor package structure to separate constructor based bean injection code set from setter based bean injection code set * Define configuration and classes specific to setter-based bean injection. * Implement tests for constructor-based and setter-based bean injections * develop codes for explaining type erasure * Write unit tests for type erasure examples * Remove evaluation article code * Modify type erasure examples and unit tests * Modify type erasure examples and unit tests * Add expected exception in TypeErasureUnitTest * Correct grammar in class name * Implement File Manager app to demonstrate Polymorphism. Develop unit tests for Polymorphism article code * Add examples for static polymorphism * Change sysout statments to slf4j log info statements * Add assertions and expected errors check on Test * Add assertions and expected errors check on Test * Correct compile time error of symbol not found * Removed commented out non-compiling test. * Replace string concatenations with String.format * Replace string concatenations with String.format * Remove verbose file info descriptor and replace with simpler one * Add example codes for Hibernate Interceptors article Write tests for session-scoped and sessionFactory-scoped interceptors * Implement serializable on customInterceptorImpl * Implement examples for spring data with spring security integration * Remove webapp example implementations; too extensive
1 parent ff76cbc commit 710c25f

16 files changed

Lines changed: 728 additions & 1 deletion

File tree

hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import org.hibernate.Transaction;
1010
import org.hibernate.type.Type;
1111

12-
public class CustomInterceptorImpl implements Interceptor {
12+
public class CustomInterceptorImpl implements Interceptor, Serializable {
1313

1414
@Override
1515
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# About this project
2+
This project contains examples from the [Spring Data with Spring Security](http://www.baeldung.com/spring-data-with-spring-security) article from Baeldung.
3+
4+
# Running the project
5+
The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so it is easy to run. You can start it any of a few ways:
6+
* Run the `main` method from `SpringDataRestApplication`
7+
* Use the Maven Spring Boot plugin: `mvn spring-boot:run`
8+
* Package the application as a JAR and run it using `java -jar spring-data-spring-security.jar`
9+
10+
# Viewing the running application
11+
To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser
12+
13+
###Relevant Articles:
14+
- [Spring Data with Spring Security](http://www.baeldung.com/spring-data-with-spring-security)
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.baeldung</groupId>
7+
<artifactId>spring-data-spring-security</artifactId>
8+
<version>1.0</version>
9+
<packaging>jar</packaging>
10+
11+
<name>intro-spring-data-spring-security</name>
12+
<description>Spring Data with Spring Security</description>
13+
14+
<parent>
15+
<artifactId>parent-boot-5</artifactId>
16+
<groupId>com.baeldung</groupId>
17+
<version>0.0.1-SNAPSHOT</version>
18+
<relativePath>../parent-boot-5</relativePath>
19+
</parent>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>org.springframework.boot</groupId>
24+
<artifactId>spring-boot-starter</artifactId>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.springframework.boot</groupId>
28+
<artifactId>spring-boot-starter-web</artifactId>
29+
</dependency>
30+
<dependency>
31+
<groupId>org.springframework.boot</groupId>
32+
<artifactId>spring-boot-starter-data-jpa</artifactId>
33+
</dependency>
34+
<dependency>
35+
<groupId>org.springframework.security</groupId>
36+
<artifactId>spring-security-data</artifactId>
37+
</dependency>
38+
<dependency>
39+
<groupId>org.springframework.boot</groupId>
40+
<artifactId>spring-boot-starter-security</artifactId>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.springframework.security</groupId>
44+
<artifactId>spring-security-test</artifactId>
45+
<scope>test</scope>
46+
</dependency>
47+
<dependency>
48+
<groupId>org.apache.tomcat.embed</groupId>
49+
<artifactId>tomcat-embed-jasper</artifactId>
50+
<!-- <scope>provided</scope> -->
51+
</dependency>
52+
<dependency>
53+
<groupId>com.h2database</groupId>
54+
<artifactId>h2</artifactId>
55+
</dependency>
56+
<dependency>
57+
<groupId>javax.servlet</groupId>
58+
<artifactId>jstl</artifactId>
59+
</dependency>
60+
</dependencies>
61+
62+
<build>
63+
<finalName>${project.artifactId}</finalName>
64+
</build>
65+
66+
67+
</project>
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung;
2+
3+
import java.util.Properties;
4+
5+
import javax.sql.DataSource;
6+
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.boot.autoconfigure.SpringBootApplication;
9+
import org.springframework.context.annotation.Bean;
10+
import org.springframework.context.annotation.Import;
11+
import org.springframework.context.annotation.PropertySource;
12+
import org.springframework.core.env.Environment;
13+
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
14+
import org.springframework.jdbc.datasource.DriverManagerDataSource;
15+
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
16+
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
17+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
18+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
19+
20+
@SpringBootApplication
21+
@PropertySource("classpath:persistence-h2.properties")
22+
@EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" })
23+
@EnableWebMvc
24+
@Import(SpringSecurityConfig.class)
25+
public class AppConfig extends WebMvcConfigurerAdapter {
26+
27+
@Autowired
28+
private Environment env;
29+
30+
@Bean
31+
public DataSource dataSource() {
32+
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
33+
dataSource.setDriverClassName(env.getProperty("driverClassName"));
34+
dataSource.setUrl(env.getProperty("url"));
35+
dataSource.setUsername(env.getProperty("user"));
36+
dataSource.setPassword(env.getProperty("password"));
37+
return dataSource;
38+
}
39+
40+
@Bean
41+
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
42+
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
43+
em.setDataSource(dataSource());
44+
em.setPackagesToScan(new String[] { "com.baeldung.models" });
45+
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
46+
em.setJpaProperties(additionalProperties());
47+
return em;
48+
}
49+
50+
final Properties additionalProperties() {
51+
final Properties hibernateProperties = new Properties();
52+
if (env.getProperty("hibernate.hbm2ddl.auto") != null) {
53+
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
54+
}
55+
if (env.getProperty("hibernate.dialect") != null) {
56+
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
57+
}
58+
if (env.getProperty("hibernate.show_sql") != null) {
59+
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
60+
}
61+
return hibernateProperties;
62+
}
63+
64+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.baeldung;
2+
3+
import javax.annotation.PostConstruct;
4+
import javax.sql.DataSource;
5+
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.context.annotation.Bean;
8+
import org.springframework.context.annotation.ComponentScan;
9+
import org.springframework.context.annotation.Configuration;
10+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
11+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
12+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
13+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
14+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
15+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
16+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
17+
import org.springframework.security.crypto.password.PasswordEncoder;
18+
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
19+
import org.springframework.web.context.WebApplicationContext;
20+
21+
import com.baeldung.security.AuthenticationSuccessHandlerImpl;
22+
import com.baeldung.security.CustomUserDetailsService;
23+
24+
@Configuration
25+
@EnableWebSecurity
26+
@ComponentScan("com.baeldung.security")
27+
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
28+
29+
@Autowired
30+
private WebApplicationContext applicationContext;
31+
private CustomUserDetailsService userDetailsService;
32+
@Autowired
33+
private AuthenticationSuccessHandlerImpl successHandler;
34+
@Autowired
35+
private DataSource dataSource;
36+
37+
@PostConstruct
38+
public void completeSetup() {
39+
userDetailsService = applicationContext.getBean(CustomUserDetailsService.class);
40+
}
41+
42+
@Override
43+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
44+
auth.userDetailsService(userDetailsService)
45+
.passwordEncoder(encoder())
46+
.and()
47+
.authenticationProvider(authenticationProvider())
48+
.jdbcAuthentication()
49+
.dataSource(dataSource);
50+
}
51+
52+
@Override
53+
public void configure(WebSecurity web) throws Exception {
54+
web.ignoring()
55+
.antMatchers("/resources/**");
56+
}
57+
58+
@Override
59+
protected void configure(final HttpSecurity http) throws Exception {
60+
http.authorizeRequests()
61+
.antMatchers("/login")
62+
.permitAll()
63+
.and()
64+
.formLogin()
65+
.permitAll()
66+
.successHandler(successHandler)
67+
.and()
68+
.csrf()
69+
.disable();
70+
}
71+
72+
@Bean
73+
public DaoAuthenticationProvider authenticationProvider() {
74+
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
75+
authProvider.setUserDetailsService(userDetailsService);
76+
authProvider.setPasswordEncoder(encoder());
77+
return authProvider;
78+
}
79+
80+
@Bean
81+
public PasswordEncoder encoder() {
82+
return new BCryptPasswordEncoder(11);
83+
}
84+
85+
@Bean
86+
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
87+
return new SecurityEvaluationContextExtension();
88+
}
89+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.data.repositories;
2+
3+
import org.springframework.data.domain.Page;
4+
import org.springframework.data.domain.Pageable;
5+
import org.springframework.data.jpa.repository.Query;
6+
import org.springframework.data.repository.PagingAndSortingRepository;
7+
8+
import com.baeldung.models.Tweet;
9+
10+
public interface TweetRepository extends PagingAndSortingRepository<Tweet, Long> {
11+
12+
@Query("select twt from Tweet twt JOIN twt.likes as lk where lk = ?#{ principal?.username } or twt.owner = ?#{ principal?.username }")
13+
Page<Tweet> getMyTweetsAndTheOnesILiked(Pageable pageable);
14+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.data.repositories;
2+
3+
import java.util.Date;
4+
import java.util.List;
5+
6+
import org.springframework.data.domain.Page;
7+
import org.springframework.data.domain.Pageable;
8+
import org.springframework.data.jpa.repository.Modifying;
9+
import org.springframework.data.jpa.repository.Query;
10+
import org.springframework.data.repository.CrudRepository;
11+
import org.springframework.data.repository.query.Param;
12+
import org.springframework.stereotype.Repository;
13+
import org.springframework.transaction.annotation.Transactional;
14+
15+
import com.baeldung.models.AppUser;
16+
import com.baeldung.models.Tweet;
17+
18+
public interface UserRepository extends CrudRepository<AppUser, Long> {
19+
AppUser findByUsername(String username);
20+
21+
List<AppUser> findByName(String name);
22+
23+
@Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE u.username = ?#{ principal?.username }")
24+
@Modifying
25+
@Transactional
26+
public void updateLastLogin(@Param("lastLogin") Date lastLogin);
27+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.baeldung.models;
2+
3+
import java.util.Date;
4+
5+
import javax.persistence.Column;
6+
import javax.persistence.Entity;
7+
import javax.persistence.GeneratedValue;
8+
import javax.persistence.GenerationType;
9+
import javax.persistence.Id;
10+
import javax.persistence.Table;
11+
12+
@Entity
13+
@Table(name = "users")
14+
public class AppUser {
15+
16+
@Id
17+
@GeneratedValue(strategy = GenerationType.SEQUENCE)
18+
private long id;
19+
20+
private String name;
21+
@Column(unique = true)
22+
private String username;
23+
private String password;
24+
private boolean enabled = true;
25+
private Date lastLogin;
26+
27+
private AppUser() {
28+
}
29+
30+
public AppUser(String name, String email, String password) {
31+
this.username = email;
32+
this.name = name;
33+
this.password = password;
34+
}
35+
36+
public long getId() {
37+
return id;
38+
}
39+
40+
public void setId(long id) {
41+
this.id = id;
42+
}
43+
44+
public String getName() {
45+
return name;
46+
}
47+
48+
public void setName(String name) {
49+
this.name = name;
50+
}
51+
52+
public String getUsername() {
53+
return username;
54+
}
55+
56+
public void setUsername(String username) {
57+
this.username = username;
58+
}
59+
60+
public String getPassword() {
61+
return password;
62+
}
63+
64+
public void setPassword(String password) {
65+
this.password = password;
66+
}
67+
68+
public boolean isEnabled() {
69+
return enabled;
70+
}
71+
72+
public void setEnabled(boolean enabled) {
73+
this.enabled = enabled;
74+
}
75+
76+
public Date getLastLogin() {
77+
return lastLogin;
78+
}
79+
80+
public void setLastLogin(Date lastLogin) {
81+
this.lastLogin = lastLogin;
82+
}
83+
}

0 commit comments

Comments
 (0)