├── spring4-hello-javaconfig
├── .gitignore
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── loiane
│ │ ├── config
│ │ ├── HelloWorldConfig.java
│ │ └── HelloWorldInit.java
│ │ └── controller
│ │ └── HelloWorldController.java
│ └── webapp
│ └── WEB-INF
│ └── views
│ └── welcome.jsp
├── spring4-hello-xml
├── .gitignore
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── loiane
│ │ └── controller
│ │ └── HelloWorldController.java
│ └── webapp
│ └── WEB-INF
│ ├── spring-servlet.xml
│ ├── views
│ └── welcome.jsp
│ └── web.xml
├── spring4-hibernate4-crud
├── .gitignore
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── loiane
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── AppInitializer.java
│ │ │ └── HibernateConfiguration.java
│ │ │ ├── controller
│ │ │ └── AppController.java
│ │ │ ├── dao
│ │ │ ├── AbstractDao.java
│ │ │ ├── EmployeeDao.java
│ │ │ └── EmployeeDaoImpl.java
│ │ │ ├── model
│ │ │ └── Employee.java
│ │ │ └── service
│ │ │ ├── EmployeeService.java
│ │ │ └── EmployeeServiceImpl.java
│ ├── resources
│ │ ├── application.properties
│ │ └── messages.properties
│ └── webapp
│ │ └── WEB-INF
│ │ └── views
│ │ ├── allemployees.jsp
│ │ ├── registration.jsp
│ │ └── success.jsp
│ └── test
│ ├── java
│ └── com
│ │ └── loiane
│ │ ├── configuration
│ │ └── HibernateTestConfiguration.java
│ │ ├── controller
│ │ └── AppControllerTest.java
│ │ ├── dao
│ │ ├── EmployeeDaoImplTest.java
│ │ └── EntityDaoImplTest.java
│ │ └── service
│ │ └── EmployeeServiceImplTest.java
│ └── resources
│ └── Employee.xml
├── spring4-rest-crud
├── .gitignore
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── loiane
│ │ ├── config
│ │ ├── HelloWorldConfig.java
│ │ └── HelloWorldInit.java
│ │ ├── controller
│ │ ├── HelloWorldRestController.java
│ │ └── UserRestController.java
│ │ ├── model
│ │ ├── Message.java
│ │ └── User.java
│ │ └── service
│ │ └── UserService.java
│ └── test
│ └── com
│ └── loiane
│ └── UserRestTest.java
├── spring4-rest-hello
├── .gitignore
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── loiane
│ ├── config
│ ├── HelloWorldConfig.java
│ └── HelloWorldInit.java
│ ├── controller
│ └── HelloWorldRestController.java
│ └── model
│ └── Message.java
└── springsecurity-hibernate
├── .gitignore
├── db-scripts
└── script.sql
├── pom.xml
└── src
└── main
├── java
└── com
│ └── loiane
│ ├── configuration
│ ├── HelloWorldConfiguration.java
│ ├── HibernateConfiguration.java
│ ├── SecurityConfiguration.java
│ ├── SecurityWebApplicationInitializer.java
│ └── SpringMvcInitializer.java
│ ├── controller
│ └── HelloWorldController.java
│ ├── dao
│ ├── AbstractDao.java
│ ├── UserDao.java
│ └── UserDaoImpl.java
│ ├── model
│ ├── State.java
│ ├── User.java
│ ├── UserProfile.java
│ └── UserProfileType.java
│ └── service
│ ├── CustomUserDetailsService.java
│ ├── UserService.java
│ └── UserServiceImpl.java
├── resources
└── application.properties
└── webapp
├── WEB-INF
└── views
│ ├── accessDenied.jsp
│ ├── admin.jsp
│ ├── dba.jsp
│ ├── login.jsp
│ └── welcome.jsp
└── static
└── css
├── app.css
└── bootstrap.css
/spring4-hello-javaconfig/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring4-hello-javaconfig/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | spring4-hello-javaconfig
6 | war
7 | 1.0-SNAPSHOT
8 | spring4-hello-javaconfig Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | 4.2.0.RELEASE
13 |
14 |
15 |
16 |
17 | org.springframework
18 | spring-webmvc
19 | ${springframework.version}
20 |
21 |
22 |
23 | javax.servlet
24 | javax.servlet-api
25 | 3.1.0
26 |
27 |
28 | javax.servlet.jsp
29 | javax.servlet.jsp-api
30 | 2.3.1
31 |
32 |
33 | javax.servlet
34 | jstl
35 | 1.2
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.apache.maven.plugins
44 | maven-war-plugin
45 | 2.4
46 |
47 | src/main/webapp
48 | Spring4MVCHelloWorldNoXMLDemo
49 | false
50 |
51 |
52 |
53 |
54 | spring4-hello-javaconfig
55 |
56 |
57 |
--------------------------------------------------------------------------------
/spring4-hello-javaconfig/src/main/java/com/loiane/config/HelloWorldConfig.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.ComponentScan;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.web.servlet.ViewResolver;
7 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
9 | import org.springframework.web.servlet.view.JstlView;
10 |
11 | @Configuration
12 | @EnableWebMvc
13 | @ComponentScan(basePackages = "com.loiane")
14 | public class HelloWorldConfig {
15 |
16 | @Bean(name="HelloWorld")
17 | public ViewResolver viewResolver() {
18 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
19 | viewResolver.setViewClass(JstlView.class);
20 | viewResolver.setPrefix("/WEB-INF/views/");
21 | viewResolver.setSuffix(".jsp");
22 |
23 | return viewResolver;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/spring4-hello-javaconfig/src/main/java/com/loiane/config/HelloWorldInit.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.web.WebApplicationInitializer;
4 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
5 | import org.springframework.web.servlet.DispatcherServlet;
6 |
7 | import javax.servlet.ServletContext;
8 | import javax.servlet.ServletException;
9 | import javax.servlet.ServletRegistration;
10 |
11 | public class HelloWorldInit implements WebApplicationInitializer {
12 |
13 | public void onStartup(ServletContext servletContext) throws ServletException {
14 |
15 | AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
16 | ctx.register(HelloWorldConfig.class);
17 | ctx.setServletContext(servletContext);
18 |
19 | ServletRegistration.Dynamic servlet = servletContext.addServlet(
20 | "dispatcher", new DispatcherServlet(ctx));
21 |
22 | servlet.setLoadOnStartup(1);
23 | servlet.addMapping("/");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/spring4-hello-javaconfig/src/main/java/com/loiane/controller/HelloWorldController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.ui.ModelMap;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestMethod;
7 |
8 | @Controller
9 | @RequestMapping("/")
10 | public class HelloWorldController {
11 |
12 | @RequestMapping(method = RequestMethod.GET)
13 | public String sayHello(ModelMap model) {
14 | model.addAttribute("greeting", "Hello World from Spring 4 MVC");
15 | return "welcome";
16 | }
17 |
18 | @RequestMapping(value = "/helloagain", method = RequestMethod.GET)
19 | public String sayHelloAgain(ModelMap model) {
20 | model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
21 | return "welcome";
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/spring4-hello-javaconfig/src/main/webapp/WEB-INF/views/welcome.jsp:
--------------------------------------------------------------------------------
1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 |
3 |
4 | HelloWorld page
5 |
6 |
7 | Greeting : ${greeting}
8 |
9 |
10 |
--------------------------------------------------------------------------------
/spring4-hello-xml/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring4-hello-xml/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | spring4-hello-xml
6 | war
7 | 1.0-SNAPSHOT
8 | spring4-hello-xml Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | 4.2.0.RELEASE
13 |
14 |
15 |
16 |
17 | org.springframework
18 | spring-webmvc
19 | ${springframework.version}
20 |
21 |
22 |
23 | javax.servlet
24 | javax.servlet-api
25 | 3.1.0
26 |
27 |
28 | javax.servlet.jsp
29 | javax.servlet.jsp-api
30 | 2.3.1
31 |
32 |
33 | javax.servlet
34 | jstl
35 | 1.2
36 |
37 |
38 |
39 |
40 | spring4-hello-xml
41 |
42 |
43 |
--------------------------------------------------------------------------------
/spring4-hello-xml/src/main/java/com/loiane/controller/HelloWorldController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.ui.ModelMap;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestMethod;
7 |
8 | @Controller
9 | @RequestMapping("/")
10 | public class HelloWorldController {
11 |
12 | @RequestMapping(method = RequestMethod.GET)
13 | public String sayHello(ModelMap model) {
14 | model.addAttribute("greeting", "Hello World from Spring 4 MVC");
15 | return "welcome";
16 | }
17 |
18 |
19 | @RequestMapping(value="/helloagain", method = RequestMethod.GET)
20 | public String sayHelloAgain(ModelMap model) {
21 | model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
22 | return "welcome";
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/spring4-hello-xml/src/main/webapp/WEB-INF/spring-servlet.xml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
18 |
19 | /WEB-INF/views/
20 |
21 |
22 | .jsp
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/spring4-hello-xml/src/main/webapp/WEB-INF/views/welcome.jsp:
--------------------------------------------------------------------------------
1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 |
3 |
4 | HelloWorld page
5 |
6 |
7 | Greeting : ${greeting}
8 |
9 |
10 |
--------------------------------------------------------------------------------
/spring4-hello-xml/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 | spring4-hello-xml
8 |
9 |
10 | dispatcher
11 |
12 | org.springframework.web.servlet.DispatcherServlet
13 |
14 |
15 | contextConfigLocation
16 | /WEB-INF/spring-servlet.xml
17 |
18 | 1
19 |
20 |
21 |
22 | dispatcher
23 | /
24 |
25 |
26 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | spring4-hibernate4-crud
6 | war
7 | 1.0-SNAPSHOT
8 | spring4-hibernate4-crud Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | 4.0.6.RELEASE
13 | 4.3.6.Final
14 | 5.1.31
15 | 2.3
16 | 6.9.4
17 | 1.10.19
18 | 1.4.187
19 | 2.2
20 |
21 |
22 |
23 |
24 |
25 | org.springframework
26 | spring-core
27 | ${springframework.version}
28 |
29 |
30 | org.springframework
31 | spring-web
32 | ${springframework.version}
33 |
34 |
35 | org.springframework
36 | spring-webmvc
37 | ${springframework.version}
38 |
39 |
40 | org.springframework
41 | spring-tx
42 | ${springframework.version}
43 |
44 |
45 | org.springframework
46 | spring-orm
47 | ${springframework.version}
48 |
49 |
50 |
51 |
52 | org.hibernate
53 | hibernate-core
54 | ${hibernate.version}
55 |
56 |
57 |
58 |
59 | javax.validation
60 | validation-api
61 | 1.1.0.Final
62 |
63 |
64 | org.hibernate
65 | hibernate-validator
66 | 5.1.3.Final
67 |
68 |
69 |
70 |
71 | mysql
72 | mysql-connector-java
73 | ${mysql.version}
74 |
75 |
76 |
77 |
78 | joda-time
79 | joda-time
80 | ${joda-time.version}
81 |
82 |
83 |
84 |
85 | org.jadira.usertype
86 | usertype.core
87 | 3.0.0.CR1
88 |
89 |
90 |
91 |
92 | javax.servlet
93 | javax.servlet-api
94 | 3.1.0
95 |
96 |
97 | javax.servlet.jsp
98 | javax.servlet.jsp-api
99 | 2.3.1
100 |
101 |
102 | javax.servlet
103 | jstl
104 | 1.2
105 |
106 |
107 |
108 |
109 |
110 | org.springframework
111 | spring-test
112 | ${springframework.version}
113 | test
114 |
115 |
116 | org.testng
117 | testng
118 | ${testng.version}
119 | test
120 |
121 |
122 | org.mockito
123 | mockito-all
124 | ${mockito.version}
125 | test
126 |
127 |
128 | com.h2database
129 | h2
130 | ${h2.version}
131 | test
132 |
133 |
134 | dbunit
135 | dbunit
136 | ${dbunit.version}
137 | test
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 | org.apache.maven.plugins
147 | maven-war-plugin
148 | 2.4
149 |
150 | src/main/webapp
151 | spring4-hibernate4-crud
152 | false
153 |
154 |
155 |
156 |
157 | spring4-hibernate4-crud
158 |
159 |
160 |
161 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.context.MessageSource;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.ComponentScan;
6 | import org.springframework.context.annotation.Configuration;
7 | import org.springframework.context.support.ResourceBundleMessageSource;
8 | import org.springframework.web.servlet.ViewResolver;
9 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
10 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
11 | import org.springframework.web.servlet.view.JstlView;
12 |
13 | @Configuration
14 | @EnableWebMvc
15 | @ComponentScan(basePackages = "com.loiane")
16 | public class AppConfig {
17 |
18 | @Bean
19 | public ViewResolver viewResolver() {
20 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
21 | viewResolver.setViewClass(JstlView.class);
22 | viewResolver.setPrefix("/WEB-INF/views/");
23 | viewResolver.setSuffix(".jsp");
24 |
25 | return viewResolver;
26 | }
27 |
28 | @Bean
29 | public MessageSource messageSource() {
30 | ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
31 | messageSource.setBasename("messages");
32 | return messageSource;
33 | }
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/config/AppInitializer.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import javax.servlet.ServletContext;
4 | import javax.servlet.ServletException;
5 | import javax.servlet.ServletRegistration;
6 |
7 | import org.springframework.web.WebApplicationInitializer;
8 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
9 | import org.springframework.web.servlet.DispatcherServlet;
10 |
11 | public class AppInitializer implements WebApplicationInitializer {
12 |
13 | public void onStartup(ServletContext container) throws ServletException {
14 |
15 | AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
16 | ctx.register(AppConfig.class);
17 | ctx.setServletContext(container);
18 |
19 | ServletRegistration.Dynamic servlet = container.addServlet(
20 | "dispatcher", new DispatcherServlet(ctx));
21 |
22 | servlet.setLoadOnStartup(1);
23 | servlet.addMapping("/");
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/config/HibernateConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import java.util.Properties;
4 |
5 | import javax.sql.DataSource;
6 |
7 | import org.hibernate.SessionFactory;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.ComponentScan;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.context.annotation.PropertySource;
13 | import org.springframework.core.env.Environment;
14 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
15 | import org.springframework.orm.hibernate4.HibernateTransactionManager;
16 | import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
17 | import org.springframework.transaction.annotation.EnableTransactionManagement;
18 |
19 | @Configuration
20 | @EnableTransactionManagement
21 | @ComponentScan({ "com.websystique.springmvc.configuration" })
22 | @PropertySource(value = { "classpath:application.properties" })
23 | public class HibernateConfiguration {
24 |
25 | @Autowired
26 | private Environment environment;
27 |
28 | @Bean
29 | public LocalSessionFactoryBean sessionFactory() {
30 | LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
31 | sessionFactory.setDataSource(dataSource());
32 | sessionFactory.setPackagesToScan(new String[] { "com.loiane.model" });
33 | sessionFactory.setHibernateProperties(hibernateProperties());
34 | return sessionFactory;
35 | }
36 |
37 | @Bean
38 | public DataSource dataSource() {
39 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
40 | dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
41 | dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
42 | dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
43 | dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
44 | return dataSource;
45 | }
46 |
47 | private Properties hibernateProperties() {
48 | Properties properties = new Properties();
49 | properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
50 | properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
51 | properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
52 | return properties;
53 | }
54 |
55 | @Bean
56 | @Autowired
57 | public HibernateTransactionManager transactionManager(SessionFactory s) {
58 | HibernateTransactionManager txManager = new HibernateTransactionManager();
59 | txManager.setSessionFactory(s);
60 | return txManager;
61 | }
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/controller/AppController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import java.util.List;
4 | import java.util.Locale;
5 |
6 | import javax.validation.Valid;
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.MessageSource;
10 | import org.springframework.stereotype.Controller;
11 | import org.springframework.ui.ModelMap;
12 | import org.springframework.validation.BindingResult;
13 | import org.springframework.validation.FieldError;
14 | import org.springframework.web.bind.annotation.PathVariable;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.RequestMethod;
17 |
18 | import com.loiane.model.Employee;
19 | import com.loiane.service.EmployeeService;
20 |
21 | @Controller
22 | @RequestMapping("/")
23 | public class AppController {
24 |
25 | @Autowired
26 | EmployeeService service;
27 |
28 | @Autowired
29 | MessageSource messageSource;
30 |
31 | /*
32 | * This method will list all existing employees.
33 | */
34 | @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
35 | public String listEmployees(ModelMap model) {
36 |
37 | List employees = service.findAllEmployees();
38 | model.addAttribute("employees", employees);
39 | return "allemployees";
40 | }
41 |
42 | /*
43 | * This method will provide the medium to add a new employee.
44 | */
45 | @RequestMapping(value = { "/new" }, method = RequestMethod.GET)
46 | public String newEmployee(ModelMap model) {
47 | Employee employee = new Employee();
48 | model.addAttribute("employee", employee);
49 | model.addAttribute("edit", false);
50 | return "registration";
51 | }
52 |
53 | /*
54 | * This method will be called on form submission, handling POST request for
55 | * saving employee in database. It also validates the user input
56 | */
57 | @RequestMapping(value = { "/new" }, method = RequestMethod.POST)
58 | public String saveEmployee(@Valid Employee employee, BindingResult result,
59 | ModelMap model) {
60 |
61 | if (result.hasErrors()) {
62 | return "registration";
63 | }
64 |
65 | /*
66 | * Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation
67 | * and applying it on field [ssn] of Model class [Employee].
68 | *
69 | * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
70 | * framework as well while still using internationalized messages.
71 | *
72 | */
73 | if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
74 | FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
75 | result.addError(ssnError);
76 | return "registration";
77 | }
78 |
79 | service.saveEmployee(employee);
80 |
81 | model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
82 | return "success";
83 | }
84 |
85 |
86 | /*
87 | * This method will provide the medium to update an existing employee.
88 | */
89 | @RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.GET)
90 | public String editEmployee(@PathVariable String ssn, ModelMap model) {
91 | Employee employee = service.findEmployeeBySsn(ssn);
92 | model.addAttribute("employee", employee);
93 | model.addAttribute("edit", true);
94 | return "registration";
95 | }
96 |
97 | /*
98 | * This method will be called on form submission, handling POST request for
99 | * updating employee in database. It also validates the user input
100 | */
101 | @RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.POST)
102 | public String updateEmployee(@Valid Employee employee, BindingResult result,
103 | ModelMap model, @PathVariable String ssn) {
104 |
105 | if (result.hasErrors()) {
106 | return "registration";
107 | }
108 |
109 | if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
110 | FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
111 | result.addError(ssnError);
112 | return "registration";
113 | }
114 |
115 | service.updateEmployee(employee);
116 |
117 | model.addAttribute("success", "Employee " + employee.getName() + " updated successfully");
118 | return "success";
119 | }
120 |
121 |
122 | /*
123 | * This method will delete an employee by it's SSN value.
124 | */
125 | @RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)
126 | public String deleteEmployee(@PathVariable String ssn) {
127 | service.deleteEmployeeBySsn(ssn);
128 | return "redirect:/list";
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/dao/AbstractDao.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import java.io.Serializable;
4 |
5 | import java.lang.reflect.ParameterizedType;
6 |
7 | import org.hibernate.Criteria;
8 | import org.hibernate.Session;
9 | import org.hibernate.SessionFactory;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 |
12 | public abstract class AbstractDao {
13 |
14 | private final Class persistentClass;
15 |
16 | @SuppressWarnings("unchecked")
17 | public AbstractDao(){
18 | this.persistentClass =(Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
19 | }
20 |
21 | @Autowired
22 | private SessionFactory sessionFactory;
23 |
24 | protected Session getSession(){
25 | return sessionFactory.getCurrentSession();
26 | }
27 |
28 | @SuppressWarnings("unchecked")
29 | public T getByKey(PK key) {
30 | return (T) getSession().get(persistentClass, key);
31 | }
32 |
33 | public void persist(T entity) {
34 | getSession().persist(entity);
35 | }
36 |
37 | public void delete(T entity) {
38 | getSession().delete(entity);
39 | }
40 |
41 | protected Criteria createEntityCriteria(){
42 | return getSession().createCriteria(persistentClass);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/dao/EmployeeDao.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import java.util.List;
4 |
5 | import com.loiane.model.Employee;
6 |
7 | public interface EmployeeDao {
8 |
9 | Employee findById(int id);
10 |
11 | void saveEmployee(Employee employee);
12 |
13 | void deleteEmployeeBySsn(String ssn);
14 |
15 | List findAllEmployees();
16 |
17 | Employee findEmployeeBySsn(String ssn);
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/dao/EmployeeDaoImpl.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import java.util.List;
4 |
5 | import org.hibernate.Criteria;
6 | import org.hibernate.Query;
7 | import org.hibernate.criterion.Restrictions;
8 | import org.springframework.stereotype.Repository;
9 |
10 | import com.loiane.model.Employee;
11 |
12 | @Repository("employeeDao")
13 | public class EmployeeDaoImpl extends AbstractDao implements EmployeeDao {
14 |
15 | public Employee findById(int id) {
16 | return getByKey(id);
17 | }
18 |
19 | public void saveEmployee(Employee employee) {
20 | persist(employee);
21 | }
22 |
23 | public void deleteEmployeeBySsn(String ssn) {
24 | Query query = getSession().createSQLQuery("delete from Employee where ssn = :ssn");
25 | query.setString("ssn", ssn);
26 | query.executeUpdate();
27 | }
28 |
29 | @SuppressWarnings("unchecked")
30 | public List findAllEmployees() {
31 | Criteria criteria = createEntityCriteria();
32 | return (List) criteria.list();
33 | }
34 |
35 | public Employee findEmployeeBySsn(String ssn) {
36 | Criteria criteria = createEntityCriteria();
37 | criteria.add(Restrictions.eq("ssn", ssn));
38 | return (Employee) criteria.uniqueResult();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/model/Employee.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | import java.math.BigDecimal;
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 | import javax.validation.constraints.Digits;
12 | import javax.validation.constraints.NotNull;
13 | import javax.validation.constraints.Size;
14 |
15 | import org.hibernate.annotations.Type;
16 | import org.hibernate.validator.constraints.NotEmpty;
17 | import org.joda.time.LocalDate;
18 | import org.springframework.format.annotation.DateTimeFormat;
19 |
20 | @Entity
21 | @Table(name="EMPLOYEE")
22 | public class Employee {
23 |
24 | @Id
25 | @GeneratedValue(strategy = GenerationType.IDENTITY)
26 | private int id;
27 |
28 | @Size(min=3, max=50)
29 | @Column(name = "NAME", nullable = false)
30 | private String name;
31 |
32 | @NotNull
33 | @DateTimeFormat(pattern="dd/MM/yyyy")
34 | @Column(name = "JOINING_DATE", nullable = false)
35 | @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
36 | private LocalDate joiningDate;
37 |
38 | @NotNull
39 | @Digits(integer=8, fraction=2)
40 | @Column(name = "SALARY", nullable = false)
41 | private BigDecimal salary;
42 |
43 | @NotEmpty
44 | @Column(name = "SSN", unique=true, nullable = false)
45 | private String ssn;
46 |
47 | public int getId() {
48 | return id;
49 | }
50 |
51 | public void setId(int id) {
52 | this.id = id;
53 | }
54 |
55 | public String getName() {
56 | return name;
57 | }
58 |
59 | public void setName(String name) {
60 | this.name = name;
61 | }
62 |
63 | public LocalDate getJoiningDate() {
64 | return joiningDate;
65 | }
66 |
67 | public void setJoiningDate(LocalDate joiningDate) {
68 | this.joiningDate = joiningDate;
69 | }
70 |
71 | public BigDecimal getSalary() {
72 | return salary;
73 | }
74 |
75 | public void setSalary(BigDecimal salary) {
76 | this.salary = salary;
77 | }
78 |
79 | public String getSsn() {
80 | return ssn;
81 | }
82 |
83 | public void setSsn(String ssn) {
84 | this.ssn = ssn;
85 | }
86 |
87 | @Override
88 | public int hashCode() {
89 | final int prime = 31;
90 | int result = 1;
91 | result = prime * result + id;
92 | result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
93 | return result;
94 | }
95 |
96 | @Override
97 | public boolean equals(Object obj) {
98 | if (this == obj)
99 | return true;
100 | if (obj == null)
101 | return false;
102 | if (!(obj instanceof Employee))
103 | return false;
104 | Employee other = (Employee) obj;
105 | if (id != other.id)
106 | return false;
107 | if (ssn == null) {
108 | if (other.ssn != null)
109 | return false;
110 | } else if (!ssn.equals(other.ssn))
111 | return false;
112 | return true;
113 | }
114 |
115 | @Override
116 | public String toString() {
117 | return "Employee [id=" + id + ", name=" + name + ", joiningDate="
118 | + joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
119 | }
120 |
121 |
122 |
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/service/EmployeeService.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import java.util.List;
4 |
5 | import com.loiane.model.Employee;
6 |
7 | public interface EmployeeService {
8 |
9 | Employee findById(int id);
10 |
11 | void saveEmployee(Employee employee);
12 |
13 | void updateEmployee(Employee employee);
14 |
15 | void deleteEmployeeBySsn(String ssn);
16 |
17 | List findAllEmployees();
18 |
19 | Employee findEmployeeBySsn(String ssn);
20 |
21 | boolean isEmployeeSsnUnique(Integer id, String ssn);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/java/com/loiane/service/EmployeeServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 | import org.springframework.transaction.annotation.Transactional;
8 |
9 | import com.loiane.dao.EmployeeDao;
10 | import com.loiane.model.Employee;
11 |
12 | @Service("employeeService")
13 | @Transactional
14 | public class EmployeeServiceImpl implements EmployeeService {
15 |
16 | @Autowired
17 | private EmployeeDao dao;
18 |
19 | public Employee findById(int id) {
20 | return dao.findById(id);
21 | }
22 |
23 | public void saveEmployee(Employee employee) {
24 | dao.saveEmployee(employee);
25 | }
26 |
27 | /*
28 | * Since the method is running with Transaction, No need to call hibernate update explicitly.
29 | * Just fetch the entity from db and update it with proper values within transaction.
30 | * It will be updated in db once transaction ends.
31 | */
32 | public void updateEmployee(Employee employee) {
33 | Employee entity = dao.findById(employee.getId());
34 | if(entity!=null){
35 | entity.setName(employee.getName());
36 | entity.setJoiningDate(employee.getJoiningDate());
37 | entity.setSalary(employee.getSalary());
38 | entity.setSsn(employee.getSsn());
39 | }
40 | }
41 |
42 | public void deleteEmployeeBySsn(String ssn) {
43 | dao.deleteEmployeeBySsn(ssn);
44 | }
45 |
46 | public List findAllEmployees() {
47 | return dao.findAllEmployees();
48 | }
49 |
50 | public Employee findEmployeeBySsn(String ssn) {
51 | return dao.findEmployeeBySsn(ssn);
52 | }
53 |
54 | public boolean isEmployeeSsnUnique(Integer id, String ssn) {
55 | Employee employee = findEmployeeBySsn(ssn);
56 | return ( employee == null || ((id != null) && (employee.getId() == id)));
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | jdbc.driverClassName = com.mysql.jdbc.Driver
2 | jdbc.url = jdbc:mysql://localhost:3306/blog
3 | jdbc.username = root
4 | jdbc.password =
5 | hibernate.dialect = org.hibernate.dialect.MySQLDialect
6 | hibernate.show_sql = true
7 | hibernate.format_sql = true
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/resources/messages.properties:
--------------------------------------------------------------------------------
1 | Size.employee.name=Name must be between {2} and {1} characters long
2 | NotNull.employee.joiningDate=Joining Date can not be blank
3 | NotNull.employee.salary=Salary can not be blank
4 | Digits.employee.salary=Only numeric data with max 8 digits and with max 2 precision is allowed
5 | NotEmpty.employee.ssn=SSN can not be blank
6 | typeMismatch=Invalid format
7 | non.unique.ssn=SSN {0} already exist. Please fill in different value.
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/webapp/WEB-INF/views/allemployees.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 | pageEncoding="ISO-8859-1"%>
3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
4 |
5 |
6 |
7 | University Enrollments
8 |
9 |
15 |
16 |
17 |
18 |
19 |
20 | List of Employees
21 |
22 |
23 | NAME | Joining Date | Salary | SSN | |
24 |
25 |
26 |
27 | ${employee.name} |
28 | ${employee.joiningDate} |
29 | ${employee.salary} |
30 | ${employee.ssn} |
31 | delete |
32 |
33 |
34 |
35 |
36 | Add New Employee
37 |
38 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/webapp/WEB-INF/views/registration.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 | pageEncoding="ISO-8859-1"%>
3 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
5 |
6 |
7 |
8 |
9 |
10 | Employee Registration Form
11 |
12 |
18 |
19 |
20 |
21 |
22 |
23 | Registration Form
24 |
25 |
26 |
27 |
65 |
66 |
67 |
68 | Go back to List of All Employees
69 |
70 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/main/webapp/WEB-INF/views/success.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 | pageEncoding="ISO-8859-1"%>
3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
4 |
5 |
6 |
7 |
8 | Registration Confirmation Page
9 |
10 |
11 | message : ${success}
12 |
13 |
14 | Go back to List of All Employees
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/java/com/loiane/configuration/HibernateTestConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import java.util.Properties;
4 |
5 | import javax.sql.DataSource;
6 |
7 | import org.hibernate.SessionFactory;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.ComponentScan;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.core.env.Environment;
13 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
14 | import org.springframework.orm.hibernate4.HibernateTransactionManager;
15 | import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
16 | import org.springframework.transaction.annotation.EnableTransactionManagement;
17 |
18 | /*
19 | * This class is same as real HibernateConfiguration class in sources.
20 | * Only difference is that method dataSource & hibernateProperties
21 | * implementations are specific to Hibernate working with H2 database.
22 | */
23 |
24 | @Configuration
25 | @EnableTransactionManagement
26 | @ComponentScan({"com.loiane.dao"})
27 | public class HibernateTestConfiguration {
28 |
29 | @Autowired
30 | private Environment environment;
31 |
32 | @Bean
33 | public LocalSessionFactoryBean sessionFactory() {
34 | LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
35 | sessionFactory.setDataSource(dataSource());
36 | sessionFactory.setPackagesToScan(new String[] { "com.loiane.model" });
37 | sessionFactory.setHibernateProperties(hibernateProperties());
38 | return sessionFactory;
39 | }
40 |
41 | @Bean(name = "dataSource")
42 | public DataSource dataSource() {
43 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
44 | dataSource.setDriverClassName("org.h2.Driver");
45 | dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
46 | dataSource.setUsername("sa");
47 | dataSource.setPassword("");
48 | return dataSource;
49 | }
50 |
51 | private Properties hibernateProperties() {
52 | Properties properties = new Properties();
53 | properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
54 | properties.put("hibernate.hbm2ddl.auto", "create-drop");
55 | return properties;
56 | }
57 |
58 | @Bean
59 | @Autowired
60 | public HibernateTransactionManager transactionManager(SessionFactory s) {
61 | HibernateTransactionManager txManager = new HibernateTransactionManager();
62 | txManager.setSessionFactory(s);
63 | return txManager;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/java/com/loiane/controller/AppControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import static org.mockito.Matchers.any;
4 | import static org.mockito.Matchers.anyString;
5 | import static org.mockito.Matchers.anyInt;
6 | import static org.mockito.Mockito.doNothing;
7 | import static org.mockito.Mockito.when;
8 | import static org.mockito.Mockito.verify;
9 |
10 | import java.math.BigDecimal;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import com.loiane.controller.AppController;
15 | import org.joda.time.LocalDate;
16 | import org.mockito.InjectMocks;
17 | import org.mockito.Mock;
18 | import org.mockito.MockitoAnnotations;
19 | import org.mockito.Spy;
20 | import static org.mockito.Mockito.atLeastOnce;
21 |
22 | import org.springframework.context.MessageSource;
23 | import org.springframework.ui.ModelMap;
24 | import org.springframework.validation.BindingResult;
25 | import org.testng.Assert;
26 | import org.testng.annotations.BeforeClass;
27 | import org.testng.annotations.Test;
28 |
29 |
30 | import com.loiane.model.Employee;
31 | import com.loiane.service.EmployeeService;
32 |
33 | public class AppControllerTest {
34 |
35 | @Mock
36 | EmployeeService service;
37 |
38 | @Mock
39 | MessageSource message;
40 |
41 | @InjectMocks
42 | AppController appController;
43 |
44 | @Spy
45 | List employees = new ArrayList();
46 |
47 | @Spy
48 | ModelMap model;
49 |
50 | @Mock
51 | BindingResult result;
52 |
53 | @BeforeClass
54 | public void setUp(){
55 | MockitoAnnotations.initMocks(this);
56 | employees = getEmployeeList();
57 | }
58 |
59 | @Test
60 | public void listEmployees(){
61 | when(service.findAllEmployees()).thenReturn(employees);
62 | Assert.assertEquals(appController.listEmployees(model), "allemployees");
63 | Assert.assertEquals(model.get("employees"), employees);
64 | verify(service, atLeastOnce()).findAllEmployees();
65 | }
66 |
67 | @Test
68 | public void newEmployee(){
69 | Assert.assertEquals(appController.newEmployee(model), "registration");
70 | Assert.assertNotNull(model.get("employee"));
71 | Assert.assertFalse((Boolean)model.get("edit"));
72 | Assert.assertEquals(((Employee)model.get("employee")).getId(), 0);
73 | }
74 |
75 |
76 | @Test
77 | public void saveEmployeeWithValidationError(){
78 | when(result.hasErrors()).thenReturn(true);
79 | doNothing().when(service).saveEmployee(any(Employee.class));
80 | Assert.assertEquals(appController.saveEmployee(employees.get(0), result, model), "registration");
81 | }
82 |
83 | @Test
84 | public void saveEmployeeWithValidationErrorNonUniqueSSN(){
85 | when(result.hasErrors()).thenReturn(false);
86 | when(service.isEmployeeSsnUnique(anyInt(), anyString())).thenReturn(false);
87 | Assert.assertEquals(appController.saveEmployee(employees.get(0), result, model), "registration");
88 | }
89 |
90 |
91 | @Test
92 | public void saveEmployeeWithSuccess(){
93 | when(result.hasErrors()).thenReturn(false);
94 | when(service.isEmployeeSsnUnique(anyInt(), anyString())).thenReturn(true);
95 | doNothing().when(service).saveEmployee(any(Employee.class));
96 | Assert.assertEquals(appController.saveEmployee(employees.get(0), result, model), "success");
97 | Assert.assertEquals(model.get("success"), "Employee Axel registered successfully");
98 | }
99 |
100 | @Test
101 | public void editEmployee(){
102 | Employee emp = employees.get(0);
103 | when(service.findEmployeeBySsn(anyString())).thenReturn(emp);
104 | Assert.assertEquals(appController.editEmployee(anyString(), model), "registration");
105 | Assert.assertNotNull(model.get("employee"));
106 | Assert.assertTrue((Boolean)model.get("edit"));
107 | Assert.assertEquals(((Employee)model.get("employee")).getId(), 1);
108 | }
109 |
110 | @Test
111 | public void updateEmployeeWithValidationError(){
112 | when(result.hasErrors()).thenReturn(true);
113 | doNothing().when(service).updateEmployee(any(Employee.class));
114 | Assert.assertEquals(appController.updateEmployee(employees.get(0), result, model,""), "registration");
115 | }
116 |
117 | @Test
118 | public void updateEmployeeWithValidationErrorNonUniqueSSN(){
119 | when(result.hasErrors()).thenReturn(false);
120 | when(service.isEmployeeSsnUnique(anyInt(), anyString())).thenReturn(false);
121 | Assert.assertEquals(appController.updateEmployee(employees.get(0), result, model,""), "registration");
122 | }
123 |
124 | @Test
125 | public void updateEmployeeWithSuccess(){
126 | when(result.hasErrors()).thenReturn(false);
127 | when(service.isEmployeeSsnUnique(anyInt(), anyString())).thenReturn(true);
128 | doNothing().when(service).updateEmployee(any(Employee.class));
129 | Assert.assertEquals(appController.updateEmployee(employees.get(0), result, model, ""), "success");
130 | Assert.assertEquals(model.get("success"), "Employee Axel updated successfully");
131 | }
132 |
133 |
134 | @Test
135 | public void deleteEmployee(){
136 | doNothing().when(service).deleteEmployeeBySsn(anyString());
137 | Assert.assertEquals(appController.deleteEmployee("123"), "redirect:/list");
138 | }
139 |
140 | public List getEmployeeList(){
141 | Employee e1 = new Employee();
142 | e1.setId(1);
143 | e1.setName("Axel");
144 | e1.setJoiningDate(new LocalDate());
145 | e1.setSalary(new BigDecimal(10000));
146 | e1.setSsn("XXX111");
147 |
148 | Employee e2 = new Employee();
149 | e2.setId(2);
150 | e2.setName("Jeremy");
151 | e2.setJoiningDate(new LocalDate());
152 | e2.setSalary(new BigDecimal(20000));
153 | e2.setSsn("XXX222");
154 |
155 | employees.add(e1);
156 | employees.add(e2);
157 | return employees;
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/java/com/loiane/dao/EmployeeDaoImplTest.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import java.math.BigDecimal;
4 |
5 | import org.dbunit.dataset.IDataSet;
6 | import org.dbunit.dataset.xml.FlatXmlDataSet;
7 | import org.joda.time.LocalDate;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.testng.Assert;
10 | import org.testng.annotations.Test;
11 |
12 | import com.loiane.model.Employee;
13 |
14 |
15 | public class EmployeeDaoImplTest extends EntityDaoImplTest{
16 |
17 | @Autowired
18 | EmployeeDao employeeDao;
19 |
20 | @Override
21 | protected IDataSet getDataSet() throws Exception{
22 | IDataSet dataSet = new FlatXmlDataSet(this.getClass().getClassLoader().getResourceAsStream("Employee.xml"));
23 | return dataSet;
24 | }
25 |
26 | /* In case you need multiple datasets (mapping different tables) and you do prefer to keep them in separate XML's
27 | @Override
28 | protected IDataSet getDataSet() throws Exception {
29 | IDataSet[] datasets = new IDataSet[] {
30 | new FlatXmlDataSet(this.getClass().getClassLoader().getResourceAsStream("Employee.xml")),
31 | new FlatXmlDataSet(this.getClass().getClassLoader().getResourceAsStream("Benefits.xml")),
32 | new FlatXmlDataSet(this.getClass().getClassLoader().getResourceAsStream("Departements.xml"))
33 | };
34 | return new CompositeDataSet(datasets);
35 | }
36 | */
37 |
38 | @Test
39 | public void findById(){
40 | Assert.assertNotNull(employeeDao.findById(1));
41 | Assert.assertNull(employeeDao.findById(3));
42 | }
43 |
44 |
45 | @Test
46 | public void saveEmployee(){
47 | employeeDao.saveEmployee(getSampleEmployee());
48 | Assert.assertEquals(employeeDao.findAllEmployees().size(), 3);
49 | }
50 |
51 | @Test
52 | public void deleteEmployeeBySsn(){
53 | employeeDao.deleteEmployeeBySsn("11111");
54 | Assert.assertEquals(employeeDao.findAllEmployees().size(), 1);
55 | }
56 |
57 | @Test
58 | public void deleteEmployeeByInvalidSsn(){
59 | employeeDao.deleteEmployeeBySsn("23423");
60 | Assert.assertEquals(employeeDao.findAllEmployees().size(), 2);
61 | }
62 |
63 | @Test
64 | public void findAllEmployees(){
65 | Assert.assertEquals(employeeDao.findAllEmployees().size(), 2);
66 | }
67 |
68 | @Test
69 | public void findEmployeeBySsn(){
70 | Assert.assertNotNull(employeeDao.findEmployeeBySsn("11111"));
71 | Assert.assertNull(employeeDao.findEmployeeBySsn("14545"));
72 | }
73 |
74 | public Employee getSampleEmployee(){
75 | Employee employee = new Employee();
76 | employee.setName("Karen");
77 | employee.setSsn("12345");
78 | employee.setSalary(new BigDecimal(10980));
79 | employee.setJoiningDate(new LocalDate());
80 | return employee;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/java/com/loiane/dao/EntityDaoImplTest.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import javax.sql.DataSource;
4 |
5 | import org.dbunit.database.DatabaseDataSourceConnection;
6 | import org.dbunit.database.IDatabaseConnection;
7 | import org.dbunit.dataset.IDataSet;
8 | import org.dbunit.operation.DatabaseOperation;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.test.context.ContextConfiguration;
11 | import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
12 | import org.testng.annotations.BeforeMethod;
13 |
14 | import com.loiane.configuration.HibernateTestConfiguration;
15 |
16 |
17 | @ContextConfiguration(classes = { HibernateTestConfiguration.class })
18 | public abstract class EntityDaoImplTest extends AbstractTransactionalTestNGSpringContextTests {
19 |
20 | @Autowired
21 | DataSource dataSource;
22 |
23 | @BeforeMethod
24 | public void setUp() throws Exception {
25 | IDatabaseConnection dbConn = new DatabaseDataSourceConnection(
26 | dataSource);
27 | DatabaseOperation.CLEAN_INSERT.execute(dbConn, getDataSet());
28 | }
29 |
30 | protected abstract IDataSet getDataSet() throws Exception;
31 |
32 | }
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/java/com/loiane/service/EmployeeServiceImplTest.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import static org.mockito.Matchers.any;
4 | import static org.mockito.Matchers.anyString;
5 | import static org.mockito.Matchers.anyInt;
6 | import static org.mockito.Mockito.atLeastOnce;
7 | import static org.mockito.Mockito.doNothing;
8 | import static org.mockito.Mockito.verify;
9 |
10 | import java.math.BigDecimal;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import static org.mockito.Mockito.when;
15 |
16 | import org.joda.time.LocalDate;
17 | import org.mockito.InjectMocks;
18 | import org.mockito.Mock;
19 | import org.mockito.MockitoAnnotations;
20 | import org.mockito.Spy;
21 | import org.testng.Assert;
22 | import org.testng.annotations.BeforeClass;
23 | import org.testng.annotations.Test;
24 |
25 | import com.loiane.dao.EmployeeDao;
26 | import com.loiane.model.Employee;
27 |
28 | public class EmployeeServiceImplTest {
29 |
30 | @Mock
31 | EmployeeDao dao;
32 |
33 | @InjectMocks
34 | EmployeeServiceImpl employeeService;
35 |
36 | @Spy
37 | List employees = new ArrayList();
38 |
39 | @BeforeClass
40 | public void setUp(){
41 | MockitoAnnotations.initMocks(this);
42 | employees = getEmployeeList();
43 | }
44 |
45 | @Test
46 | public void findById(){
47 | Employee emp = employees.get(0);
48 | when(dao.findById(anyInt())).thenReturn(emp);
49 | Assert.assertEquals(employeeService.findById(emp.getId()),emp);
50 | }
51 |
52 | @Test
53 | public void saveEmployee(){
54 | doNothing().when(dao).saveEmployee(any(Employee.class));
55 | employeeService.saveEmployee(any(Employee.class));
56 | verify(dao, atLeastOnce()).saveEmployee(any(Employee.class));
57 | }
58 |
59 | @Test
60 | public void updateEmployee(){
61 | Employee emp = employees.get(0);
62 | when(dao.findById(anyInt())).thenReturn(emp);
63 | employeeService.updateEmployee(emp);
64 | verify(dao, atLeastOnce()).findById(anyInt());
65 | }
66 |
67 | @Test
68 | public void deleteEmployeeBySsn(){
69 | doNothing().when(dao).deleteEmployeeBySsn(anyString());
70 | employeeService.deleteEmployeeBySsn(anyString());
71 | verify(dao, atLeastOnce()).deleteEmployeeBySsn(anyString());
72 | }
73 |
74 | @Test
75 | public void findAllEmployees(){
76 | when(dao.findAllEmployees()).thenReturn(employees);
77 | Assert.assertEquals(employeeService.findAllEmployees(), employees);
78 | }
79 |
80 | @Test
81 | public void findEmployeeBySsn(){
82 | Employee emp = employees.get(0);
83 | when(dao.findEmployeeBySsn(anyString())).thenReturn(emp);
84 | Assert.assertEquals(employeeService.findEmployeeBySsn(anyString()), emp);
85 | }
86 |
87 | @Test
88 | public void isEmployeeSsnUnique(){
89 | Employee emp = employees.get(0);
90 | when(dao.findEmployeeBySsn(anyString())).thenReturn(emp);
91 | Assert.assertEquals(employeeService.isEmployeeSsnUnique(emp.getId(), emp.getSsn()), true);
92 | }
93 |
94 |
95 | public List getEmployeeList(){
96 | Employee e1 = new Employee();
97 | e1.setId(1);
98 | e1.setName("Axel");
99 | e1.setJoiningDate(new LocalDate());
100 | e1.setSalary(new BigDecimal(10000));
101 | e1.setSsn("XXX111");
102 |
103 | Employee e2 = new Employee();
104 | e2.setId(2);
105 | e2.setName("Jeremy");
106 | e2.setJoiningDate(new LocalDate());
107 | e2.setSalary(new BigDecimal(20000));
108 | e2.setSsn("XXX222");
109 |
110 | employees.add(e1);
111 | employees.add(e2);
112 | return employees;
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/spring4-hibernate4-crud/src/test/resources/Employee.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spring4-rest-crud/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring4-rest-crud/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | spring4-rest-crud
6 | war
7 | 1.0-SNAPSHOT
8 | spring4-rest-crud Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | 4.2.0.RELEASE
13 |
14 |
15 |
16 |
17 | org.springframework
18 | spring-core
19 | ${springframework.version}
20 |
21 |
22 | org.springframework
23 | spring-web
24 | ${springframework.version}
25 |
26 |
27 | org.springframework
28 | spring-webmvc
29 | ${springframework.version}
30 |
31 |
32 | org.springframework
33 | spring-tx
34 | ${springframework.version}
35 |
36 |
37 |
38 | javax.servlet
39 | javax.servlet-api
40 | 3.1.0
41 |
42 |
43 | javax.servlet.jsp.jstl
44 | jstl-api
45 | 1.2
46 |
47 |
48 |
49 | javax.servlet.jsp
50 | javax.servlet.jsp-api
51 | 2.3.1
52 |
53 |
54 |
55 | org.codehaus.jackson
56 | jackson-mapper-asl
57 | 1.9.13
58 |
59 |
60 |
61 | com.fasterxml.jackson.core
62 | jackson-databind
63 | 2.6.0
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | org.apache.maven.plugins
73 | maven-war-plugin
74 | 2.4
75 |
76 | src/main/webapp
77 | spring4-rest-crud
78 | false
79 |
80 |
81 |
82 |
83 |
84 | spring4-rest-crud
85 |
86 |
87 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/config/HelloWorldConfig.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
6 |
7 | @Configuration
8 | @EnableWebMvc
9 | @ComponentScan(basePackages = "com.loiane")
10 | public class HelloWorldConfig {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/config/HelloWorldInit.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.web.WebApplicationInitializer;
4 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
5 | import org.springframework.web.servlet.DispatcherServlet;
6 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
7 |
8 | import javax.servlet.ServletContext;
9 | import javax.servlet.ServletException;
10 | import javax.servlet.ServletRegistration;
11 |
12 | public class HelloWorldInit extends AbstractAnnotationConfigDispatcherServletInitializer {
13 |
14 | @Override
15 | protected String[] getServletMappings() {
16 | return new String[] { "/" };
17 | }
18 |
19 | @Override
20 | protected Class>[] getRootConfigClasses() {
21 | return new Class[] { HelloWorldConfig.class };
22 | }
23 |
24 | @Override
25 | protected Class>[] getServletConfigClasses() {
26 | return null;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/controller/HelloWorldRestController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import com.loiane.model.Message;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | @RestController
9 | public class HelloWorldRestController {
10 |
11 | @RequestMapping("/hello/{name}")
12 | public Message message(@PathVariable String name) {
13 |
14 | Message msg = new Message(name, "Hello " + name);
15 | return msg;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/controller/UserRestController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import com.loiane.model.User;
4 | import com.loiane.service.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpHeaders;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.MediaType;
9 | import org.springframework.http.ResponseEntity;
10 | import org.springframework.web.bind.annotation.*;
11 | import org.springframework.web.util.UriComponentsBuilder;
12 |
13 | import java.util.List;
14 |
15 | @RestController
16 | public class UserRestController {
17 |
18 | @Autowired
19 | UserService userService;
20 |
21 | @RequestMapping(value = "/user/", method = RequestMethod.GET)
22 | public ResponseEntity> listAllUsers() {
23 | List users = userService.findAllUsers();
24 | if(users.isEmpty()){
25 | return new ResponseEntity>(HttpStatus.NO_CONTENT); //You many decide to return HttpStatus.NOT_FOUND
26 | }
27 | return new ResponseEntity>(users, HttpStatus.OK);
28 | }
29 |
30 | @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
31 | public ResponseEntity getUser(@PathVariable("id") long id) {
32 | System.out.println("Fetching User with id " + id);
33 | User user = userService.findById(id);
34 | if (user == null) {
35 | System.out.println("User with id " + id + " not found");
36 | return new ResponseEntity(HttpStatus.NOT_FOUND);
37 | }
38 | return new ResponseEntity(user, HttpStatus.OK);
39 | }
40 |
41 | @RequestMapping(value = "/user/", method = RequestMethod.POST)
42 | public ResponseEntity createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
43 | System.out.println("Creating User " + user.getName());
44 |
45 | if (userService.isUserExist(user)) {
46 | System.out.println("A User with name " + user.getName() + " already exist");
47 | return new ResponseEntity(HttpStatus.CONFLICT);
48 | }
49 |
50 | userService.saveUser(user);
51 |
52 | HttpHeaders headers = new HttpHeaders();
53 | headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
54 | return new ResponseEntity(headers, HttpStatus.CREATED);
55 | }
56 |
57 | @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
58 | public ResponseEntity updateUser(@PathVariable("id") long id, @RequestBody User user) {
59 | System.out.println("Updating User " + id);
60 |
61 | User currentUser = userService.findById(id);
62 |
63 | if (currentUser==null) {
64 | System.out.println("User with id " + id + " not found");
65 | return new ResponseEntity(HttpStatus.NOT_FOUND);
66 | }
67 |
68 | currentUser.setName(user.getName());
69 |
70 | userService.updateUser(currentUser);
71 | return new ResponseEntity(currentUser, HttpStatus.OK);
72 | }
73 |
74 | @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
75 | public ResponseEntity deleteUser(@PathVariable("id") long id) {
76 | System.out.println("Fetching & Deleting User with id " + id);
77 |
78 | User user = userService.findById(id);
79 | if (user == null) {
80 | System.out.println("Unable to delete. User with id " + id + " not found");
81 | return new ResponseEntity(HttpStatus.NOT_FOUND);
82 | }
83 |
84 | userService.deleteUserById(id);
85 | return new ResponseEntity(HttpStatus.NO_CONTENT);
86 | }
87 |
88 | @RequestMapping(value = "/user/", method = RequestMethod.DELETE)
89 | public ResponseEntity deleteAllUsers() {
90 | System.out.println("Deleting All Users");
91 |
92 | userService.deleteAllUsers();
93 | return new ResponseEntity(HttpStatus.NO_CONTENT);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/model/Message.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | public class Message {
4 |
5 | private String name;
6 | private String text;
7 |
8 | public Message() {}
9 |
10 | public Message(String name, String text) {
11 | this.name = name;
12 | this.text = text;
13 | }
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public void setName(String name) {
20 | this.name = name;
21 | }
22 |
23 | public String getText() {
24 | return text;
25 | }
26 |
27 | public void setText(String text) {
28 | this.text = text;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/model/User.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | public class User {
4 |
5 | private long id;
6 |
7 | private String name;
8 |
9 | public User(long id, String name) {
10 | this.id = id;
11 | this.name = name;
12 | }
13 |
14 | public User() {}
15 |
16 | public long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(long id) {
21 | this.id = id;
22 | }
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public void setName(String name) {
29 | this.name = name;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/main/java/com/loiane/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import com.loiane.model.User;
4 | import org.springframework.stereotype.Service;
5 | import org.springframework.transaction.annotation.Transactional;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Iterator;
9 | import java.util.List;
10 | import java.util.concurrent.atomic.AtomicLong;
11 |
12 | @Service("userService")
13 | @Transactional
14 | public class UserService {
15 |
16 | private static final AtomicLong counter = new AtomicLong();
17 |
18 | private static List users;
19 |
20 | static{
21 | users= populateDummyUsers();
22 | }
23 |
24 | public List findAllUsers() {
25 | return users;
26 | }
27 |
28 | public User findById(long id) {
29 | for(User user : users){
30 | if(user.getId() == id){
31 | return user;
32 | }
33 | }
34 | return null;
35 | }
36 |
37 | public User findByName(String name) {
38 | for(User user : users){
39 | if(user.getName().equalsIgnoreCase(name)){
40 | return user;
41 | }
42 | }
43 | return null;
44 | }
45 |
46 | public void saveUser(User user) {
47 | user.setId(counter.incrementAndGet());
48 | users.add(user);
49 | }
50 |
51 | public void updateUser(User user) {
52 | int index = users.indexOf(user);
53 | users.set(index, user);
54 | }
55 |
56 | public void deleteUserById(long id) {
57 |
58 | for (Iterator iterator = users.iterator(); iterator.hasNext(); ) {
59 | User user = iterator.next();
60 | if (user.getId() == id) {
61 | iterator.remove();
62 | }
63 | }
64 | }
65 |
66 | public boolean isUserExist(User user) {
67 | return findByName(user.getName())!=null;
68 | }
69 |
70 | private static List populateDummyUsers(){
71 | List users = new ArrayList();
72 | users.add(new User(counter.incrementAndGet(),"Gandalf"));
73 | users.add(new User(counter.incrementAndGet(),"Frodo"));
74 | users.add(new User(counter.incrementAndGet(),"Legolas"));
75 | users.add(new User(counter.incrementAndGet(), "Sam"));
76 | return users;
77 | }
78 |
79 | public void deleteAllUsers() {
80 | users.clear();
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/spring4-rest-crud/src/test/com/loiane/UserRestTest.java:
--------------------------------------------------------------------------------
1 | package com.loiane;
2 |
3 | import com.loiane.model.User;
4 | import org.springframework.web.client.RestTemplate;
5 |
6 | import java.net.URI;
7 | import java.util.LinkedHashMap;
8 | import java.util.List;
9 |
10 | public class UserRestTest {
11 |
12 | public static final String REST_SERVICE_URI = "http://localhost:8080/spring4-rest-crud";
13 |
14 | /* GET */
15 | @SuppressWarnings("unchecked")
16 | private static void listAllUsers(){
17 | System.out.println("Testing listAllUsers API-----------");
18 |
19 | RestTemplate restTemplate = new RestTemplate();
20 | List> usersMap = restTemplate.getForObject(REST_SERVICE_URI+"/user/", List.class);
21 |
22 | if(usersMap!=null){
23 | for(LinkedHashMap map : usersMap){
24 | System.out.println("User : id="+map.get("id")+", Name="+map.get("name"));;
25 | }
26 | }else{
27 | System.out.println("No user exist----------");
28 | }
29 | }
30 |
31 | /* GET */
32 | private static void getUser(){
33 | System.out.println("Testing getUser API----------");
34 | RestTemplate restTemplate = new RestTemplate();
35 | User user = restTemplate.getForObject(REST_SERVICE_URI+"/user/1", User.class);
36 | System.out.println(user);
37 | }
38 |
39 | /* POST */
40 | private static void createUser() {
41 | System.out.println("Testing create User API----------");
42 | RestTemplate restTemplate = new RestTemplate();
43 | User user = new User(0,"Saruman");
44 | URI uri = restTemplate.postForLocation(REST_SERVICE_URI+"/user/", user, User.class);
45 | System.out.println("Location : "+uri.toASCIIString());
46 | }
47 |
48 | /* PUT */
49 | private static void updateUser() {
50 | System.out.println("Testing update User API----------");
51 | RestTemplate restTemplate = new RestTemplate();
52 | User user = new User(1,"Liriel");
53 | restTemplate.put(REST_SERVICE_URI+"/user/1", user);
54 | System.out.println(user);
55 | }
56 |
57 | /* DELETE */
58 | private static void deleteUser() {
59 | System.out.println("Testing delete User API----------");
60 | RestTemplate restTemplate = new RestTemplate();
61 | restTemplate.delete(REST_SERVICE_URI+"/user/3");
62 | }
63 |
64 |
65 | /* DELETE */
66 | private static void deleteAllUsers() {
67 | System.out.println("Testing all delete Users API----------");
68 | RestTemplate restTemplate = new RestTemplate();
69 | restTemplate.delete(REST_SERVICE_URI+"/user/");
70 | }
71 |
72 | public static void main(String args[]){
73 | listAllUsers();
74 | getUser();
75 | createUser();
76 | listAllUsers();
77 | updateUser();
78 | listAllUsers();
79 | deleteUser();
80 | listAllUsers();
81 | deleteAllUsers();
82 | listAllUsers();
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/spring4-rest-hello/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring4-rest-hello/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | spring4-rest-hello
6 | war
7 | 1.0-SNAPSHOT
8 | spring4-rest-hello Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | 4.2.0.RELEASE
13 |
14 |
15 |
16 |
17 | org.springframework
18 | spring-core
19 | ${springframework.version}
20 |
21 |
22 | org.springframework
23 | spring-web
24 | ${springframework.version}
25 |
26 |
27 | org.springframework
28 | spring-webmvc
29 | ${springframework.version}
30 |
31 |
32 |
33 | javax.servlet
34 | javax.servlet-api
35 | 3.1.0
36 |
37 |
38 | javax.servlet.jsp.jstl
39 | jstl-api
40 | 1.2
41 |
42 |
43 |
44 | javax.servlet.jsp
45 | javax.servlet.jsp-api
46 | 2.3.1
47 |
48 |
49 |
50 | org.codehaus.jackson
51 | jackson-mapper-asl
52 | 1.9.13
53 |
54 |
55 |
56 | com.fasterxml.jackson.core
57 | jackson-databind
58 | 2.6.0
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | org.apache.maven.plugins
68 | maven-war-plugin
69 | 2.4
70 |
71 | src/main/webapp
72 | spring4-rest-hello
73 | false
74 |
75 |
76 |
77 |
78 |
79 | spring4-rest-hello
80 |
81 |
82 |
--------------------------------------------------------------------------------
/spring4-rest-hello/src/main/java/com/loiane/config/HelloWorldConfig.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
6 |
7 | @Configuration
8 | @EnableWebMvc
9 | @ComponentScan(basePackages = "com.loiane")
10 | public class HelloWorldConfig {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring4-rest-hello/src/main/java/com/loiane/config/HelloWorldInit.java:
--------------------------------------------------------------------------------
1 | package com.loiane.config;
2 |
3 | import org.springframework.web.WebApplicationInitializer;
4 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
5 | import org.springframework.web.servlet.DispatcherServlet;
6 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
7 |
8 | import javax.servlet.ServletContext;
9 | import javax.servlet.ServletException;
10 | import javax.servlet.ServletRegistration;
11 |
12 | public class HelloWorldInit extends AbstractAnnotationConfigDispatcherServletInitializer {
13 |
14 | @Override
15 | protected String[] getServletMappings() {
16 | return new String[] { "/" };
17 | }
18 |
19 | @Override
20 | protected Class>[] getRootConfigClasses() {
21 | return new Class[] { HelloWorldConfig.class };
22 | }
23 |
24 | @Override
25 | protected Class>[] getServletConfigClasses() {
26 | return null;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/spring4-rest-hello/src/main/java/com/loiane/controller/HelloWorldRestController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import com.loiane.model.Message;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | @RestController
9 | public class HelloWorldRestController {
10 |
11 | @RequestMapping("/hello/{name}")
12 | public Message message(@PathVariable String name) {
13 |
14 | Message msg = new Message(name, "Hello " + name);
15 | return msg;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/spring4-rest-hello/src/main/java/com/loiane/model/Message.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | public class Message {
4 |
5 | private String name;
6 | private String text;
7 |
8 | public Message() {}
9 |
10 | public Message(String name, String text) {
11 | this.name = name;
12 | this.text = text;
13 | }
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public void setName(String name) {
20 | this.name = name;
21 | }
22 |
23 | public String getText() {
24 | return text;
25 | }
26 |
27 | public void setText(String text) {
28 | this.text = text;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
4 |
5 | target/*
6 |
7 | *.iml
8 |
9 | ## Directory-based project format:
10 | .idea/
11 | # if you remove the above rule, at least ignore the following:
12 |
13 | # User-specific stuff:
14 | # .idea/workspace.xml
15 | # .idea/tasks.xml
16 | # .idea/dictionaries
17 |
18 | # Sensitive or high-churn files:
19 | # .idea/dataSources.ids
20 | # .idea/dataSources.xml
21 | # .idea/sqlDataSources.xml
22 | # .idea/dynamic.xml
23 | # .idea/uiDesigner.xml
24 |
25 | # Gradle:
26 | # .idea/gradle.xml
27 | # .idea/libraries
28 |
29 | # Mongo Explorer plugin:
30 | # .idea/mongoSettings.xml
31 |
32 | ## File-based project format:
33 | *.ipr
34 | *.iws
35 |
36 | ## Plugin-specific files:
37 |
38 | # IntelliJ
39 | out/
40 |
41 | # mpeltonen/sbt-idea plugin
42 | .idea_modules/
43 |
44 | # JIRA plugin
45 | atlassian-ide-plugin.xml
46 |
47 | # Crashlytics plugin (for Android Studio and IntelliJ)
48 | com_crashlytics_export_strings.xml
49 | crashlytics.properties
50 | crashlytics-build.properties
51 |
52 |
53 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/db-scripts/script.sql:
--------------------------------------------------------------------------------
1 | /*All User's are stored in APP_USER table*/
2 | create table APP_USER (
3 | id BIGINT NOT NULL AUTO_INCREMENT,
4 | sso_id VARCHAR(30) NOT NULL,
5 | password VARCHAR(100) NOT NULL,
6 | first_name VARCHAR(30) NOT NULL,
7 | last_name VARCHAR(30) NOT NULL,
8 | email VARCHAR(30) NOT NULL,
9 | state VARCHAR(30) NOT NULL,
10 | PRIMARY KEY (id),
11 | UNIQUE (sso_id)
12 | );
13 |
14 | /* USER_PROFILE table contains all possible roles */
15 | create table USER_PROFILE(
16 | id BIGINT NOT NULL AUTO_INCREMENT,
17 | type VARCHAR(30) NOT NULL,
18 | PRIMARY KEY (id),
19 | UNIQUE (type)
20 | );
21 |
22 | /* JOIN TABLE for MANY-TO-MANY relationship*/
23 | CREATE TABLE APP_USER_USER_PROFILE (
24 | user_id BIGINT NOT NULL,
25 | user_profile_id BIGINT NOT NULL,
26 | PRIMARY KEY (user_id, user_profile_id),
27 | CONSTRAINT FK_APP_USER FOREIGN KEY (user_id) REFERENCES APP_USER (id),
28 | CONSTRAINT FK_USER_PROFILE FOREIGN KEY (user_profile_id) REFERENCES USER_PROFILE (id)
29 | );
30 |
31 | /* Populate USER_PROFILE Table */
32 | INSERT INTO USER_PROFILE(type)
33 | VALUES ('USER');
34 |
35 | INSERT INTO USER_PROFILE(type)
36 | VALUES ('ADMIN');
37 |
38 | INSERT INTO USER_PROFILE(type)
39 | VALUES ('DBA');
40 |
41 | /* Populate APP_USER Table */
42 | INSERT INTO APP_USER(sso_id, password, first_name, last_name, email, state)
43 | VALUES ('bill','abc123', 'Bill','Watcher','bill@xyz.com', 'Active');
44 |
45 | INSERT INTO APP_USER(sso_id, password, first_name, last_name, email, state)
46 | VALUES ('danny','abc124', 'Danny','Theys','danny@xyz.com', 'Active');
47 |
48 | INSERT INTO APP_USER(sso_id, password, first_name, last_name, email, state)
49 | VALUES ('sam','abc125', 'Sam','Smith','samy@xyz.com', 'Active');
50 |
51 | INSERT INTO APP_USER(sso_id, password, first_name, last_name, email, state)
52 | VALUES ('nicole','abc126', 'Nicole','warner','nicloe@xyz.com', 'Active');
53 |
54 | INSERT INTO APP_USER(sso_id, password, first_name, last_name, email, state)
55 | VALUES ('kenny','abc127', 'Kenny','Roger','kenny@xyz.com', 'Active');
56 |
57 | /* Populate JOIN Table */
58 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
59 | SELECT user.id, profile.id FROM app_user user, user_profile profile
60 | where user.sso_id='bill' and profile.type='USER';
61 |
62 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
63 | SELECT user.id, profile.id FROM app_user user, user_profile profile
64 | where user.sso_id='danny' and profile.type='USER';
65 |
66 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
67 | SELECT user.id, profile.id FROM app_user user, user_profile profile
68 | where user.sso_id='sam' and profile.type='ADMIN';
69 |
70 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
71 | SELECT user.id, profile.id FROM app_user user, user_profile profile
72 | where user.sso_id='nicole' and profile.type='DBA';
73 |
74 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
75 | SELECT user.id, profile.id FROM app_user user, user_profile profile
76 | where user.sso_id='kenny' and profile.type='ADMIN';
77 |
78 | INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
79 | SELECT user.id, profile.id FROM app_user user, user_profile profile
80 | where user.sso_id='kenny' and profile.type='DBA';
81 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.loiane
5 | springsecurity-hibernate
6 | war
7 | 1.0-SNAPSHOT
8 | springsecurity-hibernate Maven Webapp
9 | http://maven.apache.org
10 |
11 | 4.1.6.RELEASE
12 | 4.0.1.RELEASE
13 | 4.3.6.Final
14 | 5.1.31
15 |
16 |
17 |
18 |
19 |
20 |
21 | org.springframework
22 | spring-core
23 | ${springframework.version}
24 |
25 |
26 | org.springframework
27 | spring-web
28 | ${springframework.version}
29 |
30 |
31 | org.springframework
32 | spring-webmvc
33 | ${springframework.version}
34 |
35 |
36 | org.springframework
37 | spring-tx
38 | ${springframework.version}
39 |
40 |
41 | org.springframework
42 | spring-orm
43 | ${springframework.version}
44 |
45 |
46 |
47 |
48 |
49 | org.springframework.security
50 | spring-security-web
51 | ${springsecurity.version}
52 |
53 |
54 | org.springframework.security
55 | spring-security-config
56 | ${springsecurity.version}
57 |
58 |
59 |
60 |
61 | org.hibernate
62 | hibernate-core
63 | ${hibernate.version}
64 |
65 |
66 |
67 |
68 | mysql
69 | mysql-connector-java
70 | ${mysql.connector.version}
71 |
72 |
73 |
74 | javax.servlet
75 | javax.servlet-api
76 | 3.1.0
77 |
78 |
79 | javax.servlet.jsp
80 | javax.servlet.jsp-api
81 | 2.3.1
82 |
83 |
84 | javax.servlet
85 | jstl
86 | 1.2
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 | org.apache.maven.plugins
95 | maven-war-plugin
96 | 2.4
97 |
98 | src/main/webapp
99 | springsecurity-hibernate
100 | false
101 |
102 |
103 |
104 |
105 | springsecurity-hibernate
106 |
107 |
108 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/configuration/HelloWorldConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.ComponentScan;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.web.servlet.ViewResolver;
7 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
10 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
11 | import org.springframework.web.servlet.view.JstlView;
12 |
13 | @Configuration
14 | @EnableWebMvc
15 | @ComponentScan(basePackages = "com.loiane")
16 | public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {
17 |
18 | @Bean(name="HelloWorld")
19 | public ViewResolver viewResolver() {
20 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
21 | viewResolver.setViewClass(JstlView.class);
22 | viewResolver.setPrefix("/WEB-INF/views/");
23 | viewResolver.setSuffix(".jsp");
24 |
25 | return viewResolver;
26 | }
27 |
28 | /*
29 | * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
30 | *
31 | */
32 | @Override
33 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
34 | registry.addResourceHandler("/static/**").addResourceLocations("/static/");
35 | }
36 | }
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/configuration/HibernateConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import java.util.Properties;
4 |
5 | import javax.sql.DataSource;
6 |
7 | import org.hibernate.SessionFactory;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.ComponentScan;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.context.annotation.PropertySource;
13 | import org.springframework.core.env.Environment;
14 | import org.springframework.jdbc.datasource.DriverManagerDataSource;
15 | import org.springframework.orm.hibernate4.HibernateTransactionManager;
16 | import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
17 | import org.springframework.transaction.annotation.EnableTransactionManagement;
18 |
19 | @Configuration
20 | @EnableTransactionManagement
21 | @ComponentScan({"com.loiane.configuration"})
22 | @PropertySource(value = { "classpath:application.properties" })
23 | public class HibernateConfiguration {
24 |
25 | @Autowired
26 | private Environment environment;
27 |
28 | @Bean
29 | public LocalSessionFactoryBean sessionFactory() {
30 | LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
31 | sessionFactory.setDataSource(dataSource());
32 | sessionFactory.setPackagesToScan(new String[] { "com.loiane.model" });
33 | sessionFactory.setHibernateProperties(hibernateProperties());
34 | return sessionFactory;
35 | }
36 |
37 | @Bean
38 | public DataSource dataSource() {
39 | DriverManagerDataSource dataSource = new DriverManagerDataSource();
40 | dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
41 | dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
42 | dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
43 | dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
44 | return dataSource;
45 | }
46 |
47 | private Properties hibernateProperties() {
48 | Properties properties = new Properties();
49 | properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
50 | properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
51 | properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
52 | return properties;
53 | }
54 |
55 | @Bean
56 | @Autowired
57 | public HibernateTransactionManager transactionManager(SessionFactory s) {
58 | HibernateTransactionManager txManager = new HibernateTransactionManager();
59 | txManager.setSessionFactory(s);
60 | return txManager;
61 | }
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/configuration/SecurityConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.beans.factory.annotation.Qualifier;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10 | import org.springframework.security.core.userdetails.UserDetailsService;
11 |
12 | @Configuration
13 | @EnableWebSecurity
14 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
15 |
16 | @Autowired
17 | @Qualifier("customUserDetailsService")
18 | UserDetailsService userDetailsService;
19 |
20 | @Autowired
21 | public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
22 | auth.userDetailsService(userDetailsService);
23 | }
24 |
25 | @Override
26 | protected void configure(HttpSecurity http) throws Exception {
27 | http.authorizeRequests()
28 | .antMatchers("/", "/home").permitAll()
29 | .antMatchers("/admin/**").access("hasRole('ADMIN')")
30 | .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
31 | .and().formLogin().loginPage("/login")
32 | .usernameParameter("ssoId").passwordParameter("password")
33 | .and().csrf()
34 | .and().exceptionHandling().accessDeniedPage("/Access_Denied");
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/configuration/SecurityWebApplicationInitializer.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
4 |
5 | public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/configuration/SpringMvcInitializer.java:
--------------------------------------------------------------------------------
1 | package com.loiane.configuration;
2 |
3 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
4 |
5 | public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
6 |
7 | @Override
8 | protected Class>[] getRootConfigClasses() {
9 | return new Class[] { HelloWorldConfiguration.class };
10 | }
11 |
12 | @Override
13 | protected Class>[] getServletConfigClasses() {
14 | return null;
15 | }
16 |
17 | @Override
18 | protected String[] getServletMappings() {
19 | return new String[] { "/" };
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/controller/HelloWorldController.java:
--------------------------------------------------------------------------------
1 | package com.loiane.controller;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 | import javax.servlet.http.HttpServletResponse;
5 |
6 | import org.springframework.security.core.Authentication;
7 | import org.springframework.security.core.context.SecurityContextHolder;
8 | import org.springframework.security.core.userdetails.UserDetails;
9 | import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
10 | import org.springframework.stereotype.Controller;
11 | import org.springframework.ui.ModelMap;
12 | import org.springframework.web.bind.annotation.RequestMapping;
13 | import org.springframework.web.bind.annotation.RequestMethod;
14 |
15 | @Controller
16 | public class HelloWorldController {
17 |
18 |
19 | @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
20 | public String homePage(ModelMap model) {
21 | model.addAttribute("greeting", "Hi, Welcome to mysite");
22 | return "welcome";
23 | }
24 |
25 | @RequestMapping(value = "/admin", method = RequestMethod.GET)
26 | public String adminPage(ModelMap model) {
27 | model.addAttribute("user", getPrincipal());
28 | return "admin";
29 | }
30 |
31 | @RequestMapping(value = "/db", method = RequestMethod.GET)
32 | public String dbaPage(ModelMap model) {
33 | model.addAttribute("user", getPrincipal());
34 | return "dba";
35 | }
36 |
37 | @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
38 | public String accessDeniedPage(ModelMap model) {
39 | model.addAttribute("user", getPrincipal());
40 | return "accessDenied";
41 | }
42 |
43 | @RequestMapping(value = "/login", method = RequestMethod.GET)
44 | public String loginPage() {
45 | return "login";
46 | }
47 |
48 | @RequestMapping(value="/logout", method = RequestMethod.GET)
49 | public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
50 | Authentication auth = SecurityContextHolder.getContext().getAuthentication();
51 | if (auth != null){
52 | new SecurityContextLogoutHandler().logout(request, response, auth);
53 | }
54 | return "redirect:/login?logout";
55 | }
56 |
57 | private String getPrincipal(){
58 | String userName = null;
59 | Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
60 |
61 | if (principal instanceof UserDetails) {
62 | userName = ((UserDetails)principal).getUsername();
63 | } else {
64 | userName = principal.toString();
65 | }
66 | return userName;
67 | }
68 |
69 |
70 | }
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/dao/AbstractDao.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import java.io.Serializable;
4 |
5 | import java.lang.reflect.ParameterizedType;
6 |
7 | import org.hibernate.Criteria;
8 | import org.hibernate.Session;
9 | import org.hibernate.SessionFactory;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 |
12 | public abstract class AbstractDao {
13 |
14 | private final Class persistentClass;
15 |
16 | @SuppressWarnings("unchecked")
17 | public AbstractDao(){
18 | this.persistentClass =(Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
19 | }
20 |
21 | @Autowired
22 | private SessionFactory sessionFactory;
23 |
24 | protected Session getSession(){
25 | return sessionFactory.getCurrentSession();
26 | }
27 |
28 | @SuppressWarnings("unchecked")
29 | public T getByKey(PK key) {
30 | return (T) getSession().get(persistentClass, key);
31 | }
32 |
33 | public void persist(T entity) {
34 | getSession().persist(entity);
35 | }
36 |
37 | public void delete(T entity) {
38 | getSession().delete(entity);
39 | }
40 |
41 | protected Criteria createEntityCriteria(){
42 | return getSession().createCriteria(persistentClass);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/dao/UserDao.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import com.loiane.model.User;
4 |
5 | public interface UserDao {
6 |
7 | User findById(int id);
8 |
9 | User findBySSO(String sso);
10 |
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/dao/UserDaoImpl.java:
--------------------------------------------------------------------------------
1 | package com.loiane.dao;
2 |
3 | import org.hibernate.Criteria;
4 | import org.hibernate.criterion.Restrictions;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import com.loiane.model.User;
8 |
9 | @Repository("userDao")
10 | public class UserDaoImpl extends AbstractDao implements UserDao {
11 |
12 | public User findById(int id) {
13 | return getByKey(id);
14 | }
15 |
16 | public User findBySSO(String sso) {
17 | Criteria crit = createEntityCriteria();
18 | crit.add(Restrictions.eq("ssoId", sso));
19 | return (User) crit.uniqueResult();
20 | }
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/model/State.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | public enum State {
4 |
5 | ACTIVE("Active"),
6 | INACTIVE("Inactive"),
7 | DELETED("Deleted"),
8 | LOCKED("Locked");
9 |
10 | private String state;
11 |
12 | private State(final String state){
13 | this.state = state;
14 | }
15 |
16 | public String getState(){
17 | return this.state;
18 | }
19 |
20 | @Override
21 | public String toString(){
22 | return this.state;
23 | }
24 |
25 | public String getName(){
26 | return this.name();
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/model/User.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.FetchType;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import javax.persistence.JoinColumn;
13 | import javax.persistence.JoinTable;
14 | import javax.persistence.ManyToMany;
15 | import javax.persistence.Table;
16 |
17 | @Entity
18 | @Table(name="APP_USER")
19 | public class User {
20 |
21 | @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
22 | private int id;
23 |
24 | @Column(name="SSO_ID", unique=true, nullable=false)
25 | private String ssoId;
26 |
27 | @Column(name="PASSWORD", nullable=false)
28 | private String password;
29 |
30 | @Column(name="FIRST_NAME", nullable=false)
31 | private String firstName;
32 |
33 | @Column(name="LAST_NAME", nullable=false)
34 | private String lastName;
35 |
36 | @Column(name="EMAIL", nullable=false)
37 | private String email;
38 |
39 | @Column(name="STATE", nullable=false)
40 | private String state=State.ACTIVE.getState();
41 |
42 | @ManyToMany(fetch = FetchType.EAGER)
43 | @JoinTable(name = "APP_USER_USER_PROFILE",
44 | joinColumns = { @JoinColumn(name = "USER_ID") },
45 | inverseJoinColumns = { @JoinColumn(name = "USER_PROFILE_ID") })
46 | private Set userProfiles = new HashSet();
47 |
48 | public int getId() {
49 | return id;
50 | }
51 |
52 | public void setId(int id) {
53 | this.id = id;
54 | }
55 |
56 | public String getSsoId() {
57 | return ssoId;
58 | }
59 |
60 | public void setSsoId(String ssoId) {
61 | this.ssoId = ssoId;
62 | }
63 |
64 | public String getPassword() {
65 | return password;
66 | }
67 |
68 | public void setPassword(String password) {
69 | this.password = password;
70 | }
71 |
72 | public String getFirstName() {
73 | return firstName;
74 | }
75 |
76 | public void setFirstName(String firstName) {
77 | this.firstName = firstName;
78 | }
79 |
80 | public String getLastName() {
81 | return lastName;
82 | }
83 |
84 | public void setLastName(String lastName) {
85 | this.lastName = lastName;
86 | }
87 |
88 | public String getEmail() {
89 | return email;
90 | }
91 |
92 | public void setEmail(String email) {
93 | this.email = email;
94 | }
95 |
96 | public String getState() {
97 | return state;
98 | }
99 |
100 | public void setState(String state) {
101 | this.state = state;
102 | }
103 |
104 | public Set getUserProfiles() {
105 | return userProfiles;
106 | }
107 |
108 | public void setUserProfiles(Set userProfiles) {
109 | this.userProfiles = userProfiles;
110 | }
111 |
112 | @Override
113 | public int hashCode() {
114 | final int prime = 31;
115 | int result = 1;
116 | result = prime * result + id;
117 | result = prime * result + ((ssoId == null) ? 0 : ssoId.hashCode());
118 | return result;
119 | }
120 |
121 | @Override
122 | public boolean equals(Object obj) {
123 | if (this == obj)
124 | return true;
125 | if (obj == null)
126 | return false;
127 | if (!(obj instanceof User))
128 | return false;
129 | User other = (User) obj;
130 | if (id != other.id)
131 | return false;
132 | if (ssoId == null) {
133 | if (other.ssoId != null)
134 | return false;
135 | } else if (!ssoId.equals(other.ssoId))
136 | return false;
137 | return true;
138 | }
139 |
140 | @Override
141 | public String toString() {
142 | return "User [id=" + id + ", ssoId=" + ssoId + ", password=" + password
143 | + ", firstName=" + firstName + ", lastName=" + lastName
144 | + ", email=" + email + ", state=" + state + ", userProfiles=" + userProfiles +"]";
145 | }
146 |
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/model/UserProfile.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | @Entity
11 | @Table(name="USER_PROFILE")
12 | public class UserProfile {
13 |
14 | @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
15 | private int id;
16 |
17 | @Column(name="TYPE", length=15, unique=true, nullable=false)
18 | private String type = UserProfileType.USER.getUserProfileType();
19 |
20 | public int getId() {
21 | return id;
22 | }
23 |
24 | public void setId(int id) {
25 | this.id = id;
26 | }
27 |
28 | public String getType() {
29 | return type;
30 | }
31 |
32 | public void setType(String type) {
33 | this.type = type;
34 | }
35 |
36 |
37 | @Override
38 | public int hashCode() {
39 | final int prime = 31;
40 | int result = 1;
41 | result = prime * result + id;
42 | result = prime * result + ((type == null) ? 0 : type.hashCode());
43 | return result;
44 | }
45 |
46 | @Override
47 | public boolean equals(Object obj) {
48 | if (this == obj)
49 | return true;
50 | if (obj == null)
51 | return false;
52 | if (!(obj instanceof UserProfile))
53 | return false;
54 | UserProfile other = (UserProfile) obj;
55 | if (id != other.id)
56 | return false;
57 | if (type == null) {
58 | if (other.type != null)
59 | return false;
60 | } else if (!type.equals(other.type))
61 | return false;
62 | return true;
63 | }
64 |
65 | @Override
66 | public String toString() {
67 | return "UserProfile [id=" + id + ", type=" + type + "]";
68 | }
69 |
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/model/UserProfileType.java:
--------------------------------------------------------------------------------
1 | package com.loiane.model;
2 |
3 | public enum UserProfileType {
4 | USER("USER"),
5 | DBA("DBA"),
6 | ADMIN("ADMIN");
7 |
8 | String userProfileType;
9 |
10 | private UserProfileType(String userProfileType){
11 | this.userProfileType = userProfileType;
12 | }
13 |
14 | public String getUserProfileType(){
15 | return userProfileType;
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/service/CustomUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.security.core.GrantedAuthority;
8 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 | import org.springframework.security.core.userdetails.UserDetailsService;
11 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
12 | import org.springframework.stereotype.Service;
13 | import org.springframework.transaction.annotation.Transactional;
14 |
15 | import com.loiane.model.User;
16 | import com.loiane.model.UserProfile;
17 |
18 | @Service("customUserDetailsService")
19 | public class CustomUserDetailsService implements UserDetailsService{
20 |
21 | @Autowired
22 | private UserService userService;
23 |
24 | @Transactional(readOnly=true)
25 | public UserDetails loadUserByUsername(String ssoId)
26 | throws UsernameNotFoundException {
27 | User user = userService.findBySso(ssoId);
28 | System.out.println("User : "+user);
29 | if(user==null){
30 | System.out.println("User not found");
31 | throw new UsernameNotFoundException("Username not found");
32 | }
33 | return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
34 | user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user));
35 | }
36 |
37 |
38 | private List getGrantedAuthorities(User user){
39 | List authorities = new ArrayList();
40 |
41 | for(UserProfile userProfile : user.getUserProfiles()){
42 | System.out.println("UserProfile : "+userProfile);
43 | authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
44 | }
45 | System.out.print("authorities :"+authorities);
46 | return authorities;
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import com.loiane.model.User;
4 |
5 | public interface UserService {
6 |
7 | User findById(int id);
8 |
9 | User findBySso(String sso);
10 |
11 | }
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/java/com/loiane/service/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.loiane.service;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Service;
5 | import org.springframework.transaction.annotation.Transactional;
6 |
7 | import com.loiane.dao.UserDao;
8 | import com.loiane.model.User;
9 |
10 | @Service("userService")
11 | @Transactional
12 | public class UserServiceImpl implements UserService{
13 |
14 | @Autowired
15 | private UserDao dao;
16 |
17 | public User findById(int id) {
18 | return dao.findById(id);
19 | }
20 |
21 | public User findBySso(String sso) {
22 | return dao.findBySSO(sso);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | jdbc.driverClassName = com.mysql.jdbc.Driver
2 | jdbc.url = jdbc:mysql://localhost:3306/blog
3 | jdbc.username = root
4 | jdbc.password =
5 | hibernate.dialect = org.hibernate.dialect.MySQLDialect
6 | hibernate.show_sql = true
7 | hibernate.format_sql = true
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/WEB-INF/views/accessDenied.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 |
4 |
5 |
6 | AccessDenied page
7 |
8 |
9 | Dear ${user}, You are not authorized to access this page
10 | ">Logout
11 |
12 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/WEB-INF/views/admin.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 |
4 |
5 |
6 | Admin page
7 |
8 |
9 | Dear ${user}, Welcome to Admin Page.
10 | ">Logout
11 |
12 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/WEB-INF/views/dba.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 |
4 |
5 |
6 | DBA page
7 |
8 |
9 | Dear ${user}, Welcome to DBA Page.
10 | ">Logout
11 |
12 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/WEB-INF/views/login.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 |
4 |
5 |
6 | Login page
7 |
8 |
9 |
10 |
11 |
12 |
13 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/WEB-INF/views/welcome.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2 |
3 |
4 |
5 | Welcome page
6 |
7 |
8 | Greeting : ${greeting}
9 | This is a welcome page.
10 |
11 |
--------------------------------------------------------------------------------
/springsecurity-hibernate/src/main/webapp/static/css/app.css:
--------------------------------------------------------------------------------
1 |
2 | html{
3 | background-color:#2F2F2F;
4 | }
5 |
6 | body, #mainWrapper {
7 | height: 100%;
8 | background-image: -webkit-gradient(
9 | linear,
10 | right bottom,
11 | right top,
12 | color-stop(0, #EDEDED),
13 | color-stop(0.08, #EAEAEA),
14 | color-stop(1, #2F2F2F),
15 | color-stop(1, #AAAAAA)
16 | );
17 | background-image: -o-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
18 | background-image: -moz-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
19 | background-image: -webkit-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
20 | background-image: -ms-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
21 | background-image: linear-gradient(to top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
22 | }
23 |
24 | body, #mainWrapper, .form-control{
25 | font-size:12px!important;
26 | }
27 |
28 | #mainWrapper {
29 | /*height: 720px; Without explicit px values, % in children's does not work*/
30 | height: 100vh; /*with Viewport-Percentage, we can handles all devices screens */
31 | padding-left:10px;
32 | padding-right:10px;
33 | padding-bottom:10px;
34 | }
35 |
36 | .login-container {
37 | margin-top: 100px;
38 | background-color: floralwhite;
39 | width: 40%;
40 | left: 30%;
41 | position: absolute;
42 | }
43 |
44 | .login-card {
45 | width: 80%;
46 | margin: auto;
47 | }
48 | .login-form {
49 | padding: 10%;
50 | }
51 |
--------------------------------------------------------------------------------