提交 0d372a39 编写于 作者: sq3536's avatar sq3536

init

上级 4f6069f5
*volumes
*target
.settings
*node_modules
*bin
*.project
*.classpath
*.factorypath
.history
.vscode
.idea
**.iml
*.jar
*.log
.DS_Store
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ibizlab-boot-starter-parent</artifactId>
<groupId>cn.ibizlab</groupId>
<version>2.4.0-SNAPSHOT</version>
<relativePath>../ibizlab-boot-starter-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ibizlab-boot-starter-data</artifactId>
<groupId>cn.ibizlab</groupId>
<version>2.4.0-SNAPSHOT</version>
<name>iBizLab Boot Starter Data</name>
<description>iBizLab Boot Starter Data</description>
<dependencies>
<dependency>
<groupId>cn.ibizlab</groupId>
<artifactId>ibizlab-boot-starter</artifactId>
<version>${parent.version}</version>
</dependency>
<!-- 阿里Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- H2内存库 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>jobs-spring-boot-starter</artifactId>
<version>${baomidou-jobs.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- drools -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
</dependency>
<dependency>
<groupId>org.flowable</groupId>
<artifactId>flowable-json-converter</artifactId>
</dependency>
<dependency>
<groupId>org.flowable</groupId>
<artifactId>flowable-ui-modeler-conf</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.ibizlab.util.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD})
public @interface Audit
{
}
package cn.ibizlab.util.annotation;
import cn.ibizlab.util.enums.DEFieldDefaultValueType;
import cn.ibizlab.util.enums.DEPredefinedFieldType;
import cn.ibizlab.util.enums.DupCheck;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD})
public @interface DEField
{
/**
* 属性名称
* @return
*/
String name() default "";
/**
* 属性名称
* @return
*/
String value() default "";
/**
* 是否为数据主键
* @return
*/
boolean isKeyField() default false;
/**
* 默认值
* @return
*/
String defaultValue() default "";
/**
* 属性类型
* @return
*/
String fieldType() default"";
/**
* 默认值类型
* @return
*/
DEFieldDefaultValueType defaultValueType() default DEFieldDefaultValueType.NONE;
/**
* 预置属性类型
* @return
*/
DEPredefinedFieldType preType() default DEPredefinedFieldType.NONE;
/**
* 逻辑删除有效值
* @return
*/
String logicval() default "";
/**
* 逻辑删除无效值
* @return
*/
String logicdelval() default "";
/**
* 代码表
* @return
*/
String dict() default "";
/**
* 日期格式化
* @return
*/
String format() default "";
/**
* 重复性检查
* @return
*/
DupCheck dupCheck() default DupCheck.NONE;
/**
* 范围属性
*/
String dupCheckField() default "";
boolean dynaInstTagField() default false;
}
package cn.ibizlab.util.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface VersionCheck
{
String entity();
String versionfield();
}
package cn.ibizlab.util.domain;
import lombok.Data;
import org.flowable.bpmn.model.Process;
import org.springframework.core.io.Resource;
import org.kie.api.runtime.KieContainer;
import java.io.File;
import java.io.Serializable;
import java.util.List;
@Data
public class DELogic implements Serializable {
String id;
String name;
Process process;
KieContainer container;
List<DELogic> refLogic;
List<Resource> refRuleFiles;
String md5;
int logicMode;
long loadedTime;
}
package cn.ibizlab.util.domain;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.annotation.Transient;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Data
public class DTOBase implements Serializable {
@JsonIgnore
@JSONField(serialize = false)
private Set<String> focusNull;
public void modify(String field,Object val) {
if(val==null) {
this.getFocusNull(true).add(field.toLowerCase());
}
else {
this.getFocusNull(true).remove(field.toLowerCase());
}
}
@JsonIgnore
@JSONField(serialize = false)
public Set<String> getFocusNull() {
if(focusNull==null) {
focusNull=new HashSet<>();
}
if(focusNull.size()>0 && extensionparams.containsKey("dirtyflagenable"))
{
Set<String> nocheck=new HashSet<>();
for(String key:focusNull)
{
if(!extensionparams.containsKey(key+"dirtyflag")) {
nocheck.add(key);
}
}
for(String key:nocheck) {
focusNull.remove(key);
}
}
return focusNull;
}
private Set<String> getFocusNull(boolean newflag) {
if(focusNull==null) {
focusNull=new HashSet<>();
}
return focusNull;
}
@JsonIgnore
@JSONField(serialize = false)
private Map<String,Object> extensionparams=new HashMap<String,Object>();
@JsonIgnore
@JSONField(serialize = false)
public Map<String, Object> getExtensionparams() {
return extensionparams;
}
public void setExtensionparams(Map<String, Object> extensionparams) {
this.extensionparams = extensionparams;
}
@JsonAnyGetter
@JSONField(name = "_any", unwrapped = true, serialize = true, deserialize = false)
public Map<String , Object> any() {
return extensionparams;
}
@JsonIgnore
@JSONField(serialize = false)
@Transient
private BeanMap map;
@JsonIgnore
@JSONField(serialize = false)
@Transient
private BeanMap getMap()
{
if(map==null) {
map=BeanMap.create(this);
}
return map;
}
public Object get(String field) {
String fieldRealName= DEFieldCacheMap.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
return getMap().get(fieldRealName);
}
else {
return this.extensionparams.get(field.toLowerCase());
}
}
@JsonAnySetter
@JSONField(name = "_any", unwrapped = true, serialize = false, deserialize = true)
public void set(String field, Object value) {
field=field.toLowerCase();
String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
if (value == null) {
getMap().put(fieldRealName, null);
}
else {
getMap().put(fieldRealName, DEFieldCacheMap.fieldValueOf(this.getClass(), fieldRealName, value));
}
}
else {
this.extensionparams.put(field.toLowerCase(),value);
}
}
}
package cn.ibizlab.util.domain;
public class DTOClient extends DTOBase {
@Override
public void modify(String field,Object val) {
getExtensionparams().put("dirtyflagenable",true);
if(val==null){
this.getFocusNull().add(field.toLowerCase());
getExtensionparams().put(field.toLowerCase()+"dirtyflag",true);
}
else{
this.getFocusNull().remove(field.toLowerCase());
getExtensionparams().remove(field.toLowerCase()+"dirtyflag");
}
}
}
package cn.ibizlab.util.domain;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.annotation.Transient;
import org.springframework.util.AlternativeJdkIdGenerator;
import org.springframework.util.ObjectUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import org.springframework.util.StringUtils;
import java.util.*;
public class EntityBase implements Serializable {
@JsonIgnore
@JSONField(serialize = false)
@TableField(exist = false)
@Transient
private Set<String> focusNull;
@JsonIgnore
@JSONField(serialize = false)
@Transient
public Set<String> getFocusNull() {
if(focusNull==null) {
focusNull=new HashSet<>();
}
return focusNull;
}
public void setFocusNull(Set<String> focusNull) {
this.focusNull = focusNull;
}
public void modify(String field,Object val) {
}
public Serializable getDefaultKey(boolean gen) {
String Id=(new AlternativeJdkIdGenerator()).generateId().toString();
return gen?Id.replace("-", ""):Id;
}
@JsonIgnore
@JSONField(serialize = false)
@TableField(exist = false)
@Transient
private BeanMap map;
@JsonIgnore
@JSONField(serialize = false)
@Transient
private BeanMap getMap()
{
if(map==null) {
map=BeanMap.create(this);
}
return map;
}
@JsonIgnore
@TableField(exist = false)
@JSONField(serialize = false)
@Transient
private Map<String,Object> extensionparams=new HashMap<String,Object>();
@JsonIgnore
@JSONField(serialize = false)
@Transient
public Map<String, Object> getExtensionparams() {
return extensionparams;
}
public void setExtensionparams(Map<String, Object> extensionparams) {
this.extensionparams = extensionparams;
}
public Object get(String field) {
String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
return getMap().get(fieldRealName);
}
else {
return this.extensionparams.get(field.toLowerCase());
}
}
@JsonAnyGetter
@JSONField(name = "_any", unwrapped = true, serialize = true, deserialize = false)
public Map<String , Object> any() {
return extensionparams;
}
@JsonAnySetter
@JSONField(name = "_any", unwrapped = true, serialize = false, deserialize = true)
public void set(String field, Object value) {
field=field.toLowerCase();
String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
if (value == null) {
getMap().put(fieldRealName, null);
}
else {
getMap().put(fieldRealName, DEFieldCacheMap.fieldValueOf(this.getClass(), fieldRealName, value));
}
}
else {
this.extensionparams.put(field.toLowerCase(),value);
}
}
/**
* 复制当前对象数据到目标对象
* @param targetEntity 目标数据对象
* @param bIncEmpty 是否包括空值
* @param <T>
* @return
*/
public <T> T copyTo(T targetEntity, boolean bIncEmpty){
if(targetEntity instanceof EntityBase){
EntityBase target= (EntityBase) targetEntity;
Hashtable<String, Field> sourceFields=DEFieldCacheMap.getFieldMap(this.getClass());
for(String field : sourceFields.keySet()){
Object value=this.get(field);
if( !ObjectUtils.isEmpty(value) || ObjectUtils.isEmpty(value) && getFocusNull().contains(field) && bIncEmpty ){
target.set(field,value);
}
}
}
return targetEntity;
}
/**
* 重置当前数据对象属性值
* @param field
*/
public void reset(String field){
}
}
\ No newline at end of file
package cn.ibizlab.util.domain;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
public class EntityClient extends EntityBase {
@Override
public void modify(String field,Object val) {
getExtensionparams().put("dirtyflagenable",true);
if(val==null){
this.getFocusNull().add(field.toLowerCase());
getExtensionparams().put(field.toLowerCase()+"dirtyflag",true);
}
else{
this.getFocusNull().remove(field.toLowerCase());
getExtensionparams().remove(field.toLowerCase()+"dirtyflag");
}
}
@Override
public void reset(String field) {
if(!ObjectUtils.isEmpty(field)){
String resetField=field.toLowerCase();
this.set(resetField,null);
this.getFocusNull().remove(resetField);
getExtensionparams().remove(resetField+"dirtyflag");
}
}
}
package cn.ibizlab.util.domain;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
public class EntityMP extends EntityBase {
public UpdateWrapper getUpdateWrapper(boolean clean) {
UpdateWrapper wrapper=new UpdateWrapper();
for(String nullField:getFocusNull()) {
wrapper.set(nullField,null);
}
if(clean) {
getFocusNull().clear();
}
return wrapper;
}
@Override
public void modify(String field,Object val) {
if(val==null) {
this.getFocusNull().add(field.toLowerCase());
}
else {
this.getFocusNull().remove(field.toLowerCase());
}
}
@Override
public void reset(String field){
if(!ObjectUtils.isEmpty(field)){
String resetField=field.toLowerCase();
this.set(resetField,null);
getFocusNull().remove(resetField);
}
}
}
package cn.ibizlab.util.domain;
public class EntityMongo extends EntityBase {
}
package cn.ibizlab.util.domain;
import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.sql.Timestamp;
@TableName(value = "IBZCFG")
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class IBZConfig {
/**
* 配置标识
* 系统+配置类型+引用对象+用户标识联合主键
*/
@TableId
private String cfgId;
/**
* 系统标识
*/
private String systemId;
/**
* 配置类型
* 门户配置/表格自定义配置/自定义查询...消费方自定义
*/
private String cfgType;
/**
* 引用对象
* 门户页标识/具体表格视图标识...消费方具体使用位置的标识
*/
private String targetType;
/**
* 用户标识
* 默认当前登录者
*/
private String userId;
/**
* 配置
* JSONObject
*/
private String cfg;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", locale = "zh" , timezone="GMT+8")
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Timestamp updateDate;
public String getCfgId()
{
if(ObjectUtils.isEmpty(cfgId)&&
(!(ObjectUtils.isEmpty(systemId)))&&
(!(ObjectUtils.isEmpty(cfgType)))&&
(!(ObjectUtils.isEmpty(targetType)))&&
(!(ObjectUtils.isEmpty(userId))))
{
cfgId= DigestUtils.md5DigestAsHex((systemId+"||"+cfgType+"||"+targetType+"||"+userId).getBytes());
}
return cfgId;
}
}
package cn.ibizlab.util.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Objects;
/**
* 实体[DataAudit] 数据对象
*/
@TableName(value = "IBZDATAAUDIT")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class IBZDataAudit implements Serializable{
@TableId(value= "dataauditid",type=IdType.UUID)//指定主键生成策略
private String dataauditid;
private String dataauditname;
private String oppersonid;
private String oppersonname;
private String audittype;
private Timestamp optime;
private String ipaddress;
private String auditinfo;
private Object auditobjectdata;
private String auditobject;
private int isdatachanged;
}
\ No newline at end of file
package cn.ibizlab.util.domain;
import java.sql.Timestamp;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* 实体[IBZUSER] 数据对象
*/
@TableName(value = "IBZUSER")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class IBZUSER implements Serializable{
@Size(min = 0, max = 100, message = "[用户标识]长度必须在[100]以内!")
@TableId(value= "userid",type=IdType.INPUT)//指定主键生成策略
private String userid;
@Size(min = 0, max = 200, message = "[用户全局名]长度必须在[200]以内!")
private String username;
@Size(min = 0, max = 100, message = "[用户姓名]长度必须在[100]以内!")
private String personname;
@Size(min = 0, max = 100, message = "[用户代码]长度必须在[100]以内!")
private String usercode;
@Size(min = 0, max = 100, message = "[登录别名]长度必须在[100]以内!")
private String loginname;
@Size(min = 0, max = 100, message = "[登录密码]长度必须在[100]以内!")
private String password;
@Size(min = 0, max = 100, message = "[区属]长度必须在[100]以内!")
private String domains;
@Size(min = 0, max = 100, message = "[主部门id]长度必须在[100]以内!")
private String mdeptid;
@Size(min = 0, max = 100, message = "[主部门代码]长度必须在[100]以内!")
private String mdeptcode;
@Size(min = 0, max = 200, message = "[主部门名称]长度必须在[200]以内!")
private String mdeptname;
@Size(min = 0, max = 100, message = "[业务编码]长度必须在[100]以内!")
private String bcode;
@Size(min = 0, max = 100, message = "[岗位id]长度必须在[100]以内!")
private String postid;
@Size(min = 0, max = 100, message = "[岗位代码]长度必须在[100]以内!")
private String postcode;
@Size(min = 0, max = 200, message = "[岗位名称]长度必须在[200]以内!")
private String postname;
@Size(min = 0, max = 100, message = "[单位id]长度必须在[100]以内!")
private String orgid;
@Size(min = 0, max = 100, message = "[单位代码]长度必须在[100]以内!")
private String orgcode;
@Size(min = 0, max = 200, message = "[单位名称]长度必须在[200]以内!")
private String orgname;
@Size(min = 0, max = 36, message = "[昵称]长度必须在[36]以内!")
private String nickname;
@Size(min = 0, max = 100, message = "[邮箱]长度必须在[100]以内!")
private String email;
@Size(min = 0, max = 100, message = "[通信账号]长度必须在[100]以内!")
private String avatar;
@Size(min = 0, max = 100, message = "[联系电话]长度必须在[100]以内!")
private String phone;
@Size(min = 0, max = 100, message = "[保留字段]长度必须在[100]以内!")
private String reserver;
@Size(min = 0, max = 100, message = "[头像]长度必须在[100]以内!")
private String usericon;
@Size(min = 0, max = 10, message = "[性别]长度必须在[10]以内!")
private String sex;
private Timestamp birthday;
@Size(min = 0, max = 36, message = "[证件号码]长度必须在[36]以内!")
private String certcode;
@Size(min = 0, max = 200, message = "[地址]长度必须在[200]以内!")
private String addr;
@Size(min = 0, max = 100, message = "[主题]长度必须在[100]以内!")
private String theme;
@Size(min = 0, max = 100, message = "[语言]长度必须在[100]以内!")
private String lang;
@Size(min = 0, max = 10, message = "[字号]长度必须在[10]以内!")
private String fontsize;
@Size(min = 0, max = 500, message = "[备注]长度必须在[500]以内!")
private String memo;
private int superuser;
}
\ No newline at end of file
package cn.ibizlab.util.domain;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
public class LiquibaseProp{
private String url;
private String username;
private String password;
private String isSyncDBSchema;
private String defaultSchema;
private String conf;
}
\ No newline at end of file
package cn.ibizlab.util.domain;
import java.util.List;
/**
* 实体转换器基类
* @param <D> domainDTO
* @param <E> domain
*/
public interface MappingBase<D, E> {
/**
* dto转domain
* @param dto
* @return
*/
E toDomain(D dto);
/**
* domain转dto
* @param entity
* @return
*/
D toDto(E entity);
/**
* dto集合转domain集合
* @param dtoList
* @return
*/
List <E> toDomain(List<D> dtoList);
/**
* domain集合转dto集合
* @param entityList
* @return
*/
List <D> toDto(List<E> entityList);
}
package cn.ibizlab.util.enums;
/**
* 实体属性默认值类型
*/
public enum DEFieldDefaultValueType {
/**
* 用户全局对象
*/
SESSION,
/**
* 系统全局对象
*/
APPLICATION,
/**
* 唯一编码
*/
UNIQUEID,
/**
* 网页请求
*/
CONTEXT,
/**
* 数据对象属性
*/
PARAM,
/**
* 当前时间
*/
CURTIME,
/**
* 当前操作用户(编号)
*/
OPERATOR,
/**
* 当前操作用户(名称)
*/
OPERATORNAME,
/**
* 当前应用数据
*/
APPDATA,
/**
* 默认值
*/
NONE,
/**
* 用户自定义
*/
USER,
/**
* 用户自定义2
*/
USER2,
/**
* 用户自定义3
*/
USER3,
/**
* 用户自定义4
*/
USER4
}
package cn.ibizlab.util.enums;
/**
* 实体属性预定义类型
*/
public enum DEPredefinedFieldType {
/**
* 创建人标识
*/
CREATEMAN,
/**
* 创建人名称
*/
CREATEMANNAME,
/**
* 更新人标识
*/
UPDATEMAN,
/**
* 更新人名称
*/
UPDATEMANNAME,
/**
* 创建时间
*/
CREATEDATE,
/**
* 更新时间
*/
UPDATEDATE,
/**
* 组织机构标识
*/
ORGID,
/**
* 组织机构名称
*/
ORGNAME,
/**
* 部门标识
*/
ORGSECTORID,
/**
* 部门名称
*/
ORGSECTORNAME,
/**
* 逻辑有效
*/
LOGICVALID,
/**
* 排序
*/
ORDERVALUE,
/**
* 不处理
*/
NONE,
/**
* 动态父类型
*/
PARENTTYPE,
/**
* 动态父标识
*/
PARENTID,
/**
* 动态父名称
*/
PARENTNAME
}
package cn.ibizlab.util.enums;
/**
* 属性重复值检查
*/
public enum DupCheck {
/**
* 不检查
*/
NONE,
/**
* 全部检查
*/
ALL,
/**
* 非空检查
*/
NOTNULL,
/**
* 指定范围检查
*/
RANGE,
}
package cn.ibizlab.util.filter;
public interface ISearchContext {
}
package cn.ibizlab.util.filter;
import com.fasterxml.jackson.annotation.*;
import org.springframework.data.annotation.Transient;
import java.util.*;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class QueryFilter {
public static QueryFilter createQuery()
{
QueryFilter queryFilter=new QueryFilter();
return queryFilter;
}
public QueryFilter eq(String column,Object value) {
return op(column,SegmentCond.eq(value));
}
public QueryFilter ne(String column,Object value) {
return op(column,SegmentCond.ne(value));
}
public QueryFilter gt(String column,Object value) {
return op(column,SegmentCond.gt(value));
}
public QueryFilter ge(String column,Object value) {
return op(column,SegmentCond.ge(value));
}
public QueryFilter lt(String column,Object value) {
return op(column,SegmentCond.lt(value));
}
public QueryFilter le(String column,Object value) {
return op(column,SegmentCond.le(value));
}
public QueryFilter isnull(String column) {
return op(column,SegmentCond.isnull());
}
public QueryFilter isnotnull(String column) {
return op(column,SegmentCond.isnotnull());
}
public QueryFilter in(String column,Collection value) {
return op(column,SegmentCond.in(value));
}
public QueryFilter notin(String column,Collection value) {
return op(column,SegmentCond.notin(value));
}
public QueryFilter like(String column,String value) {
return op(column,SegmentCond.like(value));
}
public QueryFilter startsWith(String column,String value) {
return op(column,SegmentCond.startsWith(value));
}
public QueryFilter endsWith(String column,String value) {
return op(column,SegmentCond.endsWith(value));
}
public QueryFilter between(String column,Object from,Object to) {
return op(column,SegmentCond.between(from,to));
}
@JsonIgnore
@Transient
private Map<String,SegmentCond> map;
private Map<String,SegmentCond> getMap()
{
if(map==null) {
map=new LinkedHashMap<>();
}
return map;
}
@JsonAnyGetter
public Map<String , SegmentCond> any() {
return getMap();
}
@JsonAnySetter
public void set(String column, SegmentCond value) {
getMap().put(column,value);
}
@JsonProperty(index = 999)
private List<QueryFilter> $or;
public List<QueryFilter> get$or() {
return $or;
}
public void set$or(List<QueryFilter> $or) {
this.$or = $or;
}
public QueryFilter or(QueryFilter... ors)
{
if ($or == null) {
$or = new ArrayList();
}
Collections.addAll($or, ors);
return this;
}
@JsonProperty(index = 999)
private List<QueryFilter> $and;
public List<QueryFilter> get$and() {
return $and;
}
public void set$and(List<QueryFilter> $and) {
this.$and = $and;
}
public QueryFilter and(QueryFilter... ands)
{
if ($and == null) {
$and = new ArrayList();
}
Collections.addAll($and, ands);
return this;
}
@Override
public String toString() {
return "QueryFilter{" +
"map=" + map +
", $or=" + $or +
'}';
}
private QueryFilter op(String column, SegmentCond segmentCond) {
if(this.getMap().containsKey(column)) {
((SegmentCond)this.getMap().get(column)).getMap().putAll(segmentCond.getMap());
}
else {
this.getMap().put(column,segmentCond);
}
return this;
}
public static class SegmentCond {
@JsonIgnore
@Transient
private Map<String,Object> map;
@Override
public String toString() {
return "SegmentCond{" +
"map=" + map +
'}';
}
private Map<String,Object> getMap()
{
if(map==null) {
map=new LinkedHashMap<>();
}
return map;
}
@JsonAnyGetter
public Map<String , Object> any() {
return getMap();
}
@JsonAnySetter
public void set(String column, Object value) {
getMap().put(column,value);
}
public static SegmentCond eq(Object value) {
return op(Segment.EQ,value);
}
public static SegmentCond ne(Object value) {
return op(Segment.NE,value);
}
public static SegmentCond gt(Object value) {
return op(Segment.GT,value);
}
public static SegmentCond ge(Object value) {
return op(Segment.GE,value);
}
public static SegmentCond lt(Object value) {
return op(Segment.LT,value);
}
public static SegmentCond le(Object value) {
return op(Segment.LE,value);
}
public static SegmentCond isnull() {
return op(Segment.IS_NULL,true);
}
public static SegmentCond isnotnull() {
return op(Segment.IS_NOT_NULL,true);
}
public static SegmentCond in(Collection value) {
return op(Segment.IN,value);
}
public static SegmentCond notin(Collection value) {
return op(Segment.NOTIN,value);
}
public static SegmentCond like(String value) {
return op(Segment.LIKE,value);
}
public static SegmentCond startsWith(String value) {
return op(Segment.LEFTLIKE,value);
}
public static SegmentCond endsWith(String value) {
return op(Segment.RIGHTLIKE,value);
}
public static SegmentCond between(Object from,Object to) {
return op(Segment.GE,from).op(Segment.LT,to);
}
private static SegmentCond op(Segment segment,Object value) {
SegmentCond segmentCond=new SegmentCond();
segmentCond.getMap().put(segment.keyword,value);
return segmentCond;
}
}
public enum Segment {
AND("$and"),
OR("$or"),
EQ("$eq"),
NE("$ne"),
GT("$gt"),
GE("$gte"),
LT("$lt"),
LE("$lte"),
IS_NULL("$null"),
IS_NOT_NULL("$notNull"),
IN("$in"),
NOTIN("$notIn"),
LIKE("$like"),
LEFTLIKE("$startsWith"),
RIGHTLIKE("$endsWith"),
EXISTS("$exists"),
NOTEXISTS("$notExists");
private final String keyword;
Segment(final String keyword) {
this.keyword = keyword;
}
}
/*
SQL: (field1>1 and field2='3' and (field3 like "a" or (field4 is not null and field5 in ['11','12']) )
JAVA: QueryFilter filter=QueryFilter.createQuery()
.gt("field1",1)
.eq("field2",'3')
.or(QueryFilter.createQuery().like("field3","a")
,QueryFilter.createQuery().isnotnull("field4").in("field5",Arrays.asList("11","12")));
JSON: {
"$or":[
{
"field3":{"$like":"a"}
},
{
"field4":{ "$notNull":true},
"field5":{"$in":["11","12"]}
}],
"field1":{"$gt":1},
"field2":{"$eq":"3" }
}
*/
}
package cn.ibizlab.util.filter;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.ParameterizedType;
import java.util.*;
import java.util.function.Consumer;
@Slf4j
@Data
public class QueryWrapperContext<T> extends SearchContextBase implements ISearchContext{
@JsonIgnore
@JSONField(serialize = false)
private QueryWrapper<T> selectCond=new QueryWrapper<T>();
/**
* 解析查询上下文中的参数,构建mybatis-plus分页对象
* @return
*/
@JsonIgnore
@JSONField(serialize = false)
public Page getPages(){
Page page;
List<String> asc_fieldList = new ArrayList<>();
List<String> desc_fieldList = new ArrayList<>();
int currentPage=getPageable().getPageNumber();
int pageSize=getPageable().getPageSize();
//构造mybatis-plus分页
if(ObjectUtils.isEmpty(currentPage) || ObjectUtils.isEmpty(pageSize)) {
page=new Page(1,Short.MAX_VALUE);
}
else {
page=new Page(currentPage+1,pageSize);
}
//构造mybatis-plus排序
Sort sort = getPageable().getSort();
Iterator<Sort.Order> it_sort = sort.iterator();
if(ObjectUtils.isEmpty(it_sort)) {
return page;
}
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> type = (Class<T>)parameterizedType.getActualTypeArguments()[0];
while (it_sort.hasNext()) {
Sort.Order sort_order = it_sort.next();
if(sort_order.getDirection()== Sort.Direction.ASC){
asc_fieldList.add(DEFieldCacheMap.getFieldColumnName(type,sort_order.getProperty()));
}
else if(sort_order.getDirection()== Sort.Direction.DESC){
desc_fieldList.add(DEFieldCacheMap.getFieldColumnName(type,sort_order.getProperty()));
}
}
if(asc_fieldList.size()>0){
page.setAscs(asc_fieldList);
}
if(desc_fieldList.size()>0){
page.setDescs(desc_fieldList);
}
return page;
}
public QueryWrapper<T> getSearchCond(){
return this.selectCond;
}
/**
* 填充自定义查询条件
* @return
*/
public QueryWrapper<T> getSelectCond() {
if(!ObjectUtils.isEmpty(filter)){
Consumer queryWrapper = parseQueryFilter(filter);
if(!ObjectUtils.isEmpty(queryWrapper)){
selectCond.and(queryWrapper);
}
}
return selectCond;
}
/**
* 解析自定义查询条件
* @param queryFilter
* @return
*/
private Consumer<QueryWrapper<T>> parseQueryFilter(QueryFilter queryFilter){
if(queryFilter.any().size()==0 && queryFilter.get$or()==null && queryFilter.get$and()==null) {
return null;
}
Consumer<QueryWrapper<T>> consumer = queryWrapper -> {
Consumer fieldConsumer=parseFieldMap(queryFilter.any());
Consumer orConsumer=parseOrQueryFilter(queryFilter.get$or());
Consumer andConsumer=parseAndQueryFilter(queryFilter.get$and());
if(!ObjectUtils.isEmpty(fieldConsumer)){
queryWrapper.and(fieldConsumer);
}
if(!ObjectUtils.isEmpty(orConsumer)){
queryWrapper.and(orConsumer);
}
if(!ObjectUtils.isEmpty(andConsumer)){
queryWrapper.and(andConsumer);
}
};
return consumer;
}
/**
* 解析自定义条件[or]
* @param queryFilters
* @return
*/
private Consumer<QueryWrapper<T>> parseOrQueryFilter(List<QueryFilter> queryFilters) {
if(queryFilters==null || queryFilters.size()==0)
return null;
Consumer<QueryWrapper<T>> consumer = queryWrapper -> {
for(QueryFilter queryFilter: queryFilters){
Consumer tempQueryWrapper=parseQueryFilter(queryFilter);
queryWrapper.or(tempQueryWrapper);
}
};
return consumer;
}
/**
* 解析自定义条件[and]
* @param queryFilters
* @return
*/
private Consumer<QueryWrapper<T>> parseAndQueryFilter(List<QueryFilter> queryFilters) {
if(queryFilters==null || queryFilters.size()==0) {
return null;
}
Consumer<QueryWrapper<T>> consumer = queryWrapper -> {
for(QueryFilter queryFilter: queryFilters){
Consumer tempQueryWrapper=parseQueryFilter(queryFilter);
queryWrapper.and(tempQueryWrapper);
}
};
return consumer;
}
/**
* 解析自定义条件[字段条件]
* @param fieldMap
* @return
*/
private Consumer<QueryWrapper<T>> parseFieldMap(Map<String , QueryFilter.SegmentCond> fieldMap) {
if(fieldMap.size()==0) {
return null;
}
Consumer<QueryWrapper<T>> consumer = queryWrapper -> {
for(Map.Entry<String, QueryFilter.SegmentCond> field: fieldMap.entrySet()){
String fieldName=field.getKey();
QueryFilter.SegmentCond segmentCond=field.getValue();
Map<String , Object> segmentCondMap = segmentCond.any();
for(Map.Entry<String , Object> fieldCond: segmentCondMap.entrySet()){
Object value=fieldCond.getValue();
switch (fieldCond.getKey()){
case "$eq":
queryWrapper.eq(fieldName,value);
break;
case "$ne":
queryWrapper.ne(fieldName,value);
break;
case "$gt":
queryWrapper.gt(fieldName,value);
break;
case "$gte":
queryWrapper.ge(fieldName,value);
break;
case "$lt":
queryWrapper.lt(fieldName,value);
break;
case "$lte":
queryWrapper.le(fieldName,value);
break;
case "$null":
queryWrapper.isNull(fieldName);
break;
case "$notNull":
queryWrapper.isNotNull(fieldName);
break;
case "$in":
queryWrapper.in(fieldName,(Collection)value);
break;
case "$notIn":
queryWrapper.notIn(fieldName,(Collection)value);
break;
case "$like":
queryWrapper.like(fieldName,value);
break;
case "$startsWith":
queryWrapper.likeRight(fieldName,value);
break;
case "$endsWith":
queryWrapper.likeLeft(fieldName,value);
break;
case "$exists":
break;
case "$notExists":
break;
}
}
}
};
return consumer;
}
}
package cn.ibizlab.util.filter;
import cn.ibizlab.util.security.AuthenticationUser;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.util.ObjectUtils;
import java.util.*;
@Slf4j
@Data
public class SearchContextBase implements ISearchContext{
/**
* 自定义查询条件
*/
@JsonProperty("customcond")
public String customCond;
/**
* 自定义查询参数
*/
@JsonProperty("customparams")
public String customParams;
/**
* 快速搜索
*/
@JsonProperty("query")
public String query;
/**
* 条件表达式
*/
@JsonProperty("filter")
public QueryFilter filter;
/**
* 数据查询
*/
public List dataQueryList;
/**
* 当前页数
*/
public int page=0;
/**
* 每页显示条数
*/
public int size=20;
/**
* 排序
*/
public String sort;
/**
* 排序对象
*/
@JsonIgnore
public Sort pageSort;
/**
* 工作流步骤标识
*/
public String userTaskId;
/**
* 工作流流程标识
*/
public String processDefinitionKey;
/**
* 工作流标识
*/
@JsonProperty("srfwf")
public String srfWF;
/**
* 获取工作流步骤标识
*/
public String getUserTaskId() {
if(ObjectUtils.isEmpty(userTaskId)){
Object taskId=params.get("usertaskid");
return ObjectUtils.isEmpty(taskId)?null:String.valueOf(taskId);
}else{
return userTaskId;
}
}
/**
* 获取工作流流程标识
* @return
*/
public String getProcessDefinitionKey() {
if(ObjectUtils.isEmpty(processDefinitionKey)){
Object processKey=params.get("processdefinitionkey");
return ObjectUtils.isEmpty(processKey)?null:String.valueOf(processKey);
}
else{
return processDefinitionKey;
}
}
/**
* 获取分页参数
* @return
*/
public Pageable getPageable() {
if(ObjectUtils.isEmpty(pageSort)) {
return PageRequest.of(page,size);
}
else {
return PageRequest.of(page,size,pageSort);
}
}
/**
* 设置排序值
* @param strSort
*/
public void setSort(String strSort) {
this.sort=strSort;
if(!ObjectUtils.isEmpty(strSort)){
String sortArr[]=strSort.split(",");
String sortField=sortArr[0];
String sortDirection=sortArr[1];
if(sortDirection.equalsIgnoreCase("asc")){
this.pageSort=Sort.by(Sort.Direction.ASC,sortField);
}
else if(sortDirection.equalsIgnoreCase("desc")){
this.pageSort=Sort.by(Sort.Direction.DESC,sortField);
}
}
}
/**
* 上下文参数
*/
Map<String,Object> params = new HashMap<String,Object>() ;
/**
* 获取数据上下文
* @return
*/
public Map<String,Object> getDatacontext() {
return params;
}
/**
* 获取网页请求上下文
* @return
*/
public Map<String,Object> getWebcontext() {
return params;
}
/**
* 获取用户上下文
* @return
*/
@JsonIgnore
public Map<String,Object> getSessioncontext() {
return AuthenticationUser.getAuthenticationUser().getSessionParams();
}
@JsonAnyGetter
public Map<String , Object> any() {
return params;
}
@JsonAnySetter
public void set(String name, Object value) {
params.put(name, value);
}
}
package cn.ibizlab.util.helper;
import cn.ibizlab.util.annotation.Audit;
import cn.ibizlab.util.annotation.DEField;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* 实体对象属性缓存类
*/
public class DEFieldCacheMap {
private static Hashtable<String, Hashtable<String,Field>> cacheMap = new Hashtable<>();
private static Hashtable<String, List<Field>> cacheList = new Hashtable<>();
private static Hashtable<String, Hashtable<String,String>> cacheKey = new Hashtable<>();
private static Hashtable<String, Hashtable<String,DEField>> cacheDEField = new Hashtable<>();
private static Hashtable<String, Hashtable<String,Audit>> cacheAuditField = new Hashtable<>();
private static Hashtable<String, String> cacheDEKeyField = new Hashtable<>();
private static Object objLock1=new Object();
/**
* 将实体对象中的属性存入缓存中
* @param
* @return
*/
public static <T> Hashtable<String,Field> getFieldMap(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheMap.containsKey(className)) {
return cacheMap.get(className);
}
synchronized (objLock1) {
if(cacheMap.containsKey(className)) {
return cacheMap.get(className);
}
Hashtable<String,Field> result = new Hashtable<String,Field>();
List<Field> list=new ArrayList<Field>();
Hashtable<String,String> keys=new Hashtable<String,String>();
Hashtable<String,DEField> defields=new Hashtable<>();
Hashtable<String, Audit> auditfields=new Hashtable<>();
Hashtable<String,String> dekeyfields=new Hashtable<>();
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields){
result.put(field.getName(),field);
list.add(field);
keys.put(field.getName().toLowerCase(),field.getName());
DEField deField=field.getAnnotation(DEField.class);
Audit auditField=field.getAnnotation(Audit.class);
if(!ObjectUtils.isEmpty(deField)) {
defields.put(field.getName(),deField);
if(deField.isKeyField()) {
cacheDEKeyField.put(className,field.getName());
}
}
if(!ObjectUtils.isEmpty(auditField)) {
auditfields.put(field.getName(),auditField);
}
}
cacheMap.put(className, result);
cacheList.put(className,list);
cacheKey.put(className,keys);
cacheDEField.put(className,defields);
cacheAuditField.put(className,auditfields);
return result;
}
}
public static Hashtable<String,Field> getFieldMap(String className) {
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheMap.containsKey(className)) {
return cacheMap.get(className);
}
Class clazz = null;
try {
clazz = Class.forName(className);
return getFieldMap(clazz);
}
catch (Exception ex) {
cacheMap.put(className, new Hashtable<String,Field>());
return cacheMap.get(className);
}
}
/**
* 从缓存中查询实体对象属性集合
* @param
* @return
*/
public static <T> Hashtable<String,DEField> getDEFields(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheDEField.containsKey(className)) {
return cacheDEField.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheDEField.get(className);
}
}
/**
* 从缓存中查询审计属性集合
* @param
* @return
*/
public static <T> Hashtable<String,Audit> getAuditFields(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheAuditField.containsKey(className)) {
return cacheAuditField.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheAuditField.get(className);
}
}
/**
* 从缓存中查询实体对象主键
* @param
* @return
*/
public static <T> String getDEKeyField(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheDEKeyField.containsKey(className)) {
return cacheDEKeyField.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheDEKeyField.get(className);
}
}
/**
* 从缓存中查询实体对象属性列表
* @param
* @return
*/
public static <T> List<Field> getFields(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheList.containsKey(className)) {
return cacheList.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheList.get(className);
}
}
public static List<Field> getFields(String className) {
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheList.containsKey(className)) {
return cacheList.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheList.get(className);
}
}
/**
* 从缓存中查询实体对象属性列表
* @param
* @return
*/
public static <T> Hashtable<String,String> getFieldKeys(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cacheKey.containsKey(className)) {
return cacheKey.get(className);
}
else{
DEFieldCacheMap.getFieldMap(className);
return cacheKey.get(className);
}
}
public static <T> String getFieldRealName(Class<T> clazz,String fieldname) {
fieldname=fieldname.toLowerCase();
Hashtable<String,String> keys=DEFieldCacheMap.getFieldKeys(clazz);
if(keys.containsKey(fieldname)) {
return keys.get(fieldname);
}
else if(keys.containsKey(fieldname.replace("_",""))) {
return keys.get(fieldname.replace("_",""));
}
else {
return "";
}
}
public static <T> Field getField(Class<T> clazz,String fieldname) {
String fieldRealName=DEFieldCacheMap.getFieldRealName(clazz,fieldname);
if(!ObjectUtils.isEmpty(fieldRealName)) {
return DEFieldCacheMap.getFieldMap(clazz).get(fieldRealName);
}
else {
return null;
}
}
public static <T> String getFieldColumnName(Class<T> clazz,String fieldname) {
Field field = DEFieldCacheMap.getField(clazz,fieldname);
if(field!=null) {
DEField deField=field.getAnnotation(DEField.class);
if(deField!=null&& !ObjectUtils.isEmpty(deField.name()))
return deField.name();
}
return fieldname;
}
public static <T> Object fieldValueOf(Class<T> clazz,String fieldname,Object fieldValue) {
if(fieldValue==null)
return null;
Object resultValue=fieldValue;
Field field = DEFieldCacheMap.getField(clazz,fieldname);
if(field!=null) {
Class<?> type=field.getType();
resultValue = DataObject.objectValueOf(type,fieldValue);
}
return resultValue;
}
}
\ No newline at end of file
package cn.ibizlab.util.helper;
import org.springframework.core.convert.converter.Converter;
import java.sql.Timestamp;
import java.time.*;
import java.util.Date;
/**
* <p>JSR310DateConverters class.</p>
*/
public final class JSR310DateConverters {
private JSR310DateConverters() {
}
public static class TimestampToDateConverter implements Converter<Timestamp, Date> {
public static final TimestampToDateConverter INSTANCE = new TimestampToDateConverter();
private TimestampToDateConverter() {
}
@Override
public Date convert(Timestamp source) {
return source == null ? null : new Date(source.getTime());
}
}
public static class DateToTimestampConverter implements Converter<Date, Timestamp> {
public static final DateToTimestampConverter INSTANCE = new DateToTimestampConverter();
private DateToTimestampConverter() {
}
@Override
public Timestamp convert(Date source) {
return source == null ? null : new Timestamp(source.getTime());
}
}
public static class LocalDateToDateConverter implements Converter<LocalDate, Date> {
public static final LocalDateToDateConverter INSTANCE = new LocalDateToDateConverter();
private LocalDateToDateConverter() {
}
@Override
public Date convert(LocalDate source) {
return source == null ? null : Date.from(source.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}
public static class DateToLocalDateConverter implements Converter<Date, LocalDate> {
public static final DateToLocalDateConverter INSTANCE = new DateToLocalDateConverter();
private DateToLocalDateConverter() {
}
@Override
public LocalDate convert(Date source) {
return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault())
.toLocalDate();
}
}
public static class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
public static final ZonedDateTimeToDateConverter INSTANCE = new ZonedDateTimeToDateConverter();
private ZonedDateTimeToDateConverter() {
}
@Override
public Date convert(ZonedDateTime source) {
return source == null ? null : Date.from(source.toInstant());
}
}
public static class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
public static final DateToZonedDateTimeConverter INSTANCE = new DateToZonedDateTimeConverter();
private DateToZonedDateTimeConverter() {
}
@Override
public ZonedDateTime convert(Date source) {
return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
public static class LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
public static final LocalDateTimeToDateConverter INSTANCE = new LocalDateTimeToDateConverter();
private LocalDateTimeToDateConverter() {
}
@Override
public Date convert(LocalDateTime source) {
return source == null ? null : Date.from(source.atZone(ZoneId.systemDefault()).toInstant());
}
}
public static class DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
public static final DateToLocalDateTimeConverter INSTANCE = new DateToLocalDateTimeConverter();
private DateToLocalDateTimeConverter() {
}
@Override
public LocalDateTime convert(Date source) {
return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
public static class DurationToLongConverter implements Converter<Duration, Long> {
public static final DurationToLongConverter INSTANCE = new DurationToLongConverter();
private DurationToLongConverter() {
}
@Override
public Long convert(Duration source) {
return source == null ? null : source.toNanos();
}
}
public static class LongToDurationConverter implements Converter<Long, Duration> {
public static final LongToDurationConverter INSTANCE = new LongToDurationConverter();
private LongToDurationConverter() {
}
@Override
public Duration convert(Long source) {
return source == null ? null : Duration.ofNanos(source);
}
}
}
\ No newline at end of file
package cn.ibizlab.util.helper;
import cn.ibizlab.util.domain.EntityBase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class Setting {
private String property;
private String value;
public static String getValue(String configString,String propertyName)
{
return DataObject.getStringValue(getMap(configString).get(propertyName),"");
}
public static <T extends EntityBase> T getEntity(String configString,T entityBase)
{
if(entityBase!=null) {
Map map=getMap(configString);
map.keySet().forEach(key->{
entityBase.set(key.toString(),map.get(key));
});
}
return entityBase;
}
public static Map getMap(String configString)
{
Map map=new HashMap();
map.put("param",configString);
if(!(ObjectUtils.isEmpty(configString)))
{
try
{
Object obj=JSON.parse(configString);
if(obj==null)
return map;
else if (obj instanceof JSONArray)
{
List<Setting> settings= JSONArray.parseArray(configString,Setting.class);
for(Setting setting:settings)
map.put(setting.getProperty(),setting.getValue());
}
else if (obj instanceof JSONObject)
{
JSONObject jo = (JSONObject)obj;
jo.keySet().forEach(key->{
map.put(key,jo.get(key));
});
}
}
catch (Exception ex)
{
if(configString.indexOf("=")>0)
{
Properties proper = new Properties();
try {
proper.load(new StringReader(configString)); //把字符串转为reader
} catch (IOException e) {
}
Enumeration enum1 = proper.propertyNames();
while (enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = proper.getProperty(strKey);
map.put(strKey, strValue);
}
}
}
}
return map;
}
}
package cn.ibizlab.util.mapper;
import cn.ibizlab.util.domain.IBZConfig;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface IBZConfigMapper extends BaseMapper<IBZConfig>{
}
\ No newline at end of file
package cn.ibizlab.util.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.ibizlab.util.domain.IBZDataAudit;
public interface IBZDataAuditMapper extends BaseMapper<IBZDataAudit> {
}
\ No newline at end of file
package cn.ibizlab.util.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.ibizlab.util.domain.IBZUSER;
public interface IBZUSERMapper extends BaseMapper<IBZUSER>{
}
\ No newline at end of file
package cn.ibizlab.util.rest;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.service.IBZConfigService;
import com.alibaba.fastjson.JSONObject;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.service.AuthenticationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import java.util.*;
@RestController
@RequestMapping(value = "")
public class ConfigController {
@Autowired
private IBZConfigService ibzConfigService;
@RequestMapping(method = RequestMethod.PUT, value = "/configs/{configType}/{targetType}")
public ResponseEntity<Boolean> saveConfig(@PathVariable("configType") String configType, @PathVariable("targetType") String targetType, @RequestBody JSONObject config) {
String userId=AuthenticationUser.getAuthenticationUser().getUserid();
if(ObjectUtils.isEmpty(userId)){
throw new BadRequestAlertException("保存配置失败,参数缺失","IBZConfig",configType);
}
return ResponseEntity.ok(ibzConfigService.saveConfig(configType,targetType,userId,config));
}
@RequestMapping(method = RequestMethod.GET, value = "/configs/{configType}/{targetType}")
public ResponseEntity<JSONObject> getConfig(@PathVariable("configType") String configType, @PathVariable("targetType") String targetType) {
String userId=AuthenticationUser.getAuthenticationUser().getUserid();
if(ObjectUtils.isEmpty(userId)){
throw new BadRequestAlertException("获取配置失败,参数缺失","IBZConfig",configType);
}
return ResponseEntity.ok(ibzConfigService.getConfig(configType,targetType,userId));
}
@RequestMapping(method = RequestMethod.GET, value = "/configs/share/{id}")
public ResponseEntity<JSONObject> getShareConfig(@PathVariable("id") String id) {
JSONObject jo = ibzConfigService.getShareConfig(id);
if (jo == null) {
throw new BadRequestAlertException("无效的共享配置数据", "IBZConfig", id);
}
return ResponseEntity.ok(jo);
}
@RequestMapping(method = RequestMethod.GET, value = "/configs/share/{configType}/{targetType}")
public ResponseEntity<String> shareConfig(@PathVariable("configType") String configType, @PathVariable("targetType") String targetType) {
String userId = AuthenticationUser.getAuthenticationUser().getUserid();
if (ObjectUtils.isEmpty(userId)) {
throw new BadRequestAlertException("分享配置失败,参数缺失", "IBZConfig", configType);
}
String id = IdWorker.get32UUID();
ibzConfigService.saveShareConfig(id, configType, targetType, userId);
return ResponseEntity.ok(id);
}
/**
* 应用参数扩展
* @param appData
*/
protected void fillAppData(JSONObject appData){
}
}
package cn.ibizlab.util.service;
import cn.ibizlab.util.domain.IBZConfig;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.DataObject;
import cn.ibizlab.util.mapper.IBZConfigMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
@Slf4j
@Service
public class IBZConfigService extends ServiceImpl<IBZConfigMapper, IBZConfig> implements IService<IBZConfig> {
@Value("${ibiz.systemid:ibznotify}")
private String systemId;
@Value("${ibiz.admin.userid:0100}")
private String adminuserid;
@Cacheable(value="ibzrt_configs",key = "'cfgid:'+#p0+'||'+#p1+'||'+#p2")
public JSONObject getConfig(String cfgType,String targetType,String userId)
{
if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(cfgType) || ObjectUtils.isEmpty(targetType)) {
throw new BadRequestAlertException("获取配置失败,参数缺失","IBZConfig",cfgType);
}
IBZConfig config = this.getOne(Wrappers.query(IBZConfig.builder().systemId(systemId).cfgType(cfgType).targetType(targetType).userId(userId).build()), false);
if(config == null) {
config = this.getOne(Wrappers.query(IBZConfig.builder().systemId(systemId).cfgType(cfgType).targetType(targetType).userId(adminuserid).build()), false);
if(config == null) {
return new JSONObject();
}
}
return JSON.parseObject(config.getCfg());
}
@CacheEvict(value="ibzrt_configs", key = "'cfgid:'+#p0+'||'+#p1+'||'+#p2")
public boolean saveConfig(String cfgType, String targetType, String userId, JSONObject config)
{
if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(cfgType) || ObjectUtils.isEmpty(targetType)) {
throw new BadRequestAlertException("保存配置失败,参数缺失","IBZConfig",cfgType);
}
String cfg = "{}";
if(config != null) {
cfg = JSONObject.toJSONString(config);
}
return this.saveOrUpdate(IBZConfig.builder().systemId(systemId).cfgType(cfgType).targetType(targetType).userId(userId).cfg(cfg).updateDate(DataObject.getNow()).build());
}
@CacheEvict(value = "ibzrt_configs", key = "'cfgid:'+#p0+'||'+#p1+'||'+#p2")
public void resetConfig(String cfgType, String targetType, String userId)
{
if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(cfgType) || ObjectUtils.isEmpty(targetType)) {
throw new BadRequestAlertException("重置配置失败,参数缺失","IBZConfig",cfgType);
}
this.remove(Wrappers.query(IBZConfig.builder().systemId(systemId).cfgType(cfgType).targetType(targetType).userId(userId).build()));
}
@Cacheable(value="ibzrt_shareconfigs",key = "'cfgid:'+#p0")
public JSONObject saveShareConfig(String id, String cfgType,String targetType,String userId){
return this.getConfig(cfgType, targetType, userId);
}
@Cacheable(value="ibzrt_shareconfigs",key = "'cfgid:'+#p0")
public JSONObject getShareConfig(String id){
return null;
}
}
\ No newline at end of file
package cn.ibizlab.util.service;
import cn.ibizlab.util.annotation.Audit;
import cn.ibizlab.util.domain.EntityBase;
import org.springframework.scheduling.annotation.Async;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 实体[DataAudit] 服务对象接口
*/
public interface IBZDataAuditService {
@Async("asyncExecutor")
void createAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields);
@Async("asyncExecutor")
void updateAudit(HttpServletRequest request, EntityBase beforeEntity, Object serviceObj, Object idValue, Map<String, Audit> auditFields);
@Async("asyncExecutor")
void removeAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields);
}
\ No newline at end of file
package cn.ibizlab.util.web;
import cn.ibizlab.util.filter.SearchContextBase;
import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResolvedMethodParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spi.service.contexts.ParameterContext;
import springfox.documentation.spring.web.plugins.DocumentationPluginsManager;
import springfox.documentation.spring.web.readers.parameter.ExpansionContext;
import springfox.documentation.spring.web.readers.parameter.ModelAttributeParameterExpander;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Predicates.*;
import static com.google.common.collect.Lists.*;
import static springfox.documentation.schema.Collections.*;
import static springfox.documentation.schema.Maps.*;
import static springfox.documentation.schema.Types.*;
//@Component
//@Order(Ordered.HIGHEST_PRECEDENCE)
public class IBZOperationParameterReader implements OperationBuilderPlugin {
private final ModelAttributeParameterExpander expander;
private final EnumTypeDeterminer enumTypeDeterminer;
@Autowired
private DocumentationPluginsManager pluginsManager;
@Autowired
public IBZOperationParameterReader(
ModelAttributeParameterExpander expander,
EnumTypeDeterminer enumTypeDeterminer) {
this.expander = expander;
this.enumTypeDeterminer = enumTypeDeterminer;
}
@Override
public void apply(OperationContext context) {
context.operationBuilder().parameters(context.getGlobalOperationParameters());
context.operationBuilder().parameters(readParameters(context));
}
@Override
public boolean supports(DocumentationType delimiter) {
return true;
}
private List<Parameter> readParameters(final OperationContext context) {
List<ResolvedMethodParameter> methodParameters = context.getParameters();
List<Parameter> parameters = newArrayList();
for (ResolvedMethodParameter methodParameter : methodParameters) {
ResolvedType alternate = context.alternateFor(methodParameter.getParameterType());
if (!shouldIgnore(methodParameter, alternate, context.getIgnorableParameterTypes())) {
ParameterContext parameterContext = new ParameterContext(methodParameter,
new ParameterBuilder(),
context.getDocumentationContext(),
context.getGenericsNamingStrategy(),
context);
if (shouldExpand(methodParameter, alternate)) {
parameters.addAll(
expander.expand(
new ExpansionContext("", alternate, context)));
} else {
parameters.add(pluginsManager.parameter(parameterContext));
}
}
}
return FluentIterable.from(parameters).filter(not(hiddenParams())).toList();
}
private Predicate<Parameter> hiddenParams() {
return new Predicate<Parameter>() {
@Override
public boolean apply(Parameter input) {
return input.isHidden();
}
};
}
private boolean shouldIgnore(
final ResolvedMethodParameter parameter,
ResolvedType resolvedParameterType,
final Set<Class> ignorableParamTypes) {
if (ignorableParamTypes.contains(resolvedParameterType.getErasedType())) {
return true;
}
return FluentIterable.from(ignorableParamTypes)
.filter(isAnnotation())
.filter(parameterIsAnnotatedWithIt(parameter)).size() > 0;
}
private Predicate<Class> parameterIsAnnotatedWithIt(final ResolvedMethodParameter parameter) {
return new Predicate<Class>() {
@Override
public boolean apply(Class input) {
return parameter.hasParameterAnnotation(input);
}
};
}
private Predicate<Class> isAnnotation() {
return new Predicate<Class>() {
@Override
public boolean apply(Class input) {
return Annotation.class.isAssignableFrom(input);
}
};
}
private boolean shouldExpand(final ResolvedMethodParameter parameter, ResolvedType resolvedParamType) {
return !parameter.hasParameterAnnotation(RequestBody.class)
&& !parameter.hasParameterAnnotation(RequestPart.class)
&& !parameter.hasParameterAnnotation(RequestParam.class)
&& !parameter.hasParameterAnnotation(PathVariable.class)
&& !isBaseType(typeNameFor(resolvedParamType.getErasedType()))
&& !enumTypeDeterminer.isEnum(resolvedParamType.getErasedType())
&& !isContainerType(resolvedParamType)
&& !isMapType(resolvedParamType)
&& !SearchContextBase.class.isAssignableFrom(resolvedParamType.getErasedType());
}
}
package cn.ibizlab.util.web;
import cn.ibizlab.util.filter.SearchContextBase;
import cn.ibizlab.util.domain.DTOBase;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class SearchContextHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Value("${ibiz.pageLimit:1000}")
private int pageLimit=1000;
private static ObjectMapper objectMapper=new ObjectMapper();
@Override
public boolean supportsParameter(MethodParameter parameter) {
return SearchContextBase.class.isAssignableFrom(parameter.getParameterType()) || DTOBase.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Map<String, String[]> params = webRequest.getParameterMap();
LinkedHashMap<String,Object> set = new LinkedHashMap<>();
for (String key : params.keySet()) {
set.put(key,params.get(key)[0]);
}
if(SearchContextBase.class.isAssignableFrom(parameter.getParameterType()) && (!set.containsKey("size"))){
set.put("size", pageLimit);
}
String json = objectMapper.writeValueAsString(set);
return objectMapper.readValue(json, parameter.getParameterType());
}
}
\ No newline at end of file
此差异已折叠。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ibizlab-boot-starter-parent</artifactId>
<groupId>cn.ibizlab</groupId>
<version>2.4.0-SNAPSHOT</version>
<relativePath>../ibizlab-boot-starter-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ibizlab-boot-starter</artifactId>
<groupId>cn.ibizlab</groupId>
<version>2.4.0-SNAPSHOT</version>
<name>iBizLab Boot Starter</name>
<description>iBizLab Boot Starter</description>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo-shaded</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<!--MapStruct高性能属性映射工具-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.ibizlab.util.cache;
import cn.ibizlab.util.cache.cacheManager.CaffeineCacheManager;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;
/**
* Caffeine缓存配置类
*/
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
@ConditionalOnExpression("'${ibiz.cacheLevel:None}'.equals('L1')")
public class CaffeineCacheConfig {
/**
* Caffeine配置:设置过期时间
* @return
*/
@Bean
@Primary
public CacheManager cacheManager(CacheProperties cacheProperties) {
CaffeineCacheManager caffeineCacheManager=new CaffeineCacheManager();
String strCacheConfig = cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(strCacheConfig)) {
caffeineCacheManager.setCaffeineCacheConfig(CaffeineSpec.parse(strCacheConfig));
}
return caffeineCacheManager;
}
}
\ No newline at end of file
package cn.ibizlab.util.cache;
import cn.ibizlab.util.cache.cacheManager.LayeringCacheManager;
import cn.ibizlab.util.cache.listener.RedisMessageListener;
import cn.ibizlab.util.cache.redis.CustomJacksonSerializer;
import cn.ibizlab.util.enums.RedisChannelTopic;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import java.time.Duration;
/**
* 缓存配置类
* 1级缓存为caffeine
* 2级缓存为redis
*/
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
@ConditionalOnExpression("'${ibiz.cacheLevel:None}'.equals('L2')")
public class RedisCacheConfig {
@Value("${spring.cache.redis.time-to-live:3600}")
private long timeToLive;
/**
* 分层缓存管理器
* @param redisConnectionFactory
* @param cacheProperties
* @return
*/
@Bean
@Primary
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory ,CacheProperties cacheProperties){
LayeringCacheManager layeringCacheManager=new LayeringCacheManager(redisCacheWriter(redisConnectionFactory),redisCacheConfiguration(),redisTemplate(redisConnectionFactory));
String strCacheConfig = cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(strCacheConfig)) {
layeringCacheManager.setCaffeineCacheConfig(CaffeineSpec.parse(strCacheConfig));
}
return layeringCacheManager;
}
/**
* redis配置:设置过期时间及序列化方式
* @return
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(){
CustomJacksonSerializer jackson2JsonRedisSerializer = new CustomJacksonSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(timeToLive))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
return configuration;
}
/**
* 创建redis缓存
* @param connectionFactory
* @return
*/
@Bean
public RedisCacheWriter redisCacheWriter(RedisConnectionFactory connectionFactory){
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
return redisCacheWriter;
}
/**
* 发送redis广播
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
CustomJacksonSerializer jacksonSerial = new CustomJacksonSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jacksonSerial.setObjectMapper(om);
template.setValueSerializer(jacksonSerial);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSerial);
template.afterPropertiesSet();
return template;
}
/**
* 监听redis指定频道
* @param redisConnectionFactory
* @param cacheManager
* @param redisTemplate
* @return
*/
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, CacheManager cacheManager , RedisTemplate redisTemplate) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
MessageListenerAdapter messageListener=new RedisMessageListener(cacheManager,redisTemplate);
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(messageListener, RedisChannelTopic.REDIS_CACHE_DELETE_TOPIC.getChannelTopic());
container.addMessageListener(messageListener, RedisChannelTopic.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic());
container.addMessageListener(messageListener, RedisChannelTopic.REDIS_CACHE_DYNAMICMODEL_TOPIC.getChannelTopic());
return container;
}
}
\ No newline at end of file
package cn.ibizlab.util.cache.cache;
import cn.ibizlab.util.helper.Globs;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCache;
import javax.validation.constraints.NotNull;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 自定义的Caffeine缓存
*/
public class CusCaffeineCache extends CaffeineCache{
public CusCaffeineCache(String name, Cache<Object, Object> cache) {
super(name,cache);
}
public CusCaffeineCache(String name, Cache<Object, Object> cache, boolean allowNullValues) {
super(name,cache,allowNullValues);
}
@Override
public void evict(@NotNull Object key) {
if (key instanceof String && ((String) key).startsWith("glob:")) {
String globPattern = ((String)key).split("glob:")[1];
// 将Glob匹配转换成正则匹配
String regexPattern = Globs.toUnixRegexPattern(globPattern);
// String regexPattern = Globs.toWindowsRegexPattern(globPattern);
Cache<Object,Object> cache = super.getNativeCache();
Set<Object> keySet = cache.asMap().keySet();
keySet = keySet.stream().filter(o->o.toString().matches(regexPattern)).collect(Collectors.toSet());
cache.invalidateAll(keySet);
}else{
super.evict(key);
}
}
}
package cn.ibizlab.util.cache.cache;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import javax.validation.constraints.NotNull;
/**
* 自定义的redis缓存
*/
public class CusRedisCache extends RedisCache {
public CusRedisCache(String name, RedisCacheWriter redisCacheWriter, RedisCacheConfiguration configuration) {
super(name, redisCacheWriter, configuration);
}
@Override
public void evict(@NotNull Object key) {
if (key instanceof String && ((String) key).startsWith("glob:")) {
String globPattern = ((String)key).split("glob:")[1];
byte[] globPatternBytes = super.getCacheConfiguration().getConversionService().convert(globPattern,byte[].class);
if(globPatternBytes!=null){
super.getNativeCache().clean(super.getName(),globPatternBytes);
}
}else{
super.evict(key);
}
}
}
package cn.ibizlab.util.cache.cache;
import cn.ibizlab.util.cache.listener.RedisPublisher;
import cn.ibizlab.util.enums.RedisChannelTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.AbstractValueAdaptingCache;
import org.springframework.cache.support.NullValue;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.util.ObjectUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* 缓存分层类
* 1级缓存为caffeine
* 2级缓存为redis
*/
@Slf4j
public class LayeringCache extends AbstractValueAdaptingCache {
/**
* 缓存的名称
*/
private String cacheName;
/**
* Caffeine缓存
*/
private CaffeineCache caffeineCache;
/**
* redis缓存
*/
private RedisCache redisCache;
/**
* redis消息发布
*/
RedisOperations<? extends Object, ? extends Object> redisOperations;
public LayeringCache(String cacheName , CaffeineCache caffeineCache, RedisCache redisCache, RedisOperations redisOperations) {
super(true);
this.cacheName = cacheName;
this.caffeineCache = caffeineCache;
this.redisCache = redisCache;
this.redisOperations=redisOperations;
}
@Override
public String getName() {
return this.cacheName;
}
@Override
public Object getNativeCache() {
return this;
}
@Override
public ValueWrapper get(Object key) {
ValueWrapper wrapper = caffeineCache.get(key);
Object value = ObjectUtils.isEmpty(wrapper) ? null : wrapper.get();
log.debug("查询一级缓存 key:{} ", key, value);
if (ObjectUtils.isEmpty(value)) {
wrapper = redisCache.get(key);
value = ObjectUtils.isEmpty(wrapper) ? null : wrapper.get();
log.debug("查询二级缓存 key:{} ", key);
if (!ObjectUtils.isEmpty(value)) {
caffeineCache.put(key, value);
log.debug("查询二级缓存,并将数据放到一级缓存。 key:{} ", key);
}
}
return wrapper;
}
@Override
public <T> T get(Object key, Class<T> type) {
T value = caffeineCache.get(key, type);
log.debug("查询一级缓存 key:{}", key);
if (value == null) {
value = redisCache.get(key, type);
caffeineCache.put(key, value);
log.debug("查询二级缓存,并将数据放到一级缓存。 key:{}", key);
}
return value;
}
@SuppressWarnings("unchecked")
@Override
public <T> T get(Object key, Callable<T> valueLoader) {
T value = (T) caffeineCache.getNativeCache().get(key, k -> getSecondCacheValue(k, valueLoader));
if(value==null) {
value = (T) getSecondCacheValue(key, valueLoader);
}
if (value instanceof NullValue) {
return null;
}
return value;
}
@Override
public void put(Object key, Object value) {
if(value!=null) {
caffeineCache.put(key, value);
redisCache.put(key, value);
}
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
caffeineCache.putIfAbsent(key, value);
return redisCache.putIfAbsent(key, value);
}
@Override
public void evict(Object key) {
redisCache.evict(key); //清除redis中的二级缓存
caffeineCache.evict(key);//清除本机一级缓存
Map<String, Object> message = new HashMap<>();
message.put("cacheName", cacheName);
message.put("key", key);
RedisPublisher redisPublisher = new RedisPublisher(redisOperations, RedisChannelTopic.REDIS_CACHE_DELETE_TOPIC.getChannelTopic());// 创建redis发布者
redisPublisher.publisher(message);//发布消息,清除其它集群机器中的一级缓存
log.debug(String.format("清除二级缓存数据[%s]", key));
}
@Override
public void clear() {
redisCache.clear(); //清除redis中的二级缓存
caffeineCache.clear();//清除本机一级缓存
Map<String, Object> message = new HashMap<>();
message.put("cacheName", cacheName);
RedisPublisher redisPublisher = new RedisPublisher(redisOperations, RedisChannelTopic.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic());// 创建redis发布者
redisPublisher.publisher(message);//发布消息,清除其它集群机器中的一级缓存
}
@Override
protected Object lookup(Object key) {
Object value = caffeineCache.get(key);
log.debug("查询一级缓存 key:{}", key);
if (value == null) {
value = redisCache.get(key);
log.debug("查询二级缓存 key:{}", key);
}
return value;
}
/**
* 获取caffeine缓存
* @return
*/
public CaffeineCache getFirstCache() {
return this.caffeineCache;
}
/**
* 获取redis缓存
* @return
*/
public RedisCache getSecondCache() {
return this.redisCache;
}
/**
* 查询二级缓存
* @param key
* @param valueLoader
* @return
*/
private <T> Object getSecondCacheValue(Object key, Callable<T> valueLoader) {
T value = redisCache.get(key, valueLoader);
log.debug("查询二级缓存 key:{}", key);
return toStoreValue(value);
}
}
package cn.ibizlab.util.cache.cacheManager;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import lombok.Data;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.util.ObjectUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* Caffeine本地缓存
*/
@Data
public class CaffeineCacheManager implements CacheManager {
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
private static final int default_expire_after_write = 1;
private static final int default_initial_capacity = 5;
private static final int default_maximum_size = 1_000;
private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
.expireAfterAccess(default_expire_after_write, TimeUnit.HOURS)
.initialCapacity(default_initial_capacity)
.maximumSize(default_maximum_size);
/**
* 获取缓存对象
* @param cacheName
* @return
*/
@Override
public Cache getCache(String cacheName) {
Cache cache = this.cacheMap.get(cacheName);
if (cache == null) {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(cacheName);
if (cache == null) {
cache = createCache(cacheName);
this.cacheMap.put(cacheName, cache);
}
}
}
return cache;
}
/**
* 创建缓存
* @param cacheName
* @return
*/
protected Cache createCache(String cacheName) {
return new CaffeineCache(cacheName, this.cacheBuilder.build(), true);
}
/**
* 获取缓存名
* @return
*/
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
/**
* 缓存配置[缓存容量大小、时长等]
* @param caffeineCacheConfig
*/
public void setCaffeineCacheConfig(CaffeineSpec caffeineCacheConfig) {
Caffeine<Object, Object> cacheBuilder = Caffeine.from(caffeineCacheConfig);
if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) {
this.cacheBuilder = cacheBuilder;
}
}
}
package cn.ibizlab.util.cache.cacheManager;
import cn.ibizlab.util.cache.cache.CusCaffeineCache;
import cn.ibizlab.util.cache.cache.CusRedisCache;
import cn.ibizlab.util.cache.cache.LayeringCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import lombok.Data;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* 缓存分层
* 1级缓存为caffeine
* 2级缓存为redis
*/
@Data
public class LayeringCacheManager implements CacheManager {
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
private static final int default_expire_after_write = 1;
private static final int default_initial_capacity = 5;
private static final int default_maximum_size = 1_000;
private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
.expireAfterAccess(default_expire_after_write, TimeUnit.HOURS)
.initialCapacity(default_initial_capacity)
.maximumSize(default_maximum_size);
private RedisCacheWriter redisCacheWriter;
private RedisCacheConfiguration redisConfiguration;
private RedisTemplate<String, Object> redisTemplate;
public LayeringCacheManager(RedisCacheWriter redisCacheWriter , RedisCacheConfiguration redisConfiguration , RedisTemplate<String, Object> redisTemplate ){
this.redisCacheWriter=redisCacheWriter;
this.redisConfiguration=redisConfiguration;
this.redisTemplate= redisTemplate;
}
/**
* 获取缓存对象
* @param cacheName
* @return
*/
@Override
public Cache getCache(String cacheName) {
Cache cache = this.cacheMap.get(cacheName);
if (cache == null) {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(cacheName);
if (cache == null) {
cache = createCache(cacheName);
this.cacheMap.put(cacheName, cache);
}
}
}
return cache;
}
/**
* 获取集合中的缓存
* @return
*/
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
/**
* 创建缓存
* @param cacheName
* @return
*/
protected Cache createCache(String cacheName) {
return new LayeringCache(cacheName,new CusCaffeineCache(cacheName, this.cacheBuilder.build(), true),new CusRedisCache(cacheName, redisCacheWriter, redisConfiguration),redisTemplate);
}
/**
* 缓存配置[缓存容量大小、时长等]
* @param caffeineCacheConfig
*/
public void setCaffeineCacheConfig(CaffeineSpec caffeineCacheConfig) {
Caffeine<Object, Object> cacheBuilder = Caffeine.from(caffeineCacheConfig);
if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) {
this.cacheBuilder = cacheBuilder;
}
}
}
package cn.ibizlab.util.cache.listener;
import cn.ibizlab.util.cache.cache.LayeringCache;
import cn.ibizlab.util.enums.RedisChannelTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* redis消息的订阅者
*/
@Slf4j
public class RedisMessageListener extends MessageListenerAdapter {
private CacheManager cacheManager;
private RedisTemplate redisTemplate;
public RedisMessageListener(CacheManager cacheManager, RedisTemplate redisTemplate){
this.cacheManager=cacheManager;
this.redisTemplate=redisTemplate;
}
@Override
public void onMessage(Message message, byte[] pattern) {
RedisChannelTopic channelTopic = RedisChannelTopic.getChannelTopicEnum(new String(message.getChannel()));
Map<String, Object> map = null;
RedisSerializer serializer=redisTemplate.getValueSerializer();
Object result=serializer.deserialize(message.getBody());
if(result instanceof Map){
map= (Map<String, Object>) result;
}
if(ObjectUtils.isEmpty(map)|| (!map.containsKey("cacheName"))){
log.debug("解析缓存数据失败,无法获取指定值!");
return ;
}
log.debug("redis消息订阅者接收到频道【{}】发布的消息。消息内容:{}", channelTopic.getChannelTopicStr(), result.toString());
String cacheName = (String) map.get("cacheName");
Cache cache = cacheManager.getCache(cacheName);// 根据缓存名称获取多级缓存
if (cache != null && cache instanceof LayeringCache) { // 判断缓存是否是多级缓存
switch (channelTopic) {
case REDIS_CACHE_DELETE_TOPIC: // 获取一级缓存,并删除一级缓存数据
Object cacheKey = map.get("key");
if(!ObjectUtils.isEmpty(cacheKey)){
((LayeringCache) cache).getFirstCache().evict(cacheKey);
((LayeringCache) cache).getSecondCache().evict(cacheKey);
log.debug("同步删除缓存{}数据,key:{},", cacheName, cacheKey.toString());
}
else{
log.debug("同步删除缓存失败,{}缓存键值为空!",cacheName);
}
break;
case REDIS_CACHE_CLEAR_TOPIC:// 获取一级缓存,并删除一级缓存数据
((LayeringCache) cache).getFirstCache().clear();
((LayeringCache) cache).getSecondCache().clear();
log.debug("同步清除缓存{}数据", cacheName);
break;
default:
log.debug("接收到没有定义的订阅消息频道数据");
break;
}
}
}
}
package cn.ibizlab.util.cache.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.listener.ChannelTopic;
/**
* redis消息的发布者
*/
public class RedisPublisher {
private static final Logger logger = LoggerFactory.getLogger(RedisPublisher.class);
RedisOperations<? extends Object, ? extends Object> redisOperations;
/**
* 频道名称
*/
ChannelTopic channelTopic;
/**
* @param redisOperations Redis客户端
* @param channelTopic 频道名称
*/
public RedisPublisher(RedisOperations<? extends Object, ? extends Object> redisOperations, ChannelTopic channelTopic) {
this.channelTopic = channelTopic;
this.redisOperations = redisOperations;
}
/**
* 发布消息到频道(Channel)
*
* @param message 消息内容
*/
public void publisher(Object message) {
redisOperations.convertAndSend(channelTopic.toString(), message);
logger.debug("redis消息发布者向频道【{}】发布了【{}】消息", channelTopic.toString(), message.toString());
}
}
package cn.ibizlab.util.cache.redis;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CustomJacksonSerializer<T> extends Jackson2JsonRedisSerializer<T> {
public static final String DEFAULT_PACKAGE ="[\\w+\\.]+\\.AuthenticationUser";
public static final String CLASSNAME_EX="_$$_";
public static final String CLASSNAME_EX_PATTEN="(_\\$\\$_)(\\w+)";
public static final String USER_PACKAGE= AuthenticationUser.class.getName();
public CustomJacksonSerializer(Class type) {
super(type);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
String serializerContent = new String(bytes, DEFAULT_CHARSET);
Matcher matcher = Pattern.compile(DEFAULT_PACKAGE).matcher(serializerContent);
if(matcher.find()){
serializerContent=serializerContent.replaceAll(DEFAULT_PACKAGE,USER_PACKAGE);
}
if(serializerContent.contains(CLASSNAME_EX)){
serializerContent=serializerContent.replaceAll(CLASSNAME_EX_PATTEN,"");
}
return super.deserialize(serializerContent.getBytes());
}
}
package cn.ibizlab.util.client;
import cn.ibizlab.util.dict.Catalog;
import cn.ibizlab.util.dict.CodeList;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;
@Component
public class IBZDictFallback implements IBZDictFeignClient {
@Override
public Boolean syncRuntimeDict(JSONArray catalogs) {
return null;
}
@Override
public CodeList getCodeList(String code) {
return null;
}
@Override
public Catalog getCatalog(String code) {
return null;
}
}
\ No newline at end of file
package cn.ibizlab.util.client;
import cn.ibizlab.util.dict.Catalog;
import cn.ibizlab.util.dict.CodeList;
import com.alibaba.fastjson.JSONArray;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value = "${ibiz.ref.service.dict:ibzdict-api}",contextId = "dict",fallback = IBZDictFallback.class)
public interface IBZDictFeignClient
{
@RequestMapping(method = RequestMethod.POST, value = "/dictionarys/catalogs/sync")
Boolean syncRuntimeDict(@RequestBody JSONArray catalogs);
@Cacheable( value="dictcatalog",key = "'codelist:'+#p0")
@RequestMapping(method = RequestMethod.GET, value = "/dictionarys/codelist/{code}")
CodeList getCodeList(@PathVariable("code") String code);
@Cacheable( value="dictcatalog",key = "'dict:'+#p0")
@RequestMapping(method = RequestMethod.GET, value = "/dictionarys/catalogs/{code}")
Catalog getCatalog(@PathVariable("code") String code);
}
\ No newline at end of file
package cn.ibizlab.util.client;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
@Component
public class IBZLiteFallback implements IBZLiteFeignClient {
@Override
public Boolean syncSysModel(JSONObject system) {
return null;
}
}
package cn.ibizlab.util.client;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(value = "${ibiz.ref.service.lite:ibzlite-api}",contextId = "lite",fallback = IBZLiteFallback.class)
public interface IBZLiteFeignClient
{
/**
* 同步系统资模型到lite
* @param system 系统模型信息
* @return
*/
@PostMapping("/lite/syncsysmodel")
Boolean syncSysModel(@RequestBody JSONObject system);
}
package cn.ibizlab.util.client;
import cn.ibizlab.util.domain.MsgBody;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
@Component
public class IBZNotifyFallback implements IBZNotifyFeignClient {
@Override
public Boolean sendMsg(MsgBody msg) {
return null;
}
@Override
public Boolean createMsgTemplate(JSONObject template) {
return null;
}
@Override
public Boolean sendDingTalkLinkMsg(MsgBody msg) {
return null;
}
@Override
public String createDingTalkWorkRecord(MsgBody msg) {
return null;
}
@Override
public Boolean finishDingTalkWorkRecord(String msgId) {
return null;
}
}
package cn.ibizlab.util.client;
import cn.ibizlab.util.domain.MsgBody;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(value = "${ibiz.ref.service.notify:ibznotify-api}",contextId = "notify",fallback = IBZNotifyFallback.class)
public interface IBZNotifyFeignClient
{
@RequestMapping(method = RequestMethod.POST,value = "/notify/sendmsg")
Boolean sendMsg(@RequestBody MsgBody msg);
@RequestMapping(method = RequestMethod.POST,value = "/notify/createmsgtempl")
Boolean createMsgTemplate(@RequestBody JSONObject template);
@RequestMapping(method = RequestMethod.POST,value = "/notify/dingtalk/sendlinkmsg")
Boolean sendDingTalkLinkMsg(@RequestBody MsgBody msg);
@RequestMapping(method = RequestMethod.POST,value = "/notify/dingtalk/createworkrecord")
String createDingTalkWorkRecord(@RequestBody MsgBody msg);
@RequestMapping(method = RequestMethod.POST,value = "/notify/dingtalk/finishworkrecord/{msgid}")
Boolean finishDingTalkWorkRecord(@PathVariable("msgid") String msgId);
}
package cn.ibizlab.util.client;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Set;
@Component
public class IBZOUFallback implements IBZOUFeignClient {
@Override
public Map<String, Set<String>> getOUMapsByUserId(String userId) {
return null;
}
}
此差异已折叠。
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册