style(framework): 优化框架代码格式和依赖配置

- 更新pom.xml中的阿里云仓库地址为HTTPS协议
- 重构注解类的import语句,移除通配符导入并规范排列
- 简化匿名访问注解的代码结构,移除多余空行
- 调整基础实体类的字段注解格式,合并为单行声明
- 优化常量类和枚举类的代码格式,移除多余空行
- 重构启动类的日志输出格式,改进字符串拼接方式
- 规范工具类的import顺序和代码结构
- 优化Swagger配置类的代码格式和注解排列
This commit is contained in:
2025-12-23 19:35:34 +08:00
parent 09393e4636
commit 1d911e679e
318 changed files with 3008 additions and 4352 deletions
+19 -4
View File
@@ -11,6 +11,7 @@
[https://github.com/odboy-tianjun/cutejava](https://github.com/odboy-tianjun/cutejava) [https://github.com/odboy-tianjun/cutejava](https://github.com/odboy-tianjun/cutejava)
#### 项目文档 #### 项目文档
[https://cutejava-doc.odboy.cn/](https://cutejava-doc.odboy.cn/) [https://cutejava-doc.odboy.cn/](https://cutejava-doc.odboy.cn/)
#### 编码规范 #### 编码规范
@@ -22,12 +23,26 @@
- 消息队列/Socket传输类名,以`Message`结尾 - 消息队列/Socket传输类名,以`Message`结尾
- ~~常用的辅助类的类名, 以`Cs`开头~~ - ~~常用的辅助类的类名, 以`Cs`开头~~
- 常用的辅助类的类名, 以`Kit`开头。Kit有套件、装备等意思。 - 常用的辅助类的类名, 以`Kit`开头。Kit有套件、装备等意思。
- 查询分页、查询列表的方法,一律为同一个方法名
- 查询分页:queryUser(args, page)
- 查询列表:queryUser(args)
- MapperXml:这样mapper.xml文件中的实现方法只需要写一个queryUser
- 枚举类名,以`Enum`结尾 - 枚举类名,以`Enum`结尾
- 拒绝过度包装 - 拒绝过度包装
- 命名规则(Mapper or Service)
- 简单查询:get + 名词
- 列表查询:list + 名词
- 复杂查询:query + 名词 + By + 条件
- 搜索(分页)功能:search + 名词
- 统计计数:count + By + 条件
- 存在检查:exists + By + 条件
- 例子: 查询分页、查询列表的方法
- 分页:searchUser(args, page)
- 列表:listUser + (args)
- 单个:getUser + by + (args)
- Mapper
- 分页与列表共用
- selectUserByArgs(args, page)
- selectUserByArgs(args)
- MapperXml selectUserByArgs
- 单个:getUser + by + (args)
- 统计计数:count + By + (args)
#### 主要特性 #### 主要特性
@@ -15,7 +15,12 @@
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.*; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* 用于标记匿名访问方法 * 用于标记匿名访问方法
@@ -24,6 +29,4 @@ import java.lang.annotation.*;
@Documented @Documented
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface AnonymousAccess { public @interface AnonymousAccess {}
}
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;
/** /**
* Annotation for mapping HTTP {@code DELETE} requests onto specific handler methods. 支持匿名访问 DeleteMapping * Annotation for mapping HTTP {@code DELETE} requests onto specific handler methods. 支持匿名访问 DeleteMapping
* *
@@ -37,37 +39,30 @@ import java.lang.annotation.*;
@Documented @Documented
@RequestMapping(method = RequestMethod.DELETE) @RequestMapping(method = RequestMethod.DELETE)
public @interface AnonymousDeleteMapping { public @interface AnonymousDeleteMapping {
/** /**
* Alias for {@link RequestMapping#name}. * Alias for {@link RequestMapping#name}.
*/ */
@AliasFor(annotation = RequestMapping.class) String name() default ""; @AliasFor(annotation = RequestMapping.class) String name() default "";
/** /**
* Alias for {@link RequestMapping#value}. * Alias for {@link RequestMapping#value}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] value() default {}; @AliasFor(annotation = RequestMapping.class) String[] value() default {};
/** /**
* Alias for {@link RequestMapping#path}. * Alias for {@link RequestMapping#path}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] path() default {}; @AliasFor(annotation = RequestMapping.class) String[] path() default {};
/** /**
* Alias for {@link RequestMapping#params}. * Alias for {@link RequestMapping#params}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] params() default {}; @AliasFor(annotation = RequestMapping.class) String[] params() default {};
/** /**
* Alias for {@link RequestMapping#headers}. * Alias for {@link RequestMapping#headers}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] headers() default {}; @AliasFor(annotation = RequestMapping.class) String[] headers() default {};
/** /**
* Alias for {@link RequestMapping#consumes}. * Alias for {@link RequestMapping#consumes}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] consumes() default {}; @AliasFor(annotation = RequestMapping.class) String[] consumes() default {};
/** /**
* Alias for {@link RequestMapping#produces}. * Alias for {@link RequestMapping#produces}.
*/ */
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;
/** /**
* Annotation for mapping HTTP {@code GET} requests onto specific handler methods. * Annotation for mapping HTTP {@code GET} requests onto specific handler methods.
* <p> * <p>
@@ -35,39 +37,32 @@ import java.lang.annotation.*;
@Documented @Documented
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public @interface AnonymousGetMapping { public @interface AnonymousGetMapping {
/** /**
* Alias for {@link RequestMapping#name}. * Alias for {@link RequestMapping#name}.
*/ */
@AliasFor(annotation = RequestMapping.class) String name() default ""; @AliasFor(annotation = RequestMapping.class) String name() default "";
/** /**
* Alias for {@link RequestMapping#value}. * Alias for {@link RequestMapping#value}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] value() default {}; @AliasFor(annotation = RequestMapping.class) String[] value() default {};
/** /**
* Alias for {@link RequestMapping#path}. * Alias for {@link RequestMapping#path}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] path() default {}; @AliasFor(annotation = RequestMapping.class) String[] path() default {};
/** /**
* Alias for {@link RequestMapping#params}. * Alias for {@link RequestMapping#params}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] params() default {}; @AliasFor(annotation = RequestMapping.class) String[] params() default {};
/** /**
* Alias for {@link RequestMapping#headers}. * Alias for {@link RequestMapping#headers}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] headers() default {}; @AliasFor(annotation = RequestMapping.class) String[] headers() default {};
/** /**
* Alias for {@link RequestMapping#consumes}. * Alias for {@link RequestMapping#consumes}.
* *
* @since 4.3.5 * @since 4.3.5
*/ */
@AliasFor(annotation = RequestMapping.class) String[] consumes() default {}; @AliasFor(annotation = RequestMapping.class) String[] consumes() default {};
/** /**
* Alias for {@link RequestMapping#produces}. * Alias for {@link RequestMapping#produces}.
*/ */
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;
/** /**
* Annotation for mapping HTTP {@code PATCH} requests onto specific handler methods. 支持匿名访问 PatchMapping * Annotation for mapping HTTP {@code PATCH} requests onto specific handler methods. 支持匿名访问 PatchMapping
* *
@@ -37,37 +39,30 @@ import java.lang.annotation.*;
@Documented @Documented
@RequestMapping(method = RequestMethod.PATCH) @RequestMapping(method = RequestMethod.PATCH)
public @interface AnonymousPatchMapping { public @interface AnonymousPatchMapping {
/** /**
* Alias for {@link RequestMapping#name}. * Alias for {@link RequestMapping#name}.
*/ */
@AliasFor(annotation = RequestMapping.class) String name() default ""; @AliasFor(annotation = RequestMapping.class) String name() default "";
/** /**
* Alias for {@link RequestMapping#value}. * Alias for {@link RequestMapping#value}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] value() default {}; @AliasFor(annotation = RequestMapping.class) String[] value() default {};
/** /**
* Alias for {@link RequestMapping#path}. * Alias for {@link RequestMapping#path}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] path() default {}; @AliasFor(annotation = RequestMapping.class) String[] path() default {};
/** /**
* Alias for {@link RequestMapping#params}. * Alias for {@link RequestMapping#params}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] params() default {}; @AliasFor(annotation = RequestMapping.class) String[] params() default {};
/** /**
* Alias for {@link RequestMapping#headers}. * Alias for {@link RequestMapping#headers}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] headers() default {}; @AliasFor(annotation = RequestMapping.class) String[] headers() default {};
/** /**
* Alias for {@link RequestMapping#consumes}. * Alias for {@link RequestMapping#consumes}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] consumes() default {}; @AliasFor(annotation = RequestMapping.class) String[] consumes() default {};
/** /**
* Alias for {@link RequestMapping#produces}. * Alias for {@link RequestMapping#produces}.
*/ */
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;
/** /**
* Annotation for mapping HTTP {@code POST} requests onto specific handler methods. 支持匿名访问 PostMapping * Annotation for mapping HTTP {@code POST} requests onto specific handler methods. 支持匿名访问 PostMapping
* *
@@ -37,37 +39,30 @@ import java.lang.annotation.*;
@Documented @Documented
@RequestMapping(method = RequestMethod.POST) @RequestMapping(method = RequestMethod.POST)
public @interface AnonymousPostMapping { public @interface AnonymousPostMapping {
/** /**
* Alias for {@link RequestMapping#name}. * Alias for {@link RequestMapping#name}.
*/ */
@AliasFor(annotation = RequestMapping.class) String name() default ""; @AliasFor(annotation = RequestMapping.class) String name() default "";
/** /**
* Alias for {@link RequestMapping#value}. * Alias for {@link RequestMapping#value}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] value() default {}; @AliasFor(annotation = RequestMapping.class) String[] value() default {};
/** /**
* Alias for {@link RequestMapping#path}. * Alias for {@link RequestMapping#path}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] path() default {}; @AliasFor(annotation = RequestMapping.class) String[] path() default {};
/** /**
* Alias for {@link RequestMapping#params}. * Alias for {@link RequestMapping#params}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] params() default {}; @AliasFor(annotation = RequestMapping.class) String[] params() default {};
/** /**
* Alias for {@link RequestMapping#headers}. * Alias for {@link RequestMapping#headers}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] headers() default {}; @AliasFor(annotation = RequestMapping.class) String[] headers() default {};
/** /**
* Alias for {@link RequestMapping#consumes}. * Alias for {@link RequestMapping#consumes}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] consumes() default {}; @AliasFor(annotation = RequestMapping.class) String[] consumes() default {};
/** /**
* Alias for {@link RequestMapping#produces}. * Alias for {@link RequestMapping#produces}.
*/ */
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.annotation; package cn.odboy.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;
/** /**
* Annotation for mapping HTTP {@code PUT} requests onto specific handler methods. 支持匿名访问 PutMapping * Annotation for mapping HTTP {@code PUT} requests onto specific handler methods. 支持匿名访问 PutMapping
* *
@@ -37,37 +39,30 @@ import java.lang.annotation.*;
@Documented @Documented
@RequestMapping(method = RequestMethod.PUT) @RequestMapping(method = RequestMethod.PUT)
public @interface AnonymousPutMapping { public @interface AnonymousPutMapping {
/** /**
* Alias for {@link RequestMapping#name}. * Alias for {@link RequestMapping#name}.
*/ */
@AliasFor(annotation = RequestMapping.class) String name() default ""; @AliasFor(annotation = RequestMapping.class) String name() default "";
/** /**
* Alias for {@link RequestMapping#value}. * Alias for {@link RequestMapping#value}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] value() default {}; @AliasFor(annotation = RequestMapping.class) String[] value() default {};
/** /**
* Alias for {@link RequestMapping#path}. * Alias for {@link RequestMapping#path}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] path() default {}; @AliasFor(annotation = RequestMapping.class) String[] path() default {};
/** /**
* Alias for {@link RequestMapping#params}. * Alias for {@link RequestMapping#params}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] params() default {}; @AliasFor(annotation = RequestMapping.class) String[] params() default {};
/** /**
* Alias for {@link RequestMapping#headers}. * Alias for {@link RequestMapping#headers}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] headers() default {}; @AliasFor(annotation = RequestMapping.class) String[] headers() default {};
/** /**
* Alias for {@link RequestMapping#consumes}. * Alias for {@link RequestMapping#consumes}.
*/ */
@AliasFor(annotation = RequestMapping.class) String[] consumes() default {}; @AliasFor(annotation = RequestMapping.class) String[] consumes() default {};
/** /**
* Alias for {@link RequestMapping#produces}. * Alias for {@link RequestMapping#produces}.
*/ */
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import javax.validation.constraints.NotNull;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import javax.validation.constraints.NotNull;
/** /**
* 通用参数 * 通用参数
* *
@@ -31,14 +29,12 @@ public class KitArgs {
@Getter @Getter
@Setter @Setter
public static class FindByLongId extends KitObject { public static class FindByLongId extends KitObject {
@NotNull(message = "id必填") @NotNull(message = "id必填") private Long id;
private Long id;
} }
@Getter @Getter
@Setter @Setter
public static class DeleteById extends KitObject { public static class DeleteById extends KitObject {
@NotNull(message = "id必填") @NotNull(message = "id必填") private Long id;
private Long id;
} }
} }
@@ -13,23 +13,20 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class KitBaseCreateTimeTb extends KitObject { public class KitBaseCreateTimeTb extends KitObject {
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
@ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
private Date createTime; private Date createTime;
} }
@@ -13,27 +13,22 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class KitBaseTimeTb extends KitObject { public class KitBaseTimeTb extends KitObject {
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
@ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
private Date createTime; private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) @ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) private Date updateTime;
private Date updateTime;
} }
@@ -13,23 +13,20 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class KitBaseUpdateTimeTb extends KitObject { public class KitBaseUpdateTimeTb extends KitObject {
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) @ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) private Date updateTime;
private Date updateTime;
} }
@@ -13,33 +13,26 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
import java.util.Date;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedBy;
import java.lang.reflect.Field;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class KitBaseUserCreateTimeTb extends KitObject { public class KitBaseUserCreateTimeTb extends KitObject {
@CreatedBy @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建人", hidden = true) private String
@CreatedBy createBy;
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
@ApiModelProperty(value = "创建人", hidden = true)
private String createBy;
@TableField(fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
private Date createTime; private Date createTime;
@Override @Override
@@ -58,10 +51,8 @@ public class KitBaseUserCreateTimeTb extends KitObject {
} }
/* 分组校验 */ /* 分组校验 */
public @interface Create { public @interface Create {}
}
/* 分组校验 */ /* 分组校验 */
public @interface Update { public @interface Update {}
}
} }
@@ -13,20 +13,18 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableLogic;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedBy;
import java.util.Date;
/** /**
* 逻辑删除通用模型 * 逻辑删除通用模型
* *
@@ -36,22 +34,14 @@ import java.util.Date;
@Getter @Getter
@Setter @Setter
public class KitBaseUserTimeLogicTb extends KitObject { public class KitBaseUserTimeLogicTb extends KitObject {
@CreatedBy @CreatedBy @TableField(value = "create_by", fill = FieldFill.INSERT)
@TableField(value = "create_by", fill = FieldFill.INSERT) @ApiModelProperty(value = "创建人", hidden = true) private String createBy;
@ApiModelProperty(value = "创建人", hidden = true) @LastModifiedBy @TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private String createBy; @ApiModelProperty(value = "更新人", hidden = true) private String updateBy;
@LastModifiedBy @TableField(value = "create_time", fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间", hidden = true)
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新人", hidden = true)
private String updateBy;
@TableField(value = "create_time", fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建时间", hidden = true)
private Date createTime; private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间", hidden = true) @ApiModelProperty(value = "更新时间", hidden = true) private Date updateTime;
private Date updateTime; @ApiModelProperty(value = "数据有效性", hidden = true) @TableLogic @TableField("available") private Integer
@ApiModelProperty(value = "数据有效性", hidden = true) available;
@TableLogic
@TableField("available")
private Integer available;
} }
@@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
import java.util.Date;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -26,31 +27,18 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedBy;
import java.lang.reflect.Field;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class KitBaseUserTimeTb extends KitObject { public class KitBaseUserTimeTb extends KitObject {
@CreatedBy @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建人", hidden = true) private String
@CreatedBy createBy;
@TableField(fill = FieldFill.INSERT) @LastModifiedBy @TableField(fill = FieldFill.INSERT_UPDATE) @ApiModelProperty(value = "更新人", hidden = true)
@ApiModelProperty(value = "创建人", hidden = true)
private String createBy;
@LastModifiedBy
@TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新人", hidden = true)
private String updateBy; private String updateBy;
@TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
@TableField(fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
private Date createTime; private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) @ApiModelProperty(value = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true) private Date updateTime;
private Date updateTime;
@Override @Override
public String toString() { public String toString() {
@@ -68,10 +56,8 @@ public class KitBaseUserTimeTb extends KitObject {
} }
/* 分组校验 */ /* 分组校验 */
public @interface Create { public @interface Create {}
}
/* 分组校验 */ /* 分组校验 */
public @interface Update { public @interface Update {}
}
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import java.io.Serializable; import java.io.Serializable;
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/** /**
* 数据分页参数 * 数据分页参数
* *
@@ -35,13 +33,9 @@ import java.io.Serializable;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class KitPageArgs<T> implements Serializable { public class KitPageArgs<T> implements Serializable {
@NotNull(message = "参数page不能为空") @NotNull(message = "参数page不能为空") @Min(value = 1, message = "参数page最小值为1")
@Min(value = 1, message = "参数page最小值为1") @ApiModelProperty(value = "页码", example = "1") private Integer page;
@ApiModelProperty(value = "页码", example = "1") @NotNull(message = "参数size不能为空") @Min(value = 1, message = "参数size最小值为1")
private Integer page; @ApiModelProperty(value = "每页数据量", example = "10") private Integer size;
@NotNull(message = "参数size不能为空")
@Min(value = 1, message = "参数size最小值为1")
@ApiModelProperty(value = "每页数据量", example = "10")
private Integer size;
private T args; private T args;
} }
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/** /**
* 结果封装类 * 结果封装类
*/ */
@@ -13,12 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.base; package cn.odboy.base;
import lombok.*;
import java.util.Map; import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/** /**
* 元数据选项 * 元数据选项
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.constant; package cn.odboy.constant;
/** /**
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.constant; package cn.odboy.constant;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -24,7 +23,6 @@ import lombok.Getter;
public enum FileTypeEnum { public enum FileTypeEnum {
/* 文件类型 */ /* 文件类型 */
IMAGE("image", "图片"), DOC("doc", "文档"), VOICE("voice", "音频"), VIDEO("video", "视频"), OTHER("other", "其他"); IMAGE("image", "图片"), DOC("doc", "文档"), VOICE("voice", "音频"), VIDEO("video", "视频"), OTHER("other", "其他");
private final String code; private final String code;
private final String description; private final String description;
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.constant; package cn.odboy.constant;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -22,37 +21,30 @@ import lombok.Getter;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum RequestMethodEnum { public enum RequestMethodEnum {
/** /**
* 搜寻 @AnonymousGetMapping * 搜寻 @AnonymousGetMapping
*/ */
GET("GET"), GET("GET"),
/** /**
* 搜寻 @AnonymousPostMapping * 搜寻 @AnonymousPostMapping
*/ */
POST("POST"), POST("POST"),
/** /**
* 搜寻 @AnonymousPutMapping * 搜寻 @AnonymousPutMapping
*/ */
PUT("PUT"), PUT("PUT"),
/** /**
* 搜寻 @AnonymousPatchMapping * 搜寻 @AnonymousPatchMapping
*/ */
PATCH("PATCH"), PATCH("PATCH"),
/** /**
* 搜寻 @AnonymousDeleteMapping * 搜寻 @AnonymousDeleteMapping
*/ */
DELETE("DELETE"), DELETE("DELETE"),
/** /**
* 否则就是所有 Request 接口都放行 * 否则就是所有 Request 接口都放行
*/ */
ALL("All"); ALL("All");
/** /**
* Request 类型 * Request 类型
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.constant; package cn.odboy.constant;
/** /**
@@ -24,22 +23,18 @@ public interface SystemConst {
* win 系统 * win 系统
*/ */
String WIN = "win"; String WIN = "win";
/** /**
* mac 系统 * mac 系统
*/ */
String MAC = "mac"; String MAC = "mac";
/** /**
* 请求头名称 * 请求头名称
*/ */
String HEADER_NAME = "Authorization"; String HEADER_NAME = "Authorization";
/** /**
* Token前缀 * Token前缀
*/ */
String TOKEN_PREFIX = "Bearer"; String TOKEN_PREFIX = "Bearer";
/** /**
* 小数点 * 小数点
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.context; package cn.odboy.framework.context;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.context; package cn.odboy.framework.context;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
/** /**
* 主要目的是输出应用的服务地址 * 主要目的是输出应用的服务地址
* *
@@ -37,9 +35,12 @@ public class BootApplication {
Environment env = application.getEnvironment(); Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress(); String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port"); String port = env.getProperty("server.port");
String path = StrUtil.isEmpty(env.getProperty("config.servlet.context-path")) ? "" : env.getProperty("config.servlet.context-path"); String path = StrUtil.isEmpty(env.getProperty("config.servlet.context-path")) ? ""
log.info( : env.getProperty("config.servlet.context-path");
"\n----------------------------------------------------------\n\t" + "Application is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:" + port + path + "/\n\t" + "External: \thttp://" + ip + ":" + port + path + "/\n\t" + "Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" + "----------------------------------------------------------"); log.info("\n----------------------------------------------------------\n\t" +
"Application is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" + "Swagger文档: \thttp://" + ip + ":" + port +
path + "/doc.html\n" + "----------------------------------------------------------");
} }
@Bean @Bean
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,21 +13,19 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.context; package cn.odboy.framework.context;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/** /**
* 获取 HttpServletRequest * 获取 HttpServletRequest
*/ */
public class KitRequestHolder { public class KitRequestHolder {
public static HttpServletRequest getHttpServletRequest() { public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes)Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); return ((ServletRequestAttributes)Objects.requireNonNull(
RequestContextHolder.getRequestAttributes())).getRequest();
} }
} }
@@ -13,16 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.context; package cn.odboy.framework.context;
import java.util.Map;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Scriptable;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Map;
/** /**
* 脚本工具 * 脚本工具
* *
@@ -13,9 +13,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.context; package cn.odboy.framework.context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
@@ -24,14 +26,9 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j @Slf4j
@SuppressWarnings({"unchecked", "all"}) @SuppressWarnings({"unchecked", "all"})
public class KitSpringBeanHolder implements ApplicationContextAware, DisposableBean { public class KitSpringBeanHolder implements ApplicationContextAware, DisposableBean {
private static final List<CallBack> CALL_BACKS = new ArrayList<>(); private static final List<CallBack> CALL_BACKS = new ArrayList<>();
private static ApplicationContext applicationContext = null; private static ApplicationContext applicationContext = null;
private static boolean addCallback = true; private static boolean addCallback = true;
@@ -109,8 +106,8 @@ public class KitSpringBeanHolder implements ApplicationContextAware, DisposableB
*/ */
private static void assertContextInjected() { private static void assertContextInjected() {
if (applicationContext == null) { if (applicationContext == null) {
throw new IllegalStateException( throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
"applicaitonContext属性未注入, 请在applicationContext" + ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder."); ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
} }
} }
@@ -139,7 +136,8 @@ public class KitSpringBeanHolder implements ApplicationContextAware, DisposableB
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (KitSpringBeanHolder.applicationContext != null) { if (KitSpringBeanHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + KitSpringBeanHolder.applicationContext); log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" +
KitSpringBeanHolder.applicationContext);
} }
KitSpringBeanHolder.applicationContext = applicationContext; KitSpringBeanHolder.applicationContext = applicationContext;
if (addCallback) { if (addCallback) {
@@ -152,12 +150,10 @@ public class KitSpringBeanHolder implements ApplicationContextAware, DisposableB
} }
interface CallBack { interface CallBack {
/** /**
* 回调执行方法 * 回调执行方法
*/ */
void executor(); void executor();
/** /**
* 本回调任务名称 * 本回调任务名称
* *
@@ -13,12 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.doc; package cn.odboy.framework.doc;
import cn.odboy.constant.SystemConst; import cn.odboy.constant.SystemConst;
import cn.odboy.framework.properties.AppProperties; import cn.odboy.framework.properties.AppProperties;
import cn.odboy.util.KitAnonTagUtil; import cn.odboy.util.KitAnonTagUtil;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@@ -30,7 +35,11 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping; import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
@@ -38,25 +47,15 @@ import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider; import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/** /**
* api页面 /doc.html * api页面 /doc.html
*/ */
@Configuration @Configuration
@EnableSwagger2 @EnableSwagger2
public class SwaggerConfig { public class SwaggerConfig {
@Value("${server.servlet.context-path:}") @Value("${server.servlet.context-path:}") private String apiPath;
private String apiPath; @Autowired private AppProperties properties;
@Autowired @Autowired private ApplicationContext applicationContext;
private AppProperties properties;
@Autowired
private ApplicationContext applicationContext;
/** /**
* 解决Springfox与SpringBoot集成后, WebMvcRequestHandlerProvider和WebFluxRequestHandlerProvider冲突问题 * 解决Springfox与SpringBoot集成后, WebMvcRequestHandlerProvider和WebFluxRequestHandlerProvider冲突问题
@@ -67,7 +66,6 @@ public class SwaggerConfig {
@SuppressWarnings({"unchecked", "all"}) @SuppressWarnings({"unchecked", "all"})
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() { public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() { return new BeanPostProcessor() {
@Override @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
@@ -76,8 +74,10 @@ public class SwaggerConfig {
return bean; return bean;
} }
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
List<T> filteredMappings = mappings.stream().filter(mapping -> mapping.getPatternParser() == null).collect(Collectors.toList()); List<T> mappings) {
List<T> filteredMappings = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear(); mappings.clear();
mappings.addAll(filteredMappings); mappings.addAll(filteredMappings);
} }
@@ -99,14 +99,15 @@ public class SwaggerConfig {
@Bean @Bean
public Docket createRestApi() { public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).enable(properties.getSwagger().getEnabled()).pathMapping("/").apiInfo(apiInfo()).select() return new Docket(DocumentationType.SWAGGER_2).enable(properties.getSwagger().getEnabled()).pathMapping("/")
.paths(PathSelectors.regex("^(?!/error).*")).paths(PathSelectors.any()).build() .apiInfo(apiInfo()).select().paths(PathSelectors.regex("^(?!/error).*")).paths(PathSelectors.any()).build()
//添加登陆认证 //添加登陆认证
.securitySchemes(securitySchemes()).securityContexts(securityContexts()); .securitySchemes(securitySchemes()).securityContexts(securityContexts());
} }
private ApiInfo apiInfo() { private ApiInfo apiInfo() {
return new ApiInfoBuilder().description("一个简单且易上手的自动化运维平台").title("CuteJava 接口文档").version("1.4.1").build(); return new ApiInfoBuilder().description("一个简单且易上手的自动化运维平台").title("CuteJava 接口文档")
.version("1.4.1").build();
} }
private List<SecurityScheme> securitySchemes() { private List<SecurityScheme> securitySchemes() {
@@ -128,9 +129,10 @@ public class SwaggerConfig {
Set<String> urls = KitAnonTagUtil.getAllAnonymousUrl(applicationContext); Set<String> urls = KitAnonTagUtil.getAllAnonymousUrl(applicationContext);
urls = urls.stream().filter(url -> !"/".equals(url)).collect(Collectors.toSet()); urls = urls.stream().filter(url -> !"/".equals(url)).collect(Collectors.toSet());
String regExp = "^(?!" + apiPath + String.join("|" + apiPath, urls) + ").*$"; String regExp = "^(?!" + apiPath + String.join("|" + apiPath, urls) + ").*$";
return SecurityContext.builder().securityReferences(defaultAuth()).operationSelector(o -> o.requestMappingPattern() return SecurityContext.builder().securityReferences(defaultAuth())
// 排除不需要认证的接口 .operationSelector(o -> o.requestMappingPattern()
.matches(regExp)).build(); // 排除不需要认证的接口
.matches(regExp)).build();
} }
private List<SecurityReference> defaultAuth() { private List<SecurityReference> defaultAuth() {
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.exception; package cn.odboy.framework.exception;
import lombok.Getter; import lombok.Getter;
@@ -26,7 +25,6 @@ import static org.springframework.http.HttpStatus.BAD_REQUEST;
*/ */
@Getter @Getter
public class BadRequestException extends RuntimeException { public class BadRequestException extends RuntimeException {
private Integer status = BAD_REQUEST.value(); private Integer status = BAD_REQUEST.value();
public BadRequestException(String msg) { public BadRequestException(String msg) {
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.exception; package cn.odboy.framework.exception;
import lombok.Getter; import lombok.Getter;
@@ -23,7 +22,6 @@ import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
@Getter @Getter
public class ServerException extends RuntimeException { public class ServerException extends RuntimeException {
private Integer status = INTERNAL_SERVER_ERROR.value(); private Integer status = INTERNAL_SERVER_ERROR.value();
public ServerException(String msg) { public ServerException(String msg) {
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.exception.handler; package cn.odboy.framework.exception.handler;
import lombok.Data; import lombok.Data;
@Data @Data
public final class ApiError { public final class ApiError {
private Integer status = 400; private Integer status = 400;
private Long timestamp; private Long timestamp;
private String message; private String message;
@@ -42,5 +40,3 @@ public final class ApiError {
return apiError; return apiError;
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.exception.handler; package cn.odboy.framework.exception.handler;
import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.exceptions.ExceptionUtil;
@@ -36,7 +35,6 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j @Slf4j
@RestControllerAdvice @RestControllerAdvice
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
/** /**
* 处理所有不可知的异常 * 处理所有不可知的异常
*/ */
@@ -13,10 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.logging; package cn.odboy.framework.logging;
import java.lang.annotation.*; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* 统计执行时长 * 统计执行时长
@@ -32,7 +36,6 @@ public @interface ExecutionTimeStatisticsFace {
* 接口描述 * 接口描述
*/ */
String description(); String description();
/** /**
* 是否展示异常日志 * 是否展示异常日志
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.logging; package cn.odboy.framework.logging;
import cn.hutool.core.date.TimeInterval; import cn.hutool.core.date.TimeInterval;
@@ -34,15 +33,18 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ExecutionTimeStatisticsFaceAspect { public class ExecutionTimeStatisticsFaceAspect {
@Around("@annotation(executionTimeStatisticsFace)") @Around("@annotation(executionTimeStatisticsFace)")
public Object aroundFace(ProceedingJoinPoint joinPoint, ExecutionTimeStatisticsFace executionTimeStatisticsFace) throws Throwable { public Object aroundFace(ProceedingJoinPoint joinPoint, ExecutionTimeStatisticsFace executionTimeStatisticsFace)
throws Throwable {
TimeInterval timeInterval = new TimeInterval(); TimeInterval timeInterval = new TimeInterval();
try { try {
Object proceed = joinPoint.proceed(); Object proceed = joinPoint.proceed();
log.info("[{}] 接口执行成功,耗时: {} ms", executionTimeStatisticsFace.description(), timeInterval.intervalMs()); log.info("[{}] 接口执行成功,耗时: {} ms", executionTimeStatisticsFace.description(),
timeInterval.intervalMs());
return proceed; return proceed;
} catch (Exception e) { } catch (Exception e) {
if (executionTimeStatisticsFace.showErrLog()) { if (executionTimeStatisticsFace.showErrLog()) {
log.error("[{}] 接口执行失败,耗时: {} ms", executionTimeStatisticsFace.description(), timeInterval.intervalMs(), e); log.error("[{}] 接口执行失败,耗时: {} ms", executionTimeStatisticsFace.description(),
timeInterval.intervalMs(), e);
} }
throw e; throw e;
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.monitor.controller; package cn.odboy.framework.monitor.controller;
import cn.odboy.annotation.AnonymousGetMapping; import cn.odboy.annotation.AnonymousGetMapping;
@@ -31,8 +30,7 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/healthCheck") @RequestMapping("/healthCheck")
@Api(tags = "系统:健康检查接口") @Api(tags = "系统:健康检查接口")
public class HealthCheckController { public class HealthCheckController {
@Autowired @Autowired private KitHealthCheckPointService kitHealthCheckPointService;
private KitHealthCheckPointService kitHealthCheckPointService;
/** /**
* 就绪检查 * 就绪检查
@@ -49,7 +47,6 @@ public class HealthCheckController {
public ResponseEntity<?> doLiveness() { public ResponseEntity<?> doLiveness() {
return kitHealthCheckPointService.doLiveness(); return kitHealthCheckPointService.doLiveness();
} }
// /** // /**
// * 访问首页提示 // * 访问首页提示
// */ // */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.monitor.service; package cn.odboy.framework.monitor.service;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -23,7 +22,6 @@ public interface KitHealthCheckPointService {
* 就绪检查 * 就绪检查
*/ */
ResponseEntity<?> doReadiness(); ResponseEntity<?> doReadiness();
/** /**
* 存活检查 * 存活检查
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
@@ -94,7 +93,8 @@ public enum DataTypeEnum {
private String aliasPrefix; private String aliasPrefix;
private String aliasSuffix; private String aliasSuffix;
DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) { DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix,
String aliasPrefix, String aliasSuffix) {
this.feature = feature; this.feature = feature;
this.desc = desc; this.desc = desc;
this.driver = driver; this.driver = driver;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
/** /**
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
@@ -33,12 +32,10 @@ public @interface KitMpQuery {
* 基本对象的属性名 * 基本对象的属性名
*/ */
String propName() default ""; String propName() default "";
/** /**
* 查询方式 * 查询方式
*/ */
KitMpQTypeEnum type() default KitMpQTypeEnum.EQUAL; KitMpQTypeEnum type() default KitMpQTypeEnum.EQUAL;
/** /**
* 多字段模糊搜索, 仅支持String类型字段, 多个用逗号隔开, 如@MpQuery(blurry = "email,username") * 多字段模糊搜索, 仅支持String类型字段, 多个用逗号隔开, 如@MpQuery(blurry = "email,username")
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
@@ -55,13 +54,14 @@ public class MpCustomP6SpyLogger implements MessageFormattingStrategy {
* @return 格式化后的sql * @return 格式化后的sql
*/ */
@Override @Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared,
String sql, String url) {
// 去掉换行和多余空格 // 去掉换行和多余空格
if (StrUtil.isNotBlank(sql)) { if (StrUtil.isNotBlank(sql)) {
sql = sql.replaceAll("\\s+", " ").trim(); sql = sql.replaceAll("\\s+", " ").trim();
} }
// 格式化并加上颜色 // 格式化并加上颜色
return String.format("CuteJava - %s%s%s %s[%s] %sREVIEW_SQL [Interval: %dms]%s -> %s;", RED, now, RESET, GREEN, Thread.currentThread().getName(), BLUE, return String.format("CuteJava - %s%s%s %s[%s] %sREVIEW_SQL [Interval: %dms]%s -> %s;", RED, now, RESET, GREEN,
elapsed, RESET, sql); Thread.currentThread().getName(), BLUE, elapsed, RESET, sql);
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
@@ -22,9 +21,8 @@ import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById; import com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn; import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import org.apache.ibatis.session.Configuration;
import java.util.List; import java.util.List;
import org.apache.ibatis.session.Configuration;
/** /**
* 批量插入SQL注入器 * 批量插入SQL注入器
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.DbType;
@@ -13,12 +13,20 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.config; package cn.odboy.framework.mybatisplus.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils; import com.alibaba.druid.util.Utils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
@@ -26,18 +34,13 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration @Configuration
@SuppressWarnings({"unchecked", "all"}) @SuppressWarnings({"unchecked", "all"})
@ConditionalOnWebApplication @ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class) @AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true",
matchIfMissing = true)
public class RemoveDruidAdConfig { public class RemoveDruidAdConfig {
/** /**
* 方法名: removeDruidAdFilterRegistrationBean 方法描述 除去页面底部的广告 * 方法名: removeDruidAdFilterRegistrationBean 方法描述 除去页面底部的广告
* *
@@ -46,15 +49,12 @@ public class RemoveDruidAdConfig {
*/ */
@Bean @Bean
public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) { public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) {
// 获取web监控页面的参数 // 获取web监控页面的参数
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
// 提取common.js的配置路径 // 提取common.js的配置路径
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
final String filePath = "support/http/resources/js/common.js"; final String filePath = "support/http/resources/js/common.js";
//创建filter进行过滤 //创建filter进行过滤
Filter filter = new Filter() { Filter filter = new Filter() {
@Override @Override
@@ -62,7 +62,8 @@ public class RemoveDruidAdConfig {
} }
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request; HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response; HttpServletResponse httpResponse = (HttpServletResponse)response;
if (httpRequest.getRequestURI().endsWith("js/common.js")) { if (httpRequest.getRequestURI().endsWith("js/common.js")) {
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core; package cn.odboy.framework.mybatisplus.core;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -69,7 +67,8 @@ public class KitMpAnyQUtil {
return baseMapper.selectPage(page, queryWrapper); return baseMapper.selectPage(page, queryWrapper);
} }
public static <T, M> Page<M> selectPage(BaseMapper<T> baseMapper, Page<T> page, Object queryParams, Class<M> mapperClazz) { public static <T, M> Page<M> selectPage(BaseMapper<T> baseMapper, Page<T> page, Object queryParams,
Class<M> mapperClazz) {
QueryWrapper<T> queryWrapper = KitMpQUtil.build(queryParams); QueryWrapper<T> queryWrapper = KitMpQUtil.build(queryParams);
Page<T> tPage = baseMapper.selectPage(page, queryWrapper); Page<T> tPage = baseMapper.selectPage(page, queryWrapper);
Page<M> mapperTarget = new Page<>(); Page<M> mapperTarget = new Page<>();
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core; package cn.odboy.framework.mybatisplus.core;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
@@ -21,7 +20,12 @@ import cn.odboy.base.KitBaseUserTimeTb;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.IDbQuery;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery; import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
@@ -29,13 +33,12 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler; import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
import lombok.Data;
import org.apache.ibatis.annotations.Mapper;
import java.sql.Types; import java.sql.Types;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import lombok.Data;
import org.apache.ibatis.annotations.Mapper;
/** /**
* 代码生成器入口 * 代码生成器入口
@@ -67,14 +70,16 @@ public class KitMpCmdGenUtil {
private static Consumer<StrategyConfig.Builder> getEntityConfigConsumer() { private static Consumer<StrategyConfig.Builder> getEntityConfigConsumer() {
return strategyConfigBuilder -> strategyConfigBuilder.entityBuilder().enableLombok() return strategyConfigBuilder -> strategyConfigBuilder.entityBuilder().enableLombok()
// 如果不需要生成注解, 去掉.enableTableFieldAnnotation() // 如果不需要生成注解, 去掉.enableTableFieldAnnotation()
.enableTableFieldAnnotation().enableFileOverride().naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel) .enableTableFieldAnnotation().enableFileOverride().naming(NamingStrategy.underline_to_camel)
.idType(IdType.AUTO); .columnNaming(NamingStrategy.underline_to_camel).idType(IdType.AUTO);
} }
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer(List<String> tableNames) { private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer(List<String> tableNames) {
return strategyConfigBuilder -> strategyConfigBuilder.enableCapitalMode().enableSkipView().disableSqlFilter().addInclude(tableNames) return strategyConfigBuilder -> strategyConfigBuilder.enableCapitalMode().enableSkipView().disableSqlFilter()
.addInclude(tableNames)
// 实体类生成策略 // 实体类生成策略
.entityBuilder().superClass(KitBaseUserTimeTb.class).addIgnoreColumns("create_time", "update_time", "create_by", "update_by") .entityBuilder().superClass(KitBaseUserTimeTb.class)
.addIgnoreColumns("create_time", "update_time", "create_by", "update_by")
// 开启生成实体时生成字段注解。 // 开启生成实体时生成字段注解。
// 会在实体类的属性前,添加[@TableField("nickname")] // 会在实体类的属性前,添加[@TableField("nickname")]
.enableTableFieldAnnotation().disableSerialVersionUID() .enableTableFieldAnnotation().disableSerialVersionUID()
@@ -99,13 +104,13 @@ public class KitMpCmdGenUtil {
private static Consumer<GlobalConfig.Builder> getGlobalConfigConsumer() { private static Consumer<GlobalConfig.Builder> getGlobalConfigConsumer() {
String outputDir = projectRootPath + "CodeGen"; String outputDir = projectRootPath + "CodeGen";
return globalConfigBuilder -> globalConfigBuilder.enableSwagger().outputDir(outputDir).author("codegen").commentDate("yyyy-MM-dd") return globalConfigBuilder -> globalConfigBuilder.enableSwagger().outputDir(outputDir).author("codegen")
.dateType(DateType.TIME_PACK); .commentDate("yyyy-MM-dd").dateType(DateType.TIME_PACK);
} }
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer() { private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer() {
return strategyConfigBuilder -> strategyConfigBuilder.mapperBuilder().mapperAnnotation(Mapper.class).formatMapperFileName("%sMapper") return strategyConfigBuilder -> strategyConfigBuilder.mapperBuilder().mapperAnnotation(Mapper.class)
.formatXmlFileName("%sMapper").entityBuilder().formatFileName("%sTb"); .formatMapperFileName("%sMapper").formatXmlFileName("%sMapper").entityBuilder().formatFileName("%sTb");
} }
private static Consumer<DataSourceConfig.Builder> getDataSourceConfigConsumer() { private static Consumer<DataSourceConfig.Builder> getDataSourceConfigConsumer() {
@@ -138,7 +143,8 @@ public class KitMpCmdGenUtil {
this.parentModuleName = moduleName; this.parentModuleName = moduleName;
// 1.数据库配置 // 1.数据库配置
DataSourceConfig.Builder dataSourceConfigBuilder = DataSourceConfig.Builder dataSourceConfigBuilder =
new DataSourceConfig.Builder(this.databaseUrl, this.databaseUsername, this.databasePassword).driverClassName(this.driverClassName); new DataSourceConfig.Builder(this.databaseUrl, this.databaseUsername,
this.databasePassword).driverClassName(this.driverClassName);
dataSourceConfigBuilder.dbQuery(DB_QUERY); dataSourceConfigBuilder.dbQuery(DB_QUERY);
dataSourceConfigBuilder.keyWordsHandler(new MySqlKeyWordsHandler()); dataSourceConfigBuilder.keyWordsHandler(new MySqlKeyWordsHandler());
// 1.1.快速生成器 // 1.1.快速生成器
@@ -168,7 +174,8 @@ public class KitMpCmdGenUtil {
fastAutoGenerator.strategyConfig(getStrategyConfigConsumer(tableNames)); fastAutoGenerator.strategyConfig(getStrategyConfigConsumer(tableNames));
if (tablePrefix != null) { if (tablePrefix != null) {
// 表前缀, 可多个 // 表前缀, 可多个
fastAutoGenerator.strategyConfig(strategyConfigBuilder -> strategyConfigBuilder.addTablePrefix(tablePrefix)); fastAutoGenerator.strategyConfig(
strategyConfigBuilder -> strategyConfigBuilder.addTablePrefix(tablePrefix));
} }
// 5.1.Entity策略配置 // 5.1.Entity策略配置
// 生成实体时生成字段的注解, 包括@TableId注解等 // 生成实体时生成字段的注解, 包括@TableId注解等
@@ -178,10 +185,13 @@ public class KitMpCmdGenUtil {
fastAutoGenerator.strategyConfig(getEntityConfigConsumer()); fastAutoGenerator.strategyConfig(getEntityConfigConsumer());
// 5.2.Controller策略配置 // 5.2.Controller策略配置
// 开启生成@RestController控制器 // 开启生成@RestController控制器
fastAutoGenerator.strategyConfig(strategyConfigBuilder -> strategyConfigBuilder.controllerBuilder().enableRestStyle());
// 如果不需要生成Controller, fastAutoGenerator.templateConfig(templateConfig -> templateConfig.controller(""))。5.3.Service策略配置:格式化service接口和实现类的文件名称, 去掉默认的ServiceName前面的I
fastAutoGenerator.strategyConfig( fastAutoGenerator.strategyConfig(
strategyConfigBuilder -> strategyConfigBuilder.serviceBuilder().formatServiceFileName("%sService").formatServiceImplFileName("%sServiceImpl")); strategyConfigBuilder -> strategyConfigBuilder.controllerBuilder().enableRestStyle());
// 如果不需要生成Controller, fastAutoGenerator.templateConfig(templateConfig -> templateConfig.controller(""))。5.3
// .Service策略配置:格式化service接口和实现类的文件名称, 去掉默认的ServiceName前面的I
fastAutoGenerator.strategyConfig(
strategyConfigBuilder -> strategyConfigBuilder.serviceBuilder().formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl"));
// 5.4.Mapper策略配置 // 5.4.Mapper策略配置
// 格式化 mapper文件名,格式化xml实现类文件名称 // 格式化 mapper文件名,格式化xml实现类文件名称
fastAutoGenerator.strategyConfig(getStrategyConfigConsumer()); fastAutoGenerator.strategyConfig(getStrategyConfigConsumer());
@@ -194,8 +204,9 @@ public class KitMpCmdGenUtil {
if (StrUtil.isBlank(this.parentModuleName)) { if (StrUtil.isBlank(this.parentModuleName)) {
throw new BadRequestException("模块名称必填"); throw new BadRequestException("模块名称必填");
} }
return packageConfigBuilder -> packageConfigBuilder.parent(this.parentPackageName).moduleName(this.parentModuleName).entity("dal.dataobject") return packageConfigBuilder -> packageConfigBuilder.parent(this.parentPackageName)
.mapper("dal.mysql").service("service").serviceImpl("service.impl").controller("controller") .moduleName(this.parentModuleName).entity("dal.dataobject").mapper("dal.mysql").service("service")
.serviceImpl("service.impl").controller("controller")
.pathInfo(Collections.singletonMap(OutputFile.xml, mapperPath)); .pathInfo(Collections.singletonMap(OutputFile.xml, mapperPath));
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core; package cn.odboy.framework.mybatisplus.core;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
@@ -27,13 +26,16 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.lang.reflect.Field; import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.stream.Collectors;
/** /**
* 查询条件创建工具 * 查询条件创建工具
@@ -78,7 +80,8 @@ public class KitMpQUtil {
return StrUtil.toUnderlineCase(attributeName); return StrUtil.toUnderlineCase(attributeName);
} }
private static <R> void handleWrapper(KitMpQuery q, QueryWrapper<R> queryWrapper, String attributeName, Object fieldVal) { private static <R> void handleWrapper(KitMpQuery q, QueryWrapper<R> queryWrapper, String attributeName,
Object fieldVal) {
switch (q.type()) { switch (q.type()) {
case EQUAL: case EQUAL:
queryWrapper.eq(attributeName, fieldVal); queryWrapper.eq(attributeName, fieldVal);
@@ -124,7 +127,8 @@ public class KitMpQUtil {
} }
} }
private static <R> void handleInOrNotQuery(boolean b, QueryWrapper<R> queryWrapper, String attributeName, Object fieldVal) { private static <R> void handleInOrNotQuery(boolean b, QueryWrapper<R> queryWrapper, String attributeName,
Object fieldVal) {
Collection<?> wrapNotInVal = (Collection<?>)fieldVal; Collection<?> wrapNotInVal = (Collection<?>)fieldVal;
if (CollectionUtil.isNotEmpty(wrapNotInVal)) { if (CollectionUtil.isNotEmpty(wrapNotInVal)) {
Optional<?> anyValOptional = wrapNotInVal.stream().findAny(); Optional<?> anyValOptional = wrapNotInVal.stream().findAny();
@@ -149,7 +153,8 @@ public class KitMpQUtil {
} }
} }
private static <R> void handleBetweenQuery(QueryWrapper<R> queryWrapper, Object fieldVal, String finalAttributeName) { private static <R> void handleBetweenQuery(QueryWrapper<R> queryWrapper, Object fieldVal,
String finalAttributeName) {
if (fieldVal instanceof List) { if (fieldVal instanceof List) {
List<Object> between = new ArrayList<>((List<?>)fieldVal); List<Object> between = new ArrayList<>((List<?>)fieldVal);
int minLength = 2; int minLength = 2;
@@ -172,7 +177,8 @@ public class KitMpQUtil {
* @param <R> / * @param <R> /
*/ */
private static <R> void handleBlurryQuery(QueryWrapper<R> queryWrapper, String blurry, Object fieldVal) { private static <R> void handleBlurryQuery(QueryWrapper<R> queryWrapper, String blurry, Object fieldVal) {
List<String> blurryList = Arrays.stream(blurry.split(",")).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList()); List<String> blurryList =
Arrays.stream(blurry.split(",")).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
queryWrapper.and(wrapper -> { queryWrapper.and(wrapper -> {
for (String blurryItem : blurryList) { for (String blurryItem : blurryList) {
String column = StrUtil.toUnderlineCase(blurryItem); String column = StrUtil.toUnderlineCase(blurryItem);
@@ -209,14 +215,10 @@ public class KitMpQUtil {
@TableName("test_domain") @TableName("test_domain")
private static class TestDomain { private static class TestDomain {
@NotNull(groups = KitBaseUserTimeTb.Update.class) @NotNull(groups = KitBaseUserTimeTb.Update.class) @TableId(value = "user_id", type = IdType.AUTO) private Long
@TableId(value = "user_id", type = IdType.AUTO) id;
private Long id; @TableField(value = "dept_id") private Long deptId;
@TableField(value = "dept_id") @NotBlank private String username;
private Long deptId; @NotBlank private String nickName;
@NotBlank
private String username;
@NotBlank
private String nickName;
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core.interfaces; package cn.odboy.framework.mybatisplus.core.interfaces;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
@@ -26,15 +25,14 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
/** /**
* 公共抽象Mapper接口类 * 公共抽象Mapper接口类
@@ -50,7 +48,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
* @return 影响的行数 * @return 影响的行数
*/ */
int insertBatchSomeColumn(List<E> entityList); int insertBatchSomeColumn(List<E> entityList);
/** /**
* 根据id全量更新 * 根据id全量更新
* *
@@ -58,7 +55,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
* @return 影响的行数 * @return 影响的行数
*/ */
int alwaysUpdateSomeColumnById(@Param("et") E entity); int alwaysUpdateSomeColumnById(@Param("et") E entity);
/** /**
* 获取字典 * 获取字典
* *
@@ -98,7 +94,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
} }
return result; return result;
} }
/** /**
* 条件查询列表, 并返回期望的对象 * 条件查询列表, 并返回期望的对象
* *
@@ -113,7 +108,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
} }
return BeanUtil.copyToList(list, clazz); return BeanUtil.copyToList(list, clazz);
} }
/** /**
* 条件查询列表, 并返回期望的对象 * 条件查询列表, 并返回期望的对象
* *
@@ -128,7 +122,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
} }
return BeanUtil.copyToList(list, clazz); return BeanUtil.copyToList(list, clazz);
} }
/** /**
* 条件查询分页列表, 并返回期望的对象 * 条件查询分页列表, 并返回期望的对象
* *
@@ -137,7 +130,8 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
* @param clazz 期望的对象类型 * @param clazz 期望的对象类型
* @return IPage<T> * @return IPage<T>
*/ */
default <T> KitPageResult<T> queryFeatureClazzPage(Pageable pageable, LambdaQueryWrapper<E> wrapper, Class<T> clazz) { default <T> KitPageResult<T> queryFeatureClazzPage(Pageable pageable, LambdaQueryWrapper<E> wrapper,
Class<T> clazz) {
int pageNumber = pageable.getPageNumber(); int pageNumber = pageable.getPageNumber();
int pageSize = pageable.getPageSize(); int pageSize = pageable.getPageSize();
pageNumber = pageNumber <= 0 ? 1 : pageNumber; pageNumber = pageNumber <= 0 ? 1 : pageNumber;
@@ -148,7 +142,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
} }
return new KitPageResult<>(BeanUtil.copyToList(pageInfo.getRecords(), clazz), pageInfo.getTotal()); return new KitPageResult<>(BeanUtil.copyToList(pageInfo.getRecords(), clazz), pageInfo.getTotal());
} }
/** /**
* 条件查询分页列表, 并返回期望的对象 * 条件查询分页列表, 并返回期望的对象
* *
@@ -157,7 +150,8 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
* @param clazz 期望的对象类型 * @param clazz 期望的对象类型
* @return IPage<T> * @return IPage<T>
*/ */
default <T> KitPageResult<T> queryFeatureClazzPage(Pageable pageable, LambdaQueryChainWrapper<E> wrapper, Class<T> clazz) { default <T> KitPageResult<T> queryFeatureClazzPage(Pageable pageable, LambdaQueryChainWrapper<E> wrapper,
Class<T> clazz) {
int pageNumber = pageable.getPageNumber(); int pageNumber = pageable.getPageNumber();
int pageSize = pageable.getPageSize(); int pageSize = pageable.getPageSize();
pageNumber = pageNumber <= 0 ? 1 : pageNumber; pageNumber = pageNumber <= 0 ? 1 : pageNumber;
@@ -168,7 +162,6 @@ public interface KitMpMapper<E> extends BaseMapper<E> {
} }
return new KitPageResult<>(BeanUtil.copyToList(pageInfo.getRecords(), clazz), pageInfo.getTotal()); return new KitPageResult<>(BeanUtil.copyToList(pageInfo.getRecords(), clazz), pageInfo.getTotal());
} }
/** /**
* 获取目标类 * 获取目标类
* *
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core.interfaces; package cn.odboy.framework.mybatisplus.core.interfaces;
import cn.odboy.base.KitPageResult; import cn.odboy.base.KitPageResult;
@@ -21,7 +20,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -34,38 +32,22 @@ import java.util.List;
*/ */
public interface KitMpService<T> extends IService<T> { public interface KitMpService<T> extends IService<T> {
<G> int saveFeatureClazz(G resources); <G> int saveFeatureClazz(G resources);
<G> int saveFeatureClazzList(List<G> resources); <G> int saveFeatureClazzList(List<G> resources);
<G> int modifyFeatureClazzById(G resources); <G> int modifyFeatureClazzById(G resources);
<G> boolean modifyFeatureClazzListById(Collection<G> resources, int batchSize); <G> boolean modifyFeatureClazzListById(Collection<G> resources, int batchSize);
<G> G queryFeatureClazzById(Serializable id, Class<G> targetClazz); <G> G queryFeatureClazzById(Serializable id, Class<G> targetClazz);
T queryClazzByArgs(LambdaQueryWrapper<T> wrapper, SFunction<T, ?> orderColumn); T queryClazzByArgs(LambdaQueryWrapper<T> wrapper, SFunction<T, ?> orderColumn);
<G> G queryFeatureClazzByArgs(LambdaQueryWrapper<T> wrapper, SFunction<T, ?> orderColumn, Class<G> clazz); <G> G queryFeatureClazzByArgs(LambdaQueryWrapper<T> wrapper, SFunction<T, ?> orderColumn, Class<G> clazz);
<G> List<G> queryFeatureClazzListByIds(List<Serializable> ids, Class<G> targetClazz); <G> List<G> queryFeatureClazzListByIds(List<Serializable> ids, Class<G> targetClazz);
<Q> List<T> queryClazzListByArgs(Q criteria); <Q> List<T> queryClazzListByArgs(Q criteria);
List<T> queryClazzListByArgs(LambdaQueryWrapper<T> wrapper); List<T> queryClazzListByArgs(LambdaQueryWrapper<T> wrapper);
<G, Q> List<G> queryFeatureClazzListByArgs(Q criteria, Class<G> targetClazz); <G, Q> List<G> queryFeatureClazzListByArgs(Q criteria, Class<G> targetClazz);
<G> List<G> queryFeatureClazzListByArgs(LambdaQueryWrapper<T> wrapper, Class<G> targetClazz); <G> List<G> queryFeatureClazzListByArgs(LambdaQueryWrapper<T> wrapper, Class<G> targetClazz);
KitPageResult<T> queryClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable); KitPageResult<T> queryClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable);
<G> KitPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable,
<G> KitPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable, Class<G> targetClazz); Class<G> targetClazz);
<G, Q> KitPageResult<G> queryFeatureClazzPageByArgs(Q criteria, IPage<T> pageable, Class<G> targetClazz); <G, Q> KitPageResult<G> queryFeatureClazzPageByArgs(Q criteria, IPage<T> pageable, Class<G> targetClazz);
<Q> KitPageResult<T> queryClazzPageByArgs(Q criteria, IPage<T> pageable); <Q> KitPageResult<T> queryClazzPageByArgs(Q criteria, IPage<T> pageable);
int modifyClazzByArgs(LambdaQueryWrapper<T> wrapper, T entity); int modifyClazzByArgs(LambdaQueryWrapper<T> wrapper, T entity);
int removeClazzByArgs(LambdaQueryWrapper<T> wrapper); int removeClazzByArgs(LambdaQueryWrapper<T> wrapper);
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.mybatisplus.core.interfaces; package cn.odboy.framework.mybatisplus.core.interfaces;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
@@ -27,11 +26,10 @@ import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.binding.MapperMethod;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.apache.ibatis.binding.MapperMethod;
/** /**
* 公共抽象Mapper接口类 * 公共抽象Mapper接口类
@@ -138,7 +136,8 @@ public class KitMpServiceImpl<M extends KitMpMapper<T>, T> extends ServiceImpl<M
*/ */
public <G> List<G> queryFeatureClazzListByIds(List<Serializable> ids, Class<G> targetClazz) { public <G> List<G> queryFeatureClazzListByIds(List<Serializable> ids, Class<G> targetClazz) {
List<T> entitys = this.listByIds(ids); List<T> entitys = this.listByIds(ids);
return entitys == null || entitys.isEmpty() ? CollUtil.newArrayList() : BeanUtil.copyToList(entitys, targetClazz); return entitys == null || entitys.isEmpty() ? CollUtil.newArrayList()
: BeanUtil.copyToList(entitys, targetClazz);
} }
/** /**
@@ -209,18 +208,21 @@ public class KitMpServiceImpl<M extends KitMpMapper<T>, T> extends ServiceImpl<M
* @param pageable 分页参数 * @param pageable 分页参数
* @param targetClazz 目标类型 * @param targetClazz 目标类型
*/ */
public <G> KitPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable, Class<G> targetClazz) { public <G> KitPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable,
Class<G> targetClazz) {
if (wrapper == null) { if (wrapper == null) {
wrapper = new LambdaQueryWrapper<>(); wrapper = new LambdaQueryWrapper<>();
} }
IPage<T> originPageData = baseMapper.selectPage(pageable, wrapper); IPage<T> originPageData = baseMapper.selectPage(pageable, wrapper);
return new KitPageResult<>(BeanUtil.copyToList(originPageData.getRecords(), targetClazz), originPageData.getTotal()); return new KitPageResult<>(BeanUtil.copyToList(originPageData.getRecords(), targetClazz),
originPageData.getTotal());
} }
public <G, Q> KitPageResult<G> queryFeatureClazzPageByArgs(Q criteria, IPage<T> pageable, Class<G> targetClazz) { public <G, Q> KitPageResult<G> queryFeatureClazzPageByArgs(Q criteria, IPage<T> pageable, Class<G> targetClazz) {
QueryWrapper<T> wrapper = KitMpQUtil.build(criteria); QueryWrapper<T> wrapper = KitMpQUtil.build(criteria);
IPage<T> originPageData = baseMapper.selectPage(pageable, wrapper); IPage<T> originPageData = baseMapper.selectPage(pageable, wrapper);
return new KitPageResult<>(BeanUtil.copyToList(originPageData.getRecords(), targetClazz), originPageData.getTotal()); return new KitPageResult<>(BeanUtil.copyToList(originPageData.getRecords(), targetClazz),
originPageData.getTotal());
} }
public <Q> KitPageResult<T> queryClazzPageByArgs(Q criteria, IPage<T> pageable) { public <Q> KitPageResult<T> queryClazzPageByArgs(Q criteria, IPage<T> pageable) {
@@ -13,10 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties; package cn.odboy.framework.properties;
import cn.odboy.framework.properties.model.*; import cn.odboy.framework.properties.model.CaptchaModel;
import cn.odboy.framework.properties.model.ContentRsaEncodeSettingModel;
import cn.odboy.framework.properties.model.JwtAuthSettingModel;
import cn.odboy.framework.properties.model.StorageOSSModel;
import cn.odboy.framework.properties.model.SwaggerApiDocSettingModel;
import cn.odboy.framework.properties.model.ThreadPoolSettingModel;
import cn.odboy.framework.properties.model.UserLoginSettingModel;
import lombok.Data; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -39,5 +44,3 @@ public class AppProperties {
private CaptchaModel captcha; private CaptchaModel captcha;
private StorageOSSModel oss; private StorageOSSModel oss;
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -30,17 +29,14 @@ public class JwtAuthSettingModel extends KitObject {
* 必须使用最少88位的Base64对该令牌进行编码 * 必须使用最少88位的Base64对该令牌进行编码
*/ */
private String base64Secret; private String base64Secret;
/** /**
* 令牌过期时间 此处单位/毫秒 * 令牌过期时间 此处单位/毫秒
*/ */
private Long tokenValidityInSeconds; private Long tokenValidityInSeconds;
/** /**
* token 续期检查 * token 续期检查
*/ */
private Long detect; private Long detect;
/** /**
* 续期时间 * 续期时间
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import lombok.Getter; import lombok.Getter;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,20 +13,22 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
import cn.odboy.constant.CaptchaCodeEnum; import cn.odboy.constant.CaptchaCodeEnum;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
import com.wf.captcha.*; import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha; import com.wf.captcha.base.Captcha;
import java.awt.Font;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.awt.*;
/** /**
* 验证码配置 * 验证码配置
* *
@@ -36,32 +38,26 @@ import java.awt.*;
@Setter @Setter
public class UserLoginCaptchaSettingModel extends KitObject { public class UserLoginCaptchaSettingModel extends KitObject {
private CaptchaCodeEnum codeType; private CaptchaCodeEnum codeType;
/** /**
* 验证码有效期 分钟 * 验证码有效期 分钟
*/ */
private Long expiration = 5L; private Long expiration = 5L;
/** /**
* 验证码内容长度 * 验证码内容长度
*/ */
private int length = 4; private int length = 4;
/** /**
* 验证码宽度 * 验证码宽度
*/ */
private int width = 111; private int width = 111;
/** /**
* 验证码高度 * 验证码高度
*/ */
private int height = 36; private int height = 36;
/** /**
* 验证码字体 * 验证码字体
*/ */
private String fontName; private String fontName;
/** /**
* 字体大小 * 字体大小
*/ */
@@ -116,15 +112,12 @@ public class UserLoginCaptchaSettingModel extends KitObject {
// 生成随机数字和运算符 // 生成随机数字和运算符
int n1 = num(1, 10), n2 = num(1, 10); int n1 = num(1, 10), n2 = num(1, 10);
int opt = num(3); int opt = num(3);
// 计算结果 // 计算结果
int res = new int[] {n1 + n2, n1 - n2, n1 * n2}[opt]; int res = new int[] {n1 + n2, n1 - n2, n1 * n2}[opt];
// 转换为字符运算符 // 转换为字符运算符
char optChar = "+-x".charAt(opt); char optChar = "+-x".charAt(opt);
this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2)); this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2));
this.chars = String.valueOf(res); this.chars = String.valueOf(res);
return chars.toCharArray(); return chars.toCharArray();
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.properties.model; package cn.odboy.framework.properties.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.quartz.config; package cn.odboy.framework.quartz.config;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -38,7 +37,6 @@ public class QuartzConfig {
*/ */
@Component("quartzJobFactory") @Component("quartzJobFactory")
public static class QuartzJobFactory extends AdaptableJobFactory { public static class QuartzJobFactory extends AdaptableJobFactory {
private final AutowireCapableBeanFactory autowireCapableBeanFactory; private final AutowireCapableBeanFactory autowireCapableBeanFactory;
@Autowired @Autowired
@@ -13,17 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.quartz.core; package cn.odboy.framework.quartz.core;
import cn.odboy.framework.context.KitSpringBeanHolder; import cn.odboy.framework.context.KitSpringBeanHolder;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/** /**
* 执行定时任务 * 执行定时任务
*/ */
@@ -33,7 +31,8 @@ public class QuartzRunnable implements Callable<Object> {
private final Method method; private final Method method;
private final String params; private final String params;
public QuartzRunnable(String beanName, String methodName, String params) throws NoSuchMethodException, SecurityException { public QuartzRunnable(String beanName, String methodName, String params)
throws NoSuchMethodException, SecurityException {
this.target = KitSpringBeanHolder.getBean(beanName); this.target = KitSpringBeanHolder.getBean(beanName);
this.params = params; this.params = params;
if (StringUtils.isNotBlank(params)) { if (StringUtils.isNotBlank(params)) {
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.redis; package cn.odboy.framework.redis;
import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ObjUtil;
@@ -21,23 +20,32 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component @Component
@SuppressWarnings({"unchecked", "all"}) @SuppressWarnings({"unchecked", "all"})
public class KitRedisHelper { public class KitRedisHelper {
private static final Logger log = LoggerFactory.getLogger(KitRedisHelper.class); private static final Logger log = LoggerFactory.getLogger(KitRedisHelper.class);
private RedisTemplate<Object, Object> redisTemplate; private RedisTemplate<Object, Object> redisTemplate;
public KitRedisHelper(RedisTemplate<Object, Object> redisTemplate) { public KitRedisHelper(RedisTemplate<Object, Object> redisTemplate) {
@@ -205,14 +213,13 @@ public class KitRedisHelper {
public void scanDel(String pattern) { public void scanDel(String pattern) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
try (Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection( try (Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection(
(RedisCallback<Cursor<byte[]>>)connection -> (Cursor<byte[]>)new ConvertingCursor<>(connection.scan(options), (RedisCallback<Cursor<byte[]>>)connection -> (Cursor<byte[]>)new ConvertingCursor<>(
redisTemplate.getKeySerializer()::deserialize))) { connection.scan(options), redisTemplate.getKeySerializer()::deserialize))) {
while (cursor.hasNext()) { while (cursor.hasNext()) {
redisTemplate.delete(cursor.next()); redisTemplate.delete(cursor.next());
} }
} }
} }
// ============================String============================= // ============================String=============================
/** /**
@@ -295,7 +302,8 @@ public class KitRedisHelper {
public List<Object> multiGet(List<String> keys) { public List<Object> multiGet(List<String> keys) {
List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys)); List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys));
List resultList = Lists.newArrayList(); List resultList = Lists.newArrayList();
Optional.ofNullable(list).ifPresent(e -> list.forEach(ele -> Optional.ofNullable(ele).ifPresent(resultList::add))); Optional.ofNullable(list)
.ifPresent(e -> list.forEach(ele -> Optional.ofNullable(ele).ifPresent(resultList::add)));
return resultList; return resultList;
} }
@@ -364,7 +372,6 @@ public class KitRedisHelper {
return false; return false;
} }
} }
// ================================Map================================= // ================================Map=================================
/** /**
@@ -510,7 +517,6 @@ public class KitRedisHelper {
public double hdecr(String key, String item, double by) { public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by); return redisTemplate.opsForHash().increment(key, item, -by);
} }
// ============================set============================= // ============================set=============================
/** /**
@@ -612,7 +618,6 @@ public class KitRedisHelper {
return 0; return 0;
} }
} }
// ===============================list================================= // ===============================list=================================
/** /**
@@ -785,7 +790,6 @@ public class KitRedisHelper {
} }
long count = redisTemplate.delete(keys); long count = redisTemplate.delete(keys);
} }
// ============================incr============================= // ============================incr=============================
/** /**
@@ -13,12 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.redis; package cn.odboy.framework.redis;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONFactory; import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.JSONWriter;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.MurmurHash3; import org.apache.commons.codec.digest.MurmurHash3;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.AutoConfigureBefore;
@@ -40,11 +43,6 @@ import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException; import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Slf4j @Slf4j
@Configuration @Configuration
@EnableCaching @EnableCaching
@@ -54,7 +52,8 @@ public class RedisConfiguration extends CachingConfigurerSupport {
* 自动识别json对象白名单配置(仅允许解析的包名, 范围越小越安全)<br/> 未配置可能导致, 登录失败, 反复登录等问题 * 自动识别json对象白名单配置(仅允许解析的包名, 范围越小越安全)<br/> 未配置可能导致, 登录失败, 反复登录等问题
*/ */
private static final String[] WHITELIST_STR = private static final String[] WHITELIST_STR =
{"org.springframework", "cn.odboy.system.dal.dataobject", "cn.odboy.system.dal.model", "cn.odboy.task.dal.dataobject", "cn.odboy.task.dal.model",}; {"org.springframework", "cn.odboy.system.dal.dataobject", "cn.odboy.system.dal.model",
"cn.odboy.task.dal.dataobject", "cn.odboy.task.dal.model",};
/** /**
* 设置 redis 数据默认过期时间,默认2小时 设置@cacheable 序列化方式 * 设置 redis 数据默认过期时间,默认2小时 设置@cacheable 序列化方式
@@ -63,7 +62,8 @@ public class RedisConfiguration extends CachingConfigurerSupport {
public RedisCacheConfiguration redisCacheConfiguration() { public RedisCacheConfiguration redisCacheConfiguration() {
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)) configuration = configuration.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
.entryTtl(Duration.ofHours(2)); .entryTtl(Duration.ofHours(2));
return configuration; return configuration;
} }
@@ -102,7 +102,6 @@ public class RedisConfiguration extends CachingConfigurerSupport {
/** /**
* 自定义缓存key生成策略 * 自定义缓存key生成策略
*/ */
@Bean @Bean
@Override @Override
public KeyGenerator keyGenerator() { public KeyGenerator keyGenerator() {
@@ -162,7 +161,6 @@ public class RedisConfiguration extends CachingConfigurerSupport {
* @param <T> * @param <T>
*/ */
static class FastJsonRedisSerializer<T> implements RedisSerializer<T> { static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private final Class<T> clazz; private final Class<T> clazz;
FastJsonRedisSerializer(Class<T> clazz) { FastJsonRedisSerializer(Class<T> clazz) {
@@ -13,12 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.server.config; package cn.odboy.framework.server.config;
import cn.odboy.framework.properties.AppProperties; import cn.odboy.framework.properties.AppProperties;
import cn.odboy.framework.properties.model.ThreadPoolSettingModel; import cn.odboy.framework.properties.model.ThreadPoolSettingModel;
import com.alibaba.ttl.TtlRunnable; import com.alibaba.ttl.TtlRunnable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -26,17 +31,13 @@ import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* 创建自定义的线程池 * 创建自定义的线程池
*/ */
@EnableAsync @EnableAsync
@Configuration @Configuration
public class AsyncTheadPoolConfig implements AsyncConfigurer { public class AsyncTheadPoolConfig implements AsyncConfigurer {
@Autowired @Autowired private AppProperties properties;
private AppProperties properties;
/** /**
* 自定义线程池, 用法 @Async * 自定义线程池, 用法 @Async
@@ -49,8 +50,10 @@ public class AsyncTheadPoolConfig implements AsyncConfigurer {
// 自定义工厂 // 自定义工厂
ThreadFactory factory = r -> new Thread(r, "DefaultAsync-" + new AtomicInteger(1).getAndIncrement()); ThreadFactory factory = r -> new Thread(r, "DefaultAsync-" + new AtomicInteger(1).getAndIncrement());
// 自定义线程池 // 自定义线程池
return new ThreadPoolExecutor(asyncTaskPool.getCorePoolSize(), asyncTaskPool.getMaxPoolSize(), asyncTaskPool.getKeepAliveSeconds(), TimeUnit.SECONDS, return new ThreadPoolExecutor(asyncTaskPool.getCorePoolSize(), asyncTaskPool.getMaxPoolSize(),
new ArrayBlockingQueue<>(asyncTaskPool.getQueueCapacity()), factory, new ThreadPoolExecutor.CallerRunsPolicy()); asyncTaskPool.getKeepAliveSeconds(), TimeUnit.SECONDS,
new ArrayBlockingQueue<>(asyncTaskPool.getQueueCapacity()), factory,
new ThreadPoolExecutor.CallerRunsPolicy());
} }
/** /**
@@ -13,12 +13,8 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.server.converters; package cn.odboy.framework.server.converters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays; import java.util.Arrays;
@@ -26,10 +22,13 @@ import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component @Component
public class DateStringArraysToListDateConverter implements Converter<String[], List<Date>> { public class DateStringArraysToListDateConverter implements Converter<String[], List<Date>> {
private static final ThreadLocal<SimpleDateFormat> SDF = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); private static final ThreadLocal<SimpleDateFormat> SDF =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
@Override @Override
public List<Date> convert(String[] source) { public List<Date> convert(String[] source) {
@@ -13,20 +13,19 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.server.converters; package cn.odboy.framework.server.converters;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component @Component
public class DateStringToDateConverter implements Converter<String, Date> { public class DateStringToDateConverter implements Converter<String, Date> {
private static final ThreadLocal<SimpleDateFormat> SDF = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); private static final ThreadLocal<SimpleDateFormat> SDF =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
@Override @Override
public Date convert(String source) { public Date convert(String source) {
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.server.core; package cn.odboy.framework.server.core;
import cn.odboy.framework.server.converters.DateStringArraysToListDateConverter; import cn.odboy.framework.server.converters.DateStringArraysToListDateConverter;
@@ -21,6 +20,9 @@ import cn.odboy.framework.server.converters.DateStringToDateConverter;
import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig; import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter; import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -35,10 +37,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/** /**
* 跨越、静态资源映射、Http消息转换 * 跨越、静态资源映射、Http消息转换
* *
@@ -48,12 +46,9 @@ import java.util.List;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer { public class ConfigurerAdapter implements WebMvcConfigurer {
@Autowired @Autowired private DateStringArraysToListDateConverter dateStringArraysToListDateConverter;
private DateStringArraysToListDateConverter dateStringArraysToListDateConverter; @Autowired private DateStringToDateConverter dateStringToDateConverter;
@Autowired @Autowired private KitFileLocalUploadHelper fileUploadPathHelper;
private DateStringToDateConverter dateStringToDateConverter;
@Autowired
private KitFileLocalUploadHelper fileUploadPathHelper;
@Bean @Bean
public CorsFilter corsFilter() { public CorsFilter corsFilter() {
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.server.core; package cn.odboy.framework.server.core;
import cn.odboy.constant.SystemConst; import cn.odboy.constant.SystemConst;
@@ -34,8 +33,7 @@ public class KitFileLocalUploadHelper {
private static final String PATH_WINDOWS = "C:\\${appName}\\file\\"; private static final String PATH_WINDOWS = "C:\\${appName}\\file\\";
private static final String PATH_MAC = "/Users/odboy/${appName}/file/"; private static final String PATH_MAC = "/Users/odboy/${appName}/file/";
private static final String PATH_LINUX = "/home/${appName}/file/"; private static final String PATH_LINUX = "/home/${appName}/file/";
@Value("${spring.application.name}") @Value("${spring.application.name}") private String appName;
private String appName;
public String getPath() { public String getPath() {
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
@@ -7,7 +7,8 @@ import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* 解决启动io.undertow.websockets.jsr UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used的警告 * 解决启动io.undertow.websockets.jsr UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be
* used的警告
* *
* @author odboy * @author odboy
* @date 2025-10-30 * @date 2025-10-30
@@ -31,11 +32,12 @@ public class UndertowWebSocketConfig implements WebServerFactoryCustomizer<Under
int bufferSize = 1024; int bufferSize = 1024;
int maxPoolSize = calculateMaxPoolSize(processorCount); int maxPoolSize = calculateMaxPoolSize(processorCount);
int threadLocalCacheSize = calculateThreadLocalCacheSize(processorCount); int threadLocalCacheSize = calculateThreadLocalCacheSize(processorCount);
factory.addDeploymentInfoCustomizers(deploymentInfo -> { factory.addDeploymentInfoCustomizers(deploymentInfo -> {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo(); WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, bufferSize, maxPoolSize, threadLocalCacheSize)); webSocketDeploymentInfo.setBuffers(
deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo); new DefaultByteBufferPool(false, bufferSize, maxPoolSize, threadLocalCacheSize));
deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo",
webSocketDeploymentInfo);
}); });
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.config; package cn.odboy.framework.websocket.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@@ -28,7 +27,6 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
*/ */
@Configuration @Configuration
public class WebSocketEndpointConfig { public class WebSocketEndpointConfig {
@Bean @Bean
public ServerEndpointExporter serverEndpointExporter() { public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter(); return new ServerEndpointExporter();
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.context; package cn.odboy.framework.websocket.context;
import lombok.extern.slf4j.Slf4j;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
/** /**
* WebSocket客户端管理 * WebSocket客户端管理
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.context; package cn.odboy.framework.websocket.context;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,20 +13,22 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.context; package cn.odboy.framework.websocket.context;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import java.io.IOException;
import java.util.Objects;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
@Slf4j @Slf4j
@Component @Component
@ServerEndpoint("/websocket/{sid}") @ServerEndpoint("/websocket/{sid}")
@@ -62,7 +64,8 @@ public class KitWsServer {
KitWsMessage wsMessage = JSON.parseObject(message, KitWsMessage.class); KitWsMessage wsMessage = JSON.parseObject(message, KitWsMessage.class);
String bizCode = wsMessage.getBizCode(); String bizCode = wsMessage.getBizCode();
Object data = wsMessage.getData(); Object data = wsMessage.getData();
log.info("收到来 sid={} 的信息: message={}, bizCode={}, data={}", sid, message, bizCode, JSON.toJSONString(data)); log.info("收到来 sid={} 的信息: message={}, bizCode={}, data={}", sid, message, bizCode,
JSON.toJSONString(data));
} }
/** /**
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.model; package cn.odboy.framework.websocket.model;
import cn.odboy.base.KitObject; import cn.odboy.base.KitObject;
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.framework.websocket.util; package cn.odboy.framework.websocket.util;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,11 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.annotation.AnonymousAccess; import cn.odboy.annotation.AnonymousAccess;
import cn.odboy.constant.RequestMethodEnum; import cn.odboy.constant.RequestMethodEnum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@@ -27,14 +32,11 @@ import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.*;
/** /**
* 匿名标记工具 * 匿名标记工具
*/ */
@UtilityClass @UtilityClass
public class KitAnonTagUtil { public class KitAnonTagUtil {
/** /**
* 获取匿名标记的URL * 获取匿名标记的URL
* *
@@ -42,7 +44,8 @@ public class KitAnonTagUtil {
* @return / * @return /
*/ */
public static Map<String, Set<String>> getAnonymousUrl(final ApplicationContext applicationContext) { public static Map<String, Set<String>> getAnonymousUrl(final ApplicationContext applicationContext) {
RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping)applicationContext.getBean("requestMappingHandlerMapping"); RequestMappingHandlerMapping requestMappingHandlerMapping =
(RequestMappingHandlerMapping)applicationContext.getBean("requestMappingHandlerMapping");
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods(); Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();
Map<String, java.util.Set<String>> anonymousUrls = new HashMap<>(8); Map<String, java.util.Set<String>> anonymousUrls = new HashMap<>(8);
// 获取匿名标记 // 获取匿名标记
@@ -56,8 +59,10 @@ public class KitAnonTagUtil {
HandlerMethod handlerMethod = infoEntry.getValue(); HandlerMethod handlerMethod = infoEntry.getValue();
AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
if (null != anonymousAccess && infoEntry.getKey() != null) { if (null != anonymousAccess && infoEntry.getKey() != null) {
List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods()); List<RequestMethod> requestMethods =
RequestMethodEnum request = RequestMethodEnum.find(requestMethods.isEmpty() ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name()); new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
RequestMethodEnum request = RequestMethodEnum.find(
requestMethods.isEmpty() ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name());
PatternsRequestCondition patternsCondition = infoEntry.getKey().getPatternsCondition(); PatternsRequestCondition patternsCondition = infoEntry.getKey().getPatternsCondition();
if (patternsCondition != null) { if (patternsCondition != null) {
switch (Objects.requireNonNull(request)) { switch (Objects.requireNonNull(request)) {
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.core.codec.Base64Encoder; import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import lombok.experimental.UtilityClass;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import lombok.experimental.UtilityClass;
/** /**
* 加密令牌生成工具 * 加密令牌生成工具
@@ -30,7 +28,6 @@ import java.nio.charset.StandardCharsets;
*/ */
@UtilityClass @UtilityClass
public final class KitBase64SecretUtil { public final class KitBase64SecretUtil {
public static String build() { public static String build() {
// 128位uuid // 128位uuid
return Base64Encoder.encode(getLongUuid(4).getBytes(StandardCharsets.UTF_8)); return Base64Encoder.encode(getLongUuid(4).getBytes(StandardCharsets.UTF_8));
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,20 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import lombok.experimental.UtilityClass;
/** /**
* 计算类 * 计算类
*/ */
@UtilityClass @UtilityClass
public final class KitBigDecimalUtil { public final class KitBigDecimalUtil {
/** /**
* 将对象转换为 BigDecimal * 将对象转换为 BigDecimal
* *
@@ -139,15 +135,12 @@ public final class KitBigDecimalUtil {
public static void main(String[] args) { public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.123"); BigDecimal num1 = new BigDecimal("10.123");
BigDecimal num2 = new BigDecimal("2.456"); BigDecimal num2 = new BigDecimal("2.456");
System.out.println("加法结果: " + add(num1, num2)); System.out.println("加法结果: " + add(num1, num2));
System.out.println("减法结果: " + subtract(num1, num2)); System.out.println("减法结果: " + subtract(num1, num2));
System.out.println("乘法结果: " + multiply(num1, num2)); System.out.println("乘法结果: " + multiply(num1, num2));
System.out.println("除法结果: " + divide(num1, num2)); System.out.println("除法结果: " + divide(num1, num2));
Long cents = 12345L; Long cents = 12345L;
System.out.println("分转元结果: " + centsToYuan(cents)); System.out.println("分转元结果: " + centsToYuan(cents));
BigDecimal yuan = new BigDecimal("123.45"); BigDecimal yuan = new BigDecimal("123.45");
System.out.println("元转分结果: " + yuanToCents(yuan)); System.out.println("元转分结果: " + yuanToCents(yuan));
} }
@@ -13,17 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.http.useragent.UserAgent; import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil; import cn.hutool.http.useragent.UserAgentUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
/** /**
* 浏览器 相关 * 浏览器 相关
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import lombok.experimental.UtilityClass;
/** /**
* 类 相关 * 类 相关
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,19 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass;
import java.io.Closeable; import java.io.Closeable;
import lombok.experimental.UtilityClass;
/** /**
* 用于关闭各种连接, 缺啥补啥 * 用于关闭各种连接, 缺啥补啥
*/ */
@UtilityClass @UtilityClass
public final class KitCloseUtil { public final class KitCloseUtil {
public static void close(Closeable closeable) { public static void close(Closeable closeable) {
if (null != closeable) { if (null != closeable) {
try { try {
@@ -13,20 +13,23 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.base.KitSelectOptionVo; import cn.odboy.base.KitSelectOptionVo;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import lombok.experimental.UtilityClass;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.*; import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.experimental.UtilityClass;
/** /**
* 集合工具 * 集合工具
@@ -61,7 +64,8 @@ public final class KitCollUtil extends cn.hutool.core.collection.CollUtil {
* @param <U> / * @param <U> /
* @return / * @return /
*/ */
public static <T, U extends Comparable<? super U>> List<T> streamAscSort(List<T> data, Function<? super T, ? extends U> keyExtractor) { public static <T, U extends Comparable<? super U>> List<T> streamAscSort(List<T> data,
Function<? super T, ? extends U> keyExtractor) {
return data.stream().sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList()); return data.stream().sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());
} }
@@ -76,7 +80,8 @@ public final class KitCollUtil extends cn.hutool.core.collection.CollUtil {
* @param <U> / * @param <U> /
* @return / * @return /
*/ */
public static <T, U extends Comparable<? super U>> List<T> streamDescSort(List<T> data, Function<? super T, ? extends U> keyExtractor) { public static <T, U extends Comparable<? super U>> List<T> streamDescSort(List<T> data,
Function<? super T, ? extends U> keyExtractor) {
return data.stream().sorted(Comparator.comparing(keyExtractor).reversed()).collect(Collectors.toList()); return data.stream().sorted(Comparator.comparing(keyExtractor).reversed()).collect(Collectors.toList());
} }
@@ -93,7 +98,8 @@ public final class KitCollUtil extends cn.hutool.core.collection.CollUtil {
* @param <U> / * @param <U> /
* @return / * @return /
*/ */
public static <T, K, U> Map<K, U> streamToMap(List<T> data, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { public static <T, K, U> Map<K, U> streamToMap(List<T> data, Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
// 根据key去重再并流 // 根据key去重再并流
return streamDistinct(data, keyMapper).stream().collect(Collectors.toMap(keyMapper, valueMapper)); return streamDistinct(data, keyMapper).stream().collect(Collectors.toMap(keyMapper, valueMapper));
} }
@@ -185,7 +191,8 @@ public final class KitCollUtil extends cn.hutool.core.collection.CollUtil {
* @return / * @return /
*/ */
public static BigDecimal streamBigDecimalAvg(List<BigDecimal> data) { public static BigDecimal streamBigDecimalAvg(List<BigDecimal> data) {
return data.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(data.size()), 6, RoundingMode.FLOOR); return data.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add)
.divide(BigDecimal.valueOf(data.size()), 6, RoundingMode.FLOOR);
} }
public static void main(String[] args) { public static void main(String[] args) {
@@ -204,7 +211,8 @@ public final class KitCollUtil extends cn.hutool.core.collection.CollUtil {
System.out.println(JSON.toJSONString(selectOptions2)); System.out.println(JSON.toJSONString(selectOptions2));
List<KitSelectOptionVo> selectOptions3 = KitCollUtil.streamDistinct(testData, KitSelectOptionVo::getValue); List<KitSelectOptionVo> selectOptions3 = KitCollUtil.streamDistinct(testData, KitSelectOptionVo::getValue);
System.out.println(JSON.toJSONString(selectOptions3)); System.out.println(JSON.toJSONString(selectOptions3));
Map<String, String> selectMap1 = KitCollUtil.streamToMap(testData, KitSelectOptionVo::getValue, KitSelectOptionVo::getLabel); Map<String, String> selectMap1 =
KitCollUtil.streamToMap(testData, KitSelectOptionVo::getValue, KitSelectOptionVo::getLabel);
System.out.println(JSON.toJSONString(selectMap1)); System.out.println(JSON.toJSONString(selectMap1));
// 这只是一个示范 // 这只是一个示范
BigDecimal total1 = KitCollUtil.streamBigDecimalAdd(testData, "value"); BigDecimal total1 = KitCollUtil.streamBigDecimalAdd(testData, "value");
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import lombok.experimental.UtilityClass;
import java.util.Date; import java.util.Date;
import lombok.experimental.UtilityClass;
/** /**
* 时间相关工具 * 时间相关工具
@@ -69,32 +67,24 @@ public class KitDateUtil {
// 什么都不返回 // 什么都不返回
return ""; return "";
} }
long betweenSeconds = DateUtil.between(startTime, endTime, cn.hutool.core.date.DateUnit.SECOND); long betweenSeconds = DateUtil.between(startTime, endTime, cn.hutool.core.date.DateUnit.SECOND);
long days = betweenSeconds / (24 * 60 * 60); long days = betweenSeconds / (24 * 60 * 60);
long hours = (betweenSeconds % (24 * 60 * 60)) / (60 * 60); long hours = (betweenSeconds % (24 * 60 * 60)) / (60 * 60);
long minutes = (betweenSeconds % (60 * 60)) / 60; long minutes = (betweenSeconds % (60 * 60)) / 60;
long seconds = betweenSeconds % 60; long seconds = betweenSeconds % 60;
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
if (days > 0) { if (days > 0) {
result.append(days).append("天"); result.append(days).append("天");
} }
if (hours > 0) { if (hours > 0) {
result.append(hours).append("时"); result.append(hours).append("时");
} }
if (minutes > 0) { if (minutes > 0) {
result.append(minutes).append("分"); result.append(minutes).append("分");
} }
if (seconds > 0 || result.length() == 0) { if (seconds > 0 || result.length() == 0) {
result.append(seconds).append("秒"); result.append(seconds).append("秒");
} }
return result.toString(); return result.toString();
} }
@@ -110,41 +100,32 @@ public class KitDateUtil {
// 什么都不返回 // 什么都不返回
return ""; return "";
} }
long betweenMs = DateUtil.betweenMs(startTime, endTime); long betweenMs = DateUtil.betweenMs(startTime, endTime);
long days = betweenMs / (24 * 60 * 60 * 1000); long days = betweenMs / (24 * 60 * 60 * 1000);
long hours = (betweenMs % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000); long hours = (betweenMs % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000);
long minutes = (betweenMs % (60 * 60 * 1000)) / (60 * 1000); long minutes = (betweenMs % (60 * 60 * 1000)) / (60 * 1000);
long seconds = (betweenMs % (60 * 1000)) / 1000; long seconds = (betweenMs % (60 * 1000)) / 1000;
long milliseconds = betweenMs % 1000; long milliseconds = betweenMs % 1000;
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
if (days > 0) { if (days > 0) {
result.append(days).append("天"); result.append(days).append("天");
} }
if (hours > 0) { if (hours > 0) {
result.append(hours).append("时"); result.append(hours).append("时");
} }
if (minutes > 0) { if (minutes > 0) {
result.append(minutes).append("分"); result.append(minutes).append("分");
} }
if (seconds > 0) { if (seconds > 0) {
result.append(seconds).append("秒"); result.append(seconds).append("秒");
} }
if (milliseconds > 0) { if (milliseconds > 0) {
result.append(milliseconds).append("毫秒"); result.append(milliseconds).append("毫秒");
} }
// 如果所有单位都是0,则显示0毫秒 // 如果所有单位都是0,则显示0毫秒
if (result.length() == 0) { if (result.length() == 0) {
result.append("0毫秒"); result.append("0毫秒");
} }
return result.toString(); return result.toString();
} }
} }
@@ -13,24 +13,21 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass; import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets; import lombok.experimental.UtilityClass;
/** /**
* DES加密 * DES加密
*/ */
@UtilityClass @UtilityClass
public final class KitDesEncryptUtil { public final class KitDesEncryptUtil {
private static final String STR_PARAM = "Passw0rd"; private static final String STR_PARAM = "Passw0rd";
private static final IvParameterSpec IV = new IvParameterSpec(STR_PARAM.getBytes(StandardCharsets.UTF_8)); private static final IvParameterSpec IV = new IvParameterSpec(STR_PARAM.getBytes(StandardCharsets.UTF_8));
@@ -94,4 +91,3 @@ public final class KitDesEncryptUtil {
return b2; return b2;
} }
} }
@@ -13,11 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/** /**
@@ -43,7 +41,6 @@ public final class KitDistributedIdUtil {
* 序列号所占位数 * 序列号所占位数
*/ */
private final long sequenceBits; private final long sequenceBits;
/** /**
* 数据中心 ID 最大值 * 数据中心 ID 最大值
*/ */
@@ -56,7 +53,6 @@ public final class KitDistributedIdUtil {
* 序列号最大值 * 序列号最大值
*/ */
private final long sequenceMask; private final long sequenceMask;
/** /**
* 机器 ID 向左移位数 * 机器 ID 向左移位数
*/ */
@@ -69,7 +65,6 @@ public final class KitDistributedIdUtil {
* 时间戳向左移位数 * 时间戳向左移位数
*/ */
private final long timestampLeftShift; private final long timestampLeftShift;
/** /**
* 数据中心 ID * 数据中心 ID
*/ */
@@ -96,21 +91,20 @@ public final class KitDistributedIdUtil {
* @param workerIdBits 机器 ID 所占位数 * @param workerIdBits 机器 ID 所占位数
* @param sequenceBits 序列号所占位数 * @param sequenceBits 序列号所占位数
*/ */
public KitDistributedIdUtil(long dataCenterId, long workerId, long dataCenterIdBits, long workerIdBits, long sequenceBits) { public KitDistributedIdUtil(long dataCenterId, long workerId, long dataCenterIdBits, long workerIdBits,
long sequenceBits) {
this.dataCenterIdBits = dataCenterIdBits; this.dataCenterIdBits = dataCenterIdBits;
this.workerIdBits = workerIdBits; this.workerIdBits = workerIdBits;
this.sequenceBits = sequenceBits; this.sequenceBits = sequenceBits;
this.maxDataCenterId = ~(-1L << dataCenterIdBits); this.maxDataCenterId = ~(-1L << dataCenterIdBits);
this.maxWorkerId = ~(-1L << workerIdBits); this.maxWorkerId = ~(-1L << workerIdBits);
this.sequenceMask = ~(-1L << sequenceBits); this.sequenceMask = ~(-1L << sequenceBits);
this.workerIdShift = sequenceBits; this.workerIdShift = sequenceBits;
this.dataCenterIdShift = sequenceBits + workerIdBits; this.dataCenterIdShift = sequenceBits + workerIdBits;
this.timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; this.timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
if (dataCenterId > maxDataCenterId || dataCenterId < 0) { if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException("Data center ID can't be greater than " + maxDataCenterId + " or less than 0"); throw new IllegalArgumentException(
"Data center ID can't be greater than " + maxDataCenterId + " or less than 0");
} }
if (workerId > maxWorkerId || workerId < 0) { if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("Worker ID can't be greater than " + maxWorkerId + " or less than 0"); throw new IllegalArgumentException("Worker ID can't be greater than " + maxWorkerId + " or less than 0");
@@ -151,12 +145,12 @@ public final class KitDistributedIdUtil {
*/ */
public long nextId() { public long nextId() {
long currentTimestamp = System.currentTimeMillis(); long currentTimestamp = System.currentTimeMillis();
// 如果当前时间戳小于上一次生成 ID 的时间戳, 说明时钟回拨,抛出异常 // 如果当前时间戳小于上一次生成 ID 的时间戳, 说明时钟回拨,抛出异常
if (currentTimestamp < lastTimestamp.get()) { if (currentTimestamp < lastTimestamp.get()) {
throw new BadRequestException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp.get() - currentTimestamp) + " milliseconds"); throw new BadRequestException(
"Clock moved backwards. Refusing to generate id for " + (lastTimestamp.get() - currentTimestamp) +
" milliseconds");
} }
long lastTimestampValue = lastTimestamp.get(); long lastTimestampValue = lastTimestamp.get();
if (currentTimestamp == lastTimestampValue) { if (currentTimestamp == lastTimestampValue) {
// 同一毫秒内,序列号自增 // 同一毫秒内,序列号自增
@@ -165,12 +159,14 @@ public final class KitDistributedIdUtil {
// 序列号溢出,等待下一毫秒 // 序列号溢出,等待下一毫秒
currentTimestamp = waitNextMillis(lastTimestampValue); currentTimestamp = waitNextMillis(lastTimestampValue);
} }
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift) | seq; return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) |
(workerId << workerIdShift) | seq;
} else { } else {
// 时间戳改变,重置序列号 // 时间戳改变,重置序列号
sequence.set(0L); sequence.set(0L);
lastTimestamp.set(currentTimestamp); lastTimestamp.set(currentTimestamp);
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift); return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) |
(workerId << workerIdShift);
} }
} }
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
@@ -23,16 +22,11 @@ import cn.hutool.poi.excel.ExcelUtil;
import cn.odboy.constant.FileTypeEnum; import cn.odboy.constant.FileTypeEnum;
import cn.odboy.constant.SystemConst; import cn.odboy.constant.SystemConst;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
import lombok.experimental.UtilityClass; import java.io.File;
import lombok.extern.slf4j.Slf4j; import java.io.FileInputStream;
import org.apache.poi.util.IOUtils; import java.io.IOException;
import org.apache.poi.xssf.streaming.SXSSFSheet; import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile; import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files; import java.nio.file.Files;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.text.DecimalFormat; import java.text.DecimalFormat;
@@ -42,8 +36,19 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.springframework.web.multipart.MultipartFile;
import static cn.odboy.constant.SystemConst.*; import static cn.odboy.constant.SystemConst.SYMBOL_ADD;
import static cn.odboy.constant.SystemConst.SYMBOL_AT;
import static cn.odboy.constant.SystemConst.SYMBOL_EQUAL;
import static cn.odboy.constant.SystemConst.SYMBOL_SUBTRACT;
/** /**
* File工具类, 扩展 hutool 工具包 * File工具类, 扩展 hutool 工具包
@@ -51,7 +56,6 @@ import static cn.odboy.constant.SystemConst.*;
@Slf4j @Slf4j
@UtilityClass @UtilityClass
public final class KitFileUtil extends cn.hutool.core.io.FileUtil { public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* 系统临时目录 * 系统临时目录
* <br> * <br>
@@ -75,7 +79,6 @@ public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
* 定义KB的计算常量 * 定义KB的计算常量
*/ */
private static final int KB = 1024; private static final int KB = 1024;
/** /**
* 格式化小数 * 格式化小数
*/ */
@@ -191,8 +194,8 @@ public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
if (value instanceof String) { if (value instanceof String) {
String strValue = (String)value; String strValue = (String)value;
// 检查并处理以特殊字符开头的值 // 检查并处理以特殊字符开头的值
if (strValue.startsWith(SYMBOL_EQUAL) || strValue.startsWith(SYMBOL_ADD) || strValue.startsWith(SYMBOL_SUBTRACT) || strValue.startsWith( if (strValue.startsWith(SYMBOL_EQUAL) || strValue.startsWith(SYMBOL_ADD) ||
SYMBOL_AT)) { strValue.startsWith(SYMBOL_SUBTRACT) || strValue.startsWith(SYMBOL_AT)) {
// 添加单引号前缀 // 添加单引号前缀
strValue = "'" + strValue; strValue = "'" + strValue;
} }
@@ -324,7 +327,8 @@ public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
* @param response / * @param response /
* @param file / * @param file /
*/ */
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) { public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file,
boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding()); response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream"); response.setContentType("application/octet-stream");
FileInputStream fis = null; FileInputStream fis = null;
@@ -358,10 +362,8 @@ public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
public static String verifyFilename(String fileName) { public static String verifyFilename(String fileName) {
// 过滤掉特殊字符 // 过滤掉特殊字符
fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", ""); fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", "");
// 去掉文件名开头和结尾的空格和点 // 去掉文件名开头和结尾的空格和点
fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", ""); fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", "");
// 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符 // 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符
int maxFileNameLength = 255; int maxFileNameLength = 255;
if (System.getProperty(SystemConst.PROPERTY_OS_NAME).startsWith(SystemConst.OS_NAME_WINDOWS)) { if (System.getProperty(SystemConst.PROPERTY_OS_NAME).startsWith(SystemConst.OS_NAME_WINDOWS)) {
@@ -370,19 +372,15 @@ public final class KitFileUtil extends cn.hutool.core.io.FileUtil {
if (fileName.length() > maxFileNameLength) { if (fileName.length() > maxFileNameLength) {
fileName = fileName.substring(0, maxFileNameLength); fileName = fileName.substring(0, maxFileNameLength);
} }
// 过滤掉控制字符 // 过滤掉控制字符
fileName = fileName.replaceAll("[\\p{Cntrl}]", ""); fileName = fileName.replaceAll("[\\p{Cntrl}]", "");
// 过滤掉 ".." 路径 // 过滤掉 ".." 路径
fileName = fileName.replaceAll("\\.{2,}", ""); fileName = fileName.replaceAll("\\.{2,}", "");
// 去掉文件名开头的 ".." // 去掉文件名开头的 ".."
fileName = fileName.replaceAll("^\\.+/", ""); fileName = fileName.replaceAll("^\\.+/", "");
// 保留文件名中最后一个 "." 字符,过滤掉其他 "." // 保留文件名中最后一个 "." 字符,过滤掉其他 "."
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") + fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2"); fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
return fileName; return fileName;
} }
@@ -13,17 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.framework.context.KitSpringBeanHolder; import cn.odboy.framework.context.KitSpringBeanHolder;
import lombok.experimental.UtilityClass;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.util.Enumeration; import java.util.Enumeration;
import lombok.experimental.UtilityClass;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
/** /**
* IP地址 相关 * IP地址 相关
@@ -55,10 +53,12 @@ public final class KitIPUtil {
try { try {
InetAddress candidateAddress = null; InetAddress candidateAddress = null;
// 遍历所有的网络接口 // 遍历所有的网络接口
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
interfaces.hasMoreElements(); ) {
NetworkInterface anInterface = interfaces.nextElement(); NetworkInterface anInterface = interfaces.nextElement();
// 在所有的接口下再遍历IP // 在所有的接口下再遍历IP
for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) { for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses();
inetAddresses.hasMoreElements(); ) {
InetAddress inetAddr = inetAddresses.nextElement(); InetAddress inetAddr = inetAddresses.nextElement();
// 排除loopback类型地址 // 排除loopback类型地址
if (!inetAddr.isLoopbackAddress()) { if (!inetAddr.isLoopbackAddress()) {
@@ -13,15 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference; import com.alibaba.fastjson2.TypeReference;
import lombok.experimental.UtilityClass;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import lombok.experimental.UtilityClass;
/** /**
* Json工具 * Json工具
@@ -32,13 +30,11 @@ import java.util.Map;
@UtilityClass @UtilityClass
public final class KitJsonUtil { public final class KitJsonUtil {
public static <K, V> Map<K, V> toMap(String jsonStr, Class<K> kClass, Class<V> vClass) { public static <K, V> Map<K, V> toMap(String jsonStr, Class<K> kClass, Class<V> vClass) {
return JSON.parseObject(jsonStr, new TypeReference<Map<K, V>>() { return JSON.parseObject(jsonStr, new TypeReference<Map<K, V>>() {});
});
} }
public static <V> List<V> toList(String jsonStr, Class<V> vClass) { public static <V> List<V> toList(String jsonStr, Class<V> vClass) {
return JSON.parseObject(jsonStr, new TypeReference<List<V>>() { return JSON.parseObject(jsonStr, new TypeReference<List<V>>() {});
});
} }
public static void main(String[] args) { public static void main(String[] args) {
@@ -13,17 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateTime;
import cn.odboy.base.KitBaseUserTimeTb; import cn.odboy.base.KitBaseUserTimeTb;
import lombok.experimental.UtilityClass;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.experimental.UtilityClass;
/** /**
* List 工具 * List 工具
@@ -40,13 +38,14 @@ public final class KitListUtil {
* @param classifier 对象T属性表达式, 比如: User::getName * @param classifier 对象T属性表达式, 比如: User::getName
*/ */
public static <T, K> List<T> distinctByArgs(List<T> items, Function<? super T, ? extends K> classifier) { public static <T, K> List<T> distinctByArgs(List<T> items, Function<? super T, ? extends K> classifier) {
return items.stream().collect(Collectors.groupingBy(classifier)).values().stream().map(monitorItem -> monitorItem.iterator().next()) return items.stream().collect(Collectors.groupingBy(classifier)).values().stream()
.collect(Collectors.toList()); .map(monitorItem -> monitorItem.iterator().next()).collect(Collectors.toList());
} }
/** /**
* list转map, 保留新值 -> Map<String, User> userMap = items.stream().collect(Collectors.toMap(User::getName, user -> user)) <br> list转map, 保留旧值 -> Map<String, * list转map, 保留新值 -> Map<String, User> userMap = items.stream().collect(Collectors.toMap(User::getName, user ->
* User> userMap = users.stream().collect(Collectors.toMap(User::getName, user -> user, (existing, replacement) -> existing)); * user)) <br> list转map, 保留旧值 -> Map<String, User> userMap = users.stream().collect(Collectors.toMap(User::getName,
* user -> user, (existing, replacement) -> existing));
*/ */
public static void main(String[] args) { public static void main(String[] args) {
List<KitBaseUserTimeTb> entities = new ArrayList<>(); List<KitBaseUserTimeTb> entities = new ArrayList<>();
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.base.KitPageResult; import cn.odboy.base.KitPageResult;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.experimental.UtilityClass;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import lombok.experimental.UtilityClass;
/** /**
* 分页工具 * 分页工具
@@ -33,7 +31,6 @@ import java.util.List;
*/ */
@UtilityClass @UtilityClass
public final class KitPageUtil extends cn.hutool.core.util.PageUtil { public final class KitPageUtil extends cn.hutool.core.util.PageUtil {
/** /**
* List 分页 * List 分页
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
@@ -34,7 +33,8 @@ import lombok.experimental.UtilityClass;
public class KitResourceTemplateUtil { public class KitResourceTemplateUtil {
public static String render(String moduleName, String filename, Dict params) { public static String render(String moduleName, String filename, Dict params) {
String path = StrUtil.isBlank(moduleName) ? "template" : "template/" + moduleName; String path = StrUtil.isBlank(moduleName) ? "template" : "template/" + moduleName;
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(path, TemplateConfig.ResourceMode.CLASSPATH)); TemplateEngine engine =
TemplateUtil.createEngine(new TemplateConfig(path, TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate(filename); Template template = engine.getTemplate(filename);
return template.render(params); return template.render(params);
} }
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,17 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
/** /**
* 返回值处理 工具 * 返回值处理 工具
@@ -13,26 +13,28 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.security.*; import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey; import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
/** /**
* Rsa 工具类, 公钥私钥生成, 加解密 * Rsa 工具类, 公钥私钥生成, 加解密
*/ */
@UtilityClass @UtilityClass
public final class KitRsaEncryptUtil { public final class KitRsaEncryptUtil {
private static final String SRC = "123456"; private static final String SRC = "123456";
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@@ -194,7 +196,6 @@ public final class KitRsaEncryptUtil {
* RSA密钥对对象 * RSA密钥对对象
*/ */
public static class RsaKeyPair { public static class RsaKeyPair {
private final String publicKey; private final String publicKey;
private final String privateKey; private final String privateKey;
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,14 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
/** /**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
@@ -29,26 +26,23 @@ import java.util.Date;
@Slf4j @Slf4j
@UtilityClass @UtilityClass
public final class KitStringUtil { public final class KitStringUtil {
private static final char SEPARATOR = '_'; private static final char SEPARATOR = '_';
/** /**
* 驼峰命名法工具 * 驼峰命名法工具
* *
* @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" * @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/ */
public static String toCamelCase(String s) { public static String toCamelCase(String s) {
if (s == null) { if (s == null) {
return null; return null;
} }
s = s.toLowerCase(); s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length()); StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false; boolean upperCase = false;
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); char c = s.charAt(i);
if (c == SEPARATOR) { if (c == SEPARATOR) {
upperCase = true; upperCase = true;
} else if (upperCase) { } else if (upperCase) {
@@ -58,14 +52,14 @@ public final class KitStringUtil {
sb.append(c); sb.append(c);
} }
} }
return sb.toString(); return sb.toString();
} }
/** /**
* 驼峰命名法工具 * 驼峰命名法工具
* *
* @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" * @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/ */
public static String toCapitalizeCamelCase(String s) { public static String toCapitalizeCamelCase(String s) {
if (s == null) { if (s == null) {
@@ -78,24 +72,21 @@ public final class KitStringUtil {
/** /**
* 驼峰命名法工具 * 驼峰命名法工具
* *
* @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" * @return toCamelCase(" hello_world ") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/ */
public static String toUnderScoreCase(String s) { public static String toUnderScoreCase(String s) {
if (s == null) { if (s == null) {
return null; return null;
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
boolean upperCase = false; boolean upperCase = false;
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); char c = s.charAt(i);
boolean nextUpperCase = true; boolean nextUpperCase = true;
if (i < (s.length() - 1)) { if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
} }
if ((i > 0) && Character.isUpperCase(c)) { if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) { if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR); sb.append(SEPARATOR);
@@ -104,10 +95,8 @@ public final class KitStringUtil {
} else { } else {
upperCase = false; upperCase = false;
} }
sb.append(Character.toLowerCase(c)); sb.append(Character.toLowerCase(c));
} }
return sb.toString(); return sb.toString();
} }
@@ -1,4 +1,3 @@
/* /*
* Copyright 2021-2025 Odboy * Copyright 2021-2025 Odboy
* *
@@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import oshi.SystemInfo; import oshi.SystemInfo;
@@ -13,19 +13,17 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.util; package cn.odboy.util;
import cn.odboy.framework.exception.BadRequestException; import cn.odboy.framework.exception.BadRequestException;
import lombok.experimental.UtilityClass; import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolation;
import javax.validation.Validation; import javax.validation.Validation;
import javax.validation.Validator; import javax.validation.Validator;
import javax.validation.ValidatorFactory; import javax.validation.ValidatorFactory;
import javax.validation.groups.Default; import javax.validation.groups.Default;
import java.util.Set; import lombok.experimental.UtilityClass;
import java.util.stream.Collectors;
/** /**
* Bean验证工具 * Bean验证工具
@@ -46,7 +44,8 @@ public final class KitValidUtil {
public static <T> void validate(T object) { public static <T> void validate(T object) {
Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object, Default.class); Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object, Default.class);
if (!violations.isEmpty()) { if (!violations.isEmpty()) {
throw new BadRequestException(violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","))); throw new BadRequestException(
violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
} }
} }
} }
-2
View File
@@ -7,10 +7,8 @@
<version>1.4.1</version> <version>1.4.1</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cutejava-module-system</artifactId> <artifactId>cutejava-module-system</artifactId>
<name>核心模块</name> <name>核心模块</name>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>cn.odboy</groupId> <groupId>cn.odboy</groupId>
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.system.constant; package cn.odboy.system.constant;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -25,19 +24,14 @@ import lombok.Getter;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum SystemCaptchaBizEnum { public enum SystemCaptchaBizEnum {
/* 通过手机号码重置邮箱 */ /* 通过手机号码重置邮箱 */
PHONE_RESET_EMAIL_CODE("10000", "phone_reset_email_code_", "SystemEmailCaptchaTemplate.ftl", "通过手机号码重置邮箱"), PHONE_RESET_EMAIL_CODE("10000", "phone_reset_email_code_", "SystemEmailCaptchaTemplate.ftl",
"通过手机号码重置邮箱"), /* 通过旧邮箱重置邮箱 */
/* 通过旧邮箱重置邮箱 */
EMAIL_RESET_EMAIL_CODE("10001", "email_reset_email_code_", "SystemEmailCaptchaTemplate.ftl", "通过旧邮箱重置邮箱"), EMAIL_RESET_EMAIL_CODE("10001", "email_reset_email_code_", "SystemEmailCaptchaTemplate.ftl", "通过旧邮箱重置邮箱"),
/* 通过手机号码重置密码 */ /* 通过手机号码重置密码 */
PHONE_RESET_PWD_CODE("10002", "phone_reset_pwd_code_", "SystemEmailCaptchaTemplate.ftl", "通过手机号码重置密码"), PHONE_RESET_PWD_CODE("10002", "phone_reset_pwd_code_", "SystemEmailCaptchaTemplate.ftl", "通过手机号码重置密码"),
/* 通过邮箱重置密码 */ /* 通过邮箱重置密码 */
EMAIL_RESET_PWD_CODE("10003", "email_reset_pwd_code_", "SystemEmailCaptchaTemplate.ftl", "通过邮箱重置密码"); EMAIL_RESET_PWD_CODE("10003", "email_reset_pwd_code_", "SystemEmailCaptchaTemplate.ftl", "通过邮箱重置密码");
/** /**
* 业务编码 * 业务编码
*/ */
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package cn.odboy.system.constant; package cn.odboy.system.constant;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -25,16 +24,10 @@ import lombok.Getter;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum SystemDataScopeEnum { public enum SystemDataScopeEnum {
/* 全部的数据权限 */ /* 全部的数据权限 */
ALL("全部", "全部的数据权限"), ALL("全部", "全部的数据权限"), /* 自己部门的数据权限 */
THIS_LEVEL("本级", "自己部门的数据权限"), /* 自定义的数据权限 */
/* 自己部门的数据权限 */
THIS_LEVEL("本级", "自己部门的数据权限"),
/* 自定义的数据权限 */
CUSTOMIZE("自定义", "自定义的数据权限"); CUSTOMIZE("自定义", "自定义的数据权限");
private final String value; private final String value;
private final String description; private final String description;

Some files were not shown because too many files have changed in this diff Show More