();
287 | Sort.Order sortorder=null;
288 | for (int i = 0; null != page.getOrder() && i < page.getOrder().size(); i++) {
289 |
290 |
291 | Order order = page.getOrder().get(i);
292 |
293 | Columns columns = page.getColumns().get(order.getColumn());
294 | if("asc".equals(order.getDir())){
295 | sortorder=new Sort.Order(Direction.ASC, columns.getData());
296 | break;
297 | }else{
298 | sortorder=new Sort.Order(Direction.DESC, columns.getData());
299 | break;
300 | }
301 |
302 |
303 | }
304 |
305 | return sortorder;
306 | }
307 | //end ...........................................................
308 |
309 |
310 |
311 | }
312 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/jpa/service/page/PaginationResult.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.jpa.service.page;
2 |
3 | import java.io.Serializable;
4 | import java.util.List;
5 |
6 | /**
7 | *
8 | * 类名:PaginationResult.java
9 | * 标题:中信国安
10 | * 描述:
11 | * DataTables 返回分页数据的 对象
12 | * 实现Serializable 接口.
13 | *
14 | * 版权声明:Copyright (c) 2016
15 | * 公司:中信国安
16 | * @author zhangzq
17 | * @version 1.0
18 | * @date 2016年7月7日 下午2:09:03
19 | * @param
20 | */
21 | public class PaginationResult implements Serializable{
22 |
23 |
24 |
25 | /** serialVersionUID */
26 | private static final long serialVersionUID = 1L;
27 |
28 |
29 | public PaginationResult() {
30 |
31 | }
32 |
33 | /**
34 | * 暂时没有发现这个字段的含义.
35 | * datatables 提示这是必须的字段,暂时保留.
36 | */
37 | private int draw;
38 |
39 | /**
40 | * 经过查询条件查询的总个数.
41 | * (一般情况下 默认和recordsTotal 保持一样就可以)
42 | */
43 | private long recordsFiltered;
44 |
45 | /**
46 | * 查询的总个数
47 | */
48 | private long recordsTotal;
49 |
50 | /**
51 | * 查询某页返回的数据.
52 | */
53 | private List data;
54 |
55 |
56 | public int getDraw() {
57 | return draw;
58 | }
59 |
60 |
61 | public void setDraw(int draw) {
62 | this.draw = draw;
63 | }
64 |
65 |
66 | public long getRecordsFiltered() {
67 | return recordsFiltered;
68 | }
69 |
70 |
71 | public void setRecordsFiltered(long recordsFiltered) {
72 | this.recordsFiltered = recordsFiltered;
73 | }
74 |
75 | public long getRecordsTotal() {
76 | return recordsTotal;
77 | }
78 |
79 |
80 | public void setRecordsTotal(long recordsTotal) {
81 | this.recordsTotal = recordsTotal;
82 | }
83 |
84 | public List getData() {
85 | return data;
86 | }
87 |
88 |
89 | public void setData(List data) {
90 | this.data = data;
91 | }
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/jpa/service/page/Search.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.jpa.service.page;
2 |
3 | import java.io.Serializable;
4 |
5 | public class Search implements Serializable {
6 | /**
7 | *
8 | */
9 | private static final long serialVersionUID = 1L;
10 | private String value;
11 | private boolean regex;
12 |
13 | public String getValue() {
14 | return value;
15 | }
16 |
17 | public void setValue(String value) {
18 | this.value = value;
19 | }
20 |
21 | public boolean isRegex() {
22 | return regex;
23 | }
24 |
25 | public void setRegex(boolean regex) {
26 | this.regex = regex;
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/jpa/service/page/SpecificationUtil.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.jpa.service.page;
2 |
3 |
4 | import org.springframework.data.domain.PageRequest;
5 | import org.springframework.data.domain.Sort;
6 | import org.springframework.data.domain.Sort.Direction;
7 | import org.springframework.data.jpa.domain.Specification;
8 |
9 | import com.zktd.bigdata.common.mongodb.utils.ReflectionUtils;
10 | import com.zktd.bigdata.common.util.SearchFilter;
11 |
12 | import java.util.Map;
13 |
14 | public class SpecificationUtil {
15 |
16 | protected Class entityClass;
17 |
18 |
19 | public SpecificationUtil() {
20 | this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
21 | }
22 |
23 | /**
24 | * 创建分页请求.
25 | */
26 | protected PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
27 | Sort sort = null;
28 | if ("auto".equals(sortType)) {
29 | sort = new Sort(Direction.ASC, "id");
30 | } else if (sortType != null && !"".equals(sortType) && !sortType.contains("_ASC")) {
31 | sort = new Sort(Direction.DESC, sortType);
32 | } else if(null != sortType && sortType.contains("_ASC")) {
33 | sort = new Sort(Direction.ASC, sortType.split("_ASC")[0]);
34 | }
35 | return new PageRequest(pageNumber - 1, pagzSize, sort);
36 | }
37 |
38 | /**
39 | * 创建动态查询条件组合.
40 | */
41 | public Specification buildSpecification(Map searchParams,String orAnd) {
42 | Map filters = SearchFilter.parse(searchParams);
43 | Specification spec=null;
44 | if(orAnd.equals("or")){
45 | spec = DynamicSpecifications.bySearchFilterOr(filters.values(), ReflectionUtils.getSuperClassGenricType(getClass()));
46 | }else{
47 | spec = DynamicSpecifications.bySearchFilter(filters.values(), ReflectionUtils.getSuperClassGenricType(getClass()));
48 | }
49 |
50 | return spec;
51 | }
52 |
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/dao/BaseDao.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.dao;
2 |
3 |
4 | import java.io.Serializable;
5 |
6 | import org.springframework.data.mongodb.repository.MongoRepository;
7 | import org.springframework.data.repository.NoRepositoryBean;
8 |
9 | @NoRepositoryBean
10 | public interface BaseDao extends MongoRepository {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/service/CommonService.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.service;
2 |
3 |
4 | import java.io.Serializable;
5 | import java.util.List;
6 |
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.Sort;
9 | import org.springframework.data.mongodb.core.query.Query;
10 | import org.springframework.web.bind.annotation.RequestBody;
11 | import org.springframework.web.bind.annotation.RequestMapping;
12 | import org.springframework.web.bind.annotation.RequestMethod;
13 | import org.springframework.web.bind.annotation.RequestParam;
14 |
15 | public interface CommonService {
16 | @RequestMapping(value = "/save", method = RequestMethod.POST)
17 | S save(S var1);
18 |
19 | @RequestMapping(value = "/findAll", method = RequestMethod.GET)
20 | List findAll();
21 |
22 | @RequestMapping(value = "/findOne", method = RequestMethod.GET)
23 | T findOneById(ID id);
24 |
25 | @RequestMapping(value = "/findOneByExample", method = RequestMethod.GET)
26 | T findOneByExample(T t);
27 |
28 | @RequestMapping(value = "/findByExample", method = RequestMethod.GET)
29 | List findByExample(T t);
30 |
31 | @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
32 | void delete( ID id);
33 |
34 | @RequestMapping(value = "/delete", method = RequestMethod.GET)
35 | void delete(T var1);
36 | /**
37 | * @param searchParams
38 | * @param pageNumber
39 | * @param pageSize
40 | * @param sortType
41 | *
42 | * @return
43 | */
44 | @RequestMapping(value = "/searchPage", method = RequestMethod.POST)
45 | public Page searchPage(@RequestParam("query") final Query query,@RequestParam("pageNumber") final int pageNumber, @RequestParam("pageSize") final int pageSize, @RequestParam("sort") final Sort sort);
46 |
47 | @RequestMapping(value = "/search", method = RequestMethod.POST)
48 | public List search(@RequestParam("query") final Query query,@RequestParam("sort") final Sort sort);
49 | }
50 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/service/EntityService.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.service;
2 |
3 | import java.io.Serializable;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.Sort;
9 | import org.springframework.data.mongodb.core.query.Query;
10 |
11 | /**
12 | *
13 | * 所有业务查询接口的基类
14 | */
15 | public interface EntityService {
16 |
17 | /**
18 | *
19 | * 根据ID 获取实体对象
20 | *
21 | * @param id
22 | * @return
23 | */
24 | public T get(PK id);
25 |
26 | /**
27 | *
28 | * 根据主键删除实体对象
29 | *
30 | * @param id
31 | */
32 | public void delete(PK id);
33 |
34 | public void delete(Iterable entities);
35 | /**
36 | *
37 | * 根据主键删除实体对象
38 | *
39 | * @param id
40 | */
41 | public void delete(T entity);
42 |
43 | /**
44 | *
45 | * 添加实体对象
46 | *
47 | * @param t
48 | * @return
49 | */
50 | public void save(T t);
51 |
52 | /**
53 | * 获取所有实体对象
54 | */
55 | public Iterable getAll();
56 |
57 | /**
58 | * @param searchParams
59 | * @param pageNumber
60 | * @param pageSize
61 | * @param sortType
62 | * @return
63 | */
64 | Page search(Query query, int pageNumber, int pageSize, Sort sort);
65 | List search(Query query,Sort sort);
66 |
67 | //public List findAll(Map searchParams);
68 |
69 | //public List findAll(Map searchParams, Sort sort);
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/service/impl/CommonServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.service.impl;
2 |
3 | import com.zktd.bigdata.common.mongodb.service.CommonService;
4 | import com.zktd.bigdata.common.mongodb.utils.ReflectionUtils;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.data.domain.*;
8 | import org.springframework.data.mongodb.core.MongoTemplate;
9 | import org.springframework.data.mongodb.core.query.Query;
10 | import org.springframework.data.mongodb.repository.MongoRepository;
11 | import org.springframework.web.bind.annotation.RequestBody;
12 | import org.springframework.web.bind.annotation.RequestParam;
13 |
14 | import java.io.Serializable;
15 | import java.util.List;
16 |
17 | public class CommonServiceImpl, T, ID extends Serializable>
18 | implements CommonService {
19 |
20 | protected Class entityClass;
21 |
22 | @Autowired
23 | protected M baseRepository;
24 |
25 | @Autowired
26 | protected MongoTemplate mt;
27 |
28 | @Override
29 | public S save(@RequestBody S var1) {
30 | return baseRepository.save(var1);
31 | }
32 |
33 | @Override
34 | public List findAll() {
35 | return baseRepository.findAll();
36 | }
37 |
38 | @Override
39 | public T findOneById(@RequestParam ID id) {
40 | return baseRepository.findOne(id);
41 | }
42 |
43 | @Override
44 | public T findOneByExample(T t) {
45 | Example example = Example.of(t);
46 | return baseRepository.findOne(example);
47 | }
48 |
49 | @Override
50 | public List findByExample(@RequestBody T t) {
51 | Example example = Example.of(t);
52 | return baseRepository.findAll(example);
53 | }
54 |
55 | @Override
56 | public void delete(@RequestParam ID id) {
57 | baseRepository.delete(id);
58 | }
59 |
60 | @Override
61 | public void delete(@RequestBody T var1) {
62 | baseRepository.delete(var1);
63 | }
64 |
65 | public CommonServiceImpl() {
66 | this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass(),1);
67 | }
68 |
69 | @Override
70 | public Page searchPage(@RequestParam("query") final Query query,@RequestParam("pageNumber") final int pageNumber, @RequestParam("pageSize") final int pageSize, @RequestParam("sort") final Sort sort){
71 | //PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
72 |
73 | //PageRequest 是Pageable的实现 ,,,PageImpl 是Page的实现
74 | PageRequest pageRequest = new PageRequest(pageNumber, pageSize, sort);
75 | query.with(sort);
76 | long total = mt.count(query, entityClass);
77 |
78 | List list = mt.find(query.with(pageRequest), entityClass);
79 |
80 | return new PageImpl(list,pageRequest,total);
81 | }
82 | @Override
83 | public List search(@RequestParam("query") final Query query,@RequestParam("sort") final Sort sort){
84 | query.with(sort);
85 | List list = mt.find(query, entityClass);
86 | return list;
87 | }
88 |
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/service/impl/EntityServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.service.impl;
2 |
3 | import java.io.Serializable;
4 | import java.util.List;
5 |
6 | import org.springframework.data.domain.Page;
7 | import org.springframework.data.domain.PageImpl;
8 | import org.springframework.data.domain.PageRequest;
9 | import org.springframework.data.domain.Sort;
10 | import org.springframework.data.domain.Sort.Direction;
11 | import org.springframework.data.mongodb.core.MongoTemplate;
12 | import org.springframework.data.mongodb.core.query.Query;
13 |
14 | import com.zktd.bigdata.common.mongodb.dao.BaseDao;
15 | import com.zktd.bigdata.common.mongodb.service.EntityService;
16 | import com.zktd.bigdata.common.mongodb.utils.ReflectionUtils;
17 |
18 |
19 |
20 | /**
21 | *
22 | * 所有业务查询实现类的基类
23 | */
24 | public abstract class EntityServiceImpl> implements
25 | EntityService {
26 |
27 | protected Class entityClass;
28 |
29 | protected EntityDao entityDao;
30 |
31 | /**
32 | * 注入mongodbTemplate
33 | *
34 | * @param mongoTemplate
35 | */
36 | protected abstract void setMongoTemplate(MongoTemplate mongoTemplate);
37 |
38 |
39 | /**
40 | * spring mongodb 集成操作类
41 | */
42 | protected MongoTemplate mt;
43 |
44 | @Override
45 | public T get(PK id) {
46 |
47 | return entityDao.findOne(id);
48 | }
49 |
50 | @Override
51 | public void delete(PK id) {
52 | entityDao.delete(id);
53 | }
54 |
55 | public void delete(T entity){
56 | entityDao.delete(entity);
57 | }
58 |
59 | @Override
60 | public void save(T t) {
61 | entityDao.save(t);
62 | }
63 |
64 | @Override
65 | public Iterable getAll() {
66 |
67 | return entityDao.findAll();
68 | }
69 |
70 | public EntityServiceImpl() {
71 | this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
72 | }
73 |
74 |
75 | public abstract void setEntityDao(EntityDao entityDao);
76 |
77 | @Override
78 | public void delete(Iterable entities) {
79 | entityDao.delete(entities);
80 | }
81 |
82 |
83 |
84 |
85 |
86 |
87 | @Override
88 | public Page search(Query query, int pageNumber, int pageSize, Sort sort) {
89 | //PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
90 |
91 | //PageRequest 是Pageable的实现 ,,,PageImpl 是Page的实现
92 | PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);
93 | query.with(sort);
94 | long total = mt.count(query, entityClass);
95 |
96 | List list = mt.find(query.with(pageRequest), entityClass);
97 |
98 | return new PageImpl(list,pageRequest,total);
99 | }
100 | @Override
101 | public List search(Query query, Sort sort) {
102 | query.with(sort);
103 | List list = mt.find(query, entityClass);
104 | return list;
105 | }
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/utils/ReflectionUtils.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.mongodb.utils;
2 |
3 | import java.lang.reflect.Field;
4 | import java.lang.reflect.InvocationTargetException;
5 | import java.lang.reflect.Method;
6 | import java.lang.reflect.ParameterizedType;
7 | import java.lang.reflect.Type;
8 |
9 | import org.apache.commons.lang3.StringUtils;
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 | import org.springframework.util.Assert;
13 |
14 | /**
15 | * 反射工具类.
16 | *
17 | * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
18 | */
19 | public class ReflectionUtils {
20 |
21 | private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
22 |
23 | /**
24 | * 调用Getter方法.
25 | */
26 | public static Object invokeGetterMethod(Object obj, String propertyName) {
27 | String getterMethodName = "get" + StringUtils.capitalize(propertyName);
28 | return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
29 | }
30 |
31 | /**
32 | * 调用Setter方法.使用value的Class来查找Setter方法.
33 | */
34 | public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
35 | invokeSetterMethod(obj, propertyName, value, null);
36 | }
37 |
38 | /**
39 | * 调用Setter方法.
40 | *
41 | * @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
42 | */
43 | public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class> propertyType) {
44 | Class> type = propertyType != null ? propertyType : value.getClass();
45 | String setterMethodName = "set" + StringUtils.capitalize(propertyName);
46 | invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value });
47 | }
48 |
49 | /**
50 | * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
51 | */
52 | public static Object getFieldValue(final Object obj, final String fieldName) {
53 | Field field = getAccessibleField(obj, fieldName);
54 |
55 | if (field == null) {
56 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
57 | }
58 |
59 | Object result = null;
60 | try {
61 | result = field.get(obj);
62 | } catch (IllegalAccessException e) {
63 | logger.error("不可能抛出的异常{}", e.getMessage());
64 | }
65 | return result;
66 | }
67 |
68 | /**
69 | * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
70 | */
71 | public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
72 | Field field = getAccessibleField(obj, fieldName);
73 |
74 | if (field == null) {
75 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
76 | }
77 |
78 | try {
79 | field.set(obj, value);
80 | } catch (IllegalAccessException e) {
81 | logger.error("不可能抛出的异常:{}", e.getMessage());
82 | }
83 | }
84 |
85 | /**
86 | * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
87 | *
88 | * 如向上转型到Object仍无法找到, 返回null.
89 | */
90 | public static Field getAccessibleField(final Object obj, final String fieldName) {
91 | Assert.notNull(obj, "object不能为空");
92 | Assert.hasText(fieldName, "fieldName");
93 | for (Class> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
94 | try {
95 | Field field = superClass.getDeclaredField(fieldName);
96 | field.setAccessible(true);
97 | return field;
98 | } catch (NoSuchFieldException e) {//NOSONAR
99 | // Field不在当前类定义,继续向上转型
100 | }
101 | }
102 | return null;
103 | }
104 |
105 | /**
106 | * 直接调用对象方法, 无视private/protected修饰符.
107 | * 用于一次性调用的情况.
108 | */
109 | public static Object invokeMethod(final Object obj, final String methodName, final Class>[] parameterTypes,
110 | final Object[] args) {
111 | Method method = getAccessibleMethod(obj, methodName, parameterTypes);
112 | if (method == null) {
113 | throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
114 | }
115 |
116 | try {
117 | return method.invoke(obj, args);
118 | } catch (Exception e) {
119 | throw convertReflectionExceptionToUnchecked(e);
120 | }
121 | }
122 |
123 | /**
124 | * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
125 | * 如向上转型到Object仍无法找到, 返回null.
126 | *
127 | * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
128 | */
129 | public static Method getAccessibleMethod(final Object obj, final String methodName,
130 | final Class>... parameterTypes) {
131 | Assert.notNull(obj, "object不能为空");
132 |
133 | for (Class> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
134 | try {
135 | Method method = superClass.getDeclaredMethod(methodName, parameterTypes);
136 |
137 | method.setAccessible(true);
138 |
139 | return method;
140 |
141 | } catch (NoSuchMethodException e) {//NOSONAR
142 | // Method不在当前类定义,继续向上转型
143 | }
144 | }
145 | return null;
146 | }
147 |
148 | /**
149 | * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
150 | * 如无法找到, 返回Object.class.
151 | * eg.
152 | * public UserDao extends HibernateDao
153 | *
154 | * @param clazz The class to introspect
155 | * @return the first generic declaration, or Object.class if cannot be determined
156 | */
157 | @SuppressWarnings({ "unchecked", "rawtypes" })
158 | public static Class getSuperClassGenricType(final Class clazz) {
159 | return getSuperClassGenricType(clazz, 0);
160 | }
161 |
162 | /**
163 | * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
164 | * 如无法找到, 返回Object.class.
165 | *
166 | * 如public UserDao extends HibernateDao
167 | *
168 | * @param clazz clazz The class to introspect
169 | * @param index the Index of the generic ddeclaration,start from 0.
170 | * @return the index generic declaration, or Object.class if cannot be determined
171 | */
172 | @SuppressWarnings("rawtypes")
173 | public static Class getSuperClassGenricType(final Class clazz, final int index) {
174 |
175 | Type genType = clazz.getGenericSuperclass();
176 |
177 | if (!(genType instanceof ParameterizedType)) {
178 | logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
179 | return Object.class;
180 | }
181 |
182 | Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
183 |
184 | if (index >= params.length || index < 0) {
185 | logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
186 | + params.length);
187 | return Object.class;
188 | }
189 | if (!(params[index] instanceof Class)) {
190 | logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
191 | return Object.class;
192 | }
193 |
194 | return (Class) params[index];
195 | }
196 |
197 | /**
198 | * 将反射时的checked exception转换为unchecked exception.
199 | */
200 | public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
201 | if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
202 | || e instanceof NoSuchMethodException) {
203 | return new IllegalArgumentException("Reflection Exception.", e);
204 | } else if (e instanceof InvocationTargetException) {
205 | return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
206 | } else if (e instanceof RuntimeException) {
207 | return (RuntimeException) e;
208 | }
209 | return new RuntimeException("Unexpected Checked Exception.", e);
210 | }
211 | }
212 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/mongodb/utils/Reflections.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2005-2012 springside.org.cn
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | */
6 | package com.zktd.bigdata.common.mongodb.utils;
7 |
8 | import java.lang.reflect.Field;
9 | import java.lang.reflect.InvocationTargetException;
10 | import java.lang.reflect.Method;
11 | import java.lang.reflect.Modifier;
12 | import java.lang.reflect.ParameterizedType;
13 | import java.lang.reflect.Type;
14 |
15 | import org.apache.commons.lang3.StringUtils;
16 | import org.apache.commons.lang3.Validate;
17 | import org.slf4j.Logger;
18 | import org.slf4j.LoggerFactory;
19 | import org.springframework.util.Assert;
20 |
21 | /**
22 | * 反射工具类.
23 | *
24 | * 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
25 | *
26 | * @author calvin
27 | */
28 | public class Reflections {
29 | private static final String SETTER_PREFIX = "set";
30 |
31 | private static final String GETTER_PREFIX = "get";
32 |
33 | private static final String CGLIB_CLASS_SEPARATOR = "$$";
34 |
35 | private static Logger logger = LoggerFactory.getLogger(Reflections.class);
36 |
37 | /**
38 | * 调用Getter方法.
39 | */
40 | public static Object invokeGetter(Object obj, String propertyName) {
41 | String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(propertyName);
42 | return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
43 | }
44 |
45 | /**
46 | * 调用Setter方法, 仅匹配方法名。
47 | */
48 | public static void invokeSetter(Object obj, String propertyName, Object value) {
49 | String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName);
50 | invokeMethodByName(obj, setterMethodName, new Object[] { value });
51 | }
52 |
53 | /**
54 | * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
55 | */
56 | public static Object getFieldValue(final Object obj, final String fieldName) {
57 | Field field = getAccessibleField(obj, fieldName);
58 |
59 | if (field == null) {
60 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
61 | }
62 |
63 | Object result = null;
64 | try {
65 | result = field.get(obj);
66 | } catch (IllegalAccessException e) {
67 | logger.error("不可能抛出的异常{}", e.getMessage());
68 | }
69 | return result;
70 | }
71 |
72 | /**
73 | * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
74 | */
75 | public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
76 | Field field = getAccessibleField(obj, fieldName);
77 |
78 | if (field == null) {
79 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
80 | }
81 |
82 | try {
83 | field.set(obj, value);
84 | } catch (IllegalAccessException e) {
85 | logger.error("不可能抛出的异常:{}", e.getMessage());
86 | }
87 | }
88 |
89 | /**
90 | * 直接调用对象方法, 无视private/protected修饰符.
91 | * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
92 | * 同时匹配方法名+参数类型,
93 | */
94 | public static Object invokeMethod(final Object obj, final String methodName, final Class>[] parameterTypes,
95 | final Object[] args) {
96 | Method method = getAccessibleMethod(obj, methodName, parameterTypes);
97 | if (method == null) {
98 | throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
99 | }
100 |
101 | try {
102 | return method.invoke(obj, args);
103 | } catch (Exception e) {
104 | throw convertReflectionExceptionToUnchecked(e);
105 | }
106 | }
107 |
108 | /**
109 | * 直接调用对象方法, 无视private/protected修饰符,
110 | * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
111 | * 只匹配函数名,如果有多个同名函数调用第一个。
112 | */
113 | public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
114 | Method method = getAccessibleMethodByName(obj, methodName);
115 | if (method == null) {
116 | throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
117 | }
118 |
119 | try {
120 | return method.invoke(obj, args);
121 | } catch (Exception e) {
122 | throw convertReflectionExceptionToUnchecked(e);
123 | }
124 | }
125 |
126 | /**
127 | * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
128 | *
129 | * 如向上转型到Object仍无法找到, 返回null.
130 | */
131 | public static Field getAccessibleField(final Object obj, final String fieldName) {
132 | Validate.notNull(obj, "object can't be null");
133 | Validate.notBlank(fieldName, "fieldName can't be blank");
134 | for (Class> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
135 | try {
136 | Field field = superClass.getDeclaredField(fieldName);
137 | makeAccessible(field);
138 | return field;
139 | } catch (NoSuchFieldException e) {//NOSONAR
140 | // Field不在当前类定义,继续向上转型
141 | }
142 | }
143 | return null;
144 | }
145 |
146 | /**
147 | * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
148 | * 如向上转型到Object仍无法找到, 返回null.
149 | * 匹配函数名+参数类型。
150 | *
151 | * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
152 | */
153 | public static Method getAccessibleMethod(final Object obj, final String methodName,
154 | final Class>... parameterTypes) {
155 | Validate.notNull(obj, "object can't be null");
156 | Validate.notBlank(methodName, "methodName can't be blank");
157 |
158 | for (Class> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
159 | try {
160 | Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
161 | makeAccessible(method);
162 | return method;
163 | } catch (NoSuchMethodException e) {
164 | // Method不在当前类定义,继续向上转型
165 | }
166 | }
167 | return null;
168 | }
169 |
170 | /**
171 | * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
172 | * 如向上转型到Object仍无法找到, 返回null.
173 | * 只匹配函数名。
174 | *
175 | * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
176 | */
177 | public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
178 | Validate.notNull(obj, "object can't be null");
179 | Validate.notBlank(methodName, "methodName can't be blank");
180 |
181 | for (Class> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
182 | Method[] methods = searchType.getDeclaredMethods();
183 | for (Method method : methods) {
184 | if (method.getName().equals(methodName)) {
185 | makeAccessible(method);
186 | return method;
187 | }
188 | }
189 | }
190 | return null;
191 | }
192 |
193 | /**
194 | * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
195 | */
196 | public static void makeAccessible(Method method) {
197 | if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
198 | && !method.isAccessible()) {
199 | method.setAccessible(true);
200 | }
201 | }
202 |
203 | /**
204 | * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
205 | */
206 | public static void makeAccessible(Field field) {
207 | if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
208 | .isFinal(field.getModifiers())) && !field.isAccessible()) {
209 | field.setAccessible(true);
210 | }
211 | }
212 |
213 | /**
214 | * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
215 | * 如无法找到, 返回Object.class.
216 | * eg.
217 | * public UserDao extends HibernateDao
218 | *
219 | * @param clazz The class to introspect
220 | * @return the first generic declaration, or Object.class if cannot be determined
221 | */
222 | @SuppressWarnings({ "unchecked", "rawtypes" })
223 | public static Class getClassGenricType(final Class clazz) {
224 | return getClassGenricType(clazz, 0);
225 | }
226 |
227 | /**
228 | * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
229 | * 如无法找到, 返回Object.class.
230 | *
231 | * 如public UserDao extends HibernateDao
232 | *
233 | * @param clazz clazz The class to introspect
234 | * @param index the Index of the generic ddeclaration,start from 0.
235 | * @return the index generic declaration, or Object.class if cannot be determined
236 | */
237 | @SuppressWarnings("rawtypes")
238 | public static Class getClassGenricType(final Class clazz, final int index) {
239 |
240 | Type genType = clazz.getGenericSuperclass();
241 |
242 | if (!(genType instanceof ParameterizedType)) {
243 | logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
244 | return Object.class;
245 | }
246 |
247 | Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
248 |
249 | if (index >= params.length || index < 0) {
250 | logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
251 | + params.length);
252 | return Object.class;
253 | }
254 | if (!(params[index] instanceof Class)) {
255 | logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
256 | return Object.class;
257 | }
258 |
259 | return (Class) params[index];
260 | }
261 |
262 | @SuppressWarnings("rawtypes")
263 | public static Class> getUserClass(Object instance) {
264 | Assert.notNull(instance, "Instance must not be null");
265 | Class clazz = instance.getClass();
266 | if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
267 | Class> superClass = clazz.getSuperclass();
268 | if (superClass != null && !Object.class.equals(superClass)) {
269 | return superClass;
270 | }
271 | }
272 | return clazz;
273 |
274 | }
275 |
276 | /**
277 | * 将反射时的checked exception转换为unchecked exception.
278 | */
279 | public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
280 | if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
281 | || e instanceof NoSuchMethodException) {
282 | return new IllegalArgumentException(e);
283 | } else if (e instanceof InvocationTargetException) {
284 | return new RuntimeException(((InvocationTargetException) e).getTargetException());
285 | } else if (e instanceof RuntimeException) {
286 | return (RuntimeException) e;
287 | }
288 | return new RuntimeException("Unexpected Checked Exception.", e);
289 | }
290 | }
291 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/util/Collections3.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2005-2012 springside.org.cn
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | */
6 | package com.zktd.bigdata.common.util;
7 |
8 | import java.util.ArrayList;
9 | import java.util.Collection;
10 | import java.util.HashMap;
11 | import java.util.Iterator;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | import org.apache.commons.beanutils.PropertyUtils;
16 | import org.apache.commons.lang3.StringUtils;
17 |
18 | import com.zktd.bigdata.common.mongodb.utils.Reflections;
19 |
20 | /**
21 | * Collections工具集.
22 | *
23 | * 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
24 | *
25 | * 函数主要由两部分组成,一是自反射提取元素的功能,二是源自Apache Commons Collection, 争取不用在项目里引入它。
26 | *
27 | * @author calvin
28 | */
29 | public class Collections3 {
30 |
31 | /**
32 | * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
33 | *
34 | * @param collection 来源集合.
35 | * @param keyPropertyName 要提取为Map中的Key值的属性名.
36 | * @param valuePropertyName 要提取为Map中的Value值的属性名.
37 | */
38 | @SuppressWarnings({ "rawtypes", "unchecked" })
39 | public static Map extractToMap(final Collection collection, final String keyPropertyName,
40 | final String valuePropertyName) {
41 | Map map = new HashMap(collection.size());
42 |
43 | try {
44 | for (Object obj : collection) {
45 | map.put(PropertyUtils.getProperty(obj, keyPropertyName),
46 | PropertyUtils.getProperty(obj, valuePropertyName));
47 | }
48 | } catch (Exception e) {
49 | throw Reflections.convertReflectionExceptionToUnchecked(e);
50 | }
51 |
52 | return map;
53 | }
54 |
55 | /**
56 | * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
57 | *
58 | * @param collection 来源集合.
59 | * @param propertyName 要提取的属性名.
60 | */
61 | @SuppressWarnings({ "rawtypes", "unchecked" })
62 | public static List extractToList(final Collection collection, final String propertyName) {
63 | List list = new ArrayList(collection.size());
64 |
65 | try {
66 | for (Object obj : collection) {
67 | list.add(PropertyUtils.getProperty(obj, propertyName));
68 | }
69 | } catch (Exception e) {
70 | throw Reflections.convertReflectionExceptionToUnchecked(e);
71 | }
72 |
73 | return list;
74 | }
75 |
76 | /**
77 | * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
78 | *
79 | * @param collection 来源集合.
80 | * @param propertyName 要提取的属性名.
81 | * @param separator 分隔符.
82 | */
83 | @SuppressWarnings("rawtypes")
84 | public static String extractToString(final Collection collection, final String propertyName, final String separator) {
85 | List list = extractToList(collection, propertyName);
86 | return StringUtils.join(list, separator);
87 | }
88 |
89 | /**
90 | * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
91 | */
92 | @SuppressWarnings("rawtypes")
93 | public static String convertToString(final Collection collection, final String separator) {
94 | return StringUtils.join(collection, separator);
95 | }
96 |
97 | /**
98 | * 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix,后面加入postfix,如mymessage
。
99 | */
100 | @SuppressWarnings("rawtypes")
101 | public static String convertToString(final Collection collection, final String prefix, final String postfix) {
102 | StringBuilder builder = new StringBuilder();
103 | for (Object o : collection) {
104 | builder.append(prefix).append(o).append(postfix);
105 | }
106 | return builder.toString();
107 | }
108 |
109 | /**
110 | * 判断是否为空.
111 | */
112 | @SuppressWarnings("rawtypes")
113 | public static boolean isEmpty(Collection collection) {
114 | return (collection == null || collection.isEmpty());
115 | }
116 |
117 | /**
118 | * 判断是否为空.
119 | */
120 | @SuppressWarnings("rawtypes")
121 | public static boolean isNotEmpty(Collection collection) {
122 | return (collection != null && !(collection.isEmpty()));
123 | }
124 |
125 | /**
126 | * 取得Collection的第一个元素,如果collection为空返回null.
127 | */
128 | public static T getFirst(Collection collection) {
129 | if (isEmpty(collection)) {
130 | return null;
131 | }
132 |
133 | return collection.iterator().next();
134 | }
135 |
136 | /**
137 | * 获取Collection的最后一个元素 ,如果collection为空返回null.
138 | */
139 | public static T getLast(Collection collection) {
140 | if (isEmpty(collection)) {
141 | return null;
142 | }
143 |
144 | // 当类型为List时,直接取得最后一个元素 。
145 | if (collection instanceof List) {
146 | List list = (List) collection;
147 | return list.get(list.size() - 1);
148 | }
149 |
150 | // 其他类型通过iterator滚动到最后一个元素.
151 | Iterator iterator = collection.iterator();
152 | while (true) {
153 | T current = iterator.next();
154 | if (!iterator.hasNext()) {
155 | return current;
156 | }
157 | }
158 | }
159 |
160 | /**
161 | * 返回a+b的新List.
162 | */
163 | public static List union(final Collection a, final Collection b) {
164 | List result = new ArrayList(a);
165 | result.addAll(b);
166 | return result;
167 | }
168 |
169 | /**
170 | * 返回a-b的新List.
171 | */
172 | public static List subtract(final Collection a, final Collection b) {
173 | List list = new ArrayList(a);
174 | for (T element : b) {
175 | list.remove(element);
176 | }
177 |
178 | return list;
179 | }
180 |
181 | /**
182 | * 返回a与b的交集的新List.
183 | */
184 | public static List intersection(Collection a, Collection b) {
185 | List list = new ArrayList();
186 |
187 | for (T element : a) {
188 | if (b.contains(element)) {
189 | list.add(element);
190 | }
191 | }
192 | return list;
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/util/ConvertUtils.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.util;
2 |
3 | import org.apache.commons.beanutils.PropertyUtils;
4 | import org.apache.commons.beanutils.converters.DateConverter;
5 | import org.apache.commons.lang3.StringUtils;
6 |
7 | import com.zktd.bigdata.common.mongodb.utils.ReflectionUtils;
8 |
9 | import java.text.DateFormat;
10 | import java.text.SimpleDateFormat;
11 | import java.util.ArrayList;
12 | import java.util.Collection;
13 | import java.util.Date;
14 | import java.util.List;
15 |
16 | public class ConvertUtils {
17 |
18 | static {
19 | registerDateConverter();
20 | }
21 |
22 | /**
23 | * 提取集合中的对象的属性(通过getter函数), 组合成List.
24 | *
25 | * @param collection 来源集合.
26 | * @param propertyName 要提取的属性名.
27 | */
28 | @SuppressWarnings({"unchecked", "rawtypes"})
29 | public static List convertElementPropertyToList(final Collection collection, final String propertyName) {
30 | List list = new ArrayList();
31 |
32 | try {
33 | for (Object obj : collection) {
34 | list.add(PropertyUtils.getProperty(obj, propertyName));
35 | }
36 | } catch (Exception e) {
37 | throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
38 | }
39 |
40 | return list;
41 | }
42 |
43 | /**
44 | * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
45 | *
46 | * @param collection 来源集合.
47 | * @param propertyName 要提取的属性名.
48 | * @param separator 分隔符.
49 | */
50 | @SuppressWarnings("rawtypes")
51 | public static String convertElementPropertyToString(final Collection collection, final String propertyName,
52 | final String separator) {
53 | List list = convertElementPropertyToList(collection, propertyName);
54 | return StringUtils.join(list, separator);
55 | }
56 |
57 | /**
58 | * 转换字符串到相应类型.
59 | *
60 | * @param value 待转换的字符串.
61 | * @param toType 转换目标类型.
62 | */
63 | public static Object convertStringToObject(String value, Class> toType) {
64 | try {
65 | return org.apache.commons.beanutils.ConvertUtils.convert(value, toType);
66 | } catch (Exception e) {
67 | throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
68 | }
69 | }
70 |
71 | /**
72 | * 定义日期Converter的格式: yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss
73 | */
74 | private static void registerDateConverter() {
75 | DateConverter dc = new DateConverter();
76 | dc.setUseLocaleFormat(true);
77 | dc.setPatterns(new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});
78 | org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class);
79 | }
80 |
81 | public static String getDateYYYYMMDD(Date date) {
82 | if (null == date) {
83 | return "";
84 | }
85 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
86 |
87 | return (df.format(date));
88 | }
89 |
90 |
91 | /**
92 | * @param [obj]
93 | * @return java.lang.String
94 | * @desc null对象返回空字符串
95 | * @author wangzhenjiang
96 | * @date 2017-12-15 02:13
97 | */
98 | public static String convertNullStr(Object obj) {
99 | if (null == obj) {
100 | return "";
101 | }
102 |
103 |
104 | return obj.toString().trim();
105 | }
106 |
107 |
108 | /**
109 | * @desc string(2017-12-15 14:35) 返回 date(2017-12-15 14:35:00)
110 | * @author wangzhenjiang
111 | * @date 2017-12-15 02:35
112 | * @param [str]
113 | * @return java.util.Date
114 | */
115 | public static Date ToDateTime(String str) {
116 |
117 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
118 | java.util.Date sdate = null; //初始化
119 | try {
120 |
121 | sdate = sdf.parse(str);
122 |
123 | } catch (Exception e) {
124 | e.printStackTrace();
125 | }
126 | return sdate;
127 | }
128 |
129 | /**
130 | * @desc date(2017-12-15 14:35:33) 返回 String(2017-12-15 14:35:33)
131 | * @author wangzhenjiang
132 | * @date 2017-12-15 02:35
133 | * @param [str]
134 | * @return java.util.Date
135 | */
136 | public static String dateToString(Date date) {
137 |
138 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
139 | String str=null;
140 | try {
141 |
142 | str= sdf.format(date);
143 |
144 | } catch (Exception e) {
145 | e.printStackTrace();
146 | }
147 | return str;
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/util/JsonUtil.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.util;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.DeserializationFeature;
5 | import com.fasterxml.jackson.databind.ObjectMapper;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 | import org.springframework.util.Assert;
9 |
10 | import java.io.IOException;
11 | import java.text.SimpleDateFormat;
12 | import java.util.Locale;
13 |
14 | public class JsonUtil {
15 |
16 | private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
17 |
18 | private static ObjectMapper objectMapper = new ObjectMapper();
19 | static {
20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
21 | SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
22 | //日期格式处理
23 | objectMapper.setDateFormat(DATE_FORMAT);
24 | }
25 |
26 | /**
27 | * 按json转化两个对象
28 | * @param srcObj 源对象
29 | * @param targetType 目标类型
30 | * @param
31 | * @return
32 | */
33 | public static T convertByJson(Object srcObj, Class targetType) {
34 | Assert.notNull(srcObj, "源对象不能为null");
35 |
36 | T ret = null;
37 | String jsonStr = null;
38 | try {
39 | if (srcObj instanceof String) {
40 | jsonStr = (String) srcObj;
41 | }
42 | else {
43 | jsonStr = objectMapper.writeValueAsString(srcObj);
44 | }
45 | ret = objectMapper.readValue(jsonStr, targetType);
46 | } catch (Exception e) {
47 | logger.error("转换json出错, srcObj={}, targetType={}, jsonStr={}", srcObj, targetType, jsonStr);
48 | logger.error(e.getMessage(), e);
49 | }
50 | return ret;
51 | }
52 |
53 | /**
54 | * 对象转json string
55 | * @param obj
56 | * @return
57 | */
58 | public static String toJsonStr(Object obj) {
59 | if (obj == null) {
60 | return "";
61 | }
62 |
63 | String ret = "";
64 | try {
65 | ret = objectMapper.writeValueAsString(obj);
66 | } catch (JsonProcessingException e) {
67 | logger.error(e.getMessage(), e);
68 | }
69 | return ret;
70 | }
71 |
72 | /**
73 | * 解析json str
74 | * @param jsonStr
75 | * @param targetType
76 | * @param
77 | * @return
78 | */
79 | public static T parseJson(String jsonStr, Class targetType) {
80 | T ret = null;
81 | try {
82 | ret = objectMapper.readValue(jsonStr, targetType);
83 | } catch (IOException e) {
84 | logger.error(e.getMessage(), e);
85 | }
86 | return ret;
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/util/ResponseBean.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.util;
2 |
3 | import java.io.Serializable;
4 |
5 | public class ResponseBean implements Serializable {
6 |
7 | // http 状态码
8 | private int code;
9 |
10 | // 返回信息
11 | private String msg ="error";
12 |
13 | // 返回的数据
14 | private Object data;
15 | public ResponseBean(){
16 |
17 | }
18 | public ResponseBean(int code, String msg, Object data) {
19 | this.code = code;
20 | this.msg = msg;
21 | this.data = data;
22 | }
23 |
24 | public int getCode() {
25 | return code;
26 | }
27 |
28 | public void setCode(int code) {
29 | this.code = code;
30 | }
31 |
32 | public String getMsg() {
33 | return msg;
34 | }
35 |
36 | public void setMsg(String msg) {
37 | this.msg = msg;
38 | }
39 |
40 | public Object getData() {
41 | return data;
42 | }
43 |
44 | public void setData(Object data) {
45 | this.data = data;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/bigdata-common-service/src/main/java/com/zktd/bigdata/common/util/SearchFilter.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common.util;
2 |
3 | import java.util.Date;
4 | import java.util.Map;
5 | import java.util.Map.Entry;
6 |
7 | import org.apache.commons.lang3.StringUtils;
8 |
9 | import com.google.common.collect.Maps;
10 |
11 | public class SearchFilter {
12 |
13 | public enum Operator {
14 | NEQ, EQ, LIKE, GT, LT, GTE, LTE, ISNULL, ISNOTNULL
15 | }
16 |
17 | /** 属性数据类型. */
18 | public enum PropertyType {
19 | S(String.class), I(Integer.class), L(Long.class), N(Double.class), D(Date.class), B(Boolean.class);
20 |
21 | private Class> clazz;
22 |
23 | private PropertyType(Class> clazz) {
24 | this.clazz = clazz;
25 | }
26 |
27 | public Class> getValue() {
28 | return clazz;
29 | }
30 | }
31 |
32 | public String fieldName;
33 | public Object value;
34 | public Operator operator;
35 |
36 | public SearchFilter(String fieldName, Operator operator, Object value) {
37 | this.fieldName = fieldName;
38 | this.value = value;
39 | this.operator = operator;
40 | }
41 |
42 | /**
43 | * searchParams中key的格式为OPERATOR_FIELDNAME
44 | */
45 | @SuppressWarnings("rawtypes")
46 | public static Map parse(Map searchParams) {
47 | Map filters = Maps.newHashMap();
48 |
49 | for (Entry entry : searchParams.entrySet()) {
50 | // 过滤掉空值
51 | String key = entry.getKey();
52 | Object value = entry.getValue();
53 | if (StringUtils.isBlank((String) value)) {
54 | continue;
55 | }
56 |
57 | // 拆分operator与filedAttribute
58 | String[] names = StringUtils.split(key, "_");
59 | if (names.length != 2) {
60 | throw new IllegalArgumentException(key + " is not a valid search filter name");
61 | }
62 | String filedName = names[1];
63 | String firstPart = names[0];
64 | String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
65 | String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());
66 | Operator operator = Operator.valueOf(matchTypeCode);
67 | Class propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
68 | Object obj = ConvertUtils.convertStringToObject(value.toString(), propertyClass);
69 | // 创建searchFilter
70 | SearchFilter filter = new SearchFilter(filedName, operator, obj);
71 | filters.put(key, filter);
72 | }
73 | return filters;
74 | }
75 | }
--------------------------------------------------------------------------------
/bigdata-server-zipkin/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | zktd-bigdata-platform
7 | zktd.bigdata
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | bigdata-server-zipkin
13 |
14 |
15 |
16 | org.springframework.cloud
17 | spring-cloud-starter-eureka
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-test
27 | test
28 |
29 |
30 |
31 | io.zipkin.java
32 | zipkin-server
33 |
34 |
35 |
36 | io.zipkin.java
37 | zipkin-autoconfigure-ui
38 |
39 |
40 | mysql
41 | mysql-connector-java
42 | runtime
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-jdbc
47 |
48 |
49 | io.zipkin.java
50 | zipkin-autoconfigure-storage-mysql
51 |
52 |
53 | io.zipkin.java
54 | zipkin-storage-mysql
55 | 2.4.9
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/bigdata-server-zipkin/src/main/java/com/zktd/bigdata/ServerZipkinApplication.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata;
2 |
3 | import org.apache.tomcat.jdbc.pool.DataSource;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Primary;
9 | import zipkin.server.EnableZipkinServer;
10 | import zipkin.storage.mysql.MySQLStorage;
11 |
12 |
13 | @SpringBootApplication
14 | @EnableEurekaClient
15 | @EnableZipkinServer
16 | public class ServerZipkinApplication {
17 |
18 | public static void main(String[] args) {
19 | SpringApplication.run(ServerZipkinApplication.class, args);
20 | }
21 |
22 | @Bean
23 | @Primary
24 | public MySQLStorage mySQLStorage(DataSource datasource) {
25 | return MySQLStorage.builder().datasource(datasource).executor(Runnable::run).build();
26 | }
27 | }
--------------------------------------------------------------------------------
/bigdata-server-zipkin/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8888
3 |
4 | spring:
5 | datasource:
6 | url: jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
7 | username: root
8 | password: root
9 | initialSize: 20
10 | driverClassName: com.mysql.jdbc.Driver
11 | sleuth:
12 | enabled: false
13 |
14 | zipkin:
15 | storage:
16 | type: mysql
--------------------------------------------------------------------------------
/bigdata-server-zipkin/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | System.out
6 |
7 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
8 |
9 |
10 |
11 | ../logs/cmp-content-service.log
12 |
13 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
14 |
15 |
16 | ../logs/cmp-content-service.log.%d{yyyy-MM-dd}
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/bigdata-service-discovery/bin/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | zktd.bigdata
5 | zktd-bigdata-platform
6 | 0.0.1-SNAPSHOT
7 |
8 | bigdata-service-discovery
9 | bigdata-service-discovery
10 |
11 |
12 |
13 | org.springframework.cloud
14 | spring-cloud-starter-eureka-server
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter-actuator
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/bigdata-service-discovery/bin/src/main/java/com/zktd/bigdata/DiscoveryApplication.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-service-discovery/bin/src/main/java/com/zktd/bigdata/DiscoveryApplication.class
--------------------------------------------------------------------------------
/bigdata-service-discovery/bin/src/main/resources/bootstrap.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: ${service.server.port:1111}
3 |
4 | eureka:
5 | client:
6 | register-with-eureka: false
7 | fetch-registry: false
8 | serviceUrl:
9 | defaultZone: ${eureka.serviceUrl:http://localhost:1111/eureka/}
10 |
11 |
--------------------------------------------------------------------------------
/bigdata-service-discovery/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | zktd.bigdata
5 | zktd-bigdata-platform
6 | 0.0.1-SNAPSHOT
7 |
8 | bigdata-service-discovery
9 | bigdata-service-discovery
10 |
11 |
12 |
13 | org.springframework.cloud
14 | spring-cloud-starter-eureka-server
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter-actuator
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/bigdata-service-discovery/src/main/java/com/zktd/bigdata/DiscoveryApplication.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata;
2 |
3 |
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.builder.SpringApplicationBuilder;
6 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
7 | import org.springframework.cloud.netflix.feign.EnableFeignClients;
8 |
9 | @EnableEurekaServer
10 | @SpringBootApplication
11 | @EnableFeignClients
12 | public class DiscoveryApplication {
13 | public static void main(String[] args) {
14 | new SpringApplicationBuilder(DiscoveryApplication.class).web(true).run(args);
15 |
16 | }
17 | }
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/bigdata-service-discovery/src/main/resources/bootstrap.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: ${service.server.port:1111}
3 |
4 | eureka:
5 | client:
6 | register-with-eureka: false
7 | fetch-registry: false
8 | serviceUrl:
9 | defaultZone: ${eureka.serviceUrl:http://localhost:1111/eureka/}
10 |
11 |
--------------------------------------------------------------------------------
/bigdata-test-service/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 | 4.0.0
6 |
7 | bigdata-test-service
8 | bigdata-test-service
9 |
10 |
11 | zktd.bigdata
12 | zktd-bigdata-platform
13 | 0.0.1-SNAPSHOT
14 |
15 |
16 |
17 |
18 |
19 | org.springframework.cloud
20 | spring-cloud-starter-eureka
21 |
22 |
23 | zktd.bigdata
24 | bigdata-token-api
25 | ${project.version}
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | org.apache.shiro
35 | shiro-spring
36 | ${shiro-spring.version}
37 |
38 |
39 | com.auth0
40 | java-jwt
41 | ${java-jwt.version}
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-web
46 |
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-starter-thymeleaf
51 |
52 |
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-configuration-processor
57 | true
58 |
59 |
60 | org.springframework.cloud
61 | spring-cloud-starter-zipkin
62 |
63 |
64 | org.springframework.cloud
65 | spring-cloud-starter-hystrix
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/bigdata-test-service/src/main/java/com/zktd/bigdata/TestWebApplication.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
7 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
8 | import org.springframework.cloud.netflix.feign.EnableFeignClients;
9 |
10 |
11 | @EnableDiscoveryClient
12 | @EnableFeignClients
13 | @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
14 | public class TestWebApplication {
15 |
16 | public static void main(String[] args) {
17 | SpringApplication.run(TestWebApplication.class);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/bigdata-test-service/src/main/java/com/zktd/bigdata/controller/TestController.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.controller;
2 |
3 | import com.zktd.bigdata.common.util.ResponseBean;
4 | import com.zktd.bigdata.token.entity.User;
5 | import com.zktd.bigdata.token.service.TokenService;
6 | import lombok.extern.slf4j.Slf4j;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 | import org.springframework.web.bind.annotation.ResponseBody;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import javax.servlet.ServletRequest;
14 | import javax.servlet.ServletResponse;
15 | import javax.servlet.http.HttpServletRequest;
16 |
17 |
18 |
19 | @RestController
20 | @Slf4j
21 | @RequestMapping("/testapi")
22 | public class TestController {
23 |
24 | @Autowired
25 | private TokenService tokenService;
26 |
27 |
28 | /**
29 | * test
30 | * http://localhost:5555/api-test/testapi/test?username=222
31 | * @param request
32 | * @param response
33 | * @return
34 | */
35 | @RequestMapping(value = "/test", method = RequestMethod.POST)
36 | @ResponseBody
37 | public ResponseBean test(ServletRequest request, ServletResponse response) {
38 | HttpServletRequest httpServletRequest = (HttpServletRequest) request;
39 | String username = httpServletRequest.getParameter("username");
40 |
41 | log.info("test====" + username);
42 |
43 | User user=new User();
44 | user.setUserName(username);
45 |
46 | String ss= tokenService.test(user);
47 | return new ResponseBean(200, ss, null);
48 |
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/bigdata-test-service/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | ## swagger2
2 | swagger:
3 | enable: true
4 | group: content #api 的组信息
5 | title: test& #标题
6 | description: 测试 #描述信息
7 | version: v1.10 #版本
8 | contact-name: 中科同德 #联系人名称
9 | contact-url: http://www.bbb.com #联系人url
10 | contact-email: 363701272@qq.com
11 | base-package: com.zktd
12 | license: Apache License Version 2.0
13 | license-url: https://github.com/springfox/springfox/blob/master/LICENSE
14 | host: localhost:8511
15 |
--------------------------------------------------------------------------------
/bigdata-test-service/src/main/resources/bootstrap.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | application:
3 | name: test-service
4 | zipkin:
5 | base-url: http://localhost:8888/
6 |
7 | server:
8 | port: ${service.server.port:8111}
9 | contextPath: /
10 |
11 | #默认feign的hystrix为关闭状态
12 | feign:
13 | hystrix:
14 | enabled: true
15 | hystrix:
16 | command:
17 | default:
18 | execution:
19 | timeout:
20 | enabled: true
21 | isolation:
22 | thread:
23 | timeoutInMilliseconds: 60000
24 | eureka:
25 | instance:
26 | status-page-url: http://localhost:${server.port}/swagger-ui.html # ${server.port}为该服务的端口号
27 | # prefer-ip-address: true
28 | client:
29 | serviceUrl:
30 | defaultZone: ${eureka.serviceUrl:http://localhost:1111/eureka/}
--------------------------------------------------------------------------------
/bigdata-test-service/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | System.out
6 |
7 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
8 |
9 |
10 |
11 | ../logs/cmp-content-service.log
12 |
13 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
14 |
15 |
16 | ../logs/cmp-content-service.log.%d{yyyy-MM-dd}
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/bigdata-token-api/bin/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | zktd.bigdata
5 | zktd-bigdata-platform
6 | 0.0.1-SNAPSHOT
7 |
8 | bigdata-token-api
9 | bigdata-token-api
10 |
11 |
12 | zktd.bigdata
13 | bigdata-common-service
14 | ${project.version}
15 |
16 |
17 | org.springframework.cloud
18 | spring-cloud-starter-feign
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/Function.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/Function.class
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/User.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/User.class
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/UserRoleListCheck.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/entity/UserRoleListCheck.class
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/SecretService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/SecretService.class
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/TokenService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/TokenService.class
--------------------------------------------------------------------------------
/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/UserService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-api/bin/src/main/java/com/zktd/bigdata/token/service/UserService.class
--------------------------------------------------------------------------------
/bigdata-token-api/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | zktd.bigdata
5 | zktd-bigdata-platform
6 | 0.0.1-SNAPSHOT
7 |
8 | bigdata-token-api
9 | bigdata-token-api
10 |
11 |
12 | zktd.bigdata
13 | bigdata-common-service
14 | ${project.version}
15 |
16 |
17 | org.springframework.cloud
18 | spring-cloud-starter-feign
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/entity/Function.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.entity;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.*;
6 |
7 | import org.springframework.data.annotation.Id;
8 | import org.springframework.data.mongodb.core.mapping.Document;
9 | import org.springframework.data.mongodb.core.mapping.Field;
10 |
11 | import com.zktd.bigdata.common.util.ConvertUtils;
12 |
13 | import java.util.Date;
14 |
15 | /**
16 | * 系统功能目录
17 | * @author ouburikou
18 | *
19 | */
20 | @Data
21 | @Document(collection = "function")
22 | public class Function implements java.io.Serializable {
23 |
24 | @Id
25 | private String id;
26 | @Field
27 | private String functionName;
28 | @Field
29 | private String password;
30 |
31 | @Field
32 | private String createTime = ConvertUtils.dateToString(new Date());
33 |
34 | @Field
35 | private String childId;
36 | @Field
37 | private Integer pid;
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/entity/User.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.entity;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.data.annotation.Id;
6 | import org.springframework.data.mongodb.core.mapping.Document;
7 | import org.springframework.data.mongodb.core.mapping.Field;
8 |
9 | import com.zktd.bigdata.common.util.ConvertUtils;
10 |
11 | import lombok.Data;
12 |
13 |
14 | @Data
15 | @Document(collection = "user")
16 | public class User implements java.io.Serializable{
17 |
18 | @Id
19 | private String id;
20 | @Field
21 | private String userName;
22 | @Field
23 | private String password;
24 |
25 | @Field
26 | private String createTime = ConvertUtils.dateToString(new Date());
27 |
28 | @Field
29 | private String status;//用户状态:0-未审核,1-已审核 ,2-锁定
30 |
31 |
32 |
33 | }
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/entity/UserRoleListCheck.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.entity;
2 |
3 | import lombok.Data;
4 | import lombok.extern.slf4j.Slf4j;
5 |
6 | /**
7 | * 给用户添加role时使用。
8 | * @author ouburikou
9 | *
10 | */
11 | @Slf4j
12 | @Data
13 | public class UserRoleListCheck {
14 |
15 | private String username;
16 | private String roleName;
17 | private boolean check=false;
18 |
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/hystrix/TokenServiceFallbackFactory.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.hystrix;
2 |
3 | import com.zktd.bigdata.common.util.ResponseBean;
4 | import com.zktd.bigdata.token.entity.User;
5 | import com.zktd.bigdata.token.service.TokenService;
6 | import feign.hystrix.FallbackFactory;
7 | import org.springframework.stereotype.Component;
8 | import org.springframework.web.bind.annotation.RequestBody;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 |
11 | @Component
12 | public class TokenServiceFallbackFactory implements FallbackFactory {
13 |
14 | @Override
15 | public TokenService create(Throwable cause) {
16 | return new TokenService() {
17 | @Override
18 | public String test(@RequestBody User user){
19 |
20 | return "fallback"+cause.getMessage();
21 | }
22 |
23 | @Override
24 | public ResponseBean chekcToken(@RequestParam("token") String token){
25 | return null;
26 | }
27 |
28 | };
29 | }
30 | }
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/hystrix/TokenServiceHystrix.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.hystrix;
2 |
3 | import com.zktd.bigdata.common.util.ResponseBean;
4 | import com.zktd.bigdata.token.entity.User;
5 | import com.zktd.bigdata.token.service.TokenService;
6 | import org.springframework.stereotype.Component;
7 | import org.springframework.web.bind.annotation.RequestBody;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 |
11 | /**
12 | * @author wangxinwei
13 | * @desc
14 | * @company 北京鑫为科技
15 | * @create 2018-12-10 00:12
16 | */
17 | @Component
18 | @RequestMapping("fallback")
19 | public class TokenServiceHystrix implements TokenService {
20 |
21 |
22 | @Override
23 | public String test(@RequestBody User user){
24 |
25 | return "fallback";
26 | }
27 |
28 | @Override
29 | public ResponseBean chekcToken(@RequestParam("token") String token){
30 | return null;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/service/SecretService.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.service;
2 |
3 |
4 | import org.springframework.stereotype.Service;
5 |
6 | import io.swagger.annotations.Api;
7 | import io.swagger.annotations.ApiOperation;
8 |
9 |
10 | /**
11 | * Created by ouburikou on 17/11/2.
12 | */
13 | @Api(description = "Secret接口")
14 | @Service
15 | public interface SecretService {
16 |
17 | @ApiOperation(value = "secret", notes = "获取secret")
18 | public String secret(String userId);
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/service/TokenService.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.service;
2 |
3 |
4 | import com.zktd.bigdata.common.util.ResponseBean;
5 | import com.zktd.bigdata.token.entity.User;
6 | import com.zktd.bigdata.token.hystrix.TokenServiceHystrix;
7 | import io.swagger.annotations.Api;
8 | import io.swagger.annotations.ApiOperation;
9 | import org.springframework.cloud.netflix.feign.FeignClient;
10 | import org.springframework.web.bind.annotation.RequestBody;
11 | import org.springframework.web.bind.annotation.RequestMapping;
12 | import org.springframework.web.bind.annotation.RequestMethod;
13 | import org.springframework.web.bind.annotation.RequestParam;
14 |
15 |
16 | /**
17 | * Created by ouburikou on 17/11/2.
18 | */
19 | @Api(description = "token接口")
20 | @FeignClient(name = "token-service",fallback = TokenServiceHystrix.class)
21 |
22 | //@FeignClient(name = "token-service",fallbackFactory = TokenServiceFallbackFactory.class)
23 |
24 | //@FeignClient(value = "token-service")
25 |
26 | @RequestMapping("/token/api")
27 | public interface TokenService {
28 |
29 | @ApiOperation(value = "chekcToken", notes = "验证token")
30 | @RequestMapping(value = "/chekcToken", method = RequestMethod.POST)
31 | ResponseBean chekcToken(@RequestParam("token") String token);
32 |
33 |
34 |
35 | @ApiOperation(value = "test", notes = "test")
36 | @RequestMapping(value = "/test222", method = RequestMethod.POST)
37 | String test(@RequestBody User user);
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/bigdata-token-api/src/main/java/com/zktd/bigdata/token/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.token.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.cloud.netflix.feign.FeignClient;
6 | import org.springframework.web.bind.annotation.RequestBody;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 |
10 | import com.zktd.bigdata.common.jpa.service.page.Pagination;
11 | import com.zktd.bigdata.common.jpa.service.page.PaginationResult;
12 | import com.zktd.bigdata.token.entity.User;
13 |
14 | import io.swagger.annotations.Api;
15 | import io.swagger.annotations.ApiOperation;
16 |
17 | @Api(description = "user接口")
18 | @FeignClient(value = "token-service")
19 | @RequestMapping("/token/user")
20 | public interface UserService {
21 |
22 |
23 | @ApiOperation(value = "findUserByUserName", notes = "通过用户名获取用户信息")
24 | @RequestMapping(value = "/findUserByUserName", method = RequestMethod.POST)
25 | public User findUserByUserName(String userName) ;
26 |
27 | @ApiOperation(value = "findUserByUserId", notes = "通过用户id获取用户信息")
28 | @RequestMapping(value = "/findUserByUserId", method = RequestMethod.POST)
29 | public User findUserByUserId(String userId) ;
30 |
31 |
32 | @ApiOperation(value = "save", notes = "添加用户")
33 | @RequestMapping(value = "/save", method = RequestMethod.POST)
34 | public void save(User user) ;
35 |
36 | /**
37 | * 用户列表
38 | * @return
39 | */
40 | @ApiOperation(value="findAllByPage",notes="获取用户分页列表")
41 | @RequestMapping(value = "/findAllByPage",method = RequestMethod.POST)
42 | PaginationResult findAllByPage(@RequestBody Pagination pagination);
43 |
44 | @ApiOperation(value = "findUserList", notes = "获取用户列表")
45 | @RequestMapping(value = "/findUserList", method = RequestMethod.POST)
46 | public List findUserList(User user);
47 |
48 |
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | bigdata-token-service
6 | bigdata-token-service
7 |
8 |
9 | zktd.bigdata
10 | zktd-bigdata-platform
11 | 0.0.1-SNAPSHOT
12 |
13 |
14 |
15 | org.springframework.cloud
16 | spring-cloud-starter-eureka
17 |
18 |
19 | zktd.bigdata
20 | bigdata-token-api
21 | ${project.version}
22 |
23 |
24 | org.apache.shiro
25 | shiro-spring
26 | ${shiro-spring.version}
27 |
28 |
29 | com.auth0
30 | java-jwt
31 | ${java-jwt.version}
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-web
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter-redis
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-thymeleaf
44 |
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-configuration-processor
50 | true
51 |
52 |
53 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/TokenWebApplication.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/TokenWebApplication.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/common/RedisConfig.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/common/RedisConfig.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/common/RedisUtil.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/common/RedisUtil.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/controller/TokenController.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/controller/TokenController.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/controller/UserController.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/controller/UserController.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/repository/UserRepository.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/repository/UserRepository.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/SecretServiceImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/SecretServiceImpl.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/TokenServiceImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/TokenServiceImpl.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/UserServiceImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/token/service/impl/UserServiceImpl.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/util/JWTUtil.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/util/JWTUtil.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/util/JwtConfig.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wzjgn/zktd-bigdata-platform/e802216bd89283a295b66bfb60c4c92004857e9b/bigdata-token-service/bin/src/main/java/com/zktd/bigdata/util/JwtConfig.class
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | redis:
3 | host: 127.0.0.1
4 |
5 | data:
6 | mongodb:
7 | database: bigdata
8 | port: 27017
9 | host: 127.0.0.1
10 |
11 | jwt:
12 | accessToken: 6000000
13 | refreshToken: 60000000
14 | exp: 10
15 | secret: 123456
16 |
17 | ## swagger2
18 | swagger:
19 | enable: true
20 | group: content #api 的组信息
21 | title: token&用户管理 #标题
22 | description: 用户登录注册、token生成、检测、刷新 #描述信息
23 | version: v1.10 #版本
24 | contact-name: 中科同德 #联系人名称
25 | contact-url: http://www.bbb.com #联系人url
26 | contact-email: 363701272@qq.com
27 | base-package: com.zktd
28 | license: Apache License Version 2.0
29 | license-url: https://github.com/springfox/springfox/blob/master/LICENSE
30 | host: localhost:8511
31 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/bootstrap.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | application:
3 | name: token-service
4 |
5 | server:
6 | port: ${service.server.port:8000}
7 | contextPath: /
8 |
9 |
10 | eureka:
11 | instance:
12 | status-page-url: http://localhost:${server.port}/swagger-ui.html # ${server.port}为该服务的端口号
13 | # prefer-ip-address: true
14 | client:
15 | serviceUrl:
16 | defaultZone: ${eureka.serviceUrl:http://localhost:1111/eureka/}
17 |
18 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | System.out
6 |
7 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
8 |
9 |
10 |
11 | ../logs/cmp-content-service.log
12 |
13 | %date [%level] [%thread] %logger{80} [%file : %line] %msg%n
14 |
15 |
16 | ../logs/cmp-content-service.log.%d{yyyy-MM-dd}
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/static/js/common.js:
--------------------------------------------------------------------------------
1 | var zuul_url="http://localhost:5555";
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/static/js/login.js:
--------------------------------------------------------------------------------
1 | function login(){
2 |
3 |
4 | var formvalue= $("#loginForm").serialize();
5 |
6 | $.ajax({
7 | // url:zuul_url+"/api-token/login",
8 | url:"http://localhost:8000/login",
9 | type:'POST',
10 | dataType: "json",
11 | data:formvalue,
12 | success:function(d){
13 |
14 | if (d.msg=='success'){
15 |
16 | localStorage.setItem('token', d.data);
17 | window.location.href="/index.html"
18 |
19 | }else if(d.msg=='false'){
20 | alert("登录失败");
21 | localStorage.removeItem('token');
22 | }
23 | }
24 | });
25 | }
26 |
27 | function test(){
28 |
29 | $.ajax({
30 | url:"http://localhost:8000/test",
31 | type:'GET',
32 | dataType: "json",
33 | beforeSend: function (xhr) {
34 | xhr.setRequestHeader("token", localStorage.getItem('token'));
35 | },
36 | success:function(d, textStatus, request){
37 |
38 | if (d.msg=='success'){
39 |
40 | alert(request.getResponseHeader('newToken'));
41 | localStorage.setItem('token',request.getResponseHeader('newToken'));
42 |
43 | }else if(d.msg=='false'){
44 | alert("操作失败");
45 |
46 | }
47 | }
48 | });
49 | }
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Insert title here
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/bigdata-token-service/bin/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Insert title here
8 |
9 |
10 |
23 |
24 |
--------------------------------------------------------------------------------
/bigdata-token-service/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | bigdata-token-service
6 | bigdata-token-service
7 |
8 |
9 | zktd.bigdata
10 | zktd-bigdata-platform
11 | 0.0.1-SNAPSHOT
12 |
13 |
14 |
15 | org.springframework.cloud
16 | spring-cloud-starter-eureka
17 |
18 |
19 | zktd.bigdata
20 | bigdata-token-api
21 | ${project.version}
22 |
23 |
24 | org.apache.shiro
25 | shiro-spring
26 | ${shiro-spring.version}
27 |
28 |
29 | com.auth0
30 | java-jwt
31 | ${java-jwt.version}
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-web
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter-redis
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-thymeleaf
44 |
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-configuration-processor
50 | true
51 |
52 |
53 | org.springframework.cloud
54 | spring-cloud-starter-zipkin
55 |
56 |
57 |
--------------------------------------------------------------------------------
/bigdata-token-service/src/main/java/com/zktd/bigdata/TokenWebApplication.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
7 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
8 |
9 |
10 | @EnableDiscoveryClient
11 | @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
12 | public class TokenWebApplication {
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(TokenWebApplication.class);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/bigdata-token-service/src/main/java/com/zktd/bigdata/common/RedisConfig.java:
--------------------------------------------------------------------------------
1 | package com.zktd.bigdata.common;
2 |
3 | import com.fasterxml.jackson.annotation.JsonAutoDetect;
4 | import com.fasterxml.jackson.annotation.PropertyAccessor;
5 | import com.fasterxml.jackson.databind.ObjectMapper;
6 | import org.springframework.cache.CacheManager;
7 | import org.springframework.cache.annotation.CachingConfigurerSupport;
8 | import org.springframework.cache.annotation.EnableCaching;
9 | import org.springframework.cache.interceptor.KeyGenerator;
10 | import org.springframework.context.annotation.Bean;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.data.redis.cache.RedisCacheManager;
13 | import org.springframework.data.redis.connection.RedisConnectionFactory;
14 | import org.springframework.data.redis.core.RedisTemplate;
15 | import org.springframework.data.redis.core.StringRedisTemplate;
16 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
17 | import org.springframework.data.redis.serializer.StringRedisSerializer;
18 |
19 | import java.lang.reflect.Method;
20 |
21 | @Configuration
22 | @EnableCaching
23 | public class RedisConfig extends CachingConfigurerSupport {
24 |
25 | @Bean
26 | public KeyGenerator keyGenerator() {
27 | return new KeyGenerator() {
28 | @Override
29 | public Object generate(Object target, Method method, Object... params) {
30 | StringBuilder sb = new StringBuilder();
31 | sb.append(target.getClass().getName());
32 | sb.append(method.getName());
33 | for (Object obj : params) {
34 | sb.append(obj.toString());
35 | }
36 | return sb.toString();
37 | }
38 | };
39 |
40 | }
41 |
42 | @Bean
43 | public CacheManager cacheManager(RedisTemplate, ?> redisTemplate) {
44 | return new RedisCacheManager(redisTemplate);
45 | }
46 |
47 | @Bean
48 | public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
49 | StringRedisTemplate template = new StringRedisTemplate(factory);
50 | Jackson2JsonRedisSerializer