depts = deptRepo.findAll();
61 | for(Department temp:depts){
62 | total++;
63 | }
64 | assertEquals(0, total);
65 | }
66 |
67 | @Autowired
68 | private DeptRepository deptRepo;
69 | }
70 |
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/tomniu/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.config;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.security.authentication.AuthenticationManager;
6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7 | import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.security.core.AuthenticationException;
10 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
11 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
12 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
13 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
14 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
15 |
16 | @Configuration
17 | class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
18 | @Override
19 | public void init(AuthenticationManagerBuilder auth) throws Exception {
20 | auth.inMemoryAuthentication()
21 | .withUser("admin").password("123456").roles("USER");
22 | }
23 | }
24 |
25 | @Configuration
26 | @EnableResourceServer
27 | @EnableAuthorizationServer
28 | class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
29 | String applicationName = "staffmanager";
30 | @Autowired
31 | AuthenticationManagerBuilder authenticationManager;
32 |
33 | @Override
34 | public void configure(AuthorizationServerEndpointsConfigurer endpoints)
35 | throws Exception {
36 |
37 | endpoints.authenticationManager(new AuthenticationManager() {
38 | @Override
39 | public Authentication authenticate(Authentication authentication)
40 | throws AuthenticationException {
41 | return authenticationManager.getOrBuild().authenticate(authentication);
42 | }
43 | });
44 | }
45 |
46 | @Override
47 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
48 |
49 | clients.inMemory().withClient(applicationName)
50 | .authorizedGrantTypes("password", "authorization_code", "refresh_token")
51 | .authorities("ROLE_USER").scopes("write").resourceIds(applicationName)
52 | .secret("888888");
53 | }
54 | }
--------------------------------------------------------------------------------
/rest/src/main/java/com/tomniu/controller/DeptController.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.controller;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.hibernate.Hibernate;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.http.HttpHeaders;
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.http.MediaType;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.transaction.annotation.Transactional;
13 | import org.springframework.web.bind.annotation.*;
14 | import org.springframework.web.util.UriComponentsBuilder;
15 |
16 | import com.tomniu.model.Department;
17 | import com.tomniu.model.DeptJson;
18 | import com.tomniu.model.DeptRepository;
19 |
20 | /**
21 | * User: Tom Niu
22 | *
Version: 1.0
23 | */
24 |
25 | @RestController
26 | public class DeptController {
27 |
28 | @Autowired
29 | private DeptRepository deptRepo;
30 | //-------------------Retrieve All Departments------------------------------
31 | @RequestMapping(value="/dept", method = RequestMethod.GET)
32 | public ResponseEntity> listAllDepts() {
33 | Iterable depts = deptRepo.findAll();
34 | List deptJsons = new ArrayList();
35 | if(depts==null){
36 | return new ResponseEntity>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
37 | } else {
38 | for (Department dept: depts) {
39 | DeptJson deptJson = new DeptJson(dept, dept.getEmps());
40 | deptJsons.add(deptJson);
41 | }
42 | return new ResponseEntity>(deptJsons, HttpStatus.OK);
43 | }
44 | }
45 | //-------------------Retrieve One Departments by Dept Id-------------------
46 | @RequestMapping(value = "/dept/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
47 | public ResponseEntity getUser(@PathVariable("id") long id) {
48 | System.out.println("Fetching User with id " + id);
49 |
50 | Department dept = deptRepo.findOne(id);
51 | if (dept == null) {
52 | System.out.println("dept with id " + id + " not found");
53 | return new ResponseEntity(HttpStatus.NOT_FOUND);
54 | } else {
55 | System.out.println(dept.getDeptName());
56 | System.out.println(dept.getEmps().size());
57 | DeptJson deptInfo = new DeptJson(dept, dept.getEmps());
58 | return new ResponseEntity(deptInfo, HttpStatus.OK);
59 | }
60 | }
61 | //-------------------Create new Department---------------------------------
62 | @RequestMapping(value = "/dept", method = RequestMethod.POST)
63 | public ResponseEntity createUser(@RequestBody DeptJson deptJson, UriComponentsBuilder ucBuilder) {
64 |
65 | Department dept = deptJson.getDept();
66 | System.out.println("Creating Dept " + deptJson.getDept());
67 | dept = deptRepo.save(dept);
68 | System.out.println("saved Dept " + dept);
69 | HttpHeaders headers = new HttpHeaders();
70 | headers.setLocation(ucBuilder.path("/dept/{id}").buildAndExpand(dept.getDeptId()).toUri());
71 | return new ResponseEntity(headers, HttpStatus.CREATED);
72 | }
73 | }
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/tomniu/controller/DeptController.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.controller;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.hibernate.Hibernate;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.http.HttpHeaders;
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.http.MediaType;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.transaction.annotation.Transactional;
13 | import org.springframework.web.bind.annotation.*;
14 | import org.springframework.web.util.UriComponentsBuilder;
15 |
16 | import com.tomniu.model.Department;
17 | import com.tomniu.model.DeptJson;
18 | import com.tomniu.model.DeptRepository;
19 |
20 | /**
21 | * User: Tom Niu
22 | *
Version: 1.0
23 | */
24 |
25 | @RestController
26 | public class DeptController {
27 |
28 | @Autowired
29 | private DeptRepository deptRepo;
30 | //-------------------Retrieve All Departments------------------------------
31 | @RequestMapping(value="/dept", method = RequestMethod.GET)
32 | public ResponseEntity> listAllDepts() {
33 | Iterable depts = deptRepo.findAll();
34 | List deptJsons = new ArrayList();
35 | if(depts==null){
36 | return new ResponseEntity>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
37 | } else {
38 | for (Department dept: depts) {
39 | DeptJson deptJson = new DeptJson(dept, dept.getEmps());
40 | deptJsons.add(deptJson);
41 | }
42 | return new ResponseEntity>(deptJsons, HttpStatus.OK);
43 | }
44 | }
45 | //-------------------Retrieve One Departments by Dept Id-------------------
46 | @RequestMapping(value = "/dept/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
47 | public ResponseEntity getUser(@PathVariable("id") long id) {
48 | System.out.println("Fetching Dept with id " + id);
49 |
50 | Department dept = deptRepo.findOne(id);
51 | if (dept == null) {
52 | System.out.println("dept with id " + id + " not found");
53 | return new ResponseEntity(HttpStatus.NOT_FOUND);
54 | } else {
55 | System.out.println(dept.getDeptName());
56 | System.out.println(dept.getEmps().size());
57 | DeptJson deptInfo = new DeptJson(dept, dept.getEmps());
58 | return new ResponseEntity(deptInfo, HttpStatus.OK);
59 | }
60 | }
61 | //-------------------Create new Department---------------------------------
62 | @RequestMapping(value = "/dept", method = RequestMethod.POST)
63 | public ResponseEntity createUser(@RequestBody DeptJson deptJson, UriComponentsBuilder ucBuilder) {
64 |
65 | Department dept = deptJson.getDept();
66 | System.out.println("Creating Dept " + deptJson.getDept());
67 | dept = deptRepo.save(dept);
68 | System.out.println("saved Dept " + dept);
69 | HttpHeaders headers = new HttpHeaders();
70 | headers.setLocation(ucBuilder.path("/dept/{id}").buildAndExpand(dept.getDeptId()).toUri());
71 | return new ResponseEntity(headers, HttpStatus.CREATED);
72 | }
73 | }
--------------------------------------------------------------------------------
/security/src/main/java/com/tomniu/controller/DeptController.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.controller;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.hibernate.Hibernate;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.http.HttpHeaders;
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.http.MediaType;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.transaction.annotation.Transactional;
13 | import org.springframework.web.bind.annotation.*;
14 | import org.springframework.web.util.UriComponentsBuilder;
15 |
16 | import com.tomniu.model.Department;
17 | import com.tomniu.model.DeptJson;
18 | import com.tomniu.model.DeptRepository;
19 |
20 | /**
21 | * User: Tom Niu
22 | *
Version: 1.0
23 | */
24 |
25 | @RestController
26 | public class DeptController {
27 |
28 | @Autowired
29 | private DeptRepository deptRepo;
30 | //-------------------Retrieve All Departments------------------------------
31 | @RequestMapping(value="/dept", method = RequestMethod.GET)
32 | public ResponseEntity> listAllDepts() {
33 | Iterable depts = deptRepo.findAll();
34 | List deptJsons = new ArrayList();
35 | if(depts==null){
36 | return new ResponseEntity>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
37 | } else {
38 | for (Department dept: depts) {
39 | DeptJson deptJson = new DeptJson(dept, dept.getEmps());
40 | deptJsons.add(deptJson);
41 | }
42 | return new ResponseEntity>(deptJsons, HttpStatus.OK);
43 | }
44 | }
45 | //-------------------Retrieve One Departments by Dept Id-------------------
46 | @RequestMapping(value = "/dept/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
47 | public ResponseEntity getUser(@PathVariable("id") long id) {
48 | System.out.println("Fetching User with id " + id);
49 |
50 | Department dept = deptRepo.findOne(id);
51 | if (dept == null) {
52 | System.out.println("dept with id " + id + " not found");
53 | return new ResponseEntity(HttpStatus.NOT_FOUND);
54 | } else {
55 | System.out.println(dept.getDeptName());
56 | System.out.println(dept.getEmps().size());
57 | DeptJson deptInfo = new DeptJson(dept, dept.getEmps());
58 | return new ResponseEntity(deptInfo, HttpStatus.OK);
59 | }
60 | }
61 | //-------------------Create new Department---------------------------------
62 | @RequestMapping(value = "/dept", method = RequestMethod.POST)
63 | public ResponseEntity createUser(@RequestBody DeptJson deptJson, UriComponentsBuilder ucBuilder) {
64 |
65 | Department dept = deptJson.getDept();
66 | System.out.println("Creating Dept " + deptJson.getDept());
67 | dept = deptRepo.save(dept);
68 | System.out.println("saved Dept " + dept);
69 | HttpHeaders headers = new HttpHeaders();
70 | headers.setLocation(ucBuilder.path("/dept/{id}").buildAndExpand(dept.getDeptId()).toUri());
71 | return new ResponseEntity(headers, HttpStatus.CREATED);
72 | }
73 | }
--------------------------------------------------------------------------------
/oauth2/src/main/java/com/tomniu/config/DatabaseConfig.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.config;
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.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.core.env.Environment;
11 | import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
12 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
13 | import org.springframework.orm.jpa.JpaTransactionManager;
14 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
15 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
16 | import org.springframework.transaction.annotation.EnableTransactionManagement;
17 |
18 |
19 | /**
20 | * Database configurations.
21 | */
22 | @Configuration
23 | @EnableTransactionManagement
24 | public class DatabaseConfig {
25 |
26 | @Bean
27 | public DataSource dataSource() {
28 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
29 | dataSource.setDriverClassName(env.getProperty("db.driver"));
30 | dataSource.setUrl(env.getProperty("db.url"));
31 | dataSource.setUsername(env.getProperty("db.username"));
32 | dataSource.setPassword(env.getProperty("db.password"));
33 | return dataSource;
34 | }
35 |
36 | /**
37 | * Declare the JPA entity manager factory.
38 | */
39 | @Bean
40 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
41 | LocalContainerEntityManagerFactoryBean entityManagerFactory =
42 | new LocalContainerEntityManagerFactoryBean();
43 |
44 | entityManagerFactory.setDataSource(dataSource);
45 |
46 | // Classpath scanning of @Component, @Service, etc annotated class
47 | entityManagerFactory.setPackagesToScan(
48 | env.getProperty("entitymanager.packagesToScan"));
49 |
50 | // Vendor adapter
51 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
52 | entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
53 |
54 | // Hibernate properties
55 | Properties additionalProperties = new Properties();
56 | additionalProperties.put(
57 | "hibernate.dialect",
58 | env.getProperty("hibernate.dialect"));
59 | additionalProperties.put(
60 | "hibernate.show_sql",
61 | env.getProperty("hibernate.show_sql"));
62 | additionalProperties.put(
63 | "hibernate.hbm2ddl.auto",
64 | env.getProperty("hibernate.hbm2ddl.auto"));
65 | entityManagerFactory.setJpaProperties(additionalProperties);
66 |
67 | return entityManagerFactory;
68 | }
69 |
70 | /**
71 | * Declare the transaction manager.
72 | */
73 | @Bean
74 | public JpaTransactionManager transactionManager() {
75 | JpaTransactionManager transactionManager =
76 | new JpaTransactionManager();
77 | transactionManager.setEntityManagerFactory(
78 | entityManagerFactory.getObject());
79 | return transactionManager;
80 | }
81 | @Bean
82 | public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
83 | return new PersistenceExceptionTranslationPostProcessor();
84 | }
85 | // ------------------------
86 | // PRIVATE
87 | // ------------------------
88 |
89 | @Autowired
90 | private Environment env;
91 |
92 | @Autowired
93 | private DataSource dataSource;
94 |
95 | @Autowired
96 | private LocalContainerEntityManagerFactoryBean entityManagerFactory;
97 | }
--------------------------------------------------------------------------------
/rest/src/main/java/com/tomniu/config/DatabaseConfig.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.config;
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.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.core.env.Environment;
11 | import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
12 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
13 | import org.springframework.orm.jpa.JpaTransactionManager;
14 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
15 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
16 | import org.springframework.transaction.annotation.EnableTransactionManagement;
17 |
18 |
19 | /**
20 | * Database configurations.
21 | */
22 | @Configuration
23 | @EnableTransactionManagement
24 | public class DatabaseConfig {
25 |
26 | @Bean
27 | public DataSource dataSource() {
28 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
29 | dataSource.setDriverClassName(env.getProperty("db.driver"));
30 | dataSource.setUrl(env.getProperty("db.url"));
31 | dataSource.setUsername(env.getProperty("db.username"));
32 | dataSource.setPassword(env.getProperty("db.password"));
33 | return dataSource;
34 | }
35 |
36 | /**
37 | * Declare the JPA entity manager factory.
38 | */
39 | @Bean
40 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
41 | LocalContainerEntityManagerFactoryBean entityManagerFactory =
42 | new LocalContainerEntityManagerFactoryBean();
43 |
44 | entityManagerFactory.setDataSource(dataSource);
45 |
46 | // Classpath scanning of @Component, @Service, etc annotated class
47 | entityManagerFactory.setPackagesToScan(
48 | env.getProperty("entitymanager.packagesToScan"));
49 |
50 | // Vendor adapter
51 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
52 | entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
53 |
54 | // Hibernate properties
55 | Properties additionalProperties = new Properties();
56 | additionalProperties.put(
57 | "hibernate.dialect",
58 | env.getProperty("hibernate.dialect"));
59 | additionalProperties.put(
60 | "hibernate.show_sql",
61 | env.getProperty("hibernate.show_sql"));
62 | additionalProperties.put(
63 | "hibernate.hbm2ddl.auto",
64 | env.getProperty("hibernate.hbm2ddl.auto"));
65 | entityManagerFactory.setJpaProperties(additionalProperties);
66 |
67 | return entityManagerFactory;
68 | }
69 |
70 | /**
71 | * Declare the transaction manager.
72 | */
73 | @Bean
74 | public JpaTransactionManager transactionManager() {
75 | JpaTransactionManager transactionManager =
76 | new JpaTransactionManager();
77 | transactionManager.setEntityManagerFactory(
78 | entityManagerFactory.getObject());
79 | return transactionManager;
80 | }
81 | @Bean
82 | public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
83 | return new PersistenceExceptionTranslationPostProcessor();
84 | }
85 | // ------------------------
86 | // PRIVATE
87 | // ------------------------
88 |
89 | @Autowired
90 | private Environment env;
91 |
92 | @Autowired
93 | private DataSource dataSource;
94 |
95 | @Autowired
96 | private LocalContainerEntityManagerFactoryBean entityManagerFactory;
97 | }
--------------------------------------------------------------------------------
/model/src/main/java/com/tomniu/config/DatabaseConfig.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.config;
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.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.core.env.Environment;
11 | import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
12 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
13 | import org.springframework.orm.jpa.JpaTransactionManager;
14 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
15 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
16 | import org.springframework.transaction.annotation.EnableTransactionManagement;
17 |
18 |
19 | /**
20 | * Database configurations.
21 | */
22 | @Configuration
23 | @EnableTransactionManagement
24 | public class DatabaseConfig {
25 |
26 | @Bean
27 | public DataSource dataSource() {
28 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
29 | dataSource.setDriverClassName(env.getProperty("db.driver"));
30 | dataSource.setUrl(env.getProperty("db.url"));
31 | dataSource.setUsername(env.getProperty("db.username"));
32 | dataSource.setPassword(env.getProperty("db.password"));
33 | return dataSource;
34 | }
35 |
36 | /**
37 | * Declare the JPA entity manager factory.
38 | */
39 | @Bean
40 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
41 | LocalContainerEntityManagerFactoryBean entityManagerFactory =
42 | new LocalContainerEntityManagerFactoryBean();
43 |
44 | entityManagerFactory.setDataSource(dataSource);
45 |
46 | // Classpath scanning of @Component, @Service, etc annotated class
47 | entityManagerFactory.setPackagesToScan(
48 | env.getProperty("entitymanager.packagesToScan"));
49 |
50 | // Vendor adapter
51 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
52 | entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
53 |
54 | // Hibernate properties
55 | Properties additionalProperties = new Properties();
56 | additionalProperties.put(
57 | "hibernate.dialect",
58 | env.getProperty("hibernate.dialect"));
59 | additionalProperties.put(
60 | "hibernate.show_sql",
61 | env.getProperty("hibernate.show_sql"));
62 | additionalProperties.put(
63 | "hibernate.hbm2ddl.auto",
64 | env.getProperty("hibernate.hbm2ddl.auto"));
65 | entityManagerFactory.setJpaProperties(additionalProperties);
66 |
67 | return entityManagerFactory;
68 | }
69 |
70 | /**
71 | * Declare the transaction manager.
72 | */
73 | @Bean
74 | public JpaTransactionManager transactionManager() {
75 | JpaTransactionManager transactionManager =
76 | new JpaTransactionManager();
77 | transactionManager.setEntityManagerFactory(
78 | entityManagerFactory.getObject());
79 | return transactionManager;
80 | }
81 | @Bean
82 | public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
83 | return new PersistenceExceptionTranslationPostProcessor();
84 | }
85 | // ------------------------
86 | // PRIVATE
87 | // ------------------------
88 |
89 | @Autowired
90 | private Environment env;
91 |
92 | @Autowired
93 | private DataSource dataSource;
94 |
95 | @Autowired
96 | private LocalContainerEntityManagerFactoryBean entityManagerFactory;
97 | }
98 |
--------------------------------------------------------------------------------
/security/src/main/java/com/tomniu/config/DatabaseConfig.java:
--------------------------------------------------------------------------------
1 | package com.tomniu.config;
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.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.core.env.Environment;
11 | import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
12 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
13 | import org.springframework.orm.jpa.JpaTransactionManager;
14 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
15 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
16 | import org.springframework.transaction.annotation.EnableTransactionManagement;
17 |
18 |
19 | /**
20 | * Database configurations.
21 | */
22 | @Configuration
23 | @EnableTransactionManagement
24 | public class DatabaseConfig {
25 |
26 | @Bean
27 | public DataSource dataSource() {
28 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
29 | dataSource.setDriverClassName(env.getProperty("db.driver"));
30 | dataSource.setUrl(env.getProperty("db.url"));
31 | dataSource.setUsername(env.getProperty("db.username"));
32 | dataSource.setPassword(env.getProperty("db.password"));
33 | return dataSource;
34 | }
35 |
36 | /**
37 | * Declare the JPA entity manager factory.
38 | */
39 | @Bean
40 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
41 | LocalContainerEntityManagerFactoryBean entityManagerFactory =
42 | new LocalContainerEntityManagerFactoryBean();
43 |
44 | entityManagerFactory.setDataSource(dataSource);
45 |
46 | // Classpath scanning of @Component, @Service, etc annotated class
47 | entityManagerFactory.setPackagesToScan(
48 | env.getProperty("entitymanager.packagesToScan"));
49 |
50 | // Vendor adapter
51 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
52 | entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
53 |
54 | // Hibernate properties
55 | Properties additionalProperties = new Properties();
56 | additionalProperties.put(
57 | "hibernate.dialect",
58 | env.getProperty("hibernate.dialect"));
59 | additionalProperties.put(
60 | "hibernate.show_sql",
61 | env.getProperty("hibernate.show_sql"));
62 | additionalProperties.put(
63 | "hibernate.hbm2ddl.auto",
64 | env.getProperty("hibernate.hbm2ddl.auto"));
65 | entityManagerFactory.setJpaProperties(additionalProperties);
66 |
67 | return entityManagerFactory;
68 | }
69 |
70 | /**
71 | * Declare the transaction manager.
72 | */
73 | @Bean
74 | public JpaTransactionManager transactionManager() {
75 | JpaTransactionManager transactionManager =
76 | new JpaTransactionManager();
77 | transactionManager.setEntityManagerFactory(
78 | entityManagerFactory.getObject());
79 | return transactionManager;
80 | }
81 | @Bean
82 | public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
83 | return new PersistenceExceptionTranslationPostProcessor();
84 | }
85 | // ------------------------
86 | // PRIVATE
87 | // ------------------------
88 |
89 | @Autowired
90 | private Environment env;
91 |
92 | @Autowired
93 | private DataSource dataSource;
94 |
95 | @Autowired
96 | private LocalContainerEntityManagerFactoryBean entityManagerFactory;
97 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Spring Boot + REST API + Security + OAuth2 + JPA (demo)
2 | ==========================================
3 | This is a example integrating the above technologies. It is under active development, and more features are in progress.
4 |
5 | **Index**:
6 | [Purpose](#purpose) •
7 | [What you'll need](#what you'll need) •
8 | [Summary](#summary) •
9 | [Run example](#Run example) •
10 | [rest](#rest) •
11 | [security](#security) •
12 | [oauth2](#oauth2) •
13 |
14 | ## Purpose
15 | This example is designed to make it easy for beginner to learn the relevent knowledge about [Maven](http://maven.apache.org/download.cgi), [Spring boot](https://projects.spring.io/spring-boot/), [Spring REST API](https://spring.io/understanding/REST), [Spring JPA](https://projects.spring.io/spring-data-jpa/), [One-to-Many](https://en.wikibooks.org/wiki/Java_Persistence/OneToMany), and [Spring OAuth2](https://spring.io/understanding/oauth)
16 | ## What you'll need
17 | * JDK 1.8 or later
18 | * Maven 3.0+
19 | * MySQL 5.6 or later
20 | ```javascript
21 | . ____ _ __ _ _
22 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
23 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
24 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
25 | ' |____| .__|_| |_|_| |_\__, | / / / /
26 | =========|_|==============|___/=/_/_/_/
27 | :: Spring Boot :: (v1.3.5.RELEASE)
28 | ```
29 |
30 | ## Summary
31 | staffManager has the following modules:
32 | * `model`: Implementing of One-to-Many relationship database with JPA
33 | * `rest`: REST endpoints and web interface
34 | * `security`: REST endpoints and web interface with Basic Authentication
35 | * `oauth2`: REST endpoints and web interface with OAuth2 Authentication
36 |
37 | ## Run example
38 |
39 | ### Installation
40 | ```javascript
41 | mvn package
42 | mvn install
43 | ```
44 | ```javascript
45 | [INFO] staffmanager ...................................... SUCCESS [ 0.218 s]
46 | [INFO] model ............................................. SUCCESS [ 5.016 s]
47 | [INFO] rest .............................................. SUCCESS [ 0.109 s]
48 | [INFO] security .......................................... SUCCESS [ 0.078 s]
49 | [INFO] oauth2 ............................................ SUCCESS [ 0.766 s]
50 | [INFO] ------------------------------------------------------------------------
51 | [INFO] BUILD SUCCESS
52 | [INFO] ------------------------------------------------------------------------
53 | ```
54 |
55 | ### Run the relevent modules
56 | ```javascript
57 | cd [rest|security|oauth2]
58 | mvn spring-boot:run
59 | ```
60 |
61 | ## rest
62 | * You can learn how to depend to other model, how to deploy REST with spring-boot-starter-web.
63 | * You need to ensure that you've installed the module of model before you compile and run rest because rest depends on model.
64 | * It provides REST endpoints including create, find one, find All and update.
65 |
66 | ###Core sources
67 | Abbreviation
68 |
69 | ###Get All departments
70 | ```javascript
71 | curl -X GET -H "Cache-Control: no-cache" -H "Postman-Token: f7944f38-4358-d880-a22b-e1185f05403e" "http://localhost:8080/dept"
72 | ```
73 |
74 | ```javascript
75 | [{"dept":{"deptId":1,"deptName":"HR"},"emps":[{"empId":1,"empName":"Tom","salary":5000.0}]},{"dept":{"deptId":2,"deptName":"IT"},"emps":[{"empId":2,"empName":"John","salary":6000.0}]},{"dept":{"deptId":3,"deptName":"Marketing"},"emps":[]},{"dept":{"deptId":4,"deptName":"IT"},"emps":[]},{"dept":{"deptId":5,"deptName":"IT"},"emps":[]}]
76 | ```
77 | ###Get one department by Id
78 | ```javascript
79 | curl -X GET -H "Cache-Control: no-cache" -H "Postman-Token: a8e98c5a-4483-45bf-9b0d-604b6dd1bb8b" "http://localhost:8080/dept/1"
80 | ```
81 | ```javascript
82 | {"dept":{"deptId":1,"deptName":"HR"},"emps":[{"empId":1,"empName":"Tom","salary":5000.0}]}
83 | ```
84 | ###Create a new department
85 | ```javascript
86 | curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: ed5b3db5-24aa-30bb-a70a-9512d411c222" -d '{"dept":{"deptName":"IT"},"emps":[{"empId":2,"empName":"John","salary":6000.0}]}' "http://localhost:8080/dept"
87 | ```
88 |
89 | following is in progress
90 | * **delete**
91 | * **update**
92 |
93 | ## security
94 | * You can learn how to authenticate the client with Basic Authentication
95 | * Precompile requirement is same as rest
96 |
97 | ###Core sources
98 | * You can change username and password as you like
99 | ```java
100 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
101 | auth.inMemoryAuthentication()
102 | .withUser("root").password("root").roles("USER");
103 | }
104 |
105 | protected void configure(HttpSecurity http) throws Exception {
106 | http.authorizeRequests().anyRequest().fullyAuthenticated();
107 | http.httpBasic();
108 | http.csrf().disable();
109 | }
110 | ```
111 |
112 | ###Get one department by Id with Basic Authentication
113 | ```javascript
114 | curl -X GET -H "Content-Type: application/json" -H "Authorization: Basic cm9vdDpyb290" -H "Cache-Control: no-cache" -H "Postman-Token: d6f03df9-2261-7981-d7cd-151b4e908753" "http://localhost:8080/dept"
115 | ```
116 |
117 | ## oauth2
118 | * You can learn how to authenticate the client with oauth2 (password mode)
119 | * Precompile requirement is same as rest
120 |
121 | ###Core sources
122 | * You can change username and password as you like
123 | ```java
124 | public void init(AuthenticationManagerBuilder auth) throws Exception {
125 | auth.inMemoryAuthentication()
126 | .withUser("admin").password("123456").roles("USER");
127 | }
128 |
129 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
130 | clients.inMemory().withClient(applicationName) // applicationName="staffmanager"
131 | .authorizedGrantTypes("password", "authorization_code", "refresh_token")
132 | .authorities("ROLE_USER").scopes("write").resourceIds(applicationName)
133 | .secret("888888");
134 | }
135 | ```
136 |
137 | ###Get access token
138 | ```javascript
139 | curl -X POST -vu staffmanager:888888 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=123456&username=admin&grant_type=password&scope=write&client_secret=888888&client_id=staffmanager"
140 | ```
141 | ```javascript
142 | {"access_token":"7fd3f22b-2bae-41ad-9f88-77c778b5a546","token_type":"bearer","refresh_token":"5c376a65-5bce-48c8-9fe8-95e41401b11e","xpires_in":43199,"scope":"write"}
143 | ```
144 | ###Get One Department by Id with the access token obtained.
145 | ```javascript
146 | curl -X GET -H "Authorization: Bearer 7fd3f22b-2bae-41ad-9f88-77c778b5a546" -H "Cache-Control: no-cache" -H "Postman-Token: cb8ec0b9-ac7d-ddfc-481b-1e1b0664a912" "http://localhost:8080/dept/1"
147 | ```
148 | ```javascript
149 | {"dept":{"deptId":1,"deptName":"HR"},"emps":[{"empId":1,"empName":"Tom","salary":5000.0}]}
150 | ```
151 |
--------------------------------------------------------------------------------