├── .gitignore
├── README.md
├── ToDo
├── pom.xml
└── src
├── main
├── java
│ └── org
│ │ └── sandbox
│ │ ├── SpringBootMybatisApplication.java
│ │ ├── aop
│ │ └── AopMonitor.java
│ │ ├── config
│ │ ├── CustomInterceptor.java
│ │ ├── CustomUrlRewriteFilter.java
│ │ ├── DaoConfig.java
│ │ ├── InterceptorConfig.java
│ │ ├── JmsConfig.java
│ │ ├── MysqlConfig.java
│ │ ├── OAuth2AuthorizationServerConfig.java
│ │ ├── OAuth2ResourceServerConfig.java
│ │ ├── RedisConfig.java
│ │ ├── ShiroConfig.java
│ │ ├── SwaggerConfig.java
│ │ ├── TaskConfig.java
│ │ ├── UrlRewriteConfig.java
│ │ └── WebSecurityConfig.java
│ │ ├── controller
│ │ ├── ArrayParamsController.java
│ │ ├── ExampleExceptionController.java
│ │ ├── HateoasController.java
│ │ ├── JmsController.java
│ │ ├── MongoController.java
│ │ ├── OAuthController.java
│ │ ├── PersonController.java
│ │ ├── ProfilesController.java
│ │ ├── RedisController.java
│ │ └── SecurityController.java
│ │ ├── exception
│ │ ├── CustomException.java
│ │ ├── ErrorDetail.java
│ │ ├── ExampleExceptionHandler.java
│ │ ├── ValidateObject.java
│ │ └── ValidationError.java
│ │ ├── hateoas
│ │ └── Article.java
│ │ ├── mongodb
│ │ ├── Customer.java
│ │ ├── CustomerRepository.java
│ │ ├── CustomerRepositoryCustom.java
│ │ └── CustomerRepositoryImpl.java
│ │ ├── orm
│ │ ├── Person.java
│ │ ├── PersonDao.java
│ │ ├── PersonExample.java
│ │ └── PersonMapper.java
│ │ └── service
│ │ ├── JmsConsumerService.java
│ │ ├── JmsProducerService.java
│ │ ├── MongoService.java
│ │ ├── OAuthService.java
│ │ ├── PersonService.java
│ │ ├── RedisService.java
│ │ └── SecurityService.java
└── resources
│ ├── application-dev.properties
│ ├── application-pro.properties
│ ├── application.properties
│ ├── logback.properties
│ ├── logback.xml
│ ├── messages.properties
│ ├── mysql
│ ├── PersonMapper.xml
│ ├── init.sql
│ └── mybatis-generator.xml
│ ├── static
│ └── swagger-ui
│ │ ├── css
│ │ ├── reset.css
│ │ └── screen.css
│ │ ├── images
│ │ ├── explorer_icons.png
│ │ ├── logo_small.png
│ │ ├── pet_store_api.png
│ │ ├── throbber.gif
│ │ └── wordnik_api.png
│ │ ├── index.html
│ │ ├── lib
│ │ ├── backbone-min.js
│ │ ├── handlebars-1.0.0.js
│ │ ├── highlight.7.3.pack.js
│ │ ├── jquery-1.8.0.min.js
│ │ ├── jquery.ba-bbq.min.js
│ │ ├── jquery.slideto.min.js
│ │ ├── jquery.wiggle.min.js
│ │ ├── shred.bundle.js
│ │ ├── shred
│ │ │ └── content.js
│ │ ├── swagger-oauth.js
│ │ ├── swagger.js
│ │ └── underscore-min.js
│ │ ├── o2c.html
│ │ ├── swagger-ui.js
│ │ └── swagger-ui.min.js
│ └── urlrewrite.xml
└── test
└── java
└── org
└── sandbox
├── ControllerTest.java
├── PersonServiceMockTest.java
├── PersonStandaloneMockTest.java
└── PersonWebApplicationContextTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | *.iml
3 | target
4 | */target
5 | logs
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #spring-boot-example
2 |
3 | ##introduction
4 |
5 | This project contains demos about MySQL, MyBatis, logback, url rewrite, interceptor, aop, mongodb, Test Framework(Mock), ActiveMQ,
6 | Security(Basic Authentication, Digest Authentication, OAuth2 Authentication), transaction, Rest Template.
7 |
--------------------------------------------------------------------------------
/ToDo:
--------------------------------------------------------------------------------
1 | #logback日志
2 | #url rewrite
3 | #拦截器
4 | #AOP
5 | #mongodb
6 | #test
7 | #mq
8 | #security
9 | #transaction
10 | #task
11 | #exception
12 | #document
13 | #HATEOAS
14 | Shiro
15 | Hadoop
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.sandbox.springboot
7 | spring-boot-example
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | spring-boot-example
12 | Spring Boot Example
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.2.5.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | 1.8
24 | 1.2.4
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-jdbc
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-web
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-starter-redis
39 |
40 |
41 | org.mybatis
42 | mybatis
43 | 3.3.0
44 |
45 |
46 | org.mybatis
47 | mybatis-spring
48 | 1.2.3
49 |
50 |
51 | mysql
52 | mysql-connector-java
53 | 5.1.35
54 |
55 |
56 | c3p0
57 | c3p0
58 | 0.9.1.2
59 |
60 |
61 | org.tuckey
62 | urlrewritefilter
63 | 4.0.3
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-starter-aop
68 |
69 |
70 | org.springframework.boot
71 | spring-boot-starter-data-mongodb
72 |
73 |
74 | org.springframework.boot
75 | spring-boot-starter-test
76 | test
77 |
78 |
79 | com.jayway.jsonpath
80 | json-path-assert
81 | 2.0.0
82 | test
83 |
84 |
85 | javax.inject
86 | javax.inject
87 | 1
88 |
89 |
90 | org.springframework
91 | spring-jms
92 |
93 |
94 | org.apache.activemq
95 | activemq-broker
96 |
97 |
98 | org.apache.activemq
99 | activemq-pool
100 | 5.12.0
101 |
102 |
103 | org.springframework.boot
104 | spring-boot-starter-jta-atomikos
105 |
106 |
107 | org.springframework.boot
108 | spring-boot-starter-security
109 |
110 |
111 | org.springframework.security.oauth
112 | spring-security-oauth2
113 | 2.0.7.RELEASE
114 |
115 |
116 | com.mangofactory
117 | swagger-springmvc
118 | 1.0.2
119 |
120 |
121 | org.springframework.hateoas
122 | spring-hateoas
123 | 0.17.0.RELEASE
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 | org.springframework.boot
151 | spring-boot-maven-plugin
152 |
153 |
154 | org.mybatis.generator
155 | mybatis-generator-maven-plugin
156 | 1.3.2
157 |
158 | src/main/resources/mysql/mybatis-generator.xml
159 | true
160 |
161 |
162 |
163 | mysql
164 | mysql-connector-java
165 | 5.1.35
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/SpringBootMybatisApplication.java:
--------------------------------------------------------------------------------
1 | package org.sandbox;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.builder.SpringApplicationBuilder;
6 | import org.springframework.boot.context.web.SpringBootServletInitializer;
7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8 | import org.springframework.security.core.authority.AuthorityUtils;
9 | import org.springframework.security.core.context.SecurityContextHolder;
10 |
11 | @SpringBootApplication
12 | //extends SpringBootServletInitializer
13 | public class SpringBootMybatisApplication {
14 |
15 | public static void main(String[] args) {
16 | SpringApplication.run(SpringBootMybatisApplication.class, args);
17 | }
18 |
19 | // @Override
20 | // protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
21 | // // Customize the application or call application.sources(...) to add sources
22 | //
23 | // application.sources(SpringBootMybatisApplication.class);
24 | // return application;
25 | // }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/aop/AopMonitor.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.aop;
2 |
3 | import org.aspectj.lang.JoinPoint;
4 | import org.aspectj.lang.annotation.AfterReturning;
5 | import org.aspectj.lang.annotation.Aspect;
6 | import org.springframework.stereotype.Component;
7 |
8 | /**
9 | * Author: zhangxin
10 | * Date: 15-9-1
11 | */
12 | @Aspect
13 | @Component
14 | public class AopMonitor {
15 |
16 | @AfterReturning("execution(* org.sandbox.service.PersonService.*(..))")
17 | public void afterReturningAdvisor(JoinPoint joinPoint) {
18 | System.out.println("@@@@@Completed: " + joinPoint + "@@@@@");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/CustomInterceptor.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | /**
11 | * Created by zhangxin on 15/8/31.
12 | */
13 | public class CustomInterceptor extends HandlerInterceptorAdapter {
14 |
15 | private Logger logger = LoggerFactory.getLogger(this.getClass());
16 |
17 | @Override
18 | public boolean preHandle(HttpServletRequest request,
19 | HttpServletResponse response, Object handler) throws Exception {
20 | logger.info("#####Pre request interceptor ... #####");
21 |
22 | return true;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/CustomUrlRewriteFilter.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.tuckey.web.filters.urlrewrite.Conf;
4 | import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;
5 | import org.tuckey.web.filters.urlrewrite.UrlRewriter;
6 |
7 | import javax.servlet.*;
8 | import java.io.InputStream;
9 |
10 | /**
11 | * Author: zhangxin
12 | * Date: 15-8-29
13 | */
14 | public class CustomUrlRewriteFilter extends UrlRewriteFilter {
15 | private UrlRewriter urlRewriter;
16 |
17 | @Override
18 | public void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
19 | try {
20 | InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("urlrewrite.xml");
21 | Conf conf1 = new Conf(filterConfig.getServletContext(), inputStream, "urlrewrite.xml", "");
22 | urlRewriter = new UrlRewriter(conf1);
23 | } catch (Exception e) {
24 | throw new ServletException(e);
25 | }
26 | }
27 |
28 | @Override
29 | public UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {
30 | return urlRewriter;
31 | }
32 |
33 | @Override
34 | public void destroyUrlRewriter() {
35 | if(urlRewriter != null)
36 | urlRewriter.destroy();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/DaoConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.apache.ibatis.session.SqlSessionFactory;
4 | import org.sandbox.orm.PersonDao;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 |
9 | /**
10 | * Author: zhangxin
11 | * Date: 15-9-16
12 | */
13 | @Configuration
14 | public class DaoConfig {
15 |
16 | @Autowired
17 | private SqlSessionFactory sqlSessionFactory;
18 |
19 | @Bean
20 | public PersonDao personDao() {
21 | PersonDao personDao = new PersonDao();
22 | personDao.setSqlSessionFactory(sqlSessionFactory);
23 | return personDao;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/InterceptorConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
7 |
8 | /**
9 | * Created by zhangxin on 15/8/31.
10 | */
11 | @Configuration
12 | public class InterceptorConfig extends WebMvcConfigurerAdapter {
13 |
14 | @Bean
15 | public CustomInterceptor interceptor() {
16 | return new CustomInterceptor();
17 | }
18 |
19 | @Override
20 | public void addInterceptors(InterceptorRegistry registry) {
21 | registry.addInterceptor(interceptor()).addPathPatterns("/demo/v1/**");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/JmsConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.apache.activemq.command.ActiveMQQueue;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.jms.annotation.EnableJms;
7 |
8 | import javax.jms.Queue;
9 |
10 | /**
11 | * Author: zhangxin
12 | * Date: 15-9-7
13 | */
14 | @Configuration
15 | public class JmsConfig {
16 |
17 | @Bean
18 | public Queue queue() {
19 | return new ActiveMQQueue("sample.queue");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/MysqlConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import com.mchange.v2.c3p0.ComboPooledDataSource;
4 | import org.apache.ibatis.session.SqlSessionFactory;
5 | import org.mybatis.spring.SqlSessionFactoryBean;
6 | import org.mybatis.spring.annotation.MapperScan;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 | import org.springframework.core.io.ClassPathResource;
10 | import org.springframework.jdbc.datasource.DataSourceTransactionManager;
11 |
12 | import javax.sql.DataSource;
13 |
14 | /**
15 | * Created by zhangxin on 15/8/26.
16 | */
17 |
18 | @Configuration
19 | @MapperScan(basePackages = "org.sandbox.orm")
20 | public class MysqlConfig {
21 | @Bean
22 | public DataSource dataSource() throws Exception {
23 | ComboPooledDataSource dataSource = new ComboPooledDataSource();
24 |
25 | dataSource.setDriverClass("com.mysql.jdbc.Driver");
26 | dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useCompression=true" +
27 | "&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
28 | dataSource.setUser("root");
29 | dataSource.setPassword("mysql");
30 | dataSource.setAcquireIncrement(10);
31 | dataSource.setIdleConnectionTestPeriod(60);
32 | dataSource.setMaxPoolSize(100);
33 | dataSource.setMaxStatements(50);
34 | dataSource.setMinPoolSize(10);
35 |
36 | return dataSource;
37 | }
38 |
39 | @Bean
40 | public DataSourceTransactionManager transactionManager() throws Exception {
41 | return new DataSourceTransactionManager(dataSource());
42 | }
43 |
44 | @Bean
45 | public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
46 | final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
47 | sessionFactory.setDataSource(dataSource);
48 | sessionFactory.setMapperLocations(new ClassPathResource[] {new ClassPathResource("mysql/PersonMapper.xml")});
49 | return sessionFactory.getObject();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/OAuth2AuthorizationServerConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.security.authentication.AuthenticationManager;
5 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
6 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
7 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
8 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
9 |
10 | import javax.inject.Inject;
11 |
12 | @Configuration
13 | @EnableAuthorizationServer
14 | public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
15 |
16 | @Inject
17 | private AuthenticationManager authenticationManager;
18 |
19 | @Override
20 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
21 | endpoints.authenticationManager(this.authenticationManager);
22 | }
23 |
24 | @Override
25 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
26 | clients.inMemory()
27 | .withClient("oauthclient")
28 | .secret("123456")
29 | .authorizedGrantTypes("password")
30 | .scopes("read", "write")
31 | .resourceIds("OAuth2_Resources");
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/OAuth2ResourceServerConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
7 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
8 |
9 | @Configuration
10 | @EnableResourceServer
11 | public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
12 |
13 | @Override
14 | public void configure(ResourceServerSecurityConfigurer resources) {
15 | resources.resourceId("OAuth2_Resources");
16 | }
17 |
18 | @Override
19 | public void configure(HttpSecurity http) throws Exception {
20 | http.requestMatchers().antMatchers("/demo/oauth2/**")
21 | .and()
22 | .authorizeRequests().antMatchers("/demo/oauth2/**").authenticated();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/RedisConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.data.redis.connection.RedisConnectionFactory;
6 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
7 | import org.springframework.data.redis.core.StringRedisTemplate;
8 | import redis.clients.jedis.JedisPoolConfig;
9 |
10 | /**
11 | * Author: zhangxin
12 | * Date: 15-8-28
13 | */
14 | @Configuration
15 | public class RedisConfig {
16 | @Bean
17 | public RedisConnectionFactory jedisConnectionFactory(){
18 | JedisPoolConfig poolConfig=new JedisPoolConfig();
19 | poolConfig.setMaxIdle(5);
20 | poolConfig.setMinIdle(1);
21 | poolConfig.setTestOnBorrow(true);
22 | poolConfig.setTestOnReturn(true);
23 | poolConfig.setTestWhileIdle(true);
24 | poolConfig.setNumTestsPerEvictionRun(10);
25 | poolConfig.setTimeBetweenEvictionRunsMillis(60000);
26 |
27 | JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
28 | jedisConnectionFactory.setHostName("127.0.0.1");
29 | jedisConnectionFactory.setPort(6379);
30 | jedisConnectionFactory.setDatabase(1);
31 | jedisConnectionFactory.setPassword("1234567890");
32 | return jedisConnectionFactory;
33 | }
34 |
35 | @Bean
36 | public StringRedisTemplate redisTemplate() {
37 | StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory());
38 | return redisTemplate;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/ShiroConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | //import org.apache.shiro.realm.text.PropertiesRealm;
4 | //import org.apache.shiro.spring.LifecycleBeanPostProcessor;
5 | //import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
6 | //import org.apache.shiro.web.filter.authc.AnonymousFilter;
7 | //import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
8 | //import org.apache.shiro.web.filter.authc.LogoutFilter;
9 | //import org.apache.shiro.web.filter.authc.UserFilter;
10 | //import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
11 | //import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
12 | //import org.springframework.context.annotation.Bean;
13 | import org.springframework.context.annotation.Configuration;
14 | //import org.springframework.context.annotation.DependsOn;
15 | //
16 | //import javax.servlet.Filter;
17 | //import java.util.HashMap;
18 | //import java.util.Map;
19 |
20 | /**
21 | * Author: zhangxin
22 | * Date: 15-10-20
23 | */
24 | @Configuration
25 | public class ShiroConfig {
26 |
27 | // @Bean(name = "shiroFilter")
28 | // public ShiroFilterFactoryBean shiroFilter() {
29 | // ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
30 | // shiroFilter.setLoginUrl("/login");
31 | // shiroFilter.setSuccessUrl("/index");
32 | // shiroFilter.setUnauthorizedUrl("/forbidden");
33 | // shiroFilter.setSecurityManager(securityManager());
34 | //
35 | // Map filterChainDefinitionMapping = new HashMap<>();
36 | // filterChainDefinitionMapping.put("/", "anon");
37 | // filterChainDefinitionMapping.put("/home", "authc,roles[guest]");
38 | // filterChainDefinitionMapping.put("/admin", "authc,roles[admin]");
39 | // shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMapping);
40 | //
41 | // Map filters = new HashMap<>();
42 | // filters.put("anon", new AnonymousFilter());
43 | // filters.put("authc", new FormAuthenticationFilter());
44 | // filters.put("logout", new LogoutFilter());
45 | // filters.put("roles", new RolesAuthorizationFilter());
46 | // filters.put("user", new UserFilter());
47 | // shiroFilter.setFilters(filters);
48 | //
49 | // return shiroFilter;
50 | // }
51 | //
52 | // @Bean(name = "securityManager")
53 | // public DefaultWebSecurityManager securityManager() {
54 | // DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
55 | // securityManager.setRealm(realm());
56 | // return securityManager;
57 | // }
58 | //
59 | // @Bean(name = "realm")
60 | // @DependsOn("lifecycleBeanPostProcessor")
61 | // public PropertiesRealm realm() {
62 | // PropertiesRealm propertiesRealm = new PropertiesRealm();
63 | // propertiesRealm.init();
64 | // return propertiesRealm;
65 | // }
66 | //
67 | // @Bean
68 | // public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
69 | // return new LifecycleBeanPostProcessor();
70 | // }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/SwaggerConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
4 | import com.mangofactory.swagger.models.dto.ApiInfo;
5 | import com.mangofactory.swagger.models.dto.builder.ApiInfoBuilder;
6 | import com.mangofactory.swagger.plugin.EnableSwagger;
7 | import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 |
11 | import javax.inject.Inject;
12 |
13 | /**
14 | * Author: zhangxin
15 | * Date: 15-9-17
16 | */
17 | @Configuration
18 | @EnableSwagger
19 | public class SwaggerConfig {
20 |
21 | @Inject
22 | private SpringSwaggerConfig springSwaggerConfig;
23 |
24 | private ApiInfo getApiInfo() {
25 |
26 | ApiInfo apiInfo = new ApiInfoBuilder()
27 | .title("Spring Boot Example API")
28 | .description("Spring Boot Example API")
29 | .termsOfServiceUrl("http://example.com/terms-of-service")
30 | .contact("info@example.com")
31 | .license("MIT License")
32 | .licenseUrl("http://opensource.org/licenses/MIT")
33 | .build();
34 |
35 | return apiInfo;
36 | }
37 |
38 | @Bean
39 | public SwaggerSpringMvcPlugin apiConfiguration() {
40 | SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(this.springSwaggerConfig);
41 | swaggerSpringMvcPlugin
42 | .apiInfo(getApiInfo()).apiVersion("0.1")
43 | .includePatterns("/demo/v1/persons/*.*").swaggerGroup("v1");
44 | swaggerSpringMvcPlugin.useDefaultResponseMessages(false);
45 | return swaggerSpringMvcPlugin;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/TaskConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.scheduling.annotation.EnableScheduling;
4 | import org.springframework.scheduling.annotation.Scheduled;
5 | import org.springframework.stereotype.Component;
6 |
7 | import java.text.SimpleDateFormat;
8 | import java.util.Date;
9 |
10 | /**
11 | * Author: zhangxin
12 | * Date: 15-9-15
13 | */
14 | @Component
15 | //@EnableScheduling
16 | public class TaskConfig {
17 | private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
18 | private static int count = 0;
19 |
20 | //fixedRate: 从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
21 | @Scheduled(fixedRate = 5000)
22 | public void reportCurrentTime() {
23 | System.out.println("The time is now " + simpleDateFormat.format(new Date()));
24 | }
25 |
26 | @Scheduled(cron = "0/1 * * * * ?")
27 | public void repeatShowMsg() {
28 | System.out.println("repeat show message: " + (++count));
29 | }
30 |
31 | //fixedDelay: 表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
32 | @Scheduled(fixedDelay = 10000)
33 | public void fixedDelayShowMsg() {
34 | System.out.println("fixed delay show message ... ");
35 | }
36 |
37 | @Scheduled(initialDelay = 10000, fixedRate = 6000)
38 | public void initialDelayShowMsg() {
39 | System.out.println("initial delay show message!");
40 | }
41 |
42 | @Scheduled(fixedRateString = "10000")
43 | public void fixedRateStringShowMsg() {
44 | System.out.println("fixed rate string show message ... ");
45 | }
46 |
47 | @Scheduled(fixedDelayString = "10000")
48 | public void fixedDelayStringShowMsg() {
49 | System.out.println("fixed delay string show message ...");
50 | }
51 |
52 | @Scheduled(initialDelayString = "10000", fixedDelayString = "10000")
53 | public void initialDelayStringShowMsg() {
54 | System.out.println("initial delay string show message ...");
55 | }
56 |
57 | @Scheduled(initialDelay = 10000, fixedDelay = Long.MAX_VALUE)
58 | public void runOnceMsg() {
59 | System.out.println("only run once message!!");
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/UrlRewriteConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.boot.context.embedded.FilterRegistrationBean;
4 | import org.springframework.boot.context.embedded.ServletRegistrationBean;
5 | import org.springframework.context.annotation.Bean;
6 | import org.springframework.context.annotation.Configuration;
7 | import org.springframework.web.servlet.DispatcherServlet;
8 |
9 | import javax.servlet.DispatcherType;
10 |
11 | /**
12 | * Author: zhangxin
13 | * Date: 15-8-29
14 | */
15 | @Configuration
16 | public class UrlRewriteConfig {
17 |
18 | @Bean
19 | public FilterRegistrationBean filterRegistrationBean() {
20 | FilterRegistrationBean registrationBean = new FilterRegistrationBean();
21 | registrationBean.setFilter(new CustomUrlRewriteFilter());
22 | registrationBean.addUrlPatterns("/*");
23 | registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
24 |
25 | return registrationBean;
26 | }
27 |
28 | @Bean
29 | public DispatcherServlet dispatcherServlet() {
30 | return new DispatcherServlet();
31 | }
32 |
33 | @Bean
34 | public ServletRegistrationBean dispatcherServletRegistration() {
35 | ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet(), "/*");
36 |
37 | // registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
38 |
39 | registration.setName("spring-boot-mybatis");
40 |
41 | return registration;
42 | }
43 |
44 |
45 | // @Bean
46 | // public UrlRewriteFilter urlRewriteFilter() {
47 | // UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter();
48 | // return urlRewriteFilter;
49 | // }
50 |
51 |
52 | // @Bean
53 | // public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
54 | // ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
55 | // registration.addUrlMappings("/app/*");
56 | // return registration;
57 | // }
58 |
59 | // @Bean
60 | // public FilterRegistrationBean filterRegistrationBean()
61 | // {
62 | // FilterRegistrationBean registrationBean = new FilterRegistrationBean();
63 | //
64 | // registrationBean.setFilter(new UrlRewriteFilter());
65 | // registrationBean.addUrlPatterns("*");
66 | // registrationBean.addInitParameter("confReloadCheckInterval", "5");
67 | // registrationBean.addInitParameter("logLevel", "DEBUG");
68 | //
69 | // return registrationBean;
70 | // }
71 |
72 | // @Bean
73 | // public UrlRewriteFilter urlRewriteFilter() {
74 | // UrlRewriteFilter urlRewriteFilter = new EnhancedUrlRewriteFilter();
75 | // return urlRewriteFilter;
76 | // }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/config/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.core.Ordered;
6 | import org.springframework.core.annotation.Order;
7 | import org.springframework.security.authentication.AuthenticationManager;
8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
9 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12 | import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
13 | import org.springframework.security.config.http.SessionCreationPolicy;
14 | import org.springframework.security.core.userdetails.UserDetailsService;
15 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
16 | import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint;
17 | import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
18 | import org.springframework.security.web.csrf.CsrfTokenRepository;
19 | import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
20 |
21 | /**
22 | * Created by zhangxin on 15/9/10.
23 | */
24 | @Configuration
25 | @EnableWebMvcSecurity
26 | @EnableGlobalMethodSecurity(prePostEnabled = true)
27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
28 |
29 | /**
30 | * Digest Authentication
31 | * */
32 |
33 | @Bean
34 | public DigestAuthenticationEntryPoint digestEntryPoint() {
35 | DigestAuthenticationEntryPoint entryPoint = new DigestAuthenticationEntryPoint();
36 | entryPoint.setRealmName("Custom Realm Name");
37 | entryPoint.setKey("uniqueAndSecret");
38 | return entryPoint;
39 | }
40 |
41 | @Bean
42 | public DigestAuthenticationFilter digestFilter() throws Exception {
43 | DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
44 | filter.setAuthenticationEntryPoint(digestEntryPoint());
45 | filter.setUserDetailsService(userDetailsServiceBean());
46 | return filter;
47 | }
48 |
49 | @Override
50 | @Bean
51 | public UserDetailsService userDetailsServiceBean() throws Exception {
52 | return super.userDetailsServiceBean();
53 | }
54 |
55 | @Override
56 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
57 | auth.inMemoryAuthentication()
58 | .withUser("zhangxin").password("123456").roles("USER_ROLE")
59 | .and()
60 | .withUser("test").password("test").roles("**");
61 | }
62 |
63 | @Override
64 | protected void configure(HttpSecurity http) throws Exception {
65 | http.exceptionHandling()
66 | .authenticationEntryPoint(digestEntryPoint())
67 | .and()
68 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
69 | .and()
70 | .authorizeRequests()
71 | .antMatchers("/demo/v1/persons/**", "/demo/mongo/customers/**").permitAll()
72 | .antMatchers("/demo/security/**").authenticated()
73 | .and()
74 | .addFilterAfter(digestFilter(), BasicAuthenticationFilter.class)
75 | .csrf().disable();
76 | // .csrf().csrfTokenRepository(csrfTokenRepository());
77 | }
78 |
79 | @Override
80 | @Bean
81 | protected AuthenticationManager authenticationManager() throws Exception {
82 | return super.authenticationManager();
83 | }
84 |
85 | private CsrfTokenRepository csrfTokenRepository()
86 | {
87 | HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
88 | repository.setSessionAttributeName("_csrf");
89 | return repository;
90 | }
91 |
92 | /**
93 | * Basic Authentication
94 | * */
95 |
96 | // @Override
97 | // protected void configure(AuthenticationManagerBuilder auth) throws Exception {
98 | // auth.inMemoryAuthentication()
99 | // .withUser("test").password("test").roles("USER_ROLE");
100 | // }
101 | //
102 | // @Override
103 | // @Order(Ordered.HIGHEST_PRECEDENCE)
104 | // protected void configure(HttpSecurity http) throws Exception {
105 | // http.sessionManagement()
106 | // .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
107 | // .and()
108 | // .authorizeRequests()
109 | // .antMatchers("/demo/v1/persons/**", "/demo/mongo/customers/**").permitAll()
110 | // .antMatchers("/demo/security/**").authenticated()
111 | // .and()
112 | // .httpBasic()
113 | // .realmName("Spring Demo")
114 | // .and()
115 | // .csrf()
116 | // .disable();
117 | // }
118 | //
119 | // @Override
120 | // @Bean
121 | // protected AuthenticationManager authenticationManager() throws Exception {
122 | // return super.authenticationManager();
123 | // }
124 | }
125 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/ArrayParamsController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.http.ResponseEntity;
5 | import org.springframework.web.bind.annotation.*;
6 |
7 | /**
8 | * Created by zhangxin on 15/9/19.
9 | */
10 | @RestController
11 | @RequestMapping(value = "array")
12 | public class ArrayParamsController {
13 |
14 | @RequestMapping(method = RequestMethod.GET)
15 | @ResponseBody
16 | public ResponseEntity> testArrayParam(@RequestParam("params")String[] params) {
17 |
18 | for(int i = 0; i < params.length; i++) {
19 | System.out.println(params[i]);
20 | }
21 |
22 | return new ResponseEntity<>(null, HttpStatus.OK);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/ExampleExceptionController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.exception.CustomException;
4 | import org.sandbox.exception.ValidateObject;
5 | import org.springframework.http.HttpHeaders;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.*;
9 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
10 |
11 | import javax.validation.Valid;
12 | import java.net.URI;
13 |
14 | /**
15 | * Author: zhangxin
16 | * Date: 15-9-17
17 | */
18 | @RestController
19 | @RequestMapping(value = "demo/v1/")
20 | public class ExampleExceptionController {
21 |
22 | @RequestMapping(value = "exceptions/{id}", method = RequestMethod.GET)
23 | public ResponseEntity> getException(@PathVariable("id")String id) {
24 | if(id.equals("0"))
25 | throw new CustomException("ha ha, got exception.");
26 |
27 | return new ResponseEntity<>("no exception.", null, HttpStatus.OK);
28 | }
29 |
30 | @RequestMapping(value = "exceptions/validate", method = RequestMethod.POST)
31 | public ResponseEntity> addValidObject(@Valid @RequestBody ValidateObject validateObject) {
32 | HttpHeaders headers = new HttpHeaders();
33 | URI newUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(validateObject.getId()).toUri();
34 | headers.setLocation(newUri);
35 |
36 | return new ResponseEntity<>(null, headers, HttpStatus.CREATED);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/HateoasController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.hateoas.Article;
4 | import org.sandbox.orm.Person;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.PathVariable;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
16 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
17 |
18 | /**
19 | * Author: zhangxin
20 | * Date: 15-9-18
21 | */
22 | @RestController
23 | @RequestMapping("hateoas/")
24 | public class HateoasController {
25 |
26 | @RequestMapping(value = "articles/{title}", method = RequestMethod.GET)
27 | public ResponseEntity> getArticles(@PathVariable("title")String title) {
28 | Article article = new Article(title, "spring-boot", "1234567890987654321", 19, System.currentTimeMillis());
29 | article.add(linkTo(methodOn(HateoasController.class).getArticles(title)).withSelfRel());
30 | article.add(linkTo(methodOn(PersonController.class).getPerson(5)).withRel("author"));
31 | article.add(linkTo(methodOn(PersonController.class).setPersonObject(new Person())).withRel("author_obj"));
32 | return new ResponseEntity<>(article, HttpStatus.OK);
33 | }
34 |
35 | @RequestMapping(value = "articles", method = RequestMethod.GET)
36 | public ResponseEntity> getArticleSet() {
37 | List articleList = new ArrayList<>();
38 | for(int i = 0; i < 10; i++) {
39 | Article article = new Article("article_" + i, "spring boot example", "content_" + i,
40 | "spring boot example".length(), System.currentTimeMillis());
41 |
42 | article.add(linkTo(methodOn(HateoasController.class).getArticles(article.getTitle())).withSelfRel());
43 | article.add(linkTo(methodOn(PersonController.class).getPerson(i)).withRel("author"));
44 | articleList.add(article);
45 | }
46 |
47 | return new ResponseEntity<>(articleList, HttpStatus.OK);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/JmsController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.service.JmsProducerService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | /**
13 | * Author: zhangxin
14 | * Date: 15-9-7
15 | */
16 | @RestController
17 | @RequestMapping(value = "demo/jms")
18 | public class JmsController {
19 |
20 | @Autowired
21 | private JmsProducerService jmsProducerService;
22 |
23 | @RequestMapping(method = RequestMethod.POST)
24 | public ResponseEntity> sendMsg(@RequestParam("msg")String msg) {
25 | jmsProducerService.sendMsg(msg);
26 | return new ResponseEntity<>(null, HttpStatus.OK);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/MongoController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.mongodb.Customer;
4 | import org.sandbox.service.MongoService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.*;
9 |
10 | import java.util.List;
11 |
12 | /**
13 | * Author: zhangxin
14 | * Date: 15-9-1
15 | */
16 | @RestController
17 | @RequestMapping(value = "/demo/mongo")
18 | public class MongoController {
19 |
20 | @Autowired
21 | private MongoService mongoService;
22 |
23 | @RequestMapping(value = "customers/{firstName}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
24 | public ResponseEntity> getCustomersByFirstName(@PathVariable("firstName")String firstName) {
25 | Customer customer = mongoService.getCustomerByFirstName(firstName);
26 | return new ResponseEntity<>(customer, HttpStatus.OK);
27 | }
28 |
29 | @RequestMapping(value = "customers/lastname/{lastName}", method = RequestMethod.GET)
30 | public ResponseEntity> getCustomersByLastName(@PathVariable("lastName")String lastName) {
31 | List customers = mongoService.getCustomerByLastName(lastName);
32 | return new ResponseEntity<>(customers, HttpStatus.OK);
33 | }
34 |
35 | @RequestMapping(value = "customers", method = RequestMethod.POST)
36 | public ResponseEntity addCustomer(@RequestParam("firstName")String firstName, @RequestParam("lastName")String lastName) {
37 | mongoService.insert(firstName, lastName);
38 | return new ResponseEntity<>("insert successfully", HttpStatus.CREATED);
39 | }
40 |
41 | @RequestMapping(value = "customers/{id}", method = RequestMethod.DELETE)
42 | public ResponseEntity delCustomer(@PathVariable("id")String id) {
43 | mongoService.delete(id);
44 | return new ResponseEntity<>("delete successfully", HttpStatus.OK);
45 | }
46 |
47 | @RequestMapping(value = "customers/{id}", method = RequestMethod.PUT)
48 | public ResponseEntity updateCustomer(@PathVariable("id")String id, @RequestParam("firstName") String firstName,
49 | @RequestParam("lastName")String lastName) {
50 | mongoService.update(id, firstName, lastName);
51 | return new ResponseEntity<>("update successfully", HttpStatus.OK);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/OAuthController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.service.OAuthService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | /**
12 | * Author: zhangxin
13 | * Date: 15-9-12
14 | */
15 | @RestController
16 | @RequestMapping(value = "demo/oauth2")
17 | public class OAuthController {
18 |
19 | @Autowired
20 | private OAuthService oAuthService;
21 |
22 | @RequestMapping(method = RequestMethod.GET)
23 | public ResponseEntity> getOAuth() {
24 | String msg = oAuthService.getOAuth();
25 | return new ResponseEntity<>(msg, HttpStatus.OK);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/PersonController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import com.wordnik.swagger.annotations.Api;
4 | import com.wordnik.swagger.annotations.ApiOperation;
5 | import com.wordnik.swagger.annotations.ApiResponse;
6 | import com.wordnik.swagger.annotations.ApiResponses;
7 | import org.sandbox.exception.ErrorDetail;
8 | import org.sandbox.orm.Person;
9 | import org.sandbox.service.PersonService;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.http.HttpStatus;
12 | import org.springframework.http.ResponseEntity;
13 | import org.springframework.util.LinkedMultiValueMap;
14 | import org.springframework.util.MultiValueMap;
15 | import org.springframework.web.bind.annotation.*;
16 |
17 | /**
18 | * Created by zhangxin on 15/8/27.
19 | */
20 | @RestController
21 | @RequestMapping(value = "/demo/v1/")
22 | @Api(value = "person", description = "Spring Boot Example Persion Controller")
23 | public class PersonController {
24 | @Autowired
25 | private PersonService personService;
26 |
27 | @RequestMapping(value = "persons/{id}", method = RequestMethod.GET)
28 | @ResponseBody
29 | @ApiOperation(value = "Fetch API", notes = "Fetch person by id", response = Person.class)
30 | @ApiResponses(value = {@ApiResponse(code = 500, message = "Server Error", response = ErrorDetail.class)})
31 | public Object getPerson(@PathVariable int id) {
32 | return personService.select(id);
33 | }
34 |
35 | @RequestMapping(value = "persons", method = RequestMethod.POST)
36 | @ApiOperation(value = "POST API", notes = "Add new person by multiple params into database", response = String.class)
37 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)})
38 | public ResponseEntity setPerson(@RequestParam("name")String name,
39 | @RequestParam("age")int age,
40 | @RequestParam("country")String country) {
41 | Person person = new Person();
42 | person.setName(name);
43 | person.setAge(age);
44 | person.setCountry(country);
45 |
46 | int id = personService.insert(person);
47 |
48 | MultiValueMap headers = new LinkedMultiValueMap<>();
49 | headers.set("location", "http://localhost:8080/persons/" + id);
50 |
51 | return new ResponseEntity<>("ResponseEntity insert successfully", headers, HttpStatus.OK);
52 | }
53 |
54 | @RequestMapping(value = "persons/object", method = RequestMethod.POST)
55 | @ResponseBody
56 | @ApiOperation(value = "Set API", notes = "Add new person by person object into database", response = String.class)
57 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)})
58 | public Object setPersonObject(@RequestBody Person person) {
59 | personService.insert(person);
60 | return "insert successfully.";
61 | }
62 |
63 | @RequestMapping(value = "persons/{id}", method = RequestMethod.PUT)
64 | @ApiOperation(value = "Update API", notes = "Update person by id and multiply params", response = String.class)
65 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)})
66 | public ResponseEntity updatePerson(@PathVariable("id") int id, @RequestParam("name") String name,
67 | @RequestParam("age") int age,
68 | @RequestParam("country") String country) {
69 | Person person = new Person();
70 | person.setId(id);
71 | person.setName(name);
72 | person.setAge(age);
73 | person.setCountry(country);
74 |
75 | personService.update(person);
76 |
77 | return new ResponseEntity<>("update successfully", HttpStatus.OK);
78 | }
79 |
80 | @RequestMapping(value = "persons/object/{id}", method = RequestMethod.PUT)
81 | @ApiOperation(value = "Update API", notes = "Update person by id and person object params into database", response = String.class)
82 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)})
83 | public ResponseEntity updatePersonObject(@PathVariable("id") int id, @RequestBody Person person) {
84 | person.setId(id);
85 | personService.update(person);
86 |
87 | return new ResponseEntity<>("update successfully", HttpStatus.OK);
88 | }
89 |
90 | @RequestMapping(value = "persons/{id}", method = RequestMethod.DELETE)
91 | @ApiOperation(value = "Delete API", notes = "Delete person by id", response = Void.class)
92 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)})
93 | public ResponseEntity> delPerson(@PathVariable int id) {
94 | personService.delete(id);
95 | return new ResponseEntity<>(null, HttpStatus.OK);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/ProfilesController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Value;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.RequestMethod;
6 | import org.springframework.web.bind.annotation.ResponseBody;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | /**
10 | * Author: zhangxin
11 | * Date: 15-12-2
12 | */
13 | @RestController
14 | @RequestMapping(value = "profile")
15 | public class ProfilesController {
16 |
17 | @Value("${name}")
18 | private String name;
19 |
20 | @RequestMapping(method = RequestMethod.GET)
21 | @ResponseBody
22 | public Object getName() {
23 | return name;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/RedisController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.service.RedisService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | /**
13 | * Author: zhangxin
14 | * Date: 15-8-28
15 | */
16 | @RestController
17 | @RequestMapping(value = "v1")
18 | public class RedisController {
19 | @Autowired
20 | private RedisService redisService;
21 |
22 | @RequestMapping(value = "redis", method = RequestMethod.GET)
23 | public ResponseEntity getValue(@RequestParam("key")String key) {
24 | return new ResponseEntity<>(redisService.getValue(key), HttpStatus.OK);
25 | }
26 |
27 | @RequestMapping(value = "redis", method = RequestMethod.POST)
28 | public ResponseEntity setValue(@RequestParam("key")String key, @RequestParam("value")String value) {
29 | redisService.setValue(key, value);
30 | return new ResponseEntity<>("set key/value successfully", HttpStatus.OK);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/controller/SecurityController.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.controller;
2 |
3 | import org.sandbox.service.SecurityService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | /**
12 | * Author: zhangxin
13 | * Date: 15-9-10
14 | */
15 | @RestController
16 | @RequestMapping(value = "demo/security")
17 | public class SecurityController {
18 |
19 | @Autowired
20 | private SecurityService securityService;
21 |
22 | @RequestMapping(value = "security", method = RequestMethod.GET)
23 | public ResponseEntity> security() {
24 | String msg = securityService.secure();
25 | return new ResponseEntity<>(msg, HttpStatus.OK);
26 | }
27 |
28 | @RequestMapping(value = "authorized", method = RequestMethod.GET)
29 | public ResponseEntity> auhtorized() {
30 | String msg = securityService.authorized();
31 | return new ResponseEntity<>(msg, HttpStatus.OK);
32 | }
33 |
34 | @RequestMapping(value = "denied", method = RequestMethod.GET)
35 | public ResponseEntity> denied() {
36 | String msg = securityService.denied();
37 | return new ResponseEntity<>(msg, HttpStatus.OK);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/exception/CustomException.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.exception;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | /**
7 | * Author: zhangxin
8 | * Date: 15-9-17
9 | */
10 | @ResponseStatus(value = HttpStatus.NOT_FOUND)
11 | public class CustomException extends RuntimeException {
12 | private static final long serialVersionUID = 1L;
13 |
14 | public CustomException() {
15 | super();
16 | }
17 |
18 | public CustomException(String message) {
19 | super(message);
20 | }
21 |
22 | public CustomException(String message, Throwable throwable) {
23 | super(message, throwable);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/exception/ErrorDetail.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.exception;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | /**
8 | * Author: zhangxin
9 | * Date: 15-9-17
10 | */
11 | public class ErrorDetail {
12 |
13 | private String title;
14 | private int status;
15 | private String detail;
16 | private long timestamp;
17 | private String developerMessage;
18 | private Map> errors = new HashMap<>();
19 |
20 | public String getTitle() {
21 | return title;
22 | }
23 |
24 | public void setTitle(String title) {
25 | this.title = title;
26 | }
27 |
28 | public int getStatus() {
29 | return status;
30 | }
31 |
32 | public void setStatus(int status) {
33 | this.status = status;
34 | }
35 |
36 | public String getDetail() {
37 | return detail;
38 | }
39 |
40 | public void setDetail(String detail) {
41 | this.detail = detail;
42 | }
43 |
44 | public long getTimestamp() {
45 | return timestamp;
46 | }
47 |
48 | public void setTimestamp(long timestamp) {
49 | this.timestamp = timestamp;
50 | }
51 |
52 | public String getDeveloperMessage() {
53 | return developerMessage;
54 | }
55 |
56 | public void setDeveloperMessage(String developerMessage) {
57 | this.developerMessage = developerMessage;
58 | }
59 |
60 | public Map> getErrors() {
61 | return errors;
62 | }
63 |
64 | public void setErrors(Map> errors) {
65 | this.errors = errors;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/org/sandbox/exception/ExampleExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package org.sandbox.exception;
2 |
3 | import org.springframework.context.MessageSource;
4 | import org.springframework.http.HttpHeaders;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.validation.FieldError;
8 | import org.springframework.web.bind.MethodArgumentNotValidException;
9 | import org.springframework.web.bind.annotation.ControllerAdvice;
10 | import org.springframework.web.bind.annotation.ExceptionHandler;
11 | import org.springframework.web.context.request.WebRequest;
12 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
13 |
14 | import javax.inject.Inject;
15 | import java.util.ArrayList;
16 | import java.util.List;
17 |
18 | /**
19 | * Author: zhangxin
20 | * Date: 15-9-17
21 | */
22 | @ControllerAdvice
23 | public class ExampleExceptionHandler extends ResponseEntityExceptionHandler {
24 |
25 | @Inject
26 | private MessageSource messageSource;
27 |
28 | @ExceptionHandler(CustomException.class)
29 | public ResponseEntity> handleExampleException(CustomException ce) {
30 | ErrorDetail errorDetail = new ErrorDetail();
31 | errorDetail.setTitle("Custom Exception");
32 | errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
33 | errorDetail.setDetail(ce.getMessage());
34 | errorDetail.setTimestamp(System.currentTimeMillis());
35 | errorDetail.setDeveloperMessage(ce.getClass().getName());
36 |
37 | return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
38 | }
39 |
40 | @Override
41 | public ResponseEntity