diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a958711e..5228e580f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,45 @@ =========================== +## [2.2.0](https://github.com/buession/buession-security/releases/tag/v2.2.0) (2023-03-10) + +### 🔨依赖升级 + +- [依赖库版本升级和安全漏洞修复](https://github.com/buession/buession-parent/releases/tag/v2.2.0) +- **buession-geoip:** 升级 IP 库 + + +### ⭐ 新特性 + +- **buession-core:** ListBuilder、MapBuilder、QueueBuilder、SetBuilder 增加可以直接传递 List、Map、Queue、Set 实例的 create 方法 +- **buession-core:** Assert isEmpty 和 notEmpty 增加基础类型数组判断 +- **buession-core:** StringUtils 增加 random 增加支持字符串 +- **buession-geoip:** 增加返回 autonomous system number、autonomous system organization +- **buession-geoip:** 增加可支持设置 asn 库地址或流 +- **buession-httpclient:** 支持原生 RequestBody 子类转换 +- **buession-web:** 增加 web binder 转换器工厂 IgnoreCaseEnumConverterFactory 忽略大小写将字符串转换为枚举值 +- **buession-web:** 获取客户端真实 IP,增加标头 Client-IP 的支持 + + +### 🔔 变化 +- **buession-web:** 废弃 web binder 转换器 CaseTypeConverter、DomainTLDConverter、DomainTLDTypeConverter、GenderConverter、IpTypeConverter、ISBNTypeConverter、OrderConverter、StatusConverter,统一使用 web binder 转换器工厂 IgnoreCaseEnumConverterFactory +- **buession-core:** Executor、Resolve 增加异常支持 + + +### 🐞 Bug 修复 + +- **buession-core:** 修复 RandomDigitIdGenerator 最大值大于最小值时报错的问题 +- **buession-httpclient:** 修复 Response 返回错误的 statusCode 和 statusText +- **buession-dao:** 修复 DefaultJsonTypeHandler 为 null 或空字符串反序列化出错的 BUG + + +### ⏪ 优化 +- 其它优化 + + +--- + + ## [2.1.2](https://github.com/buession/buessionframework/releases/tag/v2.1.2) (2022-11-13) ### 🔨依赖升级 @@ -18,6 +57,7 @@ - **buession-http:** 优化 Response,使 statusCode、statusText 与 statusLine 的值始终保持一致 - **buession-geoip:** 优化国家和地区词典解析,GeoIPResolverFactory 支持从默认词典返回文件对象或流对象,以及支持从 classpath 家长词典文件 - 其它优化 +- **buession-velocity:** 配置属性 resource.loader 替换 resource.loaders ### 🐞 Bug 修复 diff --git a/README.md b/README.md index b22d74499..55858aa35 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,6 @@ - [https://mvnrepository.com/search?q=com.buession](https://mvnrepository.com/search?q=com.buession) ## Documentation ---- - 参考文档 [https://www.buession.com/](https://www.buession.com/) - Wiki [https://github.com/buession/buessionframework/wiki](https://github.com/buession/buessionframework/wiki) diff --git a/buession-aop/pom.xml b/buession-aop/pom.xml index 01d633439..6bfc11f78 100644 --- a/buession-aop/pom.xml +++ b/buession-aop/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-aop https://github.com/buession/buessionframework diff --git a/buession-beans/pom.xml b/buession-beans/pom.xml index 29c78bcf0..5a2c60fe5 100644 --- a/buession-beans/pom.xml +++ b/buession-beans/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-beans https://github.com/buession/buessionframework diff --git a/buession-beans/src/main/java/com/buession/beans/BeanUtils.java b/buession-beans/src/main/java/com/buession/beans/BeanUtils.java index 861d115a9..469aa0d38 100644 --- a/buession-beans/src/main/java/com/buession/beans/BeanUtils.java +++ b/buession-beans/src/main/java/com/buession/beans/BeanUtils.java @@ -86,9 +86,7 @@ public static void populate(final Object target, final Object source, final Conv try{ humpBeanUtilsBean.populate(target, (Map) source); - }catch(IllegalAccessException e){ - logger.error("Copy Map to {} error: {}.", target.getClass().getName(), e.getMessage()); - }catch(InvocationTargetException e){ + }catch(Exception e){ logger.error("Copy Map to {} error: {}.", target.getClass().getName(), e.getMessage()); } return; @@ -137,9 +135,7 @@ public static void copyProperties(final Object target, final Object source, fina if(source instanceof Map){ try{ org.apache.commons.beanutils.BeanUtils.populate(target, (Map) source); - }catch(IllegalAccessException e){ - logger.error("Copy Map to {} error: {}.", target.getClass().getName(), e.getMessage()); - }catch(InvocationTargetException e){ + }catch(Exception e){ logger.error("Copy Map to {} error: {}.", target.getClass().getName(), e.getMessage()); } return; diff --git a/buession-core/pom.xml b/buession-core/pom.xml index 5ed589729..16c6ab5de 100644 --- a/buession-core/pom.xml +++ b/buession-core/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-core https://github.com/buession/buessionframework diff --git a/buession-core/src/main/java/com/buession/core/Executor.java b/buession-core/src/main/java/com/buession/core/Executor.java index b92793ed3..06a05616e 100644 --- a/buession-core/src/main/java/com/buession/core/Executor.java +++ b/buession-core/src/main/java/com/buession/core/Executor.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core; @@ -44,7 +44,10 @@ public interface Executor { * 命令执行器上下文 * * @return 命令执行返回值,R 类型的实例 + * + * @throws Exception + * 异常 */ - R execute(C context); + R execute(C context) throws Exception; } diff --git a/buession-core/src/main/java/com/buession/core/Resolve.java b/buession-core/src/main/java/com/buession/core/Resolve.java index e81ae5cc4..b67089c67 100644 --- a/buession-core/src/main/java/com/buession/core/Resolve.java +++ b/buession-core/src/main/java/com/buession/core/Resolve.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core; @@ -45,7 +45,10 @@ public interface Resolve { * 待解析对象 * * @return 解析结果 + * + * @throws Exception + * 异常 */ - T resolve(final S source); + T resolve(final S source) throws Exception; } diff --git a/buession-core/src/main/java/com/buession/core/builder/ListBuilder.java b/buession-core/src/main/java/com/buession/core/builder/ListBuilder.java index 030616c22..e8645eebb 100644 --- a/buession-core/src/main/java/com/buession/core/builder/ListBuilder.java +++ b/buession-core/src/main/java/com/buession/core/builder/ListBuilder.java @@ -67,7 +67,7 @@ private ListBuilder(final List data){ * @return {@link ListBuilder} 实例 */ public static ListBuilder create(){ - return create(16); + return new ListBuilder<>(new ArrayList<>()); } /** @@ -86,6 +86,22 @@ public static ListBuilder create(final int initialCapacity){ return new ListBuilder<>(new ArrayList<>(initialCapacity)); } + /** + * 创建默认为 {@link ArrayList} 类型的 {@link ListBuilder} 实例 + * + * @param list + * the list whose elements are to be placed into this list + * @param + * Value 类型 + * + * @return {@link ListBuilder} 实例 + * + * @since 2.2.0 + */ + public static ListBuilder create(final List list){ + return new ListBuilder<>(list); + } + /** * 创建默认为 {@link ArrayList} 类型的 {@link ListBuilder} 实例 * @@ -114,7 +130,7 @@ public static ListBuilder create(final Collection c){ * * @return {@link ListBuilder} 实例 */ - public static > ListBuilder create(Class clazz){ + public static > ListBuilder create(final Class clazz){ Assert.isNull(clazz, "java.util.List class cloud not be null."); List data; diff --git a/buession-core/src/main/java/com/buession/core/builder/MapBuilder.java b/buession-core/src/main/java/com/buession/core/builder/MapBuilder.java index 1c254a88b..c4ff2d191 100644 --- a/buession-core/src/main/java/com/buession/core/builder/MapBuilder.java +++ b/buession-core/src/main/java/com/buession/core/builder/MapBuilder.java @@ -46,7 +46,7 @@ private MapBuilder(final Map data){ * @return {@link MapBuilder} 实例 */ public static MapBuilder create(){ - return create(16); + return new MapBuilder<>(new HashMap<>()); } /** @@ -101,8 +101,8 @@ public static MapBuilder create(final int initialCapacity, final fl * * @since 2.1.2 */ - public static MapBuilder create(final Map m){ - return new MapBuilder<>(new HashMap<>(m)); + public static MapBuilder create(final Map m){ + return new MapBuilder<>(m); } /** @@ -119,7 +119,7 @@ public static MapBuilder create(final Map * * @return {@link MapBuilder} 实例 */ - public static > MapBuilder create(Class clazz){ + public static > MapBuilder create(final Class clazz){ Assert.isNull(clazz, "java.util.Map class cloud not be null."); Map data; diff --git a/buession-core/src/main/java/com/buession/core/builder/QueueBuilder.java b/buession-core/src/main/java/com/buession/core/builder/QueueBuilder.java index 2bfbb959d..59a4440c9 100644 --- a/buession-core/src/main/java/com/buession/core/builder/QueueBuilder.java +++ b/buession-core/src/main/java/com/buession/core/builder/QueueBuilder.java @@ -46,11 +46,27 @@ public static QueueBuilder create(){ return new QueueBuilder<>(new LinkedList<>()); } + /** + * 创建默认为 {@link LinkedList} 类型的 {@link QueueBuilder} 实例 + * + * @param queue + * the queue whose elements are to be placed into this queue + * @param + * Value 类型 + * + * @return {@link QueueBuilder} 实例 + * + * @since 2.2.0 + */ + public static QueueBuilder create(final Queue queue){ + return new QueueBuilder<>(queue); + } + /** * 创建默认为 {@link LinkedList} 类型的 {@link QueueBuilder} 实例 * * @param c - * the collection whose elements are to be placed into this list + * the collection whose elements are to be placed into this queue * @param * Value 类型 * @@ -74,7 +90,7 @@ public static QueueBuilder create(final Collection c){ * * @return {@link QueueBuilder} 实例 */ - public static > QueueBuilder create(Class clazz){ + public static > QueueBuilder create(final Class clazz){ Assert.isNull(clazz, "java.util.Queue class cloud not be null."); Queue data; diff --git a/buession-core/src/main/java/com/buession/core/builder/SetBuilder.java b/buession-core/src/main/java/com/buession/core/builder/SetBuilder.java index c9827fda2..f9ccea0e5 100644 --- a/buession-core/src/main/java/com/buession/core/builder/SetBuilder.java +++ b/buession-core/src/main/java/com/buession/core/builder/SetBuilder.java @@ -43,7 +43,7 @@ private SetBuilder(final Set data){ * @return {@link SetBuilder} 实例 */ public static SetBuilder create(){ - return new SetBuilder<>(new HashSet<>(16)); + return new SetBuilder<>(new HashSet<>()); } /** @@ -80,6 +80,22 @@ public static SetBuilder create(final int initialCapacity, final float lo return new SetBuilder<>(new HashSet<>(initialCapacity, loadFactor)); } + /** + * 创建默认为 {@link HashSet} 类型的 {@link SetBuilder} 实例 + * + * @param set + * the set whose elements are to be placed into this set + * @param + * Value 类型 + * + * @return {@link SetBuilder} 实例 + * + * @since 2.2.0 + */ + public static SetBuilder create(final Set set){ + return new SetBuilder<>(set); + } + /** * 创建默认为 {@link HashSet} 类型的 {@link SetBuilder} 实例 * @@ -108,7 +124,7 @@ public static SetBuilder create(final Collection c){ * * @return {@link SetBuilder} 实例 */ - public static > SetBuilder create(Class clazz){ + public static > SetBuilder create(final Class clazz){ Assert.isNull(clazz, "java.util.Set class cloud not be null."); Set data; diff --git a/buession-core/src/main/java/com/buession/core/codec/MessagePropertyBeanPostProcessor.java b/buession-core/src/main/java/com/buession/core/codec/MessagePropertyBeanPostProcessor.java index 41953d2d6..9dc2a3daf 100644 --- a/buession-core/src/main/java/com/buession/core/codec/MessagePropertyBeanPostProcessor.java +++ b/buession-core/src/main/java/com/buession/core/codec/MessagePropertyBeanPostProcessor.java @@ -79,7 +79,9 @@ public Object postProcessAfterInitialization(Object bean, @Nullable String beanN } if(field.getType().isAssignableFrom(MessageObject.class) == false){ - throw new BeanCreationException("The field " + field.getName() + " is not subclass of " + MessageObject.class.getName() + ", on: " + beanName + "(" + bean.getClass().getName() + ")."); + throw new BeanCreationException( + "The field " + field.getName() + " is not subclass of " + MessageObject.class.getName() + + ", on: " + beanName + "(" + bean.getClass().getName() + ")."); } handleMessageInjected(clazz, bean, beanName, field, message); @@ -88,22 +90,29 @@ public Object postProcessAfterInitialization(Object bean, @Nullable String beanN return bean; } - private void handleMessageInjected(final Class clazz, final Object bean, final String beanName, final Field field, final Message message) throws BeansException{ + private void handleMessageInjected(final Class clazz, final Object bean, final String beanName, + final Field field, final Message message) throws BeansException{ final String key = message.value(); final String text = getEnvironment().getProperty(buildProperty(key, message.textField())); if(message.required() && text == null){ - throw new IllegalArgumentException("Could not resolve placeholder '" + key + "' in value \"${" + key + "}\", on: " + beanName + "(" + bean.getClass().getName() + ")."); + throw new IllegalArgumentException( + "Could not resolve placeholder '" + key + "' in value \"${" + key + "}\", on: " + beanName + "(" + + bean.getClass().getName() + ")."); } - final int code = getEnvironment().getProperty(buildProperty(key, message.codeField()), Integer.class); + final Integer code = getEnvironment().getProperty(buildProperty(key, message.codeField()), Integer.class); - try{ - final Object beanObject = AopUtils.isCglibProxy(bean) ? getCglibProxyTargetObject(bean) : bean; + if(code != null){ + try{ + final Object beanObject = AopUtils.isCglibProxy(bean) ? getCglibProxyTargetObject(bean) : bean; - FieldUtils.writeField(field, beanObject, new MessageObject(code, text), true); - }catch(Exception e){ - throw new BeanCreationException("Exception thrown when handleMessageInjected, on: " + beanName + "(" + clazz.getName() + ")", e); + FieldUtils.writeField(field, beanObject, new MessageObject(code, text), true); + }catch(Exception e){ + throw new BeanCreationException( + "Exception thrown when handleMessageInjected, on: " + beanName + "(" + clazz.getName() + ")", + e); + } } logger.debug("Parse message '{}', code: {}, text: {}", key, code, text); } diff --git a/buession-core/src/main/java/com/buession/core/converter/mapper/PropertyMapper.java b/buession-core/src/main/java/com/buession/core/converter/mapper/PropertyMapper.java index cd0a0ff46..279dcb06f 100644 --- a/buession-core/src/main/java/com/buession/core/converter/mapper/PropertyMapper.java +++ b/buession-core/src/main/java/com/buession/core/converter/mapper/PropertyMapper.java @@ -247,12 +247,7 @@ public Source as(Function adapter){ Supplier test = ()->predicate.test(supplier.get()); Predicate predicate = (t)->test.get(); - Supplier supplier = ()->{ - if(test.get()){ - return adapter.apply(this.supplier.get()); - } - return null; - }; + Supplier supplier = ()->test.get() ? adapter.apply(this.supplier.get()) : null; return new Source<>(supplier, predicate); } @@ -381,11 +376,11 @@ public R toInstance(Function factory){ Assert.isNull(factory, "Factory cloud not be null"); T value = supplier.get(); - if(predicate.test(value) == false){ - throw new NoSuchElementException("No value present"); + if(predicate.test(value)){ + return factory.apply(value); } - return factory.apply(value); + throw new NoSuchElementException("No value present"); } } diff --git a/buession-core/src/main/java/com/buession/core/id/RandomDigitIdGenerator.java b/buession-core/src/main/java/com/buession/core/id/RandomDigitIdGenerator.java index 89d802656..9abd7f235 100644 --- a/buession-core/src/main/java/com/buession/core/id/RandomDigitIdGenerator.java +++ b/buession-core/src/main/java/com/buession/core/id/RandomDigitIdGenerator.java @@ -36,39 +36,41 @@ */ public class RandomDigitIdGenerator implements IdGenerator { - /** - * 最小值 - */ - private long min = 1L; + /** + * 最小值 + */ + private long min = 1L; - /** - * 最大值 - */ - private long max = Long.MAX_VALUE; + /** + * 最大值 + */ + private long max = Long.MAX_VALUE; - /** - * 构造函数,生成 1 到 Long.MAX_VALUE 间的随机 ID - */ - public RandomDigitIdGenerator() { - } + /** + * 构造函数,生成 1 到 Long.MAX_VALUE 间的随机 ID + */ + public RandomDigitIdGenerator(){ + } - /** - * 构造函数 - * - * @param min 最小值 - * @param max 最大值 - */ - public RandomDigitIdGenerator(final long min, final long max) { - Assert.isFalse(min >= 1 && min <= Long.MAX_VALUE, "Id min value must between 1 and " + Long.MAX_VALUE + "."); - Assert.isFalse(max >= 1 && max <= Long.MAX_VALUE, "Id max value must between 1 and " + Long.MAX_VALUE + "."); - Assert.isFalse(min > max, "Id max value has to be greater than or equal to id min value."); - this.min = min; - this.max = max; - } + /** + * 构造函数 + * + * @param min + * 最小值 + * @param max + * 最大值 + */ + public RandomDigitIdGenerator(final long min, final long max){ + Assert.isFalse(min >= 1 && min <= Long.MAX_VALUE, "Id min value must between 1 and " + Long.MAX_VALUE + "."); + Assert.isFalse(max >= 1 && max <= Long.MAX_VALUE, "Id max value must between 1 and " + Long.MAX_VALUE + "."); + Assert.isTrue(min > max, "Id max value has to be greater than or equal to id min value."); + this.min = min; + this.max = max; + } - @Override - public Long nextId() { - return RandomUtils.nextLong(min, max); - } + @Override + public Long nextId(){ + return RandomUtils.nextLong(min, max); + } } diff --git a/buession-core/src/main/java/com/buession/core/serializer/DefaultByteArraySerializer.java b/buession-core/src/main/java/com/buession/core/serializer/DefaultByteArraySerializer.java index dcdd1966e..4f8df623d 100644 --- a/buession-core/src/main/java/com/buession/core/serializer/DefaultByteArraySerializer.java +++ b/buession-core/src/main/java/com/buession/core/serializer/DefaultByteArraySerializer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.serializer; @@ -147,7 +147,7 @@ protected static String baosWrite(final V value) throws IOException{ } @SuppressWarnings("unchecked") - protected final static V doDeserialize(final byte[] bytes, final String sourceType) throws SerializerException{ + protected static V doDeserialize(final byte[] bytes, final String sourceType) throws SerializerException{ ByteArrayInputStream byteArrayInputStream = null; ObjectInputStream objectInputStream = null; diff --git a/buession-core/src/main/java/com/buession/core/utils/Assert.java b/buession-core/src/main/java/com/buession/core/utils/Assert.java index 08c1512d7..912ced6d2 100644 --- a/buession-core/src/main/java/com/buession/core/utils/Assert.java +++ b/buession-core/src/main/java/com/buession/core/utils/Assert.java @@ -98,6 +98,134 @@ public static void notNull(final Object object, final String message){ } } + /** + * 如果 shor 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final short[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 int 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final int[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 long 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final long[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 float 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final float[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 double 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final double[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 boolean 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final boolean[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 byte 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final byte[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 char 数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + * + * @since 2.2.0 + */ + public static void isEmpty(final char[] objects, final String message){ + if(Validate.isEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + /** * 如果数组对象 objects 为 null 或为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 * @@ -168,6 +296,118 @@ public static void isEmpty(final Enumeration enumeration, final String messag } } + /** + * 如果 short 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final short[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 int 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final int[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 long 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final long[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 float 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final float[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 double 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final double[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 boolean 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final boolean[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 byte 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final byte[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 如果 char 数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 + * + * @param objects + * 数组对象 + * @param message + * 异常信息 + */ + public static void notEmpty(final char[] objects, final String message){ + if(Validate.isNotEmpty(objects)){ + throw new IllegalArgumentException(message); + } + } + /** * 如果数组对象 objects 不为 null 且不为空,抛出信息为 message 的 {@link IllegalArgumentException} 异常 * diff --git a/buession-core/src/main/java/com/buession/core/utils/StringUtils.java b/buession-core/src/main/java/com/buession/core/utils/StringUtils.java index 275205730..14c20f71c 100755 --- a/buession-core/src/main/java/com/buession/core/utils/StringUtils.java +++ b/buession-core/src/main/java/com/buession/core/utils/StringUtils.java @@ -114,7 +114,24 @@ public static boolean isFalse(final String str){ * @return 生成的随机字符串 */ public static String random(final int length){ + return random(length, Constants.ALNUM); + } + + /** + * 生成随机字符串 + * + * @param length + * 随机字符串长度 + * @param chars + * 原字符 + * + * @return 生成的随机字符串 + * + * @since 2.2.0 + */ + public static String random(final int length, final char[] chars){ Assert.isNegative(length, "Length could not be negative."); + Assert.isEmpty(chars, "chars could not be negative."); if(length == 0){ return EMPTY; @@ -122,8 +139,8 @@ public static String random(final int length){ StringBuilder sb = new StringBuilder(length); for(int i = 0; i < length; i++){ - int j = RandomUtils.nextInt(Constants.ALNUM.length); - sb.append(Constants.ALNUM[j]); + int j = RandomUtils.nextInt(chars.length); + sb.append(chars[j]); } return sb.toString(); @@ -497,7 +514,8 @@ public static boolean regionMatches(final CharSequence cs, final boolean ignoreC } // The same check as in String.regionMatches(): - if(Character.toUpperCase(c1) != Character.toUpperCase(c2) && Character.toLowerCase(c1) != Character.toLowerCase(c2)){ + if(Character.toUpperCase(c1) != Character.toUpperCase(c2) && + Character.toLowerCase(c1) != Character.toLowerCase(c2)){ return false; } } diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/AlnumConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/AlnumConstraintValidator.java index 3fc5e195c..9a5075ea1 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/AlnumConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/AlnumConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -35,10 +35,6 @@ */ public abstract class AlnumConstraintValidator implements ConstraintValidator { - @Override - public void initialize(Alnum alnum){ - } - public final static class CharSequenceAlnumConstraintValidator extends AlnumConstraintValidator { @Override diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/EmptyConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/EmptyConstraintValidator.java index 696dcf983..5a71ed5cc 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/EmptyConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/EmptyConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2020 Buession.com Inc. | + * | Copyright @ 2013-2022 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -57,37 +57,37 @@ public boolean isValid(Object[] value, ConstraintValidatorContext context){ } - public final static class MapEmptyConstraintValidator extends EmptyConstraintValidator { + public final static class MapEmptyConstraintValidator extends EmptyConstraintValidator> { @Override - public boolean isValid(Map value, ConstraintValidatorContext context){ + public boolean isValid(Map value, ConstraintValidatorContext context){ return Validate.isEmpty(value); } } - public final static class CollectionEmptyConstraintValidator extends EmptyConstraintValidator { + public final static class CollectionEmptyConstraintValidator extends EmptyConstraintValidator> { @Override - public boolean isValid(Collection value, ConstraintValidatorContext context){ + public boolean isValid(Collection value, ConstraintValidatorContext context){ return Validate.isEmpty(value); } } - public final static class IteratorEmptyConstraintValidator extends EmptyConstraintValidator { + public final static class IteratorEmptyConstraintValidator extends EmptyConstraintValidator> { @Override - public boolean isValid(Iterator value, ConstraintValidatorContext context){ + public boolean isValid(Iterator value, ConstraintValidatorContext context){ return Validate.isEmpty(value); } } - public final static class EnumerationEmptyConstraintValidator extends EmptyConstraintValidator { + public final static class EnumerationEmptyConstraintValidator extends EmptyConstraintValidator> { @Override - public boolean isValid(Enumeration value, ConstraintValidatorContext context){ + public boolean isValid(Enumeration value, ConstraintValidatorContext context){ return Validate.isEmpty(value); } diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/IDCardConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/IDCardConstraintValidator.java index 50ccc0702..50a137619 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/IDCardConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/IDCardConstraintValidator.java @@ -48,6 +48,7 @@ public void initialize(IDCard idCard){ try{ this.birthday = idCard.birthday() == null ? null : (new SimpleDateFormat()).parse(idCard.birthday()); }catch(ParseException e){ + // } } diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MimeTypeConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MimeTypeConstraintValidator.java index c7d327d16..710c79505 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MimeTypeConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MimeTypeConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -36,10 +36,6 @@ */ public abstract class MimeTypeConstraintValidator implements ConstraintValidator { - @Override - public void initialize(MimeType mimeType){ - } - @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context){ return Validate.isMimeType(value); diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MobileConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MobileConstraintValidator.java index 2bf43e08a..45ce361a5 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MobileConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/MobileConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -35,10 +35,6 @@ */ public class MobileConstraintValidator implements ConstraintValidator { - @Override - public void initialize(Mobile mobile){ - } - @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context){ return Validate.isMobile(value); diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/NotEmptyConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/NotEmptyConstraintValidator.java index 38175b911..f5d9efc8c 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/NotEmptyConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/NotEmptyConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2020 Buession.com Inc. | + * | Copyright @ 2013-2022 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -39,7 +39,8 @@ */ public abstract class NotEmptyConstraintValidator implements ConstraintValidator { - public final static class CharSequenceNotEmptyConstraintValidator extends NotEmptyConstraintValidator { + public final static class CharSequenceNotEmptyConstraintValidator + extends NotEmptyConstraintValidator { @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context){ @@ -57,37 +58,38 @@ public boolean isValid(Object[] value, ConstraintValidatorContext context){ } - public final static class MapNotEmptyConstraintValidator extends NotEmptyConstraintValidator { + public final static class MapNotEmptyConstraintValidator extends NotEmptyConstraintValidator> { @Override - public boolean isValid(Map value, ConstraintValidatorContext context){ + public boolean isValid(Map value, ConstraintValidatorContext context){ return Validate.isNotEmpty(value); } } - public final static class CollectionNotEmptyConstraintValidator extends NotEmptyConstraintValidator { + public final static class CollectionNotEmptyConstraintValidator extends NotEmptyConstraintValidator> { @Override - public boolean isValid(Collection value, ConstraintValidatorContext context){ + public boolean isValid(Collection value, ConstraintValidatorContext context){ return Validate.isNotEmpty(value); } } - public final static class IteratorNotEmptyConstraintValidator extends NotEmptyConstraintValidator { + public final static class IteratorNotEmptyConstraintValidator extends NotEmptyConstraintValidator> { @Override - public boolean isValid(Iterator value, ConstraintValidatorContext context){ + public boolean isValid(Iterator value, ConstraintValidatorContext context){ return Validate.isNotEmpty(value); } } - public final static class EnumerationNotEmptyConstraintValidator extends NotEmptyConstraintValidator { + public final static class EnumerationNotEmptyConstraintValidator + extends NotEmptyConstraintValidator> { @Override - public boolean isValid(Enumeration value, ConstraintValidatorContext context){ + public boolean isValid(Enumeration value, ConstraintValidatorContext context){ return Validate.isNotEmpty(value); } diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PortConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PortConstraintValidator.java index 9cfe341d8..762f334c1 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PortConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PortConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -36,10 +36,6 @@ */ public abstract class PortConstraintValidator implements ConstraintValidator { - @Override - public void initialize(Port port){ - } - @Override public boolean isValid(Integer value, ConstraintValidatorContext context){ return value != null && Validate.isPort(value); diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PostCodeConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PostCodeConstraintValidator.java index 43571004c..e835450a0 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PostCodeConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/PostCodeConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -35,10 +35,6 @@ */ public class PostCodeConstraintValidator implements ConstraintValidator { - @Override - public void initialize(PostCode postCode){ - } - @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context){ return Validate.isPostCode(value); diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/QQConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/QQConstraintValidator.java index 8b6323879..caa0179e5 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/QQConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/QQConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -35,10 +35,6 @@ */ public class QQConstraintValidator implements ConstraintValidator { - @Override - public void initialize(QQ postCode){ - } - @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context){ return Validate.isQQ(value); diff --git a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/XdigitConstraintValidator.java b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/XdigitConstraintValidator.java index ad404931c..a7cf35474 100644 --- a/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/XdigitConstraintValidator.java +++ b/buession-core/src/main/java/com/buession/core/validator/constraintvalidators/XdigitConstraintValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.core.validator.constraintvalidators; @@ -35,12 +35,6 @@ */ public abstract class XdigitConstraintValidator implements ConstraintValidator { - protected boolean validWhenNull; - - @Override - public void initialize(Xdigit xdigit){ - } - public final static class CharSequenceXdigitConstraintValidator extends XdigitConstraintValidator { @Override diff --git a/buession-core/src/test/java/com/buession/core/validator/ValidateTest.java b/buession-core/src/test/java/com/buession/core/validator/ValidateTest.java index 26b3f2160..8b7c9700c 100644 --- a/buession-core/src/test/java/com/buession/core/validator/ValidateTest.java +++ b/buession-core/src/test/java/com/buession/core/validator/ValidateTest.java @@ -56,7 +56,8 @@ public void isMimeType(){ Assert.assertEquals(true, Validate.isMimeType("application/rtf")); Assert.assertEquals(true, Validate.isMimeType("application/vnd.wap.wmlc")); Assert.assertEquals(true, Validate.isMimeType("application/x-rar-compressed")); - Assert.assertEquals(true, Validate.isMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")); + Assert.assertEquals(true, + Validate.isMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")); Assert.assertEquals(true, Validate.isMimeType("video/3gpp")); Assert.assertEquals(false, Validate.isMimeType("video/-3gpp")); Assert.assertEquals(false, Validate.isMimeType("video/3gpp-")); diff --git a/buession-cron/pom.xml b/buession-cron/pom.xml index a6d501cea..00f811921 100644 --- a/buession-cron/pom.xml +++ b/buession-cron/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-cron https://github.com/buession/buessionframework diff --git a/buession-dao/pom.xml b/buession-dao/pom.xml index 71b54b35c..ea1942e76 100644 --- a/buession-dao/pom.xml +++ b/buession-dao/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-dao https://github.com/buession/buessionframework diff --git a/buession-dao/src/main/java/com/buession/dao/MongoOperation.java b/buession-dao/src/main/java/com/buession/dao/MongoOperation.java index 4e57656fa..9b761a365 100644 --- a/buession-dao/src/main/java/com/buession/dao/MongoOperation.java +++ b/buession-dao/src/main/java/com/buession/dao/MongoOperation.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.dao; @@ -31,15 +31,35 @@ */ public final class MongoOperation { + /** + * 运算符 + */ private Operator operator; + /** + * 运算值 + */ private Object value; - public MongoOperation(Object value){ + /** + * 构造函数,默认以 Operator.EQUAL 方式运算 + * + * @param value + * 运算值 + */ + public MongoOperation(final Object value){ this(Operator.EQUAL, value); } - public MongoOperation(Operator operator, Object value){ + /** + * 构造函数 + * + * @param operator + * 运算符 {@link Operator} + * @param value + * 运算值 + */ + public MongoOperation(final Operator operator, final Object value){ this.operator = operator; this.value = value; } @@ -54,7 +74,7 @@ public MongoOperation(Operator operator, Object value){ * * @since 1.3.1 */ - public static MongoOperation eq(Object value){ + public static MongoOperation eq(final Object value){ return new MongoOperation(Operator.EQUAL, value); } @@ -68,7 +88,7 @@ public static MongoOperation eq(Object value){ * * @since 1.3.1 */ - public static MongoOperation neq(Object value){ + public static MongoOperation neq(final Object value){ return new MongoOperation(Operator.NOT_EQUAL, value); } @@ -82,7 +102,7 @@ public static MongoOperation neq(Object value){ * * @since 1.3.1 */ - public static MongoOperation lt(Object value){ + public static MongoOperation lt(final Object value){ return new MongoOperation(Operator.LT, value); } @@ -96,7 +116,7 @@ public static MongoOperation lt(Object value){ * * @since 1.3.1 */ - public static MongoOperation lte(Object value){ + public static MongoOperation lte(final Object value){ return new MongoOperation(Operator.LTE, value); } @@ -110,7 +130,7 @@ public static MongoOperation lte(Object value){ * * @since 1.3.1 */ - public static MongoOperation gt(Object value){ + public static MongoOperation gt(final Object value){ return new MongoOperation(Operator.GT, value); } @@ -124,7 +144,7 @@ public static MongoOperation gt(Object value){ * * @since 1.3.1 */ - public static MongoOperation in(Object value){ + public static MongoOperation in(final Object value){ return new MongoOperation(Operator.IN, value); } @@ -138,7 +158,7 @@ public static MongoOperation in(Object value){ * * @since 1.3.1 */ - public static MongoOperation nin(Object value){ + public static MongoOperation nin(final Object value){ return new MongoOperation(Operator.NIN, value); } @@ -152,7 +172,7 @@ public static MongoOperation nin(Object value){ * * @since 1.3.1 */ - public static MongoOperation like(Object value){ + public static MongoOperation like(final Object value){ return new MongoOperation(Operator.LIKE, value); } @@ -166,44 +186,96 @@ public static MongoOperation like(Object value){ * * @since 1.3.1 */ - public static MongoOperation gte(Object value){ + public static MongoOperation gte(final Object value){ return new MongoOperation(Operator.GTE, value); } + /** + * 返回运算符 {@link Operator} + * + * @return 运算符 + */ public Operator getOperator(){ return operator; } + /** + * 设置运算符 {@link Operator} + * + * @param operator + * 运算符 + */ public void setOperator(Operator operator){ this.operator = operator; } + /** + * 返回运算值 + * + * @return 运算值 + */ public Object getValue(){ return value; } + /** + * 设置运算值 + * + * @param value + * 运算值 + */ public void setValue(Object value){ this.value = value; } + /** + * 运算符 + */ public enum Operator { + /** + * 等于 + */ EQUAL, + /** + * 不等于 + */ NOT_EQUAL, + /** + * 小于 + */ LT, + /** + * 小于等于 + */ LTE, + /** + * 大于 + */ GT, + /** + * 单元等于 + */ GTE, + /** + * IN + */ IN, + /** + * Not IN + */ NIN, + /** + * Like + */ LIKE } diff --git a/buession-dao/src/main/java/org/apache/ibatis/type/DefaultJsonTypeHandler.java b/buession-dao/src/main/java/org/apache/ibatis/type/DefaultJsonTypeHandler.java index 49d889566..1e3ed0d58 100644 --- a/buession-dao/src/main/java/org/apache/ibatis/type/DefaultJsonTypeHandler.java +++ b/buession-dao/src/main/java/org/apache/ibatis/type/DefaultJsonTypeHandler.java @@ -19,13 +19,14 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package org.apache.ibatis.type; import com.buession.core.serializer.JacksonJsonSerializer; import com.buession.core.serializer.SerializerException; +import com.buession.core.validator.Validate; import java.sql.PreparedStatement; import java.sql.SQLException; @@ -59,11 +60,16 @@ public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcTy @Override protected E parseResult(final String str) throws SQLException{ - JacksonJsonSerializer jsonSerializer = new JacksonJsonSerializer(); - try{ - return jsonSerializer.deserialize(str, type); - }catch(SerializerException e){ - throw new SQLException(str + " cloud not be deserialize to " + type.getName() + ": " + e.getMessage()); + if(Validate.hasText(str)){ + JacksonJsonSerializer jsonSerializer = new JacksonJsonSerializer(); + try{ + return jsonSerializer.deserialize(str, type); + }catch(SerializerException e){ + throw new SQLException(str + " cloud not be deserialize to " + type.getName() + ": " + e.getMessage()); + } } + + return null; } + } diff --git a/buession-geoip/pom.xml b/buession-geoip/pom.xml index 2c9dcd3ca..ec1d5d20f 100644 --- a/buession-geoip/pom.xml +++ b/buession-geoip/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-geoip https://github.com/buession/buessionframework diff --git a/buession-geoip/src/main/java/com/buession/geoip/AbstractResolver.java b/buession-geoip/src/main/java/com/buession/geoip/AbstractResolver.java index 38eaf8396..2265c6845 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/AbstractResolver.java +++ b/buession-geoip/src/main/java/com/buession/geoip/AbstractResolver.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.geoip; diff --git a/buession-geoip/src/main/java/com/buession/geoip/CacheDatabaseResolver.java b/buession-geoip/src/main/java/com/buession/geoip/CacheDatabaseResolver.java index a4c420f71..001a7a465 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/CacheDatabaseResolver.java +++ b/buession-geoip/src/main/java/com/buession/geoip/CacheDatabaseResolver.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2022 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.geoip; @@ -151,4 +151,144 @@ public CacheDatabaseResolver(final InputStream source, final Reader.FileMode fil super(source, fileMode, new CHMCache()); } + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final String database, final String asnDatabase) throws IOException{ + super(database, asnDatabase, new CHMCache()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final String database, final String asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + super(database, asnDatabase, fileMode, new CHMCache()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件 + * @param asnDatabase + * ASN 库文件 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final File database, final File asnDatabase) throws IOException{ + super(database, asnDatabase, new CHMCache()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件 + * @param asnDatabase + * ASN 库文件 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final File database, final File asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + super(database, asnDatabase, fileMode, new CHMCache()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final Path database, final Path asnDatabase) throws IOException{ + super(database, asnDatabase, new CHMCache()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final Path database, final Path asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + super(database, asnDatabase, fileMode, new CHMCache()); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final InputStream source, final InputStream asnSource) throws IOException{ + super(source, asnSource, new CHMCache()); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public CacheDatabaseResolver(final InputStream source, final InputStream asnSource, final Reader.FileMode fileMode) + throws IOException{ + super(source, asnSource, fileMode, new CHMCache()); + } + } diff --git a/buession-geoip/src/main/java/com/buession/geoip/DatabaseResolver.java b/buession-geoip/src/main/java/com/buession/geoip/DatabaseResolver.java index 47311a55b..d87faa22e 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/DatabaseResolver.java +++ b/buession-geoip/src/main/java/com/buession/geoip/DatabaseResolver.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.geoip; @@ -37,11 +37,13 @@ import com.buession.geoip.model.Geo; import com.buession.geoip.model.Location; import com.buession.geoip.model.Traits; +import com.maxmind.db.CHMCache; import com.maxmind.db.Reader; import com.maxmind.db.Metadata; import com.maxmind.db.NodeCache; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.AsnResponse; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CountryResponse; @@ -62,6 +64,8 @@ public class DatabaseResolver extends AbstractResolver { private final DatabaseReader reader; + private DatabaseReader asnReader; + /** * 构造函数 * @@ -135,6 +139,7 @@ public DatabaseResolver(final String database, final Reader.FileMode fileMode, f public DatabaseResolver(final File database) throws IOException{ Assert.isNull(database, "Database could not be null."); this.reader = new DatabaseReader.Builder(database).build(); + this.asnReader = getDefaultAsnReaderBuilder().build(); } /** @@ -151,6 +156,7 @@ public DatabaseResolver(final File database) throws IOException{ public DatabaseResolver(final File database, final NodeCache cache) throws IOException{ Assert.isNull(database, "Database could not be null."); this.reader = new DatabaseReader.Builder(database).withCache(cache).build(); + this.asnReader = getDefaultAsnReaderBuilder().withCache(cache).build(); } /** @@ -167,6 +173,7 @@ public DatabaseResolver(final File database, final NodeCache cache) throws IOExc public DatabaseResolver(final File database, final Reader.FileMode fileMode) throws IOException{ Assert.isNull(database, "Database could not be null."); this.reader = new DatabaseReader.Builder(database).fileMode(fileMode).build(); + this.asnReader = getDefaultAsnReaderBuilder().fileMode(fileMode).build(); } /** @@ -186,6 +193,8 @@ public DatabaseResolver(final File database, final Reader.FileMode fileMode, fin throws IOException{ Assert.isNull(database, "Database could not be null."); this.reader = new DatabaseReader.Builder(database).fileMode(fileMode).withCache(cache).build(); + this.asnReader = getDefaultAsnReaderBuilder().fileMode(fileMode).withCache(cache) + .build(); } /** @@ -261,6 +270,7 @@ public DatabaseResolver(final Path database, final Reader.FileMode fileMode, fin public DatabaseResolver(final InputStream source) throws IOException{ Assert.isNull(source, "Database stream could not be null."); this.reader = new DatabaseReader.Builder(source).build(); + this.asnReader = getDefaultAsnReaderBuilder().build(); } /** @@ -277,6 +287,7 @@ public DatabaseResolver(final InputStream source) throws IOException{ public DatabaseResolver(final InputStream source, final NodeCache cache) throws IOException{ Assert.isNull(source, "Database stream could not be null."); this.reader = new DatabaseReader.Builder(source).withCache(cache).build(); + this.asnReader = getDefaultAsnReaderBuilder().withCache(cache).build(); } /** @@ -293,6 +304,7 @@ public DatabaseResolver(final InputStream source, final NodeCache cache) throws public DatabaseResolver(final InputStream source, final Reader.FileMode fileMode) throws IOException{ Assert.isNull(source, "Database stream could not be null."); this.reader = new DatabaseReader.Builder(source).fileMode(fileMode).build(); + this.asnReader = getDefaultAsnReaderBuilder().fileMode(fileMode).build(); } /** @@ -312,6 +324,330 @@ public DatabaseResolver(final InputStream source, final Reader.FileMode fileMode throws IOException{ Assert.isNull(source, "Database stream could not be null."); this.reader = new DatabaseReader.Builder(source).fileMode(fileMode).withCache(cache).build(); + this.asnReader = getDefaultAsnReaderBuilder().fileMode(fileMode).withCache(cache).build(); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final String database, final String asnDatabase) throws IOException{ + this(database == null ? null : new File(database), asnDatabase == null ? null : new File(asnDatabase)); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final String database, final String asnDatabase, final NodeCache cache) throws IOException{ + this(database == null ? null : new File(database), asnDatabase == null ? null : new File(asnDatabase), cache); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final String database, final String asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + this(database == null ? null : new File(database), asnDatabase == null ? null : new File(asnDatabase), + fileMode); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final String database, final String asnDatabase, final Reader.FileMode fileMode, + final NodeCache cache) + throws IOException{ + this(database == null ? null : new File(database), asnDatabase == null ? null : new File(asnDatabase), + fileMode, cache); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件文件 + * @param asnDatabase + * ASN 库文件 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final File database, final File asnDatabase) throws IOException{ + Assert.isNull(database, "Database could not be null."); + this.reader = new DatabaseReader.Builder(database).build(); + this.asnReader = new DatabaseReader.Builder(asnDatabase).build(); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件 + * @param asnDatabase + * ASN 库文件 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final File database, final File asnDatabase, final NodeCache cache) throws IOException{ + Assert.isNull(database, "Database could not be null."); + Assert.isNull(asnDatabase, "ASN database could not be null."); + this.reader = new DatabaseReader.Builder(database).withCache(cache).build(); + this.asnReader = new DatabaseReader.Builder(asnDatabase).withCache(cache).build(); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件 + * @param asnDatabase + * ASN 库文件 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final File database, final File asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + Assert.isNull(database, "Database could not be null."); + Assert.isNull(asnDatabase, "ASN database could not be null."); + this.reader = new DatabaseReader.Builder(database).fileMode(fileMode).build(); + this.asnReader = new DatabaseReader.Builder(asnDatabase).fileMode(fileMode).build(); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件 + * @param asnDatabase + * ASN 库文件 + * @param fileMode + * 文件模式 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final File database, final File asnDatabase, final Reader.FileMode fileMode, + final NodeCache cache) + throws IOException{ + Assert.isNull(database, "Database could not be null."); + Assert.isNull(asnDatabase, "ASN database could not be null."); + this.reader = new DatabaseReader.Builder(database).fileMode(fileMode).withCache(cache).build(); + this.asnReader = new DatabaseReader.Builder(asnDatabase).fileMode(fileMode).withCache(cache).build(); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final Path database, final Path asnDatabase) throws IOException{ + this(database == null ? null : database.toFile(), asnDatabase == null ? null : asnDatabase.toFile()); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final Path database, final Path asnDatabase, final NodeCache cache) throws IOException{ + this(database == null ? null : database.toFile(), asnDatabase == null ? null : asnDatabase.toFile(), cache); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final Path database, final Path asnDatabase, final Reader.FileMode fileMode) + throws IOException{ + this(database == null ? null : database.toFile(), asnDatabase == null ? null : asnDatabase.toFile(), fileMode); + } + + /** + * 构造函数 + * + * @param database + * IP 库文件路径 + * @param asnDatabase + * ASN 库文件路径 + * @param fileMode + * 文件模式 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final Path database, final Path asnDatabase, final Reader.FileMode fileMode, + final NodeCache cache) + throws IOException{ + this(database == null ? null : database.toFile(), asnDatabase == null ? null : asnDatabase.toFile(), fileMode, + cache); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final InputStream source, final InputStream asnSource) throws IOException{ + this(source); + Assert.isNull(asnSource, "ASN database stream could not be null."); + this.asnReader = new DatabaseReader.Builder(asnSource).build(); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final InputStream source, final InputStream asnSource, final NodeCache cache) + throws IOException{ + this(source, cache); + Assert.isNull(asnSource, "ASN database stream could not be null."); + this.asnReader = new DatabaseReader.Builder(asnSource).withCache(cache).build(); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * @param fileMode + * 文件模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final InputStream source, final InputStream asnSource, final Reader.FileMode fileMode) + throws IOException{ + this(source, fileMode); + Assert.isNull(asnSource, "ASN database stream could not be null."); + this.asnReader = new DatabaseReader.Builder(asnSource).fileMode(fileMode).build(); + } + + /** + * 构造函数 + * + * @param source + * IP 库文件流 + * @param asnSource + * ASN 库文件流 + * @param fileMode + * 文件模式 + * @param cache + * 缓存模式 + * + * @throws IOException + * IO 错误 + * @since 2.2.0 + */ + public DatabaseResolver(final InputStream source, final InputStream asnSource, final Reader.FileMode fileMode, + final NodeCache cache) + throws IOException{ + this(source, fileMode, cache); + Assert.isNull(asnSource, "ASN database stream could not be null."); + this.asnReader = new DatabaseReader.Builder(asnSource).fileMode(fileMode).withCache(cache).build(); } @Override @@ -336,10 +672,13 @@ public Location location(InetAddress ipAddress, Locale locale) throws IOExceptio final CityConverter cityConverter = new CityConverter(); final ContinentConverter continentConverter = new ContinentConverter(); final TraitsConverter traitsConverter = new TraitsConverter(); - + final CityResponse response = reader.city(ipAddress); + final AsnResponse asnResponse = asnReader == null ? null : asnReader.asn(ipAddress); final com.maxmind.geoip2.record.Location location = response.getLocation(); + traitsConverter.setAsnResponse(asnResponse); + final Continent continent = continentConverter.converter(response.getContinent(), locale); final Country country = countryConverter.converter(response.getCountry(), locale); final District district = cityConverter.converter(response.getCity(), response, locale); @@ -362,4 +701,8 @@ public void close() throws IOException{ } } + protected static DatabaseReader.Builder getDefaultAsnReaderBuilder(){ + return new DatabaseReader.Builder(DatabaseResolver.class.getResourceAsStream(DEFAULT_ASN_DB)); + } + } diff --git a/buession-geoip/src/main/java/com/buession/geoip/Resolver.java b/buession-geoip/src/main/java/com/buession/geoip/Resolver.java index a2bb06031..2fe970ee6 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/Resolver.java +++ b/buession-geoip/src/main/java/com/buession/geoip/Resolver.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.geoip; @@ -33,6 +33,7 @@ import com.maxmind.db.Metadata; import com.maxmind.geoip2.exception.GeoIp2Exception; +import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.util.Locale; @@ -42,7 +43,13 @@ * * @author Yong.Teng */ -public interface Resolver { +public interface Resolver extends Closeable { + + String DEFAULT_COUNTRY_DB = "/maxmind/Country.mmdb"; + + String DEFAULT_CITY_DB = "/maxmind/City.mmdb"; + + String DEFAULT_ASN_DB = "/maxmind/ASN.mmdb"; /** * 根据 IP 地址返回国家数据 @@ -358,6 +365,4 @@ default Location location(InetAddress ipAddress) throws IOException, GeoIp2Excep Metadata getMetadata(); - void close() throws IOException; - } diff --git a/buession-geoip/src/main/java/com/buession/geoip/converter/TraitsConverter.java b/buession-geoip/src/main/java/com/buession/geoip/converter/TraitsConverter.java index c9e95cf55..331f1b820 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/converter/TraitsConverter.java +++ b/buession-geoip/src/main/java/com/buession/geoip/converter/TraitsConverter.java @@ -31,6 +31,7 @@ import com.buession.geoip.model.Organization; import com.buession.geoip.model.Traits; import com.maxmind.geoip2.model.AbstractResponse; +import com.maxmind.geoip2.model.AsnResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,6 +51,16 @@ public class TraitsConverter extends AbstractConverter | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.geoip.spring; import com.buession.core.utils.Assert; +import com.buession.geoip.DatabaseResolver; import com.buession.geoip.Resolver; -import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; @@ -41,8 +42,6 @@ */ public class GeoIPResolverFactory { - protected final static String DEFAULT_CITY_DB = "maxmind/City.mmdb"; - /** * IP 库文件路径 */ @@ -53,9 +52,24 @@ public class GeoIPResolverFactory { */ private InputStream stream; + /** + * ASN 库文件路径 + * + * @since 2.2.0 + */ + private File asnDbPath; + + /** + * ASN 库文件流 + * + * @since 2.2.0 + */ + private InputStream asnStream; + /** * IP 库加载模式 */ + @Deprecated private LoadMode loadMode = LoadMode.STREAM; /** @@ -67,11 +81,13 @@ public class GeoIPResolverFactory { * 返回 IP 库文件路径 * * @return IP 库文件路径 + * + * @throws IOException + * 数据库文件不存在时 */ public File getDbPath() throws IOException{ if(dbPath == null){ - ClassPathResource resource = new ClassPathResource(DEFAULT_CITY_DB); - dbPath = resource.getFile(); + dbPath = new File(DatabaseResolver.class.getResource(DatabaseResolver.DEFAULT_CITY_DB).getFile()); } return dbPath; @@ -84,13 +100,11 @@ public File getDbPath() throws IOException{ * IP 库文件 {@link Resource} * * @throws IOException - * IO 错误 + * 数据库文件不存在时 */ public void setDbPath(Resource dbPath) throws IOException{ Assert.isNull(dbPath, "Ip database path cloud not be null."); - this.dbPath = dbPath.getFile(); - this.loadMode = LoadMode.FILE; } /** @@ -100,13 +114,11 @@ public void setDbPath(Resource dbPath) throws IOException{ * IP 库文件路径 * * @throws IOException - * IO 错误 + * 数据库文件不存在时 */ public void setDbPath(File dbPath) throws IOException{ Assert.isNull(dbPath, "Ip database path cloud not be null."); - this.dbPath = dbPath; - this.loadMode = LoadMode.FILE; } /** @@ -116,13 +128,11 @@ public void setDbPath(File dbPath) throws IOException{ * IP 库文件路径 * * @throws IOException - * IO 错误 + * 数据库文件不存在时 */ public void setDbPath(Path dbPath) throws IOException{ Assert.isNull(dbPath, "Ip database path cloud not be null."); - this.dbPath = dbPath.toFile(); - this.loadMode = LoadMode.FILE; } /** @@ -132,22 +142,101 @@ public void setDbPath(Path dbPath) throws IOException{ * IP 库文件路径 * * @throws IOException - * IO 错误 + * 数据库文件不存在时 */ public void setDbPath(String dbPath) throws IOException{ Assert.isBlank(dbPath, "Ip database path cloud not be null or empty."); setDbPath(new File(dbPath)); } + /** + * 返回 ASN 库文件路径 + * + * @return ASN 库文件路径 + * + * @throws IOException + * ASN 库文件不存在时 + * @since 2.2.0 + */ + public File getAsnDbPath() throws IOException{ + if(asnDbPath == null){ + asnDbPath = new File(DatabaseResolver.class.getResource(DatabaseResolver.DEFAULT_ASN_DB).getFile()); + } + + return asnDbPath; + } + + /** + * 设置 ASN 库文件路径 + * + * @param asnDbPath + * ASN 库文件 {@link Resource} + * + * @throws IOException + * ASN 库文件不存在时 + * @since 2.2.0 + */ + public void setAsnDbPath(Resource asnDbPath) throws IOException{ + Assert.isNull(asnDbPath, "Ip asn database path cloud not be null."); + this.asnDbPath = asnDbPath.getFile(); + } + + /** + * 设置 ASN 库文件路径 + * + * @param asnDbPath + * IP 库文件路径 + * + * @throws IOException + * ASN 库文件不存在时 + * @since 2.2.0 + */ + public void setAsnDbPath(File asnDbPath) throws IOException{ + Assert.isNull(asnDbPath, "Ip asn database path cloud not be null."); + this.asnDbPath = asnDbPath; + } + + /** + * 设置 ASN 库文件路径 + * + * @param asnDbPath + * ASN 库文件路径 + * + * @throws IOException + * 数据库文件不存在时 + * @since 2.2.0 + */ + public void setAsnDbPath(Path asnDbPath) throws IOException{ + Assert.isNull(asnDbPath, "Ip asn database path cloud not be null."); + this.asnDbPath = asnDbPath.toFile(); + } + + /** + * 设置 ASN 库文件路径 + * + * @param asnDbPath + * ASN 库文件路径 + * + * @throws IOException + * 数据库文件不存在时 + * @since 2.2.0 + */ + public void setAsnDbPath(String asnDbPath) throws IOException{ + Assert.isBlank(asnDbPath, "Ip asn database path cloud not be null or empty."); + setAsnDbPath(new File(asnDbPath)); + } + /** * 返回 IP 库文件流 * * @return IP 库文件流 + * + * @throws IOException + * 数据库文件不存在时 */ public InputStream getStream() throws IOException{ if(stream == null){ - ClassPathResource resource = new ClassPathResource(DEFAULT_CITY_DB); - stream = resource.getInputStream(); + stream = DatabaseResolver.class.getResourceAsStream(DatabaseResolver.DEFAULT_CITY_DB); } return stream; @@ -161,9 +250,37 @@ public InputStream getStream() throws IOException{ */ public void setStream(InputStream stream){ Assert.isNull(stream, "Ip database stream cloud not be null."); - this.stream = stream; - this.loadMode = LoadMode.STREAM; + } + + /** + * 返回 ASN 库文件流 + * + * @return ASN 库文件流 + * + * @throws IOException + * ASN 库文件不存在时 + * @since 2.2.0 + */ + public InputStream getAsnStream() throws IOException{ + if(asnStream == null){ + asnStream = DatabaseResolver.class.getResourceAsStream(DatabaseResolver.DEFAULT_ASN_DB); + } + + return asnStream; + } + + /** + * 设置 asnStream 库文件流 + * + * @param asnStream + * asnStream 库文件流 + * + * @since 2.2.0 + */ + public void setAsnStream(InputStream asnStream){ + Assert.isNull(asnStream, "Ip asn database stream cloud not be null."); + this.asnStream = asnStream; } /** @@ -171,6 +288,7 @@ public void setStream(InputStream stream){ * * @return IP 库加载模式 */ + @Deprecated public LoadMode getLoadMode(){ return loadMode; } diff --git a/buession-geoip/src/main/java/com/buession/geoip/spring/GeoIPResolverFactoryBean.java b/buession-geoip/src/main/java/com/buession/geoip/spring/GeoIPResolverFactoryBean.java index e59826179..dd73f913b 100644 --- a/buession-geoip/src/main/java/com/buession/geoip/spring/GeoIPResolverFactoryBean.java +++ b/buession-geoip/src/main/java/com/buession/geoip/spring/GeoIPResolverFactoryBean.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.geoip.spring; @@ -29,23 +29,22 @@ import com.buession.geoip.CacheDatabaseResolver; import com.buession.geoip.DatabaseResolver; import com.buession.geoip.Resolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; +import java.io.Closeable; +import java.io.IOException; + /** * GeoIP {@link Resolver} 工厂 Bean * * @author Yong.Teng */ public class GeoIPResolverFactoryBean extends GeoIPResolverFactory implements FactoryBean, - InitializingBean { + InitializingBean, Closeable { private DatabaseResolver resolver; - private final static Logger logger = LoggerFactory.getLogger(GeoIPResolverFactoryBean.class); - @Override public DatabaseResolver getObject() throws Exception{ return resolver; @@ -58,13 +57,13 @@ public Class getObjectType(){ @Override public void afterPropertiesSet() throws Exception{ - if(getLoadMode() == LoadMode.STREAM){ - resolver = isEnableCache() ? new CacheDatabaseResolver(getStream()) : new DatabaseResolver(getStream()); - logger.info("Read db from stream"); - }else{ - resolver = isEnableCache() ? new CacheDatabaseResolver(getDbPath()) : new DatabaseResolver(getDbPath()); - logger.info("Read db from file: {}", getDbPath()); - } + resolver = isEnableCache() ? new CacheDatabaseResolver(getStream(), getAsnStream()) : new DatabaseResolver( + getStream(), getAsnStream()); + } + + @Override + public void close() throws IOException{ + resolver.close(); } } diff --git a/buession-geoip/src/main/resources/maxmind/ASN.mmdb b/buession-geoip/src/main/resources/maxmind/ASN.mmdb new file mode 100644 index 000000000..066642fe2 Binary files /dev/null and b/buession-geoip/src/main/resources/maxmind/ASN.mmdb differ diff --git a/buession-geoip/src/main/resources/maxmind/City.mmdb b/buession-geoip/src/main/resources/maxmind/City.mmdb index 6e7b6dfc5..0ddbb2bee 100644 Binary files a/buession-geoip/src/main/resources/maxmind/City.mmdb and b/buession-geoip/src/main/resources/maxmind/City.mmdb differ diff --git a/buession-geoip/src/main/resources/maxmind/Country.mmdb b/buession-geoip/src/main/resources/maxmind/Country.mmdb index d18e644e2..194711907 100644 Binary files a/buession-geoip/src/main/resources/maxmind/Country.mmdb and b/buession-geoip/src/main/resources/maxmind/Country.mmdb differ diff --git a/buession-geoip/src/test/java/com/buession/geoip/DatabaseResolverTest.java b/buession-geoip/src/test/java/com/buession/geoip/DatabaseResolverTest.java index 87104b2cd..6bcfbab7b 100644 --- a/buession-geoip/src/test/java/com/buession/geoip/DatabaseResolverTest.java +++ b/buession-geoip/src/test/java/com/buession/geoip/DatabaseResolverTest.java @@ -27,6 +27,7 @@ import com.buession.geoip.model.Country; import com.buession.geoip.model.District; import com.buession.geoip.model.Location; +import com.buession.geoip.spring.GeoIPResolverFactoryBean; import org.junit.Test; /** @@ -51,6 +52,25 @@ public void country1() throws Exception{ System.out.println(country); } + @Test + public void country2() throws Exception{ + GeoIPResolverFactoryBean factoryBean = new GeoIPResolverFactoryBean(); + + factoryBean.afterPropertiesSet(); + + DatabaseResolver resolver = factoryBean.getObject(); + Country country = resolver.country(3739974408L); + System.out.println(country); + } + + @Test + public void country3() throws Exception{ + DatabaseResolver resolver = new CacheDatabaseResolver( + DatabaseResolver.class.getResourceAsStream("/maxmind/City.mmdb")); + Country country = resolver.country(3739974408L); + System.out.println(country); + } + @Test public void district() throws Exception{ DatabaseResolver resolver = new DatabaseResolver( @@ -71,7 +91,7 @@ public void district1() throws Exception{ public void location() throws Exception{ DatabaseResolver resolver = new DatabaseResolver( DatabaseResolver.class.getResourceAsStream("/maxmind/City.mmdb")); - Location location = resolver.location("60.246.49.9"); + Location location = resolver.location("1.11.64.11"); System.out.println(location); } diff --git a/buession-git/pom.xml b/buession-git/pom.xml new file mode 100644 index 000000000..ca4b9f6f7 --- /dev/null +++ b/buession-git/pom.xml @@ -0,0 +1,123 @@ + + + Buession Git + 4.0.0 + + com.buession + buession-parent + ../buession-parent + 2.2.0 + + buession-git + https://github.com/buession/buessionframework + Buession Framework Git Library + jar + + + buession.com Inc. + http://www.buession.com/ + + + + + yong.teng + yong.teng + webmaster@buession.com + + Project Manager + Developer + + + + + + + The Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + scm:git:https://github.com/buession/buessionframework.git + scm:git:https://github.com/buession/buessionframework.git + https://github.com/buession/buessionframework + + + + github + https://github.com/buession/buessionframework/issues + + + + + com.buession + buession-core + ${project.version} + + + com.buession + buession-json + ${project.version} + provided + + + + org.slf4j + slf4j-api + + + + junit + junit + + + + + buession-git + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.apache.maven.plugins + maven-resources-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.maven.plugins + maven-release-plugin + + + org.apache.maven.plugins + maven-gpg-plugin + + + org.sonatype.plugins + nexus-staging-maven-plugin + + + + \ No newline at end of file diff --git a/buession-git/src/main/java/com/buession/git/BaseCommit.java b/buession-git/src/main/java/com/buession/git/BaseCommit.java new file mode 100644 index 000000000..3460d3bf9 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/BaseCommit.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +/** + * @author Yong.Teng + * @since 2.2.0 + */ +class BaseCommit implements Info { + + /** + * Commit 总数 + */ + private Integer count; + + /** + * 构造函数 + */ + public BaseCommit(){ + } + + /** + * 构造函数 + * + * @param count + * Commit 总数 + */ + public BaseCommit(Integer count){ + this.count = count; + } + + /** + * 返回 Commit 总数 + * + * @return Commit 总数 + */ + public Integer getCount(){ + return count; + } + + /** + * 设置 Commit 总数 + * + * @param count + * Commit 总数 + */ + public void setCount(Integer count){ + this.count = count; + } + +} diff --git a/buession-git/src/main/java/com/buession/git/BaseUser.java b/buession-git/src/main/java/com/buession/git/BaseUser.java new file mode 100644 index 000000000..725d8dc3a --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/BaseUser.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +/** + * 用户实体类 + * + * @author Yong.Teng + * @since 2.2.0 + */ +abstract class BaseUser implements Info { + + /** + * 用户名称 + */ + private String name; + + /** + * 用户 E-mail + */ + private String email; + + /** + * 构造函数 + */ + public BaseUser(){ + } + + /** + * 构造函数 + * + * @param name + * 用户名称 + * @param email + * 用户 E-mail + */ + public BaseUser(String name, String email){ + this.name = name; + this.email = email; + } + + /** + * 返回用户名称 + * + * @return 用户名称 + */ + public String getName(){ + return name; + } + + /** + * 设置用户名称 + * + * @param name + * 用户名称 + */ + public void setName(String name){ + this.name = name; + } + + /** + * 返回用户 E-mail + * + * @return 用户 E-mail + */ + public String getEmail(){ + return email; + } + + /** + * 设置用户 E-mail + * + * @param email + * 用户 E-mail + */ + public void setEmail(String email){ + this.email = email; + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Build.java b/buession-git/src/main/java/com/buession/git/Build.java new file mode 100644 index 000000000..bb6db76f5 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Build.java @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import java.time.ZonedDateTime; +import java.util.Optional; + +/** + * Build 信息 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Build implements Info { + + /** + * Build 主机 + */ + private String host; + + /** + * Build 时间 + */ + private ZonedDateTime time; + + /** + * Build 用户 + */ + private User user; + + /** + * Build 版本 + */ + private String version; + + /** + * 构造函数 + */ + public Build(){ + } + + /** + * 构造函数 + * + * @param host + * Build 主机 + * @param time + * Build 时间 + * @param user + * Build 用户 + * @param version + * uild 版本 + */ + public Build(String host, ZonedDateTime time, User user, String version){ + this.host = host; + this.time = time; + this.user = user; + this.version = version; + } + + /** + * 返回 Build 主机 + * + * @return Build 主机 + */ + public String getHost(){ + return host; + } + + /** + * 设置 Build 主机 + * + * @param host + * Build 主机 + */ + public void setHost(String host){ + this.host = host; + } + + /** + * 返回 Build 时间 + * + * @return Build 时间 + */ + public ZonedDateTime getTime(){ + return time; + } + + /** + * 设置 Build 时间 + * + * @param time + * Build 时间 + */ + public void setTime(ZonedDateTime time){ + this.time = time; + } + + /** + * 返回 Build 用户 + * + * @return Build 用户 + */ + public User getUser(){ + return user; + } + + /** + * 设置 Build 用户 + * + * @param user + * Build 用户 + */ + public void setUser(User user){ + this.user = user; + } + + /** + * 返回 Build 版本 + * + * @return Build 版本 + */ + public String getVersion(){ + return version; + } + + /** + * 设置 Build 版本 + * + * @param version + * Build 版本 + */ + public void setVersion(String version){ + this.version = version; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("build") + .append("host", host) + .append("time", time) + .append("user", Optional.ofNullable(user).orElse(new User())) + .append("version", version); + + return builder.build(); + } + + public final static class User extends BaseUser { + + /** + * 构造函数 + */ + public User(){ + super(); + } + + /** + * 构造函数 + * + * @param name + * 用户名称 + * @param email + * 用户 E-mail + */ + public User(String name, String email){ + super(name, email); + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("build.user") + .append("name", getName()) + .append("email", getEmail()); + + return builder.build(); + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Closest.java b/buession-git/src/main/java/com/buession/git/Closest.java new file mode 100644 index 000000000..3e77e4510 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Closest.java @@ -0,0 +1,199 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import java.util.Optional; + +/** + * Closest + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Closest implements Info { + + /** + * Tag + */ + private Tag tag; + + /** + * 构造函数 + */ + public Closest(){ + } + + /** + * 构造函数 + * + * @param tag + * Tag + */ + public Closest(Tag tag){ + this.tag = tag; + } + + /** + * 设置 Tag + * + * @return Tag + */ + public Tag getTag(){ + return tag; + } + + /** + * 设置 Tag + * + * @param tag + * Tag + */ + public void setTag(Tag tag){ + this.tag = tag; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("closest") + .append("tag", Optional.ofNullable(tag).orElse(new Tag())); + + return builder.build(); + } + + /** + * Tag + */ + public final static class Tag implements Info { + + /** + * Tag 名称 + */ + private String name; + + /** + * Commit + */ + private Commit commit; + + /** + * 构造函数 + */ + public Tag(){ + } + + /** + * 构造函数 + * + * @param name + * Tag 名称 + * @param commit + * Commit + */ + public Tag(String name, Commit commit){ + this.name = name; + this.commit = commit; + } + + /** + * 返回 Tag 名称 + * + * @return Tag 名称 + */ + public String getName(){ + return name; + } + + /** + * 设置 Tag 名称 + * + * @param name + * Tag 名称 + */ + public void setName(String name){ + this.name = name; + } + + /** + * 返回 Commit + * + * @return Commit + */ + public Commit getCommit(){ + return commit; + } + + /** + * 设置 Commit + * + * @param commit + * Commit + */ + public void setCommit(Commit commit){ + this.commit = commit; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("closest.tag") + .append("name", name) + .append("commit", Optional.ofNullable(commit).orElse(new Commit())); + + return builder.build(); + } + + /** + * Commit + */ + public final static class Commit extends BaseCommit { + + /** + * 构造函数 + */ + public Commit(){ + } + + /** + * 构造函数 + * + * @param count + * Commit 总数 + */ + public Commit(int count){ + super(count); + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("closest.tag.commit") + .append("count", getCount()); + + return builder.build(); + } + + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Commit.java b/buession-git/src/main/java/com/buession/git/Commit.java new file mode 100644 index 000000000..4048b458f --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Commit.java @@ -0,0 +1,445 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.ZonedDateTime; +import java.util.Optional; + +/** + * Commit + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Commit implements Info { + + private ZonedDateTime time; + + private Id id; + + private Author author; + + private Committer committer; + + /** + * Commit 用户 + */ + private User user; + + /** + * Commit 信息 + */ + private Message message; + + /** + * 构造函数 + */ + public Commit(){ + } + + /** + * 构造函数 + * + * @param time + * -- + * @param id + * -- + * @param author + * -- + * @param committer + * -- + * @param user + * -- + * @param message + * -- + */ + public Commit(ZonedDateTime time, Id id, Author author, Committer committer, User user, + Message message){ + this.time = time; + this.id = id; + this.author = author; + this.committer = committer; + this.user = user; + this.message = message; + } + + public ZonedDateTime getTime(){ + return time; + } + + public void setTime(ZonedDateTime time){ + this.time = time; + } + + public Id getId(){ + return id; + } + + public void setId(Id id){ + this.id = id; + } + + public Author getAuthor(){ + return author; + } + + public void setAuthor(Author author){ + this.author = author; + } + + public Committer getCommitter(){ + return committer; + } + + public void setCommitter(Committer committer){ + this.committer = committer; + } + + /** + * 返回 Commit 用户 + * + * @return Commit 用户 + */ + public User getUser(){ + return user; + } + + /** + * 设置 Commit 用户 + * + * @param user + * Commit 用户 + */ + public void setUser(User user){ + this.user = user; + } + + /** + * 返回 Commit 信息 + * + * @return Commit 信息 + */ + public Message getMessage(){ + return message; + } + + /** + * 设置 Commit 信息 + * + * @param message + * Commit 信息 + */ + public void setMessage(Message message){ + this.message = message; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit") + .append("time", time) + .append("id", Optional.ofNullable(id).orElse(new Id())) + .append("author", Optional.ofNullable(author).orElse(new Author())) + .append("committer", Optional.ofNullable(committer).orElse(new Committer())) + .append("user", Optional.ofNullable(user).orElse(new User())) + .append("message", Optional.ofNullable(message).orElse(new Message())); + + return builder.build(); + } + + public final static class Id implements Info { + + private String value; + + private String abbrev; + + private String describe; + + private String describeShort; + + /** + * 构造函数 + */ + public Id(){ + } + + /** + * 构造函数 + * + * @param value + * -- + * @param abbrev + * -- + * @param describe + * -- + * @param describeShort + * -- + */ + public Id(String value, String abbrev, String describe, String describeShort){ + this.value = value; + this.abbrev = abbrev; + this.describe = describe; + this.describeShort = describeShort; + } + + public String getValue(){ + return value; + } + + public void setValue(String value){ + this.value = value; + } + + public String getAbbrev(){ + return abbrev; + } + + public void setAbbrev(String abbrev){ + this.abbrev = abbrev; + } + + public String getDescribe(){ + return describe; + } + + public void setDescribe(String describe){ + this.describe = describe; + } + + public String getDescribeShort(){ + return describeShort; + } + + public void setDescribeShort(String describeShort){ + this.describeShort = describeShort; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit.id") + .append(null, value) + .append("abbrev", abbrev) + .append("describe", describe) + .append("describe-short", describeShort); + + return builder.build(); + } + + } + + public final static class User extends BaseUser { + + /** + * 构造函数 + */ + public User(){ + super(); + } + + /** + * 构造函数 + * + * @param name + * 用户名称 + * @param email + * 用户 E-mail + */ + public User(String name, String email){ + super(name, email); + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit.user") + .append("name", getName()) + .append("email", getEmail()); + + return builder.build(); + } + + } + + public final static class Author implements Info { + + /** + * 时间 + */ + private ZonedDateTime time; + + /** + * 构造函数 + */ + public Author(){ + } + + /** + * 构造函数 + * + * @param time + * -- + */ + public Author(ZonedDateTime time){ + this.time = time; + } + + /** + * 返回时间 + * + * @return 时间 + */ + public ZonedDateTime getTime(){ + return time; + } + + /** + * 设置时间 + * + * @param time + * 时间 + */ + public void setTime(ZonedDateTime time){ + this.time = time; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit.author") + .append("time", time); + + return builder.build(); + } + + } + + public final static class Committer implements Info { + + /** + * 时间 + */ + private ZonedDateTime time; + + /** + * 构造函数 + */ + public Committer(){ + } + + /** + * 构造函数 + * + * @param time + * -- + */ + public Committer(ZonedDateTime time){ + this.time = time; + } + + /** + * 返回时间 + * + * @return 时间 + */ + public ZonedDateTime getTime(){ + return time; + } + + /** + * 设置时间 + * + * @param time + * 时间 + */ + public void setTime(ZonedDateTime time){ + this.time = time; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit.committer") + .append("time", time); + + return builder.build(); + } + + } + + /** + * Commit 信息 + */ + public final static class Message implements Info { + + private String full; + + @JsonProperty(value = "short") + private String $short; + + /** + * 构造函数 + */ + public Message(){ + } + + /** + * 构造函数 + * + * @param full + * -- + * @param $short + * -- + */ + public Message(String full, String $short){ + this.full = full; + this.$short = $short; + } + + public String getShort(){ + return $short; + } + + public void setShort(String $short){ + this.$short = $short; + } + + public String getFull(){ + return full; + } + + public void setFull(String full){ + this.full = full; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("commit.message") + .append("full", full) + .append("short", $short); + + return builder.build(); + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Git.java b/buession-git/src/main/java/com/buession/git/Git.java new file mode 100644 index 000000000..31381ae2e --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Git.java @@ -0,0 +1,333 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.Optional; +import java.util.Set; + +/** + * Git 信息 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public class Git { + + /** + * 分支 + */ + private String branch; + + /** + * Build 信息 + */ + private Build build; + + /** + * 远程信息 + */ + private Remote remote; + + /** + * 本地信息 + */ + private Local local; + + /** + * Commit + */ + private Commit commit; + + /** + * 仓库脏,为仓库脏时,返回 true;为干净仓库时, 返回 false + */ + private Boolean dirty; + + /** + * Closest + */ + private Closest closest; + + /** + * Tags + */ + private Set tags; + + /** + * 统计 + */ + private Total total; + + /** + * 构造函数 + */ + public Git(){ + } + + /** + * 构造函数 + * + * @param branch + * 分支 + * @param build + * Build 信息 + * @param remote + * 远程信息 + * @param local + * 本地信息 + * @param commit + * Commit + * @param dirty + * 仓库脏 + * @param closest + * Closest + * @param tags + * Tags + * @param total + * 统计 + */ + public Git(String branch, Build build, Remote remote, Local local, Commit commit, boolean dirty, + Closest closest, Set tags, Total total){ + this.branch = branch; + this.build = build; + this.remote = remote; + this.local = local; + this.commit = commit; + this.dirty = dirty; + this.closest = closest; + this.tags = tags; + this.total = total; + } + + /** + * 返回分支 + * + * @return 分支 + */ + public String getBranch(){ + return branch; + } + + /** + * 设置分支 + * + * @param branch + * 分支 + */ + public void setBranch(String branch){ + this.branch = branch; + } + + /** + * 返回 Build 信息 + * + * @return Build 信息 + */ + public Build getBuild(){ + return build; + } + + /** + * 设置 Build 信息 + * + * @param build + * Build 信息 + */ + public void setBuild(Build build){ + this.build = build; + } + + /** + * 返回远程信息 + * + * @return 远程信息 + */ + public Remote getRemote(){ + return remote; + } + + /** + * 设置远程信息 + * + * @param remote + * 远程信息 + */ + public void setRemote(Remote remote){ + this.remote = remote; + } + + /** + * 返回本地信息 + * + * @return 本地信息 + */ + public Local getLocal(){ + return local; + } + + /** + * 设置本地信息 + * + * @param local + * 本地信息 + */ + public void setLocal(Local local){ + this.local = local; + } + + /** + * 返回 Commit + * + * @return Commit + */ + public Commit getCommit(){ + return commit; + } + + /** + * 设置 Commit + * + * @param commit + * Commit + */ + public void setCommit(Commit commit){ + this.commit = commit; + } + + /** + * 仓库脏,为仓库脏时,返回 true;为干净仓库时, 返回 false + * + * @return 仓库脏,为仓库脏时,返回 true;为干净仓库时, 返回 false + */ + public Boolean isDirty(){ + return dirty; + } + + /** + * 设置仓库脏 + * + * @param dirty + * 仓库脏 + */ + public void setDirty(Boolean dirty){ + this.dirty = dirty; + } + + /** + * 返回 Closest + * + * @return Closest + */ + public Closest getClosest(){ + return closest; + } + + /** + * 设置 Closest + * + * @param closest + * Closest + */ + public void setClosest(Closest closest){ + this.closest = closest; + } + + /** + * 返回 Tags + * + * @return Tags + */ + public Set getTags(){ + return tags; + } + + /** + * 设置 Tags + * + * @param tags + * Tags + */ + public void setTags(Set tags){ + this.tags = tags; + } + + /** + * 返回统计 + * + * @return 统计 + */ + public Total getTotal(){ + return total; + } + + /** + * 设置统计 + * + * @param total + * 统计 + */ + public void setTotal(Total total){ + this.total = total; + } + + /** + * 返回 Commit Id + * + * @return Commit Id + */ + @JsonIgnore + public String getCommitId(){ + return getCommit() != null ? getCommit().getId().getValue() : null; + } + + /** + * 返回短 Commit Id + * + * @return 短 Commit Id + */ + @JsonIgnore + public String getShortCommitId(){ + return getCommit() != null ? getCommit().getId().getAbbrev() : null; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance() + .append("branch", branch) + .append("build", Optional.ofNullable(build).orElse(new Build())) + .append("remote", Optional.ofNullable(remote).orElse(new Remote())) + .append("local", Optional.ofNullable(local).orElse(new Local())) + .append("commit", Optional.ofNullable(commit).orElse(new Commit())) + .append("dirty", dirty) + .append("closest", Optional.ofNullable(closest).orElse(new Closest())) + .append("tags", tags) + .append("total", Optional.ofNullable(total).orElse(new Total())); + + return builder.build(); + } + +} diff --git a/buession-git/src/main/java/com/buession/git/GitInfoBuilder.java b/buession-git/src/main/java/com/buession/git/GitInfoBuilder.java new file mode 100644 index 000000000..ab6e8c50d --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/GitInfoBuilder.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import com.buession.lang.Constants; + +import java.time.ZonedDateTime; +import java.util.Set; + +/** + * @author Yong.Teng + * @since 2.2.0 + */ +class GitInfoBuilder { + + private final static String PREFIX = "git"; + + private final StringBuilder sb = new StringBuilder(); + + private final String group; + + private int i = 0; + + private GitInfoBuilder(final String group){ + this.group = group; + } + + public static GitInfoBuilder getInstance(){ + return getInstance(null); + } + + public static GitInfoBuilder getInstance(final String group){ + return new GitInfoBuilder(group); + } + + public GitInfoBuilder append(final String name, final String value){ + ensure(); + ensurePrefix(); + + if(name != null){ + sb.append(name).append('='); + }else{ + endDotReplaceToEqualsSign(); + } + + if(value != null){ + sb.append(value); + } + + return this; + } + + public GitInfoBuilder append(final String name, final Integer value){ + ensure(); + ensurePrefix(); + + if(name != null){ + sb.append(name).append('='); + }else{ + endDotReplaceToEqualsSign(); + } + + sb.append(value == null ? Constants.EMPTY_STRING : value.toString()); + + return this; + } + + public GitInfoBuilder append(final String name, final Boolean value){ + ensure(); + ensurePrefix(); + + if(name != null){ + sb.append(name).append('='); + }else{ + endDotReplaceToEqualsSign(); + } + + sb.append(value == null ? Constants.EMPTY_STRING : value.toString()); + + return this; + } + + public GitInfoBuilder append(final String name, final Set value){ + if(value != null){ + ensure(); + ensurePrefix(); + + if(name != null){ + sb.append(name).append('='); + }else{ + endDotReplaceToEqualsSign(); + } + + if(value == null){ + sb.append(Constants.EMPTY_STRING); + }else{ + sb.append(String.join(",", value)); + } + } + + return this; + } + + public GitInfoBuilder append(final String name, final ZonedDateTime value){ + ensure(); + ensurePrefix(); + + if(name != null){ + sb.append(name).append('='); + }else{ + endDotReplaceToEqualsSign(); + } + + sb.append(value == null ? "" : value); + + return this; + } + + public GitInfoBuilder append(final String name, final Info value){ + return append(name, value, false); + } + + public GitInfoBuilder append(final String name, final Info value, final boolean containName){ + if(value != null){ + ensure(); + + if(containName && name != null){ + sb.append(name).append('='); + } + + sb.append(value); + } + + return this; + } + + public String build(){ + return sb.toString(); + } + + private void ensurePrefix(){ + sb.append(PREFIX).append('.'); + if(group != null){ + sb.append(group).append('.'); + } + } + + private void ensure(){ + if(i++ > 0){ + sb.append(System.lineSeparator()); + } + } + + private void endDotReplaceToEqualsSign(){ + sb.setCharAt(sb.length() - 1, '='); + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Info.java b/buession-git/src/main/java/com/buession/git/Info.java new file mode 100644 index 000000000..d5e0f23b0 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Info.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +/** + * @author Yong.Teng + * @since 2.2.0 + */ +interface Info { + +} diff --git a/buession-git/src/main/java/com/buession/git/Local.java b/buession-git/src/main/java/com/buession/git/Local.java new file mode 100644 index 000000000..d10f084a9 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Local.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import java.util.Optional; + +/** + * 本地信息 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Local implements Info { + + /** + * 分支信息 + */ + private Branch branch; + + /** + * 构造函数 + */ + public Local(){ + } + + /** + * 构造函数 + * + * @param branch + * 分支信息 + */ + public Local(Branch branch){ + this.branch = branch; + } + + /** + * 返回分支信息 + * + * @return 分支信息 + */ + public Branch getBranch(){ + return branch; + } + + /** + * 设置分支信息 + * + * @param branch + * 分支信息 + */ + public void setBranch(Branch branch){ + this.branch = branch; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("local") + .append("branch", Optional.ofNullable(branch).orElse(new Branch())); + + return builder.build(); + } + + /** + * 分支信息 + */ + public final static class Branch implements Info { + + /** + * 落后情况 + */ + private String ahead; + + /** + * 超前情况 + */ + private String behind; + + /** + * 构造函数 + */ + public Branch(){ + } + + /** + * 构造函数 + * + * @param ahead + * 落后情况 + * @param behind + * 超前情况 + */ + public Branch(String ahead, String behind){ + this.ahead = ahead; + this.behind = behind; + } + + /** + * 返回落后情况 + * + * @return 落后情况 + */ + public String getAhead(){ + return ahead; + } + + /** + * 设置落后情况 + * + * @param ahead + * 落后情况 + */ + public void setAhead(String ahead){ + this.ahead = ahead; + } + + /** + * 返回超前情况 + * + * @return 超前情况 + */ + public String getBehind(){ + return behind; + } + + /** + * 设置超前情况 + * + * @param behind + * 超前情况 + */ + public void setBehind(String behind){ + this.behind = behind; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("local.branch") + .append("ahead", ahead) + .append("behind", behind); + + return builder.build(); + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Remote.java b/buession-git/src/main/java/com/buession/git/Remote.java new file mode 100644 index 000000000..8073ae278 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Remote.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import java.util.Optional; + +/** + * 远程信息 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Remote implements Info { + + /** + * 原始信息 + */ + private Origin origin; + + /** + * 构造函数 + */ + public Remote(){ + } + + /** + * 构造函数 + * + * @param origin + * 原始信息 + */ + public Remote(Origin origin){ + this.origin = origin; + } + + /** + * 返回原始信息 + * + * @return 原始信息 + */ + public Origin getOrigin(){ + return origin; + } + + /** + * 设置原始信息 + * + * @param origin + * 原始信息 + */ + public void setOrigin(Origin origin){ + this.origin = origin; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("remote") + .append("origin", Optional.ofNullable(origin).orElse(new Origin())); + + return builder.build(); + } + + /** + * 原始信息 + */ + public final static class Origin implements Info { + + /** + * 远程仓库地址 + */ + private String url; + + /** + * 构造函数 + */ + public Origin(){ + } + + /** + * 构造函数 + * + * @param url + * 远程仓库地址 + */ + public Origin(String url){ + this.url = url; + } + + /** + * 返回远程仓库地址 + * + * @return 远程仓库地址 + */ + public String getUrl(){ + return url; + } + + /** + * 设置远程仓库地址 + * + * @param url + * 远程仓库地址 + */ + public void setUrl(String url){ + this.url = url; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("remote.origin") + .append("url", url); + + return builder.build(); + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/Total.java b/buession-git/src/main/java/com/buession/git/Total.java new file mode 100644 index 000000000..dea153c34 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/Total.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import java.util.Optional; + +/** + * 统计信息 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public final class Total implements Info { + + /** + * Commit + */ + private Commit commit; + + /** + * 构造函数 + */ + public Total(){ + } + + /** + * 构造函数 + * + * @param commit + * Commit + */ + public Total(Commit commit){ + this.commit = commit; + } + + /** + * 返回 Commit + * + * @return Commit + */ + public Commit getCommit(){ + return commit; + } + + /** + * 设置 Commit + * + * @param commit + * Commit + */ + public void setCommit(Commit commit){ + this.commit = commit; + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("total") + .append("commit", Optional.ofNullable(commit).orElse(new Commit())); + + return builder.build(); + } + + /** + * Commit + */ + public final static class Commit extends BaseCommit { + + /** + * 构造函数 + */ + public Commit(){ + } + + /** + * 构造函数 + * + * @param count + * Commit 总数 + */ + public Commit(int count){ + super(count); + } + + @Override + public String toString(){ + final GitInfoBuilder builder = GitInfoBuilder.getInstance("total.commit") + .append("count", getCount()); + + return builder.build(); + } + + } + +} diff --git a/buession-git/src/main/java/com/buession/git/package-info.java b/buession-git/src/main/java/com/buession/git/package-info.java new file mode 100644 index 000000000..1f7decae3 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/package-info.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +/** + * @author Yong.Teng + * @since 2.2.0 + */ +package com.buession.git; \ No newline at end of file diff --git a/buession-git/src/main/java/com/buession/git/parser/AbstractGitParser.java b/buession-git/src/main/java/com/buession/git/parser/AbstractGitParser.java new file mode 100644 index 000000000..d3def3f20 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/AbstractGitParser.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git.parser; + +import com.buession.core.utils.Assert; +import com.buession.git.Git; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.lang.Nullable; + +import java.util.Properties; + +/** + * Git 解析器抽象类 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public abstract class AbstractGitParser implements GitParser { + + protected Resource resource; + + /** + * 构造函数 + */ + public AbstractGitParser(){ + + } + + /** + * 构造函数 + * + * @param resource + * 文件资源 + */ + public AbstractGitParser(final Resource resource){ + Assert.isNull(resource, "Git properties resource cloud not be null."); + this.resource = resource; + } + + /** + * 构造函数 + * + * @param path + * Git 信息文件路径 + */ + public AbstractGitParser(final String path){ + Assert.isBlank(path, "Git properties path cloud not be empty or null."); + this.resource = new ClassPathResource(path); + } + + @Nullable + @Override + public Git parse(){ + final Git git = new Git(); + final Properties properties = loadData(); + final GitInfoParser infoParser = new GitInfoParser(properties); + + git.setBranch(properties.getProperty("git.branch")); + git.setDirty(Boolean.parseBoolean(properties.getProperty("git.dirty"))); + + git.setBuild(infoParser.build()); + git.setRemote(infoParser.remote()); + git.setLocal(infoParser.local()); + git.setCommit(infoParser.commit()); + git.setClosest(infoParser.closest()); + git.setTags(infoParser.tags()); + git.setTotal(infoParser.total()); + + return git; + } + + protected abstract Properties loadData(); + +} diff --git a/buession-git/src/main/java/com/buession/git/parser/GitInfoParser.java b/buession-git/src/main/java/com/buession/git/parser/GitInfoParser.java new file mode 100644 index 000000000..a06cc7d68 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/GitInfoParser.java @@ -0,0 +1,217 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git.parser; + +import com.buession.core.collect.Arrays; +import com.buession.core.utils.StringUtils; +import com.buession.core.validator.Validate; +import com.buession.git.Build; +import com.buession.git.Closest; +import com.buession.git.Commit; +import com.buession.git.Local; +import com.buession.git.Remote; +import com.buession.git.Total; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Properties; +import java.util.Set; + +/** + * @author Yong.Teng + * @since 2.2.0 + */ +class GitInfoParser { + + private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"); + + private final Properties properties; + + private final static Logger logger = LoggerFactory.getLogger(GitInfoParser.class); + + public GitInfoParser(final Properties properties){ + this.properties = properties; + } + + public Build build(){ + final Build build = new Build(); + + build.setHost(getValue("build.host")); + build.setTime(coercePropertyToZonedDateTime("build.time")); + + final Build.User user = new Build.User(getValue("build.user.name"), getValue("build.user.email")); + + build.setUser(user); + build.setVersion(getValue("build.version")); + + return build; + } + + public Remote remote(){ + final Remote remote = new Remote(); + + final Remote.Origin origin = new Remote.Origin(getValue("remote.origin.url")); + + remote.setOrigin(origin); + + return remote; + } + + public Local local(){ + final Local local = new Local(); + + final Local.Branch branch = new Local.Branch(getValue("local.branch.ahead"), + getValue("local.branch.behind")); + + local.setBranch(branch); + + return local; + } + + public Commit commit(){ + final Commit commit = new Commit(); + + commit.setTime(coercePropertyToZonedDateTime(getValue("commit.time"))); + + final Commit.Id id = new Commit.Id(); + id.setValue(getValue("commit.id")); + id.setAbbrev(getValue("commit.id.abbrev")); + id.setDescribe(getValue("commit.id.describe")); + id.setDescribeShort(getValue("commit.id.describe-short")); + + commit.setId(id); + + final Commit.User uer = new Commit.User(getValue("commit.user.name"), getValue("commit.user.email")); + + commit.setUser(uer); + + final Commit.Author author = new Commit.Author( + coercePropertyToZonedDateTime("commit.author.time")); + + commit.setAuthor(author); + + final Commit.Committer committer = new Commit.Committer( + coercePropertyToZonedDateTime("commit.committer.time")); + + commit.setCommitter(committer); + + final Commit.Message message = new Commit.Message(getValue("commit.message.full"), + getValue("commit.message.short")); + + commit.setMessage(message); + + return commit; + } + + public Closest closest(){ + final Closest closest = new Closest(); + + final Closest.Tag tag = new Closest.Tag(); + tag.setName(getValue("closest.tag.name")); + + final Closest.Tag.Commit tagCommit = new Closest.Tag.Commit(); + final String s = getValue("closest.tag.commit.count"); + + try{ + tagCommit.setCount(Integer.parseInt(s)); + }catch(NumberFormatException e){ + logger.warn("git.closest.tag.commit.count value: {} cloud not convert to int.", s); + } + + tag.setCommit(tagCommit); + + closest.setTag(tag); + + return closest; + } + + public Set tags(){ + final String tags = getValue("tags"); + + if(Validate.hasText(tags)){ + return Arrays.toSet(StringUtils.split(tags, ',')); + }else{ + return null; + } + } + + public Total total(){ + final Total total = new Total(); + + final Total.Commit commit = new Total.Commit(); + final String s = getValue("total.commit.count"); + + try{ + commit.setCount(Integer.parseInt(s)); + }catch(NumberFormatException e){ + logger.warn("git.total.commit.count value: {} cloud not convert to int.", s); + } + + total.setCommit(commit); + + return total; + } + + private String getValue(final String key){ + return properties.getProperty("git." + key); + } + + private ZonedDateTime coercePropertyToZonedDateTime(final String tag){ + final String value = getValue(tag); + + if(Validate.hasText(value)){ + final Instant instant = coerceToEpoch(value); + + if(instant == null){ + logger.warn("git.{} value: {} cloud not convert to ZonedDateTime.", tag, value); + return null; + } + + return instant.atZone(ZoneOffset.UTC); + }else{ + return null; + } + } + + private static Instant coerceToEpoch(final String s){ + try{ + return Instant.ofEpochMilli(Long.parseLong(s) * 1000); + }catch(NumberFormatException e){ + // + } + + try{ + return DATE_TIME_FORMATTER.parse(s, Instant::from); + }catch(DateTimeParseException e){ + return null; + } + } + +} diff --git a/buession-git/src/main/java/com/buession/git/parser/GitParser.java b/buession-git/src/main/java/com/buession/git/parser/GitParser.java new file mode 100644 index 000000000..20082e325 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/GitParser.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git.parser; + +import com.buession.git.Git; +import org.springframework.lang.Nullable; + +/** + * Git 解析器 + * + * @author Yong.Teng + * @since 2.2.0 + */ +@FunctionalInterface +public interface GitParser { + + /** + * Git 信息解析 + * + * @return Git 信息 {@link Git} + */ + @Nullable + Git parse(); + +} diff --git a/buession-git/src/main/java/com/buession/git/parser/JsonGitParser.java b/buession-git/src/main/java/com/buession/git/parser/JsonGitParser.java new file mode 100644 index 000000000..ae9259922 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/JsonGitParser.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git.parser; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import java.util.Properties; + +/** + * JSON 格式 Git 解析器抽象类 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public class JsonGitParser extends AbstractGitParser { + + /** + * 构造函数 + */ + public JsonGitParser(){ + super(new ClassPathResource("git.properties")); + } + + /** + * 构造函数 + * + * @param resource + * 文件资源 + */ + public JsonGitParser(final Resource resource){ + super(resource); + } + + /** + * 构造函数 + * + * @param path + * Git 信息文件路径 + */ + public JsonGitParser(final String path){ + super(path); + } + + @Override + protected Properties loadData(){ + ObjectMapper objectMapper = new ObjectMapper(); + + try{ + return objectMapper.readValue(resource.getInputStream(), new TypeReference() { + + }); + }catch(Exception e){ + // + } + + return null; + } + +} diff --git a/buession-git/src/main/java/com/buession/git/parser/PropertiesGitParser.java b/buession-git/src/main/java/com/buession/git/parser/PropertiesGitParser.java new file mode 100644 index 000000000..b697a2f88 --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/PropertiesGitParser.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git.parser; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PropertiesLoaderUtils; + +import java.util.Properties; + +/** + * Properties 格式 Git 解析器抽象类 + * + * @author Yong.Teng + * @since 2.2.0 + */ +public class PropertiesGitParser extends AbstractGitParser { + + /** + * 构造函数 + */ + public PropertiesGitParser(){ + super(new ClassPathResource("git.properties")); + } + + /** + * 构造函数 + * + * @param resource + * 文件资源 + */ + public PropertiesGitParser(final Resource resource){ + super(resource); + } + + /** + * 构造函数 + * + * @param path + * Git 信息文件路径 + */ + public PropertiesGitParser(final String path){ + super(path); + } + + @Override + protected Properties loadData(){ + try{ + return PropertiesLoaderUtils.loadProperties(resource); + }catch(Exception e){ + return null; + } + } + +} diff --git a/buession-git/src/main/java/com/buession/git/parser/package-info.java b/buession-git/src/main/java/com/buession/git/parser/package-info.java new file mode 100644 index 000000000..d632158eb --- /dev/null +++ b/buession-git/src/main/java/com/buession/git/parser/package-info.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +/** + * @author Yong.Teng + * @since 2.2.0 + */ +package com.buession.git.parser; \ No newline at end of file diff --git a/buession-git/src/test/java/com/buession/git/GitTest.java b/buession-git/src/test/java/com/buession/git/GitTest.java new file mode 100644 index 000000000..ee5f63016 --- /dev/null +++ b/buession-git/src/test/java/com/buession/git/GitTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.git; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +/** + * @author Yong.Teng + * @since 2.2.0 + */ +public class GitTest { + + @Test + public void gitToString(){ + Git git = new Git(); + + git.setBranch("master"); + + Build build = new Build(); + git.setBuild(build); + + System.out.println(git.toString()); + } + + @Test + public void buildToString(){ + Build build = new Build(); + + System.out.println(build.toString()); + } + + @Test + public void gitJsonEncode() throws JsonProcessingException{ + Git git = new Git(); + + git.setBranch("master"); + + Build build = new Build(); + git.setBuild(build); + + Total total = new Total(); + Total.Commit totalCommit = new Total.Commit(); + + total.setCommit(totalCommit); + + git.setTotal(total); + + ObjectMapper objectMapper = new ObjectMapper(); + System.out.println(objectMapper.writeValueAsString(git)); + } + + @Test + public void totalJsonEncode() throws JsonProcessingException{ + Total total = new Total(); + + ObjectMapper objectMapper = new ObjectMapper(); + System.out.println(objectMapper.writeValueAsString(total)); + } + +} diff --git a/buession-httpclient/pom.xml b/buession-httpclient/pom.xml index b41561116..960bd5642 100644 --- a/buession-httpclient/pom.xml +++ b/buession-httpclient/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-httpclient https://github.com/buession/buessionframework diff --git a/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheRequestBuilder.java b/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheRequestBuilder.java index 76946bac2..f671b06e7 100644 --- a/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheRequestBuilder.java +++ b/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheRequestBuilder.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.apache; @@ -40,13 +40,13 @@ import com.buession.httpclient.core.RepeatableInputStreamRequestBody; import com.buession.httpclient.core.Request; import com.buession.httpclient.core.RequestBody; +import com.buession.httpclient.core.RequestBodyConverter; import com.buession.httpclient.core.RequestMethod; import com.buession.httpclient.core.TextRawRequestBody; import com.buession.httpclient.core.XmlRawRequestBody; import com.buession.httpclient.core.AbstractRequestBuilder; import com.buession.httpclient.apache.convert.EncodedFormRequestBodyConverter; import com.buession.httpclient.apache.convert.HtmlRawRequestBodyConverter; -import com.buession.httpclient.apache.convert.ApacheRequestBodyConverter; import com.buession.httpclient.apache.convert.JavaScriptRawRequestBodyConverter; import com.buession.httpclient.apache.convert.JsonRawRequestBodyConverter; import com.buession.httpclient.apache.convert.TextRawRequestBodyConverter; @@ -71,8 +71,8 @@ public class ApacheRequestBuilder extends AbstractRequestBuilder(), StandardCharsets.ISO_8859_1); - private final static Map, ApacheRequestBodyConverter> REQUEST_BODY_CONVERTS = new HashMap<>( - 16, 0.8F); + private final static Map, RequestBodyConverter> REQUEST_BODY_CONVERTS = + new HashMap<>(16, 0.8F); static{ REQUEST_BODY_CONVERTS.put(ChunkedInputStreamRequestBody.class, new ChunkedInputStreamRequestBodyConverter()); @@ -275,12 +275,12 @@ protected ApacheRequestBuilder setRequest(final HttpRequestBase httpRequest, fin } protected ApacheRequestBuilder setRequest(final HttpEntityEnclosingRequestBase httpRequest, - final RequestMethod method, - final RequestBody body){ + final RequestMethod method, final RequestBody body){ setRequest(httpRequest, method); if(body != null){ - ApacheRequestBodyConverter> converter = REQUEST_BODY_CONVERTS.get(body.getClass()); + final RequestBodyConverter, HttpEntity> converter = findBodyConverter(REQUEST_BODY_CONVERTS, + body); httpRequest.setEntity(converter == null ? DEFAULT_HTTP_ENTITY : converter.convert(body)); } diff --git a/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheResponseBuilder.java b/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheResponseBuilder.java index f3935e4b4..2218c0fa9 100644 --- a/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheResponseBuilder.java +++ b/buession-httpclient/src/main/java/com/buession/httpclient/apache/ApacheResponseBuilder.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.apache; @@ -58,7 +58,8 @@ public Response build(org.apache.http.HttpResponse httpResponse){ response.setProtocolVersion(ProtocolVersion.createInstance(responseProtocolVersion.getProtocol(), responseProtocolVersion.getMajor(), responseProtocolVersion.getMinor())); - response.setStatusLine(new StatusLine(response.getStatusCode(), response.getStatusText())); + response.setStatusLine( + new StatusLine(responseStatusLine.getStatusCode(), responseStatusLine.getReasonPhrase())); response.setHeaders(responseHeaderParse.parse(httpResponse.getAllHeaders())); if(httpResponse.getEntity() != null){ diff --git a/buession-httpclient/src/main/java/com/buession/httpclient/core/AbstractRequestBuilder.java b/buession-httpclient/src/main/java/com/buession/httpclient/core/AbstractRequestBuilder.java index 4fbcce016..7cf1bf7fc 100644 --- a/buession-httpclient/src/main/java/com/buession/httpclient/core/AbstractRequestBuilder.java +++ b/buession-httpclient/src/main/java/com/buession/httpclient/core/AbstractRequestBuilder.java @@ -21,13 +21,14 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.core; import com.buession.core.utils.StringUtils; import com.buession.core.validator.Validate; +import com.buession.httpclient.apache.convert.ApacheRequestBodyConverter; import com.buession.net.HttpURI; import java.util.List; @@ -105,4 +106,22 @@ protected static String determineRequestUrl(final String url, final Map RequestBodyConverter findBodyConverter( + final Map, RequestBodyConverter> converters, + final RequestBody body){ + RequestBodyConverter converter; + Class clazz = body.getClass(); + + while(clazz != null){ + converter = converters.get(clazz); + if(converter != null){ + return converter; + } + + clazz = clazz.getSuperclass(); + } + + return null; + } + } diff --git a/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpRequestBuilder.java b/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpRequestBuilder.java index c41086985..78624a073 100644 --- a/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpRequestBuilder.java +++ b/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpRequestBuilder.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.okhttp; @@ -36,6 +36,7 @@ import com.buession.httpclient.core.RepeatableInputStreamRequestBody; import com.buession.httpclient.core.Request; import com.buession.httpclient.core.RequestBody; +import com.buession.httpclient.core.RequestBodyConverter; import com.buession.httpclient.core.RequestMethod; import com.buession.httpclient.core.TextRawRequestBody; import com.buession.httpclient.core.XmlRawRequestBody; @@ -47,7 +48,6 @@ import com.buession.httpclient.okhttp.convert.JavaScriptRawRequestBodyConverter; import com.buession.httpclient.okhttp.convert.JsonRawRequestBodyConverter; import com.buession.httpclient.okhttp.convert.MultipartFormRequestBodyConverter; -import com.buession.httpclient.okhttp.convert.OkHttpRequestBodyConverter; import com.buession.httpclient.okhttp.convert.RepeatableInputStreamRequestBodyConvert; import com.buession.httpclient.okhttp.convert.TextRawRequestBodyConverter; import com.buession.httpclient.okhttp.convert.XmlRawRequestBodyConverter; @@ -65,7 +65,7 @@ public class OkHttpRequestBuilder extends AbstractRequestBuilder, OkHttpRequestBodyConverter> REQUEST_BODY_CONVERTS = new HashMap<>( + private final static Map, RequestBodyConverter> REQUEST_BODY_CONVERTS = new HashMap<>( 16, 0.8F); static{ @@ -266,12 +266,13 @@ protected OkHttpRequestBuilder setRequest(final okhttp3.Request.Builder okhttp3R } @SuppressWarnings({"unchecked"}) - private okhttp3.RequestBody buildRequestBody(RequestBody data){ + private okhttp3.RequestBody buildRequestBody(final RequestBody data){ if(data == null){ return DEFAULT_REQUEST_BODY; } - OkHttpRequestBodyConverter> convert = REQUEST_BODY_CONVERTS.get(data.getClass()); + final RequestBodyConverter, okhttp3.RequestBody> convert = REQUEST_BODY_CONVERTS.get( + data.getClass()); return convert == null ? DEFAULT_REQUEST_BODY : convert.convert(data); } diff --git a/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpResponseBuilder.java b/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpResponseBuilder.java index 0dfa8f424..74947d765 100644 --- a/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpResponseBuilder.java +++ b/buession-httpclient/src/main/java/com/buession/httpclient/okhttp/OkHttpResponseBuilder.java @@ -53,7 +53,7 @@ public Response build(okhttp3.Response httpResponse){ final OkHttpResponseHeaderParse okHttpResponseHeaderParse = new OkHttpResponseHeaderParse(); response.setProtocolVersion(protocolConverter.convert(httpResponse.protocol())); - response.setStatusLine(new StatusLine(response.getStatusCode(), response.getStatusText())); + response.setStatusLine(new StatusLine(httpResponse.code(), httpResponse.message())); response.setHeaders(okHttpResponseHeaderParse.parse(httpResponse.headers())); final ResponseBody responseBody = httpResponse.body(); diff --git a/buession-io/pom.xml b/buession-io/pom.xml index 67d444f61..41acac8da 100644 --- a/buession-io/pom.xml +++ b/buession-io/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-io https://github.com/buession/buessionframework diff --git a/buession-io/src/main/java/com/buession/io/file/File.java b/buession-io/src/main/java/com/buession/io/file/File.java index 522413f2b..120b82dff 100644 --- a/buession-io/src/main/java/com/buession/io/file/File.java +++ b/buession-io/src/main/java/com/buession/io/file/File.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.io.file; @@ -346,7 +346,8 @@ public String getExtension() throws IOException{ extension = "tar.gz"; }else{ int i = fileName.lastIndexOf('.'); - extension = i == fileName.length() - 1 ? Constants.EMPTY_STRING : fileName.substring(i + 1).toLowerCase(); + extension = + i == fileName.length() - 1 ? Constants.EMPTY_STRING : fileName.substring(i + 1).toLowerCase(); } } diff --git a/buession-io/src/main/java/com/buession/io/json/deserializer/MimeTypeStringDeserializer.java b/buession-io/src/main/java/com/buession/io/json/deserializer/MimeTypeStringDeserializer.java index 87e75619e..8c08f8b63 100644 --- a/buession-io/src/main/java/com/buession/io/json/deserializer/MimeTypeStringDeserializer.java +++ b/buession-io/src/main/java/com/buession/io/json/deserializer/MimeTypeStringDeserializer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.io.json.deserializer; @@ -28,8 +28,12 @@ import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; import java.io.IOException; @@ -39,10 +43,14 @@ * @author Yong.Teng * @since 2.0.0 */ -public class MimeTypeStringDeserializer extends JsonDeserializer { +public class MimeTypeStringDeserializer extends StdScalarDeserializer implements ContextualDeserializer { public MimeTypeStringDeserializer(){ - super(); + super(MimeType.class); + } + + public MimeTypeStringDeserializer(Class clazz){ + super(clazz); } @Override @@ -64,4 +72,11 @@ public MimeType deserialize(JsonParser jsonParser, DeserializationContext contex jsonParser.getCurrentLocation()); } + @SuppressWarnings({"unchecked"}) + @Override + public JsonDeserializer createContextual(DeserializationContext context, BeanProperty property) + throws JsonMappingException{ + return new MimeTypeStringDeserializer((Class) property.getType().getRawClass()); + } + } diff --git a/buession-io/src/main/java/com/buession/io/json/serializer/MimeTypeStringSerializer.java b/buession-io/src/main/java/com/buession/io/json/serializer/MimeTypeStringSerializer.java index e3e23c2de..b7fb2a94c 100644 --- a/buession-io/src/main/java/com/buession/io/json/serializer/MimeTypeStringSerializer.java +++ b/buession-io/src/main/java/com/buession/io/json/serializer/MimeTypeStringSerializer.java @@ -19,15 +19,20 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.io.json.serializer; import com.buession.io.MimeType; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.ContextualSerializer; +import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import java.io.IOException; @@ -37,10 +42,14 @@ * @author Yong.Teng * @since 1.3.2 */ -public class MimeTypeStringSerializer extends JsonSerializer { +public class MimeTypeStringSerializer extends StdScalarSerializer implements ContextualSerializer { public MimeTypeStringSerializer(){ - super(); + super(MimeType.class, false); + } + + public MimeTypeStringSerializer(Class clazz){ + super(clazz, false); } @Override @@ -52,5 +61,18 @@ public void serialize(MimeType value, JsonGenerator jsonGenerator, SerializerPro jsonGenerator.writeString(value.toString()); } } - + + @SuppressWarnings({"unchecked"}) + @Override + public JsonSerializer createContextual(SerializerProvider provider, BeanProperty property) + throws JsonMappingException{ + JsonFormat.Value format = findFormatOverrides(provider, property, handledType()); + + if(format != null){ + return new MimeTypeStringSerializer((Class) property.getType().getRawClass()); + } + + return this; + } + } diff --git a/buession-io/src/test/java/com/buession/io/FileTest.java b/buession-io/src/test/java/com/buession/io/FileTest.java index 81ad7df85..d2a7bf201 100644 --- a/buession-io/src/test/java/com/buession/io/FileTest.java +++ b/buession-io/src/test/java/com/buession/io/FileTest.java @@ -25,6 +25,7 @@ package com.buession.io; import com.buession.io.file.File; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; @@ -42,4 +43,12 @@ public void mimeType() throws IOException{ System.out.println(mimeType + ": " + mimeType.getDescription()); } + @Test + public void jsonEncode() throws IOException{ + File file = new File("tmp.jpeg"); + + ObjectMapper objectMapper = new ObjectMapper(); + System.out.println(objectMapper.writeValueAsString(file)); + } + } diff --git a/buession-jdbc/pom.xml b/buession-jdbc/pom.xml index 630d8615b..23b623de0 100644 --- a/buession-jdbc/pom.xml +++ b/buession-jdbc/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-jdbc https://github.com/buession/buessionframework diff --git a/buession-json/pom.xml b/buession-json/pom.xml index 23115cdc8..b33e2b6a1 100644 --- a/buession-json/pom.xml +++ b/buession-json/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-json https://github.com/buession/buessionframework diff --git a/buession-json/src/main/java/com/buession/json/deserializer/Map2EnumDeserializer.java b/buession-json/src/main/java/com/buession/json/deserializer/Map2EnumDeserializer.java index 65e80b4c9..d7294ce0f 100644 --- a/buession-json/src/main/java/com/buession/json/deserializer/Map2EnumDeserializer.java +++ b/buession-json/src/main/java/com/buession/json/deserializer/Map2EnumDeserializer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.json.deserializer; @@ -28,9 +28,14 @@ import com.buession.core.utils.EnumUtils; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,12 +49,21 @@ /** * @author Yong.Teng */ -public class Map2EnumDeserializer extends JsonDeserializer> { +@JacksonStdImpl +public class Map2EnumDeserializer extends StdScalarDeserializer> implements ContextualDeserializer { private final static Map> cache = new ConcurrentHashMap<>(32); private final static Logger logger = LoggerFactory.getLogger(Map2EnumDeserializer.class); + public Map2EnumDeserializer(){ + super(Enum.class); + } + + public Map2EnumDeserializer(Class> v){ + super(v); + } + @SuppressWarnings({"unchecked"}) @Override public Enum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException{ @@ -123,6 +137,13 @@ public Enum deserialize(JsonParser jsonParser, DeserializationContext deseria return null; } + @SuppressWarnings({"unchecked"}) + @Override + public JsonDeserializer createContextual(DeserializationContext context, BeanProperty property) + throws JsonMappingException{ + return new Map2EnumDeserializer((Class>) property.getType().getRawClass()); + } + private static String parseCacheKey(final Class clazz, final Field field, final JsonNode node){ final String className = clazz.getName(); final String fieldName = field.getName(); diff --git a/buession-json/src/main/java/com/buession/json/serializer/Enum2MapSerializer.java b/buession-json/src/main/java/com/buession/json/serializer/Enum2MapSerializer.java index edf859901..7cc88caa7 100644 --- a/buession-json/src/main/java/com/buession/json/serializer/Enum2MapSerializer.java +++ b/buession-json/src/main/java/com/buession/json/serializer/Enum2MapSerializer.java @@ -17,18 +17,24 @@ * . * * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.json.serializer; import com.buession.core.utils.FieldUtils; import com.buession.core.utils.EnumUtils; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; +import com.fasterxml.jackson.databind.ser.ContextualSerializer; +import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,12 +44,21 @@ /** * @author Yong.Teng */ -public class Enum2MapSerializer extends JsonSerializer> { +@JacksonStdImpl +public class Enum2MapSerializer extends StdScalarSerializer> implements ContextualSerializer { private final static Logger logger = LoggerFactory.getLogger(Enum2MapSerializer.class); + public Enum2MapSerializer(){ + super(Enum.class, false); + } + + public Enum2MapSerializer(Class> v){ + super(v, false); + } + @Override - public void serialize(Enum en, JsonGenerator generator, SerializerProvider provider) throws IOException{ + public void serialize(Enum en, JsonGenerator generator, SerializerProvider provider) throws IOException{ Field[] fields = en.getClass().getDeclaredFields(); generator.writeStartObject(); @@ -56,7 +71,21 @@ public void serialize(Enum en, JsonGenerator generator, SerializerProvider pr generator.writeEndObject(); } - private static void writeFieldValue(final JsonGenerator generator, final Enum en, final Field field) throws IOException{ + @SuppressWarnings({"unchecked"}) + @Override + public JsonSerializer createContextual(SerializerProvider provider, BeanProperty property) + throws JsonMappingException{ + JsonFormat.Value format = findFormatOverrides(provider, property, handledType()); + + if(format != null){ + return new Enum2MapSerializer((Class>) property.getType().getRawClass()); + } + + return this; + } + + private static void writeFieldValue(final JsonGenerator generator, final Enum en, final Field field) + throws IOException{ FieldUtils.setAccessible(field); try{ diff --git a/buession-json/src/main/java/com/buession/json/serializer/SensitiveSerializer.java b/buession-json/src/main/java/com/buession/json/serializer/SensitiveSerializer.java index c3a01a94c..920e7faf1 100644 --- a/buession-json/src/main/java/com/buession/json/serializer/SensitiveSerializer.java +++ b/buession-json/src/main/java/com/buession/json/serializer/SensitiveSerializer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.json.serializer; @@ -33,7 +33,9 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; import com.fasterxml.jackson.databind.ser.ContextualSerializer; +import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import java.io.IOException; import java.util.Objects; @@ -43,7 +45,8 @@ * @author Yong.Teng * @since 1.3.1 */ -public class SensitiveSerializer extends JsonSerializer implements ContextualSerializer { +@JacksonStdImpl +public class SensitiveSerializer extends StdScalarSerializer implements ContextualSerializer { private SensitiveStrategy strategy; @@ -51,6 +54,10 @@ public class SensitiveSerializer extends JsonSerializer implements private String replacement; + public SensitiveSerializer(){ + super(CharSequence.class); + } + @Override public void serialize(CharSequence value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException{ @@ -60,12 +67,14 @@ public void serialize(CharSequence value, JsonGenerator jsonGenerator, Serialize jsonGenerator.writeString(Constants.EMPTY_STRING); }else{ String str; + if(Validate.hasText(format)){ str = value.toString() .replaceAll(format, Optional.ofNullable(replacement).orElse(Sensitive.DEFAULT_REPLACEMENT)); }else{ str = strategy.getFunction().apply(value.toString()); } + jsonGenerator.writeString(str); } } diff --git a/buession-json/src/test/java/com/buession/json/EnumSerializer.java b/buession-json/src/test/java/com/buession/json/EnumSerializer.java index 2a9d5cf8c..9fd88d8ec 100644 --- a/buession-json/src/test/java/com/buession/json/EnumSerializer.java +++ b/buession-json/src/test/java/com/buession/json/EnumSerializer.java @@ -24,97 +24,129 @@ */ package com.buession.json; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.buession.json.annotation.JsonEnum2Map; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; +import java.util.StringJoiner; /** * @author Yong.Teng */ public class EnumSerializer { - @Test - public void test(){ - User user = new User(); + @Test + public void test(){ + User user = new User(); - user.setId(100); - user.setUsername("admin"); - user.setType(Type.ACTIVE); + user.setId(100); + user.setUsername("admin"); + user.setType(Type.ACTIVE); + user.setTypes(new Type[]{Type.ACTIVE, Type.REGISTER}); - ObjectMapper objectMapper = new ObjectMapper(); - ObjectMapper objectMapper1 = new ObjectMapper(); + ObjectMapper objectMapper = new ObjectMapper(); - try{ - String str = objectMapper.writeValueAsString(user); - System.out.println(str); - objectMapper1.readValue(str, User.class); - }catch(JsonProcessingException e){ - e.printStackTrace(); - }catch(IOException e){ - e.printStackTrace(); - } - } + try{ + String str = objectMapper.writeValueAsString(user); + System.out.println(str); - public final static class User { + User u2 = objectMapper.readValue(str, User.class); + System.out.println(u2); + }catch(IOException e){ + e.printStackTrace(); + } + } - private int id; + public final static class User { - private String username; + private int id; - private Type type; + private String username; - public int getId(){ - return id; - } + @JsonEnum2Map + private Type type; + + private Type[] types; - public void setId(final int id){ - this.id = id; - } + private int[] ivs; - public String getUsername(){ - return username; - } + public int getId(){ + return id; + } - public void setUsername(final String username){ - this.username = username; - } + public void setId(final int id){ + this.id = id; + } - public Type getType(){ - return type; - } + public String getUsername(){ + return username; + } - public void setType(final Type type){ - this.type = type; - } - } + public void setUsername(final String username){ + this.username = username; + } - public enum Type { + public Type getType(){ + return type; + } - REGISTER("register", "注册模板"), + public void setType(final Type type){ + this.type = type; + } - FIND_PASSWORD("find_password", "找回密码"), + public Type[] getTypes(){ + return types; + } - ACTIVE("active", "激活账号"); + public void setTypes(Type[] types){ + this.types = types; + } - private String value; + public int[] getIvs(){ + return ivs; + } - private String description; + public void setIvs(int[] ivs){ + this.ivs = ivs; + } - Type(String value, String description){ - this.value = value; - this.description = description; - } + @Override + public String toString(){ + return new StringJoiner(", ", User.class.getSimpleName() + "[", "]") + .add("id=" + id) + .add("username='" + username + "'") + .add("type=" + type) + .toString(); + } + } - public String getValue(){ - return value; - } + public enum Type { - public String getDescription(){ - return description; - } + REGISTER("register", "注册模板"), - } + FIND_PASSWORD("find_password", "找回密码"), + + ACTIVE("active", "激活账号"); + + private String value; + + private String description; + + Type(String value, String description){ + this.value = value; + this.description = description; + } + + public String getValue(){ + return value; + } + + public String getDescription(){ + return description; + } + + } } diff --git a/buession-lang/pom.xml b/buession-lang/pom.xml index b5b74d58c..4f6c91baf 100644 --- a/buession-lang/pom.xml +++ b/buession-lang/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-lang https://github.com/buession/buessionframework diff --git a/buession-net/pom.xml b/buession-net/pom.xml index fd1208d90..7d67ce3db 100644 --- a/buession-net/pom.xml +++ b/buession-net/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-net https://github.com/buession/buessionframework diff --git a/buession-parent/pom.xml b/buession-parent/pom.xml index 79000189f..6b4bda8d7 100644 --- a/buession-parent/pom.xml +++ b/buession-parent/pom.xml @@ -7,13 +7,13 @@ com.buession parent - 2.1.2 + 2.2.0 com.buession buession-parent https://github.com/buession/buessionframework Buession Framework Parent - 2.1.2 + 2.2.0 pom @@ -60,6 +60,7 @@ ../buession-cron ../buession-dao ../buession-geoip + ../buession-git ../buession-httpclient ../buession-io ../buession-jdbc diff --git a/buession-redis/pom.xml b/buession-redis/pom.xml index 06933dfd2..249bd4ff4 100644 --- a/buession-redis/pom.xml +++ b/buession-redis/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-redis https://github.com/buession/buessionframework diff --git a/buession-redis/src/main/java/com/buession/redis/client/jedis/operations/JedisRedisOperations.java b/buession-redis/src/main/java/com/buession/redis/client/jedis/operations/JedisRedisOperations.java index 39cdbe019..209c64189 100644 --- a/buession-redis/src/main/java/com/buession/redis/client/jedis/operations/JedisRedisOperations.java +++ b/buession-redis/src/main/java/com/buession/redis/client/jedis/operations/JedisRedisOperations.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.redis.client.jedis.operations; @@ -43,6 +43,8 @@ import com.buession.redis.exception.RedisException; import com.buession.redis.pipeline.jedis.JedisPipeline; import com.buession.redis.transaction.jedis.JedisTransaction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.Pipeline; @@ -64,6 +66,8 @@ abstract class AbstractJedisCommand extends Abstr protected Runner transactionRunner; + private final Logger logger = LoggerFactory.getLogger(getClass()); + protected AbstractJedisCommand(final C client, final ProtocolCommand command){ super(client, command); } @@ -76,20 +80,31 @@ public R execute() throws RedisException{ if(pipelineRunner == null){ throw throwNotSupportedCommandException(NotSupportedCommandException.Type.PIPELINE); }else{ - client.getTxResults().add(pipelineRunner.run()); + try{ + client.getTxResults().add(pipelineRunner.run()); + }catch(Exception e){ + logger.error(e.getMessage()); + } } }else if(connection.isTransaction()){ if(transactionRunner == null){ throw throwNotSupportedCommandException(NotSupportedCommandException.Type.TRANSACTION); }else{ - FutureResult, Object, Object> a = transactionRunner.run(); - client.getTxResults().add(a); + try{ + client.getTxResults().add(transactionRunner.run()); + }catch(Exception e){ + logger.error(e.getMessage()); + } } }else{ if(runner == null){ throw throwNotSupportedCommandException(NotSupportedCommandException.Type.NORMAL); }else{ - return runner.run(); + try{ + return runner.run(); + }catch(Exception e){ + logger.error(e.getMessage()); + } } } return null; @@ -99,7 +114,7 @@ protected Runner createPipelineRunner(final Executor> exec return new Runner() { @Override - public JedisResult run() throws RedisException{ + public JedisResult run() throws Exception{ final redis.clients.jedis.Pipeline jedisPipeline = ((JedisPipeline) pipeline()).primitive(); return newJedisResult(executor.execute(jedisPipeline)); } @@ -112,7 +127,7 @@ protected Runner createPipelineRunner(final Executor return new Runner() { @Override - public JedisResult run() throws RedisException{ + public JedisResult run() throws Exception{ final redis.clients.jedis.Pipeline jedisPipeline = ((JedisPipeline) pipeline()).primitive(); return newJedisResult(executor.execute(jedisPipeline), converter); } @@ -124,7 +139,7 @@ protected Runner createTransactionRunner(final Executor return new Runner() { @Override - public JedisResult run() throws RedisException{ + public JedisResult run() throws Exception{ final redis.clients.jedis.Transaction transaction = ((JedisTransaction) transaction()).primitive(); return newJedisResult(executor.execute(transaction)); } @@ -137,7 +152,7 @@ protected Runner createTransactionRunner(final Executor run() throws RedisException{ + public JedisResult run() throws Exception{ final redis.clients.jedis.Transaction transaction = ((JedisTransaction) transaction()).primitive(); return newJedisResult(executor.execute(transaction), converter); } @@ -169,7 +184,7 @@ public JedisCommand general(final Executor executor){ this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return executor.execute(connection.getJedis()); } @@ -182,7 +197,7 @@ public JedisCommand general(final Executor executor, final Co this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return converter.convert(executor.execute(connection.getJedis())); } @@ -228,7 +243,7 @@ public JedisSentinelCommand general(Executor executor){ this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return executor.execute(connection.getJedis()); } @@ -242,7 +257,7 @@ public JedisSentinelCommand general(final Executor executor, this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return converter.convert(executor.execute(connection.getJedis())); } @@ -288,7 +303,7 @@ public JedisClusterCommand general(Executor executor){ this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return executor.execute(connection.getCluster()); } @@ -302,7 +317,7 @@ public JedisClusterCommand general(final Executor exec this.runner = new Runner() { @Override - public R run() throws RedisException{ + public R run() throws Exception{ return converter.convert(executor.execute(connection.getCluster())); } diff --git a/buession-redis/src/main/java/com/buession/redis/core/Command.java b/buession-redis/src/main/java/com/buession/redis/core/Command.java index 68464360a..54c5c641c 100644 --- a/buession-redis/src/main/java/com/buession/redis/core/Command.java +++ b/buession-redis/src/main/java/com/buession/redis/core/Command.java @@ -99,7 +99,7 @@ interface Runner { * @throws RedisException * Redis 命令运行异常 */ - R run() throws RedisException; + R run() throws Exception; } diff --git a/buession-session/pom.xml b/buession-session/pom.xml index 8b071e71f..eea9df534 100644 --- a/buession-session/pom.xml +++ b/buession-session/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-session https://github.com/buession/buessionframework diff --git a/buession-thesaurus/pom.xml b/buession-thesaurus/pom.xml index fa1e5836b..fab967a25 100644 --- a/buession-thesaurus/pom.xml +++ b/buession-thesaurus/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-thesaurus https://github.com/buession/buessionframework diff --git a/buession-velocity/pom.xml b/buession-velocity/pom.xml index 7c11fa629..15b90d6d2 100644 --- a/buession-velocity/pom.xml +++ b/buession-velocity/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-velocity https://github.com/buession/buessionframework diff --git a/buession-velocity/src/main/java/com/buession/velocity/SpringResourceLoader.java b/buession-velocity/src/main/java/com/buession/velocity/SpringResourceLoader.java index 50f0bea48..7c622a01a 100644 --- a/buession-velocity/src/main/java/com/buession/velocity/SpringResourceLoader.java +++ b/buession-velocity/src/main/java/com/buession/velocity/SpringResourceLoader.java @@ -88,7 +88,7 @@ public void init(final ExtProperties configuration){ } if(logger.isInfoEnabled()){ - logger.info(LOADER_NAME + " for Velocity: using resource loader [{}] and resource " + "loader paths {}", + logger.info(LOADER_NAME + " for Velocity: using resource loader [{}] and resource loader paths {}", resourceLoader, Arrays.asList(resourceLoaderPaths)); } } diff --git a/buession-velocity/src/main/java/com/buession/velocity/servlet/VelocityLayoutView.java b/buession-velocity/src/main/java/com/buession/velocity/servlet/VelocityLayoutView.java index badb29c83..cb7e44773 100644 --- a/buession-velocity/src/main/java/com/buession/velocity/servlet/VelocityLayoutView.java +++ b/buession-velocity/src/main/java/com/buession/velocity/servlet/VelocityLayoutView.java @@ -99,8 +99,8 @@ public boolean checkResource(Locale locale) throws Exception{ getTemplate(layoutUrl); return true; }catch(ResourceNotFoundException e){ - throw new NestedIOException("Cannot find Velocity template for URL [" + layoutUrl + "]: Did you specify " + - "the correct resource loader path?", e); + throw new NestedIOException("Cannot find Velocity template for URL [" + layoutUrl + "]: " + + "Did you specify the correct resource loader path?", e); }catch(Exception e){ throw new NestedIOException("Cannot load Velocity template for URL [" + layoutUrl + "]", e); } diff --git a/buession-velocity/src/main/java/com/buession/velocity/spring/VelocityEngineFactory.java b/buession-velocity/src/main/java/com/buession/velocity/spring/VelocityEngineFactory.java index 1fe7c974c..f079d3b66 100644 --- a/buession-velocity/src/main/java/com/buession/velocity/spring/VelocityEngineFactory.java +++ b/buession-velocity/src/main/java/com/buession/velocity/spring/VelocityEngineFactory.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.velocity.spring; @@ -145,9 +145,7 @@ public VelocityEngine createVelocityEngine() throws IOException, VelocityExcepti initVelocityResourceLoader(velocityEngine, resourceLoaderPath); } - properties.forEach((name, value)->{ - velocityEngine.setProperty(name, value); - }); + properties.forEach(velocityEngine::setProperty); postProcessVelocityEngine(velocityEngine); @@ -183,8 +181,7 @@ protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String } } - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); - velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, isEnableCache()); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file"); velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString()); }catch(IOException ex){ if(logger.isDebugEnabled()){ @@ -194,13 +191,14 @@ protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String initSpringResourceLoader(velocityEngine, resourceLoaderPath); } + + velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, isEnableCache()); } protected void initSpringResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath){ velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADERS, SpringResourceLoader.NAME); velocityEngine.setProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, SpringResourceLoader.class.getName()); - velocityEngine.setProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CACHE, isEnableCache()); velocityEngine.setApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER, getResourceLoader()); velocityEngine.setApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPath); } diff --git a/buession-web/pom.xml b/buession-web/pom.xml index 4e39c2c10..5793d810e 100644 --- a/buession-web/pom.xml +++ b/buession-web/pom.xml @@ -7,7 +7,7 @@ com.buession buession-parent ../buession-parent - 2.1.2 + 2.2.0 buession-web https://github.com/buession/buessionframework diff --git a/buession-web/src/main/java/com/buession/web/aop/aopalliance/AbstractWebAttributeSourcePointcutAdvisor.java b/buession-web/src/main/java/com/buession/web/aop/aopalliance/AbstractWebAttributeSourcePointcutAdvisor.java index 9c82eadd9..89ea6ef2b 100644 --- a/buession-web/src/main/java/com/buession/web/aop/aopalliance/AbstractWebAttributeSourcePointcutAdvisor.java +++ b/buession-web/src/main/java/com/buession/web/aop/aopalliance/AbstractWebAttributeSourcePointcutAdvisor.java @@ -45,11 +45,9 @@ public abstract class AbstractWebAttributeSourcePointcutAdvisor extends Abstract private final static long serialVersionUID = -25452444487918871L; @SuppressWarnings({"unchecked"}) - private final static Class[] WEB_ANNOTATION_CLASSES = new Class[]{ResponseHeader.class, - ResponseHeaders.class, ContentType.class, HttpCache.class, DocumentMetaData.class}; - public AbstractWebAttributeSourcePointcutAdvisor(final AnnotationsMethodInterceptor annotationsMethodInterceptor){ - super(annotationsMethodInterceptor, WEB_ANNOTATION_CLASSES); + super(annotationsMethodInterceptor, new Class[]{ResponseHeader.class, + ResponseHeaders.class, ContentType.class, HttpCache.class, DocumentMetaData.class}); } } diff --git a/buession-web/src/main/java/com/buession/web/aop/aspect/AbstractWebAnnotationAspect.java b/buession-web/src/main/java/com/buession/web/aop/aspect/AbstractWebAnnotationAspect.java index 34196afa2..f04c7e3d6 100644 --- a/buession-web/src/main/java/com/buession/web/aop/aspect/AbstractWebAnnotationAspect.java +++ b/buession-web/src/main/java/com/buession/web/aop/aspect/AbstractWebAnnotationAspect.java @@ -44,9 +44,7 @@ public abstract class AbstractWebAnnotationAspect | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -38,6 +38,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated public abstract class AbstractIgnoreCaseEnumConverter> implements Converter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/CaseTypeConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/CaseTypeConverter.java index 03499ed42..845113c11 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/CaseTypeConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/CaseTypeConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated final public class CaseTypeConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDConverter.java index bdb7268ea..58da94b36 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated public class DomainTLDConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDTypeConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDTypeConverter.java index 10af2f517..d012dc341 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDTypeConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/DomainTLDTypeConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated public class DomainTLDTypeConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/FormatterRegistryUtils.java b/buession-web/src/main/java/com/buession/web/bind/converter/FormatterRegistryUtils.java index 82d0cbb9f..6e0c1a568 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/FormatterRegistryUtils.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/FormatterRegistryUtils.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -33,14 +33,7 @@ public class FormatterRegistryUtils { public static void addConverters(final FormatterRegistry registry){ - registry.addConverter(new CaseTypeConverter()); - registry.addConverter(new DomainTLDConverter()); - registry.addConverter(new DomainTLDTypeConverter()); - registry.addConverter(new GenderConverter()); - registry.addConverter(new IpTypeConverter()); - registry.addConverter(new ISBNTypeConverter()); - registry.addConverter(new OrderConverter()); - registry.addConverter(new StatusConverter()); + registry.addConverterFactory(new IgnoreCaseEnumConverterFactory()); } } diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/GenderConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/GenderConverter.java index 3eba3893b..694d1ec24 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/GenderConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/GenderConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated final public class GenderConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/ISBNTypeConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/ISBNTypeConverter.java index 61638c3ba..fef64d034 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/ISBNTypeConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/ISBNTypeConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated public class ISBNTypeConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/IgnoreCaseEnumConverterFactory.java b/buession-web/src/main/java/com/buession/web/bind/converter/IgnoreCaseEnumConverterFactory.java new file mode 100644 index 000000000..6b714f519 --- /dev/null +++ b/buession-web/src/main/java/com/buession/web/bind/converter/IgnoreCaseEnumConverterFactory.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.web.bind.converter; + +import com.buession.core.utils.Assert; +import com.buession.core.utils.EnumUtils; +import com.buession.core.validator.Validate; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.lang.Nullable; + +/** + * 忽略大小写将字符串转换为枚举值 + * + * @author Yong.Teng + * @since 2.2.0 + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +public class IgnoreCaseEnumConverterFactory implements ConverterFactory { + + @Override + public Converter getConverter(Class targetType){ + return new StringToEnum(getEnumType(targetType)); + } + + private static Class getEnumType(Class targetType){ + Class enumType = targetType; + + while(enumType != null && !enumType.isEnum()){ + enumType = enumType.getSuperclass(); + } + + Assert.isNull(enumType, "The target type " + targetType.getName() + " does not refer to an enum"); + + return enumType; + } + + + private static class StringToEnum implements Converter { + + private final Class enumType; + + public StringToEnum(Class enumType){ + this.enumType = enumType; + } + + @Override + @Nullable + public T convert(String source){ + if(Validate.isEmpty(source)){ + return null; + } + + return (T) EnumUtils.getEnumIgnoreCase(enumType, source.trim()); + } + } + +} diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/IpTypeConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/IpTypeConverter.java index f989052a7..81815a4dc 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/IpTypeConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/IpTypeConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated public class IpTypeConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/OrderConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/OrderConverter.java index 47bac8c8e..df988aa90 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/OrderConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/OrderConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated final public class OrderConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/StatusConverter.java b/buession-web/src/main/java/com/buession/web/bind/converter/StatusConverter.java index 172786274..9e860ea85 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/StatusConverter.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/StatusConverter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.bind.converter; @@ -32,6 +32,7 @@ * @author Yong.Teng * @since 1.2.2 */ +@Deprecated final public class StatusConverter extends AbstractIgnoreCaseEnumConverter { /** diff --git a/buession-web/src/main/java/com/buession/web/bind/converter/package-info.java b/buession-web/src/main/java/com/buession/web/bind/converter/package-info.java index 747a7481e..bba00ad51 100644 --- a/buession-web/src/main/java/com/buession/web/bind/converter/package-info.java +++ b/buession-web/src/main/java/com/buession/web/bind/converter/package-info.java @@ -22,4 +22,7 @@ * | Copyright @ 2013-2021 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ -package com.buession.web.bind.converter; \ No newline at end of file +@NonNullApi +package com.buession.web.bind.converter; + +import org.springframework.lang.NonNullApi; \ No newline at end of file diff --git a/buession-web/src/main/java/com/buession/web/http/request/RequestUtils.java b/buession-web/src/main/java/com/buession/web/http/request/RequestUtils.java index c08632654..3f7de3948 100644 --- a/buession-web/src/main/java/com/buession/web/http/request/RequestUtils.java +++ b/buession-web/src/main/java/com/buession/web/http/request/RequestUtils.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2021 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.web.http.request; @@ -44,7 +44,8 @@ public abstract class RequestUtils { /* 阿里云 */ "Ali-Cdn-Real-Ip", /* 网宿 */ - "Cdn-Src-Ip", "X-Cdn-Src-Ip", + "Cdn-Src-Ip", + "X-Cdn-Src-Ip", /* 天翼云 */ "X-Original-Forwarded-For", /* */ @@ -56,7 +57,9 @@ public abstract class RequestUtils { /* */ "WL-Proxy-Client-IP", /* */ - "Real-ClientIP" + "Real-ClientIP", + /* */ + "Client-IP" }; public final static String[] MOBILE_MAPS = new String[]{ @@ -67,9 +70,31 @@ public abstract class RequestUtils { /* IPod */ "ipod", /* Windows Phone */ - "windows phone", "windowsce", "mobile", "coolpad", "mmp", "smartphone", "midp", "wap", "xoom", + "windows phone", + /* */ + "windowsce", + /* */ + "mobile", + /* */ + "coolpad", + /* */ + "mmp", + /* */ + "smartphone", + /* */ + "midp", + /* */ + "wap", + /* */ + "xoom", /* Symbian */ - "symbian", "j2me", "ucweb", "operamini", "operamobi", + "symbian", + /* */ + "j2me", + /* */ + "ucweb", + /* Opera */ + "operamini", "operamobi", /* 微信 */ "MicroMessenger", /* QQ 浏览器 */ @@ -285,7 +310,7 @@ protected static boolean isMobile(final String userAgent, final String accept){ } } - if(accept == null){ + if(Validate.isBlank(accept)){ return false; } diff --git a/buession-web/src/main/java/com/buession/web/reactive/annotation/RequestClientIpHandlerMethodArgumentResolver.java b/buession-web/src/main/java/com/buession/web/reactive/annotation/RequestClientIpHandlerMethodArgumentResolver.java index ead579806..8b23ca73f 100644 --- a/buession-web/src/main/java/com/buession/web/reactive/annotation/RequestClientIpHandlerMethodArgumentResolver.java +++ b/buession-web/src/main/java/com/buession/web/reactive/annotation/RequestClientIpHandlerMethodArgumentResolver.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.web.reactive.annotation; @@ -100,10 +100,10 @@ protected Object resolveNamedValue(String name, MethodParameter parameter, Serve private String getClientIp(final ServerHttpRequest request, final MethodParameter parameter){ RequestClientIp requestClientIp = parameter.getParameterAnnotation(RequestClientIp.class); - String clientIp = null; if(Validate.isNotEmpty(requestClientIp.headerName())){ HttpHeaders httpHeaders = request.getHeaders(); + String clientIp; for(String headerName : requestClientIp.headerName()){ if(Validate.hasText(headerName) && ValueConstants.DEFAULT_NONE.equals(headerName) != false){ diff --git a/buession-web/src/main/java/com/buession/web/servlet/annotation/RequestClientIpHandlerMethodArgumentResolver.java b/buession-web/src/main/java/com/buession/web/servlet/annotation/RequestClientIpHandlerMethodArgumentResolver.java index 6ee594f96..e23f9827b 100644 --- a/buession-web/src/main/java/com/buession/web/servlet/annotation/RequestClientIpHandlerMethodArgumentResolver.java +++ b/buession-web/src/main/java/com/buession/web/servlet/annotation/RequestClientIpHandlerMethodArgumentResolver.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.web.servlet.annotation; @@ -103,9 +103,10 @@ protected Object resolveName(String name, MethodParameter parameter, NativeWebRe private String getClientIp(final NativeWebRequest webRequest, final MethodParameter parameter){ RequestClientIp requestClientIp = parameter.getParameterAnnotation(RequestClientIp.class); HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - String clientIp = null; if(Validate.isNotEmpty(requestClientIp.headerName())){ + String clientIp; + for(String headerName : requestClientIp.headerName()){ if(Validate.hasText(headerName) && ValueConstants.DEFAULT_NONE.equals(headerName) != false){ clientIp = request.getHeader(headerName);