From 47111f8f5231badea128fd83eaf1371d92ff5cd3 Mon Sep 17 00:00:00 2001 From: mazhicheng Date: Sun, 2 Jun 2019 10:39:16 +0800 Subject: [PATCH 1/2] =?UTF-8?q?1.=20=E4=BC=98=E5=8C=96=E5=88=86=E9=A1=B5?= =?UTF-8?q?=202.=20=E4=BF=AE=E5=A4=8DbindProperties=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E4=B8=80=E8=87=B4=E7=9A=84=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/controller/BaseController.java | 3 + .../controller/BaseCrudRestController.java | 32 +++++++-- .../core/service/impl/BaseServiceImpl.java | 12 ++-- .../java/com/diboot/core/util/BeanUtils.java | 69 ++++++++++--------- .../com/diboot/core/util/SqlExecutor.java | 4 +- .../java/com/diboot/core/vo/Pagination.java | 8 +-- .../controller/DepartmentController.java | 18 ++--- .../example/controller/UserController.java | 17 ++--- 8 files changed, 88 insertions(+), 75 deletions(-) diff --git a/diboot-core/src/main/java/com/diboot/core/controller/BaseController.java b/diboot-core/src/main/java/com/diboot/core/controller/BaseController.java index 8b5dfcb..a7dcb25 100644 --- a/diboot-core/src/main/java/com/diboot/core/controller/BaseController.java +++ b/diboot-core/src/main/java/com/diboot/core/controller/BaseController.java @@ -129,6 +129,9 @@ public class BaseController { } BeanUtils.bindProperties(page, pageParamMap); } + if(log.isTraceEnabled()){ + log.trace(JSON.stringify(page)); + } return page; } diff --git a/diboot-core/src/main/java/com/diboot/core/controller/BaseCrudRestController.java b/diboot-core/src/main/java/com/diboot/core/controller/BaseCrudRestController.java index 6078cbb..cb3625d 100644 --- a/diboot-core/src/main/java/com/diboot/core/controller/BaseCrudRestController.java +++ b/diboot-core/src/main/java/com/diboot/core/controller/BaseCrudRestController.java @@ -4,7 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.diboot.core.entity.BaseEntity; import com.diboot.core.service.BaseService; import com.diboot.core.util.BeanUtils; -import com.diboot.core.util.JSON; +import com.diboot.core.util.V; import com.diboot.core.vo.JsonResult; import com.diboot.core.vo.Status; import com.diboot.core.vo.Pagination; @@ -61,18 +61,38 @@ public abstract class BaseCrudRestController extends BaseController { * @return JsonResult * @throws Exception */ - protected JsonResult getEntityListWithPaging(HttpServletRequest request, Wrapper queryWrapper, Class clazz) throws Exception { + protected JsonResult getEntityListWithPaging(HttpServletRequest request, Wrapper queryWrapper) throws Exception { // 构建分页 Pagination pagination = buildPagination(request); - log.debug(JSON.stringify(pagination)); // 查询当前页的数据 List entityList = getService().getEntityList(queryWrapper, pagination); - // 转换为VO - entityList = BeanUtils.convertList(entityList, clazz); // 返回结果 return new JsonResult(Status.OK, entityList).bindPagination(pagination); } - + + /*** + * 获取某VO资源的集合 + *

+ * url参数示例: /metadata/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR + *

+ * @param request + * @return JsonResult + * @throws Exception + */ + protected JsonResult getVOListWithPaging(HttpServletRequest request, Wrapper queryWrapper, Class clazz) throws Exception { + // 构建分页 + Pagination pagination = buildPagination(request); + // 查询当前页的数据 + List entityList = getService().getEntityList(queryWrapper, pagination); + // 转换为VO + if(V.notEmpty(entityList) && !clazz.getName().equals(entityList.get(0).getClass().getName())){ + entityList = BeanUtils.convertList(entityList, clazz); + } + entityList = getService().getViewObjectList(entityList, clazz); + // 返回结果 + return new JsonResult(Status.OK, entityList).bindPagination(pagination); + } + /*** * 根据id获取某资源对象 * @param id diff --git a/diboot-core/src/main/java/com/diboot/core/service/impl/BaseServiceImpl.java b/diboot-core/src/main/java/com/diboot/core/service/impl/BaseServiceImpl.java index b503e88..42d1007 100644 --- a/diboot-core/src/main/java/com/diboot/core/service/impl/BaseServiceImpl.java +++ b/diboot-core/src/main/java/com/diboot/core/service/impl/BaseServiceImpl.java @@ -37,11 +37,6 @@ import java.util.concurrent.ConcurrentHashMap; public class BaseServiceImpl, T> extends ServiceImpl implements BaseService { private static final Logger log = LoggerFactory.getLogger(BaseServiceImpl.class); - /*** - * VO类与注解的缓存 - */ - private static Map> CLASS_ANNOTATION_MAP = new ConcurrentHashMap<>(); - /*** * 获取当前的Mapper对象 * @return @@ -183,6 +178,7 @@ public class BaseServiceImpl, T> extends ServiceImpl @Override public List getKeyValueList(Wrapper queryWrapper) { String sqlSelect = queryWrapper.getSqlSelect(); + // 最多支持3个属性:k, v, ext if(V.isEmpty(sqlSelect) || S.countMatches(sqlSelect, Cons.SEPARATOR_COMMA) > 2){ log.error("调用错误: getKeyValueList必须用select依次指定返回的Key,Value, ext键值字段,如: new QueryWrapper().lambda().select(Metadata::getItemName, Metadata::getItemValue)"); return Collections.emptyList(); @@ -275,10 +271,10 @@ public class BaseServiceImpl, T> extends ServiceImpl return null; } IPage page = new Page() - .setCurrent(pagination.get_pageIndex()) - .setSize(pagination.get_pageSize()) + .setCurrent(pagination.getPageIndex()) + .setSize(pagination.getPageSize()) // 如果前端传递过来了缓存的总数,则本次不再count统计 - .setTotal(pagination.get_totalCount() > 0? -1 : pagination.get_totalCount()) + .setTotal(pagination.getTotalCount() > 0? -1 : pagination.getTotalCount()) .setAscs(S.toSnakeCase(pagination.getAscList())) .setDescs(S.toSnakeCase(pagination.getDescList())); return page; diff --git a/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java b/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java index d54b157..5f8bee9 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java +++ b/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java @@ -135,49 +135,50 @@ public class BeanUtils { PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { String propertyName = descriptor.getName(); - if (propMap.containsKey(propertyName)){ - Object value = propMap.get(propertyName); - Class type = descriptor.getWriteMethod().getParameterTypes()[0]; - Object[] args = new Object[1]; - String fieldType = type.getSimpleName(); - // 类型不一致,需转型 - if(!value.getClass().getTypeName().equals(fieldType)){ - if(value instanceof String){ - // String to Date - if(fieldType.equalsIgnoreCase(Date.class.getSimpleName())){ - args[0] = D.fuzzyConvert((String)value); - } - // Map中的String型转换为其他型 - else if(fieldType.equalsIgnoreCase(Boolean.class.getSimpleName())){ - args[0] = V.isTrue((String)value); - } - else if (fieldType.equalsIgnoreCase(Integer.class.getSimpleName()) || "int".equals(fieldType)) { - args[0] = Integer.parseInt((String)value); - } - else if (fieldType.equalsIgnoreCase(Long.class.getSimpleName())) { - args[0] = Long.parseLong((String)value); - } - else if (fieldType.equalsIgnoreCase(Double.class.getSimpleName())) { - args[0] = Double.parseDouble((String)value); - } - else if (fieldType.equalsIgnoreCase(Float.class.getSimpleName())) { - args[0] = Float.parseFloat((String)value); - } - else{ - args[0] = value; - log.warn("类型不一致,暂无法自动绑定,请手动转型一致后调用!字段类型="+fieldType); - } + if (!propMap.containsKey(propertyName)){ + continue; + } + Object value = propMap.get(propertyName); + Class type = descriptor.getWriteMethod().getParameterTypes()[0]; + Object[] args = new Object[1]; + String fieldType = type.getName(); + // 类型不一致,需转型 + if(!value.getClass().getTypeName().equals(fieldType)){ + if(value instanceof String){ + // String to Date + if(fieldType.equalsIgnoreCase(Date.class.getName())){ + args[0] = D.fuzzyConvert((String)value); + } + // Map中的String型转换为其他型 + else if(fieldType.equalsIgnoreCase(Boolean.class.getName())){ + args[0] = V.isTrue((String)value); + } + else if (fieldType.equalsIgnoreCase(Integer.class.getName()) || "int".equals(fieldType)) { + args[0] = Integer.parseInt((String)value); + } + else if (fieldType.equalsIgnoreCase(Long.class.getName())) { + args[0] = Long.parseLong((String)value); + } + else if (fieldType.equalsIgnoreCase(Double.class.getName())) { + args[0] = Double.parseDouble((String)value); + } + else if (fieldType.equalsIgnoreCase(Float.class.getName())) { + args[0] = Float.parseFloat((String)value); } else{ args[0] = value; - log.warn("类型不一致,且Map中的value非String类型,暂无法自动绑定,请手动转型一致后调用!value="+value); + log.warn("类型不一致,暂无法自动绑定,请手动转型一致后调用!字段类型: {} vs {} ", value.getClass().getTypeName(), fieldType); } } else{ args[0] = value; + log.warn("类型不一致,且Map中的value非String类型,暂无法自动绑定,请手动转型一致后调用! {} vs {} ", value.getClass().getTypeName(), fieldType); } - descriptor.getWriteMethod().invoke(model, args); } + else{ + args[0] = value; + } + descriptor.getWriteMethod().invoke(model, args); } } catch (Exception e){ diff --git a/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java b/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java index 7e9f9bf..96a31aa 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java +++ b/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java @@ -39,7 +39,7 @@ public class SqlExecutor { log.warn("查询参数集合数量过多, size={},请检查调用是否合理!", params.size()); } } - log.debug("==>\tSQL: "+sql); + log.debug("==> SQL: "+sql); try(SqlSession session = sqlSessionFactory.openSession(); Connection conn = session.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)){ if(V.notEmpty(params)){ for(int i=0; i - * url参数示例: /list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR + * url参数示例: /list?_pageSize=20&_pageIndex=1&_orderBy=id&code=TST *

* @return * @throws Exception */ @GetMapping("/list") - public JsonResult getDefaultVOList(HttpServletRequest request) throws Exception{ + public JsonResult getEntityList(HttpServletRequest request) throws Exception{ QueryWrapper queryWrapper = buildQuery(request); - return super.getEntityListWithPaging(request, queryWrapper, DepartmentVO.class); + return super.getEntityListWithPaging(request, queryWrapper); } /*** - * 默认的分页实现 + * 自定义VO的分页实现 *

- * url参数示例: /listVo?page.size=20&page.index=1&page.orderBy=itemValue&type=GENDAR + * url参数示例: /listVo?_pageSize=20&_pageIndex=1&_orderBy=id&code=TST *

* @return * @throws Exception @@ -58,11 +58,7 @@ public class DepartmentController extends BaseCrudRestController { @GetMapping("/listVo") public JsonResult getCustomVOList(HttpServletRequest request) throws Exception{ QueryWrapper queryWrapper = buildQuery(request); - // 查询当前页的数据 - List entityList = departmentService.getEntityList(queryWrapper); - List voList = departmentService.getViewObjectList(entityList, DepartmentVO.class); - // 返回结果 - return new JsonResult(Status.OK, voList); + return super.getVOListWithPaging(request, queryWrapper, DepartmentVO.class); } @GetMapping("/kv") diff --git a/diboot-example/src/main/java/com/diboot/example/controller/UserController.java b/diboot-example/src/main/java/com/diboot/example/controller/UserController.java index 49d77f7..2147d6d 100644 --- a/diboot-example/src/main/java/com/diboot/example/controller/UserController.java +++ b/diboot-example/src/main/java/com/diboot/example/controller/UserController.java @@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.diboot.core.controller.BaseCrudRestController; import com.diboot.core.service.BaseService; import com.diboot.core.vo.JsonResult; +import com.diboot.core.vo.Pagination; import com.diboot.core.vo.Status; import com.diboot.example.entity.User; import com.diboot.example.service.UserService; @@ -28,9 +29,9 @@ public class UserController extends BaseCrudRestController { private UserService userService; /*** - * 默认的分页实现 + * 默认Entity的分页实现 *

- * url参数示例: /list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR + * url参数示例: /list?_pageSize=20&_pageIndex=1&_orderBy=username&gender=M *

* @return * @throws Exception @@ -38,13 +39,13 @@ public class UserController extends BaseCrudRestController { @GetMapping("/list") public JsonResult getDefaultVOList(HttpServletRequest request) throws Exception{ QueryWrapper queryWrapper = buildQuery(request); - return super.getEntityListWithPaging(request, queryWrapper, UserVO.class); + return super.getEntityListWithPaging(request, queryWrapper); } /*** - * 默认的分页实现 + * 自定义VO的分页实现 *

- * url参数示例: /listVo?page.size=20&page.index=1&page.orderBy=itemValue&type=GENDAR + * url参数示例: /listVo?_pageSize=20&_pageIndex=1&_orderBy=username&gender=M *

* @return * @throws Exception @@ -52,11 +53,7 @@ public class UserController extends BaseCrudRestController { @GetMapping("/listVo") public JsonResult getCustomVOList(HttpServletRequest request) throws Exception{ QueryWrapper queryWrapper = buildQuery(request); - // 查询当前页的数据 - List entityList = userService.getEntityList(queryWrapper); - List voList = userService.getViewObjectList(entityList, UserVO.class); - // 返回结果 - return new JsonResult(Status.OK, voList); + return super.getVOListWithPaging(request, queryWrapper, UserVO.class); } @Override From f131721ccf81eec4e144a12166dc8f11a536340d Mon Sep 17 00:00:00 2001 From: mazhicheng Date: Sun, 2 Jun 2019 14:30:49 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0utils=E9=83=A8=E5=88=86=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diboot/core/util/BatchIterator.java | 54 ----------- .../java/com/diboot/core/util/BeanUtils.java | 17 +++- .../java/com/diboot/core/util/Encryptor.java | 20 +++- .../main/java/com/diboot/core/util/JSON.java | 8 ++ .../src/main/java/com/diboot/core/util/S.java | 16 ---- .../com/diboot/core/util/SqlExecutor.java | 1 - .../src/main/java/com/diboot/core/util/V.java | 6 +- .../diboot/core/test/util/BeanUtilsTest.java | 95 +++++++++++++++++++ .../java/diboot/core/test/util/DTest.java | 30 ++++++ .../diboot/core/test/util/EncryptorTest.java | 35 +++++++ .../diboot/core/test/util/PropertiesTest.java | 28 ++++++ .../java/diboot/core/test/util/STest.java | 36 +++++++ .../java/diboot/core/test/util/VTest.java | 75 +++++++++++++++ 13 files changed, 338 insertions(+), 83 deletions(-) delete mode 100644 diboot-core/src/main/java/com/diboot/core/util/BatchIterator.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/BeanUtilsTest.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/DTest.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/EncryptorTest.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/PropertiesTest.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/STest.java create mode 100644 diboot-core/src/test/java/diboot/core/test/util/VTest.java diff --git a/diboot-core/src/main/java/com/diboot/core/util/BatchIterator.java b/diboot-core/src/main/java/com/diboot/core/util/BatchIterator.java deleted file mode 100644 index 90b9e27..0000000 --- a/diboot-core/src/main/java/com/diboot/core/util/BatchIterator.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.diboot.core.util; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * 集合批次迭代 - * @author Mazhicheng - * @version v2.0 - * @date 2019/01/01 - */ -public class BatchIterator implements Iterator> { - /** - * 每批次集合数量 - */ - private int batchSize; - /*** - * 原始list - */ - private List originalList; - private int index = 0; - private List result; - private int total = 0; - - public BatchIterator(List originalList, int batchSize) { - if (batchSize <= 0) { - return; - } - this.batchSize = batchSize; - this.originalList = originalList; - this.total = V.notEmpty(originalList)? originalList.size() : 0; - result = new ArrayList<>(batchSize); - } - - @Override - public boolean hasNext() { - return index < total; - } - - @Override - public List next() { - result.clear(); - for (int i = 0; i < batchSize && index < total; i++) { - result.add(originalList.get(index++)); - } - return result; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("BatchIterator.remove未实现!"); - } -} diff --git a/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java b/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java index 5f8bee9..dc5829b 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java +++ b/diboot-core/src/main/java/com/diboot/core/util/BeanUtils.java @@ -463,15 +463,22 @@ public class BeanUtils { * @param */ public static void bindPropValueOfList(String setterFieldName, List fromList, String getterFieldName, Map valueMatchMap){ - if(V.isEmpty(fromList)){ + if(V.isEmpty(fromList) || V.isEmpty(valueMatchMap)){ return; } try{ for(E object : fromList){ - // 获取到当前的属性值 - String fieldValue = getStringProperty(object, getterFieldName); - // 获取到当前的value - Object value = valueMatchMap.get(fieldValue); + Object fieldValue = getProperty(object, getterFieldName); + Object value = null; + if(valueMatchMap.containsKey(fieldValue)){ + value = valueMatchMap.get(fieldValue); + } + else{ + // 获取到当前的属性值 + String fieldValueStr = getStringProperty(object, getterFieldName); + // 获取到当前的value + value = valueMatchMap.get(fieldValueStr); + } // 赋值 setProperty(object, setterFieldName, value); } diff --git a/diboot-core/src/main/java/com/diboot/core/util/Encryptor.java b/diboot-core/src/main/java/com/diboot/core/util/Encryptor.java index 000daf3..f7c84bb 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/Encryptor.java +++ b/diboot-core/src/main/java/com/diboot/core/util/Encryptor.java @@ -18,14 +18,26 @@ import java.util.concurrent.ConcurrentHashMap; */ public class Encryptor { private static final Logger log = LoggerFactory.getLogger(Encryptor.class); - + + /** + * 算法 + */ private static final String KEY_ALGORITHM = "AES"; private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5PADDING"; - private static final String KEY_DEFAULT = V.notEmpty(BaseConfig.getProperty("diboot.encryptor.seed"))? BaseConfig.getProperty("diboot.encryptor.seed") : "Dibo2017M"; + /** + * 默认加密seed(可通过配置文件) + */ + private static final String KEY_DEFAULT = V.notEmpty(BaseConfig.getProperty("diboot.encryptor.seed"))? BaseConfig.getProperty("diboot.encryptor.seed") : "DibootV2"; + private static final String KEY_FILL = "abcdefghijklmnop"; - // 加密Cipher缓存 + + /** + * 加密Cipher缓存 + */ private static Map encryptorMap = new ConcurrentHashMap<>(); - // 解密Cipher缓存 + /** + * 解密Cipher缓存 + */ private static Map decryptorMap = new ConcurrentHashMap<>(); /** diff --git a/diboot-core/src/main/java/com/diboot/core/util/JSON.java b/diboot-core/src/main/java/com/diboot/core/util/JSON.java index d312e34..3875c07 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/JSON.java +++ b/diboot-core/src/main/java/com/diboot/core/util/JSON.java @@ -19,11 +19,19 @@ import java.util.Map; public class JSON extends JSONObject{ private static final Logger log = LoggerFactory.getLogger(JSON.class); + /** + * 序列化配置 + */ private static SerializeConfig serializeConfig = new SerializeConfig(); static { serializeConfig.put(Date.class, new SimpleDateFormatSerializer(D.FORMAT_DATETIME_Y4MDHM)); } + /** + * 将Java对象转换为Json String + * @param object + * @return + */ public static String stringify(Object object){ return toJSONString(object, serializeConfig); } diff --git a/diboot-core/src/main/java/com/diboot/core/util/S.java b/diboot-core/src/main/java/com/diboot/core/util/S.java index 842b654..1c6a6b2 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/S.java +++ b/diboot-core/src/main/java/com/diboot/core/util/S.java @@ -293,20 +293,4 @@ public class S extends StringUtils{ return null; } - /*** - * 批量替换关键字 - * @param text - * @param searchList - * @param replacementList - * @return - */ - public static String replaceEach(String text, List searchList, List replacementList){ - if(V.isEmpty(searchList) || V.isEmpty(replacementList)){ - return text; - } - String[] searchArray = searchList.toArray(new String[searchList.size()]); - String[] replacementArray = replacementList.toArray(new String[replacementList.size()]); - return replaceEach(text, searchArray, replacementArray); - } - } diff --git a/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java b/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java index 96a31aa..ead455b 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java +++ b/diboot-core/src/main/java/com/diboot/core/util/SqlExecutor.java @@ -98,7 +98,6 @@ public class SqlExecutor { /** * 执行查询和合并结果并将结果Map的key类型转成String - * * @param sql * @param params * @return diff --git a/diboot-core/src/main/java/com/diboot/core/util/V.java b/diboot-core/src/main/java/com/diboot/core/util/V.java index 692e90c..91b0a22 100644 --- a/diboot-core/src/main/java/com/diboot/core/util/V.java +++ b/diboot-core/src/main/java/com/diboot/core/util/V.java @@ -156,11 +156,11 @@ public class V { } boolean valid = str.matches("^1\\d{10}$"); if(!valid){ - valid = str.matches("^0\\d{2,3}-?\\d{7,8}$"); + valid = str.matches("^[0|4]\\d{2,3}-?\\d{7,8}$"); } return valid; - } - + } + /** * 判断是否为整型数字 * @param str diff --git a/diboot-core/src/test/java/diboot/core/test/util/BeanUtilsTest.java b/diboot-core/src/test/java/diboot/core/test/util/BeanUtilsTest.java new file mode 100644 index 0000000..6330fa6 --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/BeanUtilsTest.java @@ -0,0 +1,95 @@ +package diboot.core.test.util; + +import com.diboot.core.entity.Metadata; +import com.diboot.core.util.BeanUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * BeanUtils测试 + * @author Mazhicheng + * @version v2.0 + * @date 2019/06/02 + */ +public class BeanUtilsTest { + + @Test + public void testCopyBean(){ + String itemName = "在职"; + Metadata metadata1 = new Metadata(); + metadata1.setType("STATUS"); + metadata1.setItemName(itemName); + + Metadata metadata2 = new Metadata(); + BeanUtils.copyProperties(metadata1, metadata2); + Assert.assertTrue(metadata2.getItemName().equals(itemName)); + + Map map = new HashMap<>(); + map.put("type", "STATUS"); + map.put("itemName",itemName); + Metadata metadata3 = new Metadata(); + BeanUtils.bindProperties(metadata3, map); + Assert.assertTrue(metadata2.getItemName().equals(itemName)); + } + + @Test + public void testGetProperty(){ + Metadata metadata1 = new Metadata(); + metadata1.setId(1001L); + + // getProperty + Object id = BeanUtils.getProperty(metadata1, "id"); + Assert.assertTrue(id instanceof Long); + // getStringProperty + Assert.assertTrue(BeanUtils.getStringProperty(metadata1, "id").equals("1001")); + } + + @Test + public void testConvert(){ + List metadataList = new ArrayList<>(); + for(long id=1001; id<1005; id++){ + Metadata metadata1 = new Metadata(); + metadata1.setId(id); + metadataList.add(metadata1); + } + List metaIdList = BeanUtils.collectToList(metadataList, Metadata::getId); + Assert.assertTrue(metaIdList.size() == 4); + } + + @Test + public void testGetterSetter(){ + Assert.assertEquals(BeanUtils.convertToFieldName(Metadata::getItemName), "itemName"); + Assert.assertEquals(BeanUtils.convertToFieldName(Metadata::setItemName), "itemName"); + } + + @Test + public void testBindProp(){ + List metadataList = new ArrayList<>(); + for(long id=1001; id<1005; id++){ + Metadata metadata1 = new Metadata(); + metadata1.setId(id); + metadataList.add(metadata1); + } + Map map = new HashMap<>(); + map.put("1001", "在职"); + map.put("1002", "在职"); + map.put("1003", "离职"); + BeanUtils.bindPropValueOfList(Metadata::setItemName, metadataList, Metadata::getId, map); + Assert.assertEquals(metadataList.get(0).getItemName(), "在职"); + Assert.assertEquals(metadataList.get(2).getItemName(), "离职"); + + Map map2 = new HashMap<>(); + map2.put(1001L, "在职"); + map2.put(1002L, "在职"); + map2.put(1003L, "离职"); + BeanUtils.bindPropValueOfList("itemName", metadataList, "id", map2); + Assert.assertEquals(metadataList.get(0).getItemName(), "在职"); + Assert.assertEquals(metadataList.get(2).getItemName(), "离职"); + } + +} diff --git a/diboot-core/src/test/java/diboot/core/test/util/DTest.java b/diboot-core/src/test/java/diboot/core/test/util/DTest.java new file mode 100644 index 0000000..e7b3c06 --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/DTest.java @@ -0,0 +1,30 @@ +package diboot.core.test.util; + +import com.diboot.core.util.D; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Date; + +/** + * 日期单元测试 + * @author Mazhicheng + * @version 1.0 + * @date 2019/06/02 + */ +public class DTest { + + @Test + public void testFuzzyConvert(){ + String[] dateStrArray = { + "2019-06-02 13:35", + "2019年6月2日 13:35:00", + "2019/6/2 13:35:34:000" + }; + for(String dateStr : dateStrArray){ + Date date = D.fuzzyConvert(dateStr); + Assert.assertTrue(date != null); + } + } + +} diff --git a/diboot-core/src/test/java/diboot/core/test/util/EncryptorTest.java b/diboot-core/src/test/java/diboot/core/test/util/EncryptorTest.java new file mode 100644 index 0000000..f3428cf --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/EncryptorTest.java @@ -0,0 +1,35 @@ +package diboot.core.test.util; + +import com.diboot.core.util.Encryptor; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * + * @author Mazhicheng + * @version 1.0 + * @date 2019/06/02 + */ +public class EncryptorTest { + + @Test + public void testEncrypt(){ + String text = "Hello World"; + String encryptText = Encryptor.encrypt(text); + System.out.println(encryptText); + // 加密后长度 + Assert.assertTrue(encryptText.length() >= 24); + // 解密 + Assert.assertTrue(Encryptor.decrypt(encryptText).equals(text)); + + String seed = "ABCDEF"; + encryptText = Encryptor.encrypt(text, seed); + System.out.println(encryptText); + // 加密后长度 + Assert.assertTrue(encryptText.length() >= 24); + // 解密 + Assert.assertTrue(Encryptor.decrypt(encryptText, seed).equals(text)); + } + +} diff --git a/diboot-core/src/test/java/diboot/core/test/util/PropertiesTest.java b/diboot-core/src/test/java/diboot/core/test/util/PropertiesTest.java new file mode 100644 index 0000000..fd0d785 --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/PropertiesTest.java @@ -0,0 +1,28 @@ +package diboot.core.test.util; + +import com.diboot.core.util.PropertiesUtils; +import org.junit.Assert; +import org.junit.Test; + +/** + * 配置文件读取测试 + * @author Mazhicheng + * @version 1.0 + * @date 2019/06/02 + */ +public class PropertiesTest { + + @Test + public void testGetString(){ + String str1 = PropertiesUtils.get("spring.datasource.url"); + String str2 = PropertiesUtils.get("spring.datasource.url", "application.properties"); + Assert.assertNotNull(str1); + Assert.assertNotNull(str2); + } + + @Test + public void testGetNumber(){ + Integer num = PropertiesUtils.getInteger("spring.datasource.hikari.maximum-pool-size"); + Assert.assertTrue(num > 0 ); + } +} diff --git a/diboot-core/src/test/java/diboot/core/test/util/STest.java b/diboot-core/src/test/java/diboot/core/test/util/STest.java new file mode 100644 index 0000000..729da6b --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/STest.java @@ -0,0 +1,36 @@ +package diboot.core.test.util; + +import com.diboot.core.util.S; +import org.junit.Assert; +import org.junit.Test; + +/** + * S工具类测试 + * @author Mazhicheng + * @version 1.0 + * @date 2019/06/02 + */ +public class STest { + + @Test + public void testToSnakeCase(){ + String str = "myOrgName"; + String snakeCaseStr = "my_org_name"; + Assert.assertEquals(S.toSnakeCase(str), snakeCaseStr); + } + + @Test + public void testCamelCase(){ + String snakeCaseStr = "my_org_name"; + String camelCaseStr = "myOrgName"; + Assert.assertEquals(S.toLowerCaseCamel(snakeCaseStr), camelCaseStr); + } + + @Test + public void testCapFirst(){ + String text = "helloWorld"; + Assert.assertEquals(S.capFirst(text), "HelloWorld"); + Assert.assertEquals(S.uncapFirst("HelloWorld"), text); + } + +} diff --git a/diboot-core/src/test/java/diboot/core/test/util/VTest.java b/diboot-core/src/test/java/diboot/core/test/util/VTest.java new file mode 100644 index 0000000..4c24d7d --- /dev/null +++ b/diboot-core/src/test/java/diboot/core/test/util/VTest.java @@ -0,0 +1,75 @@ +package diboot.core.test.util; + +import com.diboot.core.util.S; +import com.diboot.core.util.V; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * V校验工具类测试 + * @author Mazhicheng + * @version 1.0 + * @date 2019/06/02 + */ +public class VTest { + + @Test + public void testEmpty(){ + String text1 = null; + Assert.assertTrue(S.isEmpty(text1)); + text1 = ""; + Assert.assertTrue(S.isEmpty(text1)); + text1 = " "; + Assert.assertFalse(S.isEmpty(text1)); + + List list = new ArrayList<>(); + Assert.assertTrue(V.isEmpty(list)); + list.add(1L); + Assert.assertTrue(V.notEmpty(list)); + } + + @Test + public void testIsEmail(){ + String text1 = "jsdjfjsdf@126.com"; + String text2 = "jsdjfjsdf.126.com"; + String text3 = "jsdjfjsdf@126"; + Assert.assertTrue(V.isEmail(text1)); + + Assert.assertFalse(V.isEmail(text2)); + Assert.assertFalse(V.isEmail(text3)); + } + + @Test + public void testIsPhone(){ + String text1 = "17712345678"; + String text2 = "0512-12345678"; + String text3 = "40012345678"; + Assert.assertTrue(V.isPhone(text1)); + Assert.assertTrue(V.isPhone(text2)); + Assert.assertTrue(V.isPhone(text3)); + + String text4 = "177123456789"; + Assert.assertFalse(V.isPhone(text4)); + } + + @Test + public void testEquals(){ + Long val1 = 128L, val2 = 128L; + Assert.assertFalse(val1 == val2); + Assert.assertTrue(V.equals(val1, val2)); + + List list1 = new ArrayList<>(), list2 = new ArrayList<>(); + list1.add(127L); + list1.add(128L); + list2.add(127L); + list2.add(128L); + + Assert.assertTrue(V.equals(list1, list2)); + } + + + +}