提交 1e513e44 编写于 作者: sq3536's avatar sq3536

bug

上级 34bf5b15
......@@ -69,22 +69,6 @@
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<exclusions>
<exclusion>
<artifactId>mapstruct</artifactId>
<groupId>org.mapstruct</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- drools -->
<dependency>
<groupId>org.drools</groupId>
......
package cn.ibizlab.util.domain;
import cn.ibizlab.util.helper.BeanCache;
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;
......@@ -100,7 +100,7 @@ public class DTOBase implements Serializable {
}
public Object get(String field) {
String fieldRealName= DEFieldCacheMap.getFieldRealName(this.getClass(),field);
String fieldRealName= BeanCache.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
return getMap().get(fieldRealName);
}
......@@ -113,13 +113,13 @@ public class DTOBase implements Serializable {
@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);
String fieldRealName=BeanCache.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));
getMap().put(fieldRealName, BeanCache.fieldValueOf(this.getClass(), fieldRealName, value));
}
}
else {
......
package cn.ibizlab.util.domain;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import cn.ibizlab.util.helper.BeanCache;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
......@@ -81,7 +81,7 @@ public class EntityBase implements Serializable {
}
public Object get(String field) {
String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
String fieldRealName= BeanCache.getFieldRealName(this.getClass(),field);
if(!ObjectUtils.isEmpty(fieldRealName)) {
return getMap().get(fieldRealName);
}
......@@ -100,13 +100,13 @@ public class EntityBase implements Serializable {
@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);
String fieldRealName=BeanCache.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));
getMap().put(fieldRealName, BeanCache.fieldValueOf(this.getClass(), fieldRealName, value));
}
}
else {
......@@ -124,13 +124,12 @@ public class EntityBase implements Serializable {
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);
}
BeanCache.get(this.getClass()).getFields().forEach(item -> {
Object value=this.get(item.getCodeName());
if( !ObjectUtils.isEmpty(value) || ObjectUtils.isEmpty(value) && getFocusNull().contains(item.getJsonName()) && bIncEmpty ){
target.set(item.getCodeName(),value);
}
});
}
return targetEntity;
}
......
package cn.ibizlab.util.domain;
import cn.ibizlab.util.helper.BeanCache;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
......@@ -9,7 +10,9 @@ public class EntityMP extends EntityBase {
public UpdateWrapper getUpdateWrapper(boolean clean) {
UpdateWrapper wrapper=new UpdateWrapper();
for(String nullField:getFocusNull()) {
wrapper.set(nullField,null);
String columnName=BeanCache.getFieldColumnName(this.getClass(),nullField);
if(!ObjectUtils.isEmpty(columnName))
wrapper.set(columnName,null);
}
if(clean) {
getFocusNull().clear();
......
package cn.ibizlab.util.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.data.annotation.Id;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
......@@ -17,17 +31,55 @@ import java.util.Objects;
@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;
@Id
@TableId(type=IdType.ASSIGN_ID)//指定主键生成策略
private String dataAuditId;
private String dataAuditName;
private String opPersonId;
private String opPersonName;
private String auditType;
private Timestamp opTime;
private String ipAddress;
@TableField(typeHandler = cn.ibizlab.util.domain.IBZDataAudit.IBZDataAuditItemTypeHandler.class)
private List<IBZDataAuditItem> auditInfo;
private Object auditObjectData;
private String auditObject;
private int isDataChanged;
@Slf4j
@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public static class IBZDataAuditItemTypeHandler extends AbstractJsonTypeHandler<List>
{
private static ObjectMapper objectMapper = new ObjectMapper();
private JavaType type;
public IBZDataAuditItemTypeHandler(Class<List> type) {
this.type = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, IBZDataAuditItem.class);
}
@Override
protected List parse(String json) {
try {
return objectMapper.readValue(json, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected String toJson(List obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static void setObjectMapper(ObjectMapper objectMapper) {
IBZDataAuditItemTypeHandler.objectMapper = objectMapper;
}
}
}
\ No newline at end of file
package cn.ibizlab.util.domain;
import lombok.Data;
@Data
public class IBZDataAuditItem {
private String id;
private String label;
private String dict;
private Object value;
private Object before;
}
package cn.ibizlab.util.filter;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import cn.ibizlab.util.helper.BeanCache;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
......@@ -57,10 +57,10 @@ public class QueryWrapperContext<T> extends SearchContextBase implements ISearch
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()));
asc_fieldList.add(BeanCache.getFieldName(type,sort_order.getProperty()));
}
else if(sort_order.getDirection()== Sort.Direction.DESC){
desc_fieldList.add(DEFieldCacheMap.getFieldColumnName(type,sort_order.getProperty()));
desc_fieldList.add(BeanCache.getFieldName(type,sort_order.getProperty()));
}
}
......
package cn.ibizlab.util.helper;
import cn.ibizlab.util.annotation.Audit;
import cn.ibizlab.util.annotation.DEField;
import cn.ibizlab.util.enums.DEPredefinedFieldType;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.*;
public class BeanCache {
private static Map<String,BeanSchema> cache=new HashMap<>();
private static Object objLock1=new Object();
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public static class BeanSchema{
private String codeName;
private String name;
private String pluralize;
private String logicName;
private FieldItem keyField;
private FieldItem orgField; //组织属性
private FieldItem orgDeptField; //部门属性
private FieldItem createManField; //创建人属性
private Map<String, FieldItem> fieldMap=new LinkedHashMap<>();
private List<FieldItem> fields=new ArrayList<>();
private List<FieldItem> deFields=new ArrayList<>();
private List<FieldItem> audits=new ArrayList<>();
public boolean containsKey(String tag) {
if(fieldMap.containsKey(tag)) {
return true;
}
else if(fieldMap.containsKey(tag.toLowerCase())) {
return true;
}
else if(fieldMap.containsKey(tag.toLowerCase().replace("_",""))) {
return true;
}
else {
return false;
}
}
public FieldItem get(String tag) {
if(fieldMap.containsKey(tag)) {
return fieldMap.get(tag);
}
else if(fieldMap.containsKey(tag.toLowerCase())) {
return fieldMap.get(tag.toLowerCase());
}
else if(fieldMap.containsKey(tag.toLowerCase().replace("_",""))) {
return fieldMap.get(tag.toLowerCase().replace("_",""));
}
else {
return null;
}
}
public Audit getAudit(String tag) {
FieldItem item=fieldMap.get(tag);
if(item!=null)
return item.getAudit();
return null;
}
public DEField getDEField(String tag) {
FieldItem item=fieldMap.get(tag);
if(item!=null)
return item.getDeField();
return null;
}
public static <T> BeanSchema from(Class<T> clazz){
String className=clazz.getName();
if(className.indexOf("_$")>0) {
className=className.substring(0, className.lastIndexOf("_$"));
}
if(cache.containsKey(className)) {
return cache.get(className);
}
synchronized (objLock1) {
if (cache.containsKey(className)) {
return cache.get(className);
}
BeanSchema schema=new BeanSchema().setCodeName(className).setName(className).setPluralize(StringAdvUtils.pluralize(className));
Map<String, FieldItem> result=schema.getFieldMap();
List<FieldItem> list = schema.getFields();
ApiModel apiModel=clazz.getAnnotation(ApiModel.class);
if(!ObjectUtils.isEmpty(apiModel)) {
if(!StringUtils.isEmpty(apiModel.value()))
schema.setName(apiModel.value());
if(!StringUtils.isEmpty(apiModel.description()))
schema.setLogicName(apiModel.description());
}
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields){
if(field.getAnnotation(Transient.class)!=null)
continue;
FieldItem item=new FieldItem().setCodeName(field.getName()).setFieldName(field.getName()).setColumnName(field.getName().toLowerCase()).setJsonName(field.getName().toLowerCase()).setLogicName(field.getName()).setField(field);
JSONField jsField=field.getAnnotation(JSONField.class);
if(!ObjectUtils.isEmpty(jsField)) {
if(!StringUtils.isEmpty(jsField.name()))
item.setJsonName(jsField.name());
if(!StringUtils.isEmpty(jsField.format()))
item.setFormat(jsField.format());
}
else
{
JsonProperty jsonProperty=field.getAnnotation(JsonProperty.class);
if((!ObjectUtils.isEmpty(jsonProperty))&&(!StringUtils.isEmpty(jsonProperty.value())))
item.setJsonName(jsonProperty.value());
}
ApiModelProperty apiModelProperty=field.getAnnotation(ApiModelProperty.class);
if(!ObjectUtils.isEmpty(apiModelProperty)) {
if(!StringUtils.isEmpty(apiModelProperty.value()))
item.setFieldName(apiModelProperty.value()).setColumnName(apiModelProperty.value());
if(!StringUtils.isEmpty(apiModelProperty.notes()))
item.setLogicName(apiModelProperty.notes());
}
org.springframework.data.mongodb.core.mapping.Field mogoField=field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class);
if(!ObjectUtils.isEmpty(mogoField)) {
if(!ObjectUtils.isEmpty(mogoField.name())) {
item.setFieldName(mogoField.name()).setColumnName(mogoField.name());
}
}
DEField deField=field.getAnnotation(DEField.class);
if(!ObjectUtils.isEmpty(deField)) {
if(!ObjectUtils.isEmpty(deField.name())) {
item.setFieldName(deField.name()).setColumnName(deField.name());
}
item.setDeField(deField);
schema.getDeFields().add(item);
DEPredefinedFieldType prefieldType=deField.preType();
//用户配置系统预置属性-组织机构标识
if(prefieldType==prefieldType.ORGID){
schema.setOrgField(item);
}
else if(prefieldType==prefieldType.ORGSECTORID){
schema.setOrgDeptField(item);
}
else if(prefieldType==prefieldType.CREATEMAN){
schema.setCreateManField(item);
}
}
Audit audit=field.getAnnotation(Audit.class);
if(!ObjectUtils.isEmpty(audit)) {
item.setAudit(audit);
schema.getAudits().add(item);
}
TableField tableField=field.getAnnotation(TableField.class);
if(!ObjectUtils.isEmpty(tableField)) {
if(tableField.exist()&&(ObjectUtils.isEmpty(tableField.value()))) {
item.setFieldName(tableField.value()).setColumnName(tableField.value());
}
else if(!tableField.exist())
item.setColumnName("");
}
TableId tableId=field.getAnnotation(TableId.class);
if(!ObjectUtils.isEmpty(tableId)) {
if(!ObjectUtils.isEmpty(tableId.value())) {
item.setFieldName(tableId.value()).setColumnName(tableId.value());
}
schema.setKeyField(item);
}
if(schema.getKeyField()==null)
{
if(!ObjectUtils.isEmpty(field.getAnnotation(Id.class)))
schema.setKeyField(item);
}
list.add(item);
result.put(item.getCodeName(),item);
result.put(item.getFieldName(),item);
result.put(item.getColumnName(),item);
result.put(item.getJsonName(),item);
result.put(item.getCodeName().toLowerCase(),item);
result.put(item.getFieldName().toLowerCase(),item);
result.put(item.getColumnName().toLowerCase(),item);
result.put(item.getJsonName().toLowerCase(),item);
}
cache.put(schema.getCodeName(),schema);
cache.put(schema.getName(),schema);
cache.put(schema.getCodeName().toLowerCase(),schema);
cache.put(schema.getName().toLowerCase(),schema);
cache.put(schema.getCodeName().toLowerCase(),schema);
cache.put(schema.getPluralize(),schema);
return schema;
}
}
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public static class FieldItem{
private String codeName;
private String fieldName;
private String columnName;
private String jsonName;
private String logicName;
private String format;
private Field field;
private Audit audit;
private DEField deField;
public String getCodeName()
{
if(codeName!=null&&codeName.length()>1)
{
if(Character.isUpperCase(codeName.charAt(1)))
codeName=codeName.substring(0,1).toUpperCase()+codeName.substring(1);
}
return codeName;
}
}
public static <T> BeanSchema get(Class<T> clazz) {
return BeanSchema.from(clazz);
}
public static <T> boolean hasAudit(Class<T> clazz) {
return !ObjectUtils.isEmpty(BeanCache.get(clazz).getAudits());
}
public static <T> List<FieldItem> getFields(Class<T> clazz) {
return get(clazz).getFields();
}
public static <T> FieldItem getField(Class<T> clazz, String fieldname) {
return BeanSchema.from(clazz).get(fieldname);
}
/**
* 从缓存中查询实体对象主键
* @param
* @return
*/
public static <T> String getKeyField(Class<T> clazz) {
BeanSchema schema=BeanSchema.from(clazz);
if(schema.getKeyField()!=null) {
return schema.getKeyField().getCodeName();
}
return "";
}
public static <T> String getFieldRealName(Class<T> clazz,String fieldname) {
FieldItem field=getField(clazz,fieldname);
if(field!=null) {
return field.getCodeName();
}
return "";
}
public static <T> String getFieldName(Class<T> clazz,String fieldname) {
FieldItem field=getField(clazz,fieldname);
if(field!=null) {
return field.getFieldName();
}
return "";
}
public static <T> String getFieldColumnName(Class<T> clazz,String fieldname) {
FieldItem field=getField(clazz,fieldname);
if(field!=null) {
return field.getColumnName();
}
return "";
}
public static <T> Object fieldValueOf(Class<T> clazz,String fieldname,Object fieldValue) {
if(fieldValue==null)
return null;
Object resultValue=fieldValue;
FieldItem item=getField(clazz,fieldname);
if(item!=null) {
Class<?> type=item.getField().getType();
resultValue = TypeUtils.castToJavaBean(fieldValue,type);
}
return resultValue;
}
}
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.service;
import cn.ibizlab.util.annotation.Audit;
import cn.ibizlab.util.annotation.DEField;
import cn.ibizlab.util.domain.EntityBase;
import cn.ibizlab.util.domain.IBZDataAuditItem;
import cn.ibizlab.util.helper.BeanCache;
import cn.ibizlab.util.security.AuthenticationUser;
import lombok.SneakyThrows;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
......@@ -11,9 +27,137 @@ import java.util.Map;
*/
public interface IBZDataAuditService {
@Async("asyncExecutor")
void createAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields);
void createAudit(HttpServletRequest request, EntityBase entity, Object idValue);
@Async("asyncExecutor")
void updateAudit(HttpServletRequest request, EntityBase beforeEntity, Object serviceObj, Object idValue, Map<String, Audit> auditFields);
void updateAudit(HttpServletRequest request, EntityBase beforeEntity, EntityBase entity, Object idValue);
@Async("asyncExecutor")
void removeAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields);
void removeAudit(HttpServletRequest request, EntityBase entity, Object idValue);
default List<IBZDataAuditItem> getAuditInfo(EntityBase entity) {
List<IBZDataAuditItem> auditFieldArray = new ArrayList<>();
BeanCache.get(entity.getClass()).getAudits().forEach(item->{
String fieldName = item.getCodeName();
DEField deField = item.getDeField();
Object value = dataTransfer(entity.get(fieldName),item.getFormat());
if(!ObjectUtils.isEmpty(value)) {
IBZDataAuditItem auditFieldObj = new IBZDataAuditItem();
auditFieldObj.setId(item.getJsonName());
auditFieldObj.setLabel(item.getLogicName());
auditFieldObj.setValue(value);
if(!ObjectUtils.isEmpty(deField)&&!ObjectUtils.isEmpty(deField.dict())) {
auditFieldObj.setDict(deField.dict());
}
auditFieldArray.add(auditFieldObj);
}
});
if(auditFieldArray.size()>0) {
return auditFieldArray;
}
return null;
}
default List<IBZDataAuditItem> getUpdateAuditInfo(EntityBase oldData, EntityBase newData){
List<IBZDataAuditItem> auditFieldArray = new ArrayList<>();
BeanCache.get(oldData.getClass()).getAudits().forEach(item->{
String fieldName = item.getCodeName();
DEField deField = item.getDeField();
Object oldValue = oldData.get(fieldName);//老属性值
Object newValue = newData.get(fieldName);//新属性值
if(!compare(oldValue, newValue)) {
IBZDataAuditItem auditFieldObj = new IBZDataAuditItem();
auditFieldObj.setId(item.getJsonName());
auditFieldObj.setLabel(item.getLogicName());
auditFieldObj.setValue(dataTransfer(newValue, deField.format()));
auditFieldObj.setBefore(dataTransfer(oldValue, deField.format()));
if(!ObjectUtils.isEmpty(deField)&&!ObjectUtils.isEmpty(deField.dict())) {
auditFieldObj.setDict(deField.dict());
}
auditFieldArray.add(auditFieldObj);
}
});
if(auditFieldArray.size()>0) {
return auditFieldArray;
}
return null;
}
default Object dataTransfer(Object value, String strFormat) {
if(value==null) {
return "";
}
Object transResult=value;
if( (!ObjectUtils.isEmpty(strFormat)) && value instanceof Timestamp) { //时间类型转换
Timestamp timestamp = (Timestamp)value;
SimpleDateFormat format = new SimpleDateFormat(strFormat);
transResult = format.format(timestamp);
}
return transResult;
}
/**
* 对象比较
* @param sourceObj 比较源对象
* @param targetObj 比较目标对象
* @return
*/
default boolean compare(Object sourceObj, Object targetObj) {
if(sourceObj == null && targetObj == null) {
return true;
}
if(sourceObj == null && targetObj != null) {
return false;
}
return sourceObj.equals(targetObj);
}
/**
* 获取Ip地址
* @param request
* @return
*/
default String getIpAddress(HttpServletRequest request, AuthenticationUser authenticationUser) {
//客户端有提交ip,以提交的ip为准
if(authenticationUser != null && !ObjectUtils.isEmpty(authenticationUser.getAddr())) {
return authenticationUser.getAddr();
}
if(request == null) {
return "";
}
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if(!ObjectUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(!ObjectUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
return XFor;
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}
\ No newline at end of file
package cn.ibizlab.util.service;
import cn.ibizlab.util.dict.Option;
import cn.ibizlab.util.domain.IBZDataAuditItem;
import cn.ibizlab.util.helper.BeanCache;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
......@@ -9,7 +12,6 @@ import cn.ibizlab.util.annotation.Audit;
import cn.ibizlab.util.annotation.DEField;
import cn.ibizlab.util.domain.EntityBase;
import cn.ibizlab.util.domain.IBZDataAudit;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import cn.ibizlab.util.mapper.IBZDataAuditMapper;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.expression.EvaluationContext;
......@@ -33,10 +35,12 @@ import java.util.*;
@Slf4j
public class SimpleAuditService extends ServiceImpl<IBZDataAuditMapper, IBZDataAudit> implements IBZDataAuditService {
private final ExpressionParser parser = new SpelExpressionParser();
private static List cacheMap = Collections.synchronizedList(new ArrayList());
public static void main(String[] args) {
System.out.println(SimpleAuditService.class.getAnnotations());
}
/**
* 定时保存审计记录
*/
......@@ -57,273 +61,74 @@ public class SimpleAuditService extends ServiceImpl<IBZDataAuditMapper, IBZDataA
}
}
/**
* 新建审计日志
* @param request
* @param entity
* @param idValue
* @param auditFields
*/
@Override
public void createAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields) {
public void createAudit(HttpServletRequest request, EntityBase entity, Object idValue) {
if(ObjectUtils.isEmpty(idValue))
idValue=entity.get(BeanCache.getKeyField(entity.getClass()));
IBZDataAudit dataAudit = new IBZDataAudit();
dataAudit.setOppersonid(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOppersonname(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAudittype("CREATE");
dataAudit.setAuditobject(entity.getClass().getSimpleName());
dataAudit.setAuditobjectdata(idValue);
dataAudit.setOptime(new Timestamp(new Date().getTime()));
dataAudit.setOpPersonId(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOpPersonName(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAuditType("CREATE");
dataAudit.setAuditObject(BeanCache.get(entity.getClass()).getCodeName());
dataAudit.setDataAuditName(BeanCache.get(entity.getClass()).getLogicName()+"[新建]");
dataAudit.setAuditObjectData(idValue);
dataAudit.setOpTime(new Timestamp(System.currentTimeMillis()));
if(request != null) {
dataAudit.setIpaddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
dataAudit.setIpAddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
}
dataAudit.setAuditinfo(getAuditInfo(entity, auditFields));
dataAudit.setIsdatachanged(1);
dataAudit.setAuditInfo(getAuditInfo(entity));
dataAudit.setIsDataChanged(1);
cacheMap.add(dataAudit);
}
/**
* 更新审计日志
* @param request
* @param beforeEntity
* @param serviceObj
* @param idValue
* @param auditFields
*/
@SneakyThrows
public void updateAudit(HttpServletRequest request, EntityBase beforeEntity, Object serviceObj, Object idValue, Map<String, Audit> auditFields) {
//获取更新后的实体
EntityBase afterEntity = getEntity(serviceObj, idValue);
public void updateAudit(HttpServletRequest request, EntityBase beforeEntity, EntityBase afterEntity, Object idValue) {
if(ObjectUtils.isEmpty(idValue))
idValue=beforeEntity.get(BeanCache.getKeyField(beforeEntity.getClass()));
//获取更新后的审计内容
String auditInfo = getUpdateAuditInfo(beforeEntity, afterEntity, auditFields);//比较更新前后差异内容
List<IBZDataAuditItem> auditInfo = getUpdateAuditInfo(beforeEntity, afterEntity);//比较更新前后差异内容
int isDataChanged = 1;
//审计内容是否发生变化
if(ObjectUtils.isEmpty(auditInfo)) {
isDataChanged = 0;
}
IBZDataAudit dataAudit = new IBZDataAudit();
dataAudit.setOppersonid(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOppersonname(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAudittype("UPDATE");
dataAudit.setAuditobject(afterEntity.getClass().getSimpleName());
dataAudit.setAuditobjectdata(idValue);
dataAudit.setOptime(new Timestamp(new Date().getTime()));
if(request!=null) {
dataAudit.setIpaddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
dataAudit.setOpPersonId(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOpPersonName(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAuditType("UPDATE");
dataAudit.setAuditObject(BeanCache.get(beforeEntity.getClass()).getCodeName());
dataAudit.setDataAuditName(BeanCache.get(beforeEntity.getClass()).getLogicName()+"[更新]");
dataAudit.setAuditObjectData(idValue);
dataAudit.setOpTime(new Timestamp(System.currentTimeMillis()));
if(request != null) {
dataAudit.setIpAddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
}
dataAudit.setAuditinfo(auditInfo);
dataAudit.setIsdatachanged(isDataChanged);
dataAudit.setAuditInfo(auditInfo);
dataAudit.setIsDataChanged(isDataChanged);
cacheMap.add(dataAudit);
}
/**
* 删除审计日志
* @param request
* @param entity
* @param idValue
* @param auditFields
*/
public void removeAudit(HttpServletRequest request, EntityBase entity, Object idValue, Map<String, Audit> auditFields) {
public void removeAudit(HttpServletRequest request, EntityBase entity, Object idValue) {
if(ObjectUtils.isEmpty(idValue))
idValue=entity.get(BeanCache.getKeyField(entity.getClass()));
IBZDataAudit dataAudit = new IBZDataAudit();
dataAudit.setOppersonid(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOppersonname(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAudittype("REMOVE");
dataAudit.setAuditobject(entity.getClass().getSimpleName());
dataAudit.setAuditobjectdata(idValue);
dataAudit.setOptime(new Timestamp(new Date().getTime()));
if(request!=null) {
dataAudit.setIpaddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
dataAudit.setOpPersonId(AuthenticationUser.getAuthenticationUser().getUserid());
dataAudit.setOpPersonName(String.format("%s[%s]", AuthenticationUser.getAuthenticationUser().getPersonname(), AuthenticationUser.getAuthenticationUser().getOrgname()));
dataAudit.setAuditType("REMOVE");
dataAudit.setAuditObject(BeanCache.get(entity.getClass()).getCodeName());
dataAudit.setDataAuditName(BeanCache.get(entity.getClass()).getLogicName()+"[删除]");
dataAudit.setAuditObjectData(idValue);
dataAudit.setOpTime(new Timestamp(System.currentTimeMillis()));
if(request != null) {
dataAudit.setIpAddress(getIpAddress(request, AuthenticationUser.getAuthenticationUser()));
}
dataAudit.setAuditinfo(getAuditInfo(entity, auditFields));
dataAudit.setIsdatachanged(1);
dataAudit.setIsDataChanged(1);
cacheMap.add(dataAudit);
}
private String getAuditInfo(EntityBase entity, Map<String, Audit> auditFields) {
String auditResult = "";
if(auditFields.size() == 0) {
return auditResult;
}
Map<String, DEField> deFields = DEFieldCacheMap.getDEFields(entity.getClass());
if(deFields.size() == 0) {
return auditResult;
}
JSONArray auditFieldArray = new JSONArray();
for (Map.Entry<String, Audit> auditField : auditFields.entrySet()) {
Object objFieldName = auditField.getKey();
String fieldName = String.valueOf(objFieldName);
DEField deField = null;
if(deFields.containsKey(fieldName)) {
deField = deFields.get(fieldName);
}
if(ObjectUtils.isEmpty(deField)) {
continue;
}
Object value = dataTransfer(entity.get(fieldName), deField.fieldType(), deField.format());
if(!ObjectUtils.isEmpty(value)) {
JSONObject auditFieldObj = new JSONObject();
auditFieldObj.put("field", deField.value());
auditFieldObj.put("value", value);
if(!ObjectUtils.isEmpty(deField.dict())) {
auditFieldObj.put("dict", deField.dict());
}
auditFieldArray.add(auditFieldObj);
}
}
if(auditFieldArray.size()>0) {
auditResult = auditFieldArray.toString();
}
return auditResult;
}
/**
* 获取更新审计内容
* @param oldData
* @param newData
* @param auditFields
* @return
*/
private String getUpdateAuditInfo(EntityBase oldData, EntityBase newData, Map<String, Audit> auditFields){
String auditResult = "";
JSONArray auditFieldArray = new JSONArray();
if(auditFields.size() == 0) {
return auditResult;
}
Map<String, DEField> deFields = DEFieldCacheMap.getDEFields(oldData.getClass());
if(deFields.size() == 0){
return auditResult;
}
for (Map.Entry<String, Audit> auditField : auditFields.entrySet()) {
Object objFieldName = auditField.getKey();//获取注解字段
String fieldName = String.valueOf(objFieldName); //属性名称
DEField deField = null;
if(deFields.containsKey(fieldName)) {
deField = deFields.get(fieldName);
}
if(ObjectUtils.isEmpty(deField)) {
continue;
}
Object oldValue = oldData.get(fieldName);//老属性值
Object newValue = newData.get(fieldName);//新属性值
if(!compare(oldValue, newValue)) {
oldValue = dataTransfer(oldValue, deField.fieldType(), deField.format());//属性值转换
newValue = dataTransfer(newValue, deField.fieldType(), deField.format());//属性值转换
JSONObject auditFieldObj = new JSONObject();
auditFieldObj.put("field", deField.value());
auditFieldObj.put("beforevalue", oldValue);
auditFieldObj.put("value", newValue);
if(!ObjectUtils.isEmpty(deField.dict())) {
auditFieldObj.put("dict", deField.dict());
}
auditFieldArray.add(auditFieldObj);
}
}
if(auditFieldArray.size()>0) {
auditResult = auditFieldArray.toString();
}
return auditResult;
}
/**
* 数据转换
* @param value 转换值
* @param dataType 转换字段类型
* @param strFormat 转换字段格式化文本
* @return
*/
private String dataTransfer(Object value, String dataType, String strFormat) {
if(value==null) {
return "";
}
String transResult=value.toString();
if((dataType.equals("DATE") || dataType.equals("DATETIME") || dataType.equals("TIME")) && (!ObjectUtils.isEmpty(strFormat))) { //时间类型转换
Timestamp timestamp = (Timestamp)value;
Date date = timestamp;
SimpleDateFormat format = new SimpleDateFormat(strFormat);
transResult = format.format(date);
}
return transResult;
}
/**
* 对象比较
* @param sourceObj 比较源对象
* @param targetObj 比较目标对象
* @return
*/
private boolean compare(Object sourceObj, Object targetObj) {
if(sourceObj == null && targetObj == null) {
return true;
}
if(sourceObj == null && targetObj != null) {
return false;
}
return sourceObj.equals(targetObj);
}
/**
* 获取实体
* @param service
* @param id
* @return
*/
@SneakyThrows
private EntityBase getEntity(Object service, Object id) {
EntityBase entity = null;
if(!ObjectUtils.isEmpty(service)) {
EvaluationContext oldContext = new StandardEvaluationContext();
oldContext.setVariable("service",service);
oldContext.setVariable("id",id);
Expression oldExp = parser.parseExpression("#service.get(#id)");
return oldExp.getValue(oldContext, EntityBase.class);
}
return entity;
}
/**
* 获取Ip地址
* @param request
* @return
*/
public String getIpAddress(HttpServletRequest request, AuthenticationUser authenticationUser) {
//客户端有提交ip,以提交的ip为准
if(authenticationUser != null && !ObjectUtils.isEmpty(authenticationUser.getAddr())) {
return authenticationUser.getAddr();
}
if(request == null) {
return "";
}
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if(!ObjectUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(!ObjectUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
return XFor;
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ObjectUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}
\ No newline at end of file
......@@ -36,6 +36,7 @@
<eureka-client.version>2.2.5.RELEASE</eureka-client.version>
<!--Java Web Token-->
<jsonwebtoken-jjwt.version>0.9.1</jsonwebtoken-jjwt.version>
<commons-lang.version>3.12.0</commons-lang.version>
<!--反序列化工具-->
<kryo.version>4.0.2</kryo.version>
<!-- Error -->
......@@ -170,6 +171,12 @@
<version>${jsonwebtoken-jjwt.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
......
......@@ -137,6 +137,26 @@
<artifactId>lombok-mapstruct-binding</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<exclusions>
<exclusion>
<artifactId>mapstruct</artifactId>
<groupId>org.mapstruct</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies>
......
package cn.ibizlab.util.helper;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* 单复数转换类
* 2018年12月30日
*/
public class Inflector {
private static final Pattern UNDERSCORE_PATTERN_1 = Pattern.compile("([A-Z]+)([A-Z][a-z])");
private static final Pattern UNDERSCORE_PATTERN_2 = Pattern.compile("([a-z\\d])([A-Z])");
private static List<RuleAndReplacement> plurals = new ArrayList<RuleAndReplacement>();
private static List<RuleAndReplacement> singulars = new ArrayList<RuleAndReplacement>();
private static List<String> uncountables = new ArrayList<String>();
private static Inflector instance;
private Inflector() {
initialize();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 单数转复数
System.out.println(Inflector.getInstance().pluralize("water"));
System.out.println(Inflector.getInstance().pluralize("box"));
System.out.println(Inflector.getInstance().pluralize("tomato"));
// 复数转单数
System.out.println(Inflector.getInstance().singularize("apples"));
}
private void initialize() {
plural("$", "s");
plural("s$", "s");
plural("(ax|test)is$", "$1es");
plural("(octop|vir)us$", "$1i");
plural("(alias|status)$", "$1es");
plural("(bu)s$", "$1es");
plural("(buffal|tomat)o$", "$1oes");
plural("([ti])um$", "$1a");
plural("sis$", "ses");
plural("(?:([^f])fe|([lr])f)$", "$1$2ves");
plural("(hive)$", "$1s");
plural("([^aeiouy]|qu)y$", "$1ies");
plural("(x|ch|ss|sh)$", "$1es");
plural("(matr|vert|ind)ix|ex$", "$1ices");
plural("([m|l])ouse$", "$1ice");
plural("(ox)$", "$1es");
plural("(quiz)$", "$1zes");
singular("s$", "");
singular("(n)ews$", "$1ews");
singular("([ti])a$", "$1um");
singular("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
singular("(^analy)ses$", "$1sis");
singular("([^f])ves$", "$1fe");
singular("(hive)s$", "$1");
singular("(tive)s$", "$1");
singular("([lr])ves$", "$1f");
singular("([^aeiouy]|qu)ies$", "$1y");
singular("(s)eries$", "$1eries");
singular("(m)ovies$", "$1ovie");
singular("(x|ch|ss|sh)es$", "$1");
singular("([m|l])ice$", "$1ouse");
singular("(bus)es$", "$1");
singular("(o)es$", "$1");
singular("(shoe)s$", "$1");
singular("(cris|ax|test)es$", "$1is");
singular("([octop|vir])i$", "$1us");
singular("(alias|status)es$", "$1");
singular("^(ox)es", "$1");
singular("(vert|ind)ices$", "$1ex");
singular("(matr)ices$", "$1ix");
singular("(quiz)zes$", "$1");
irregular("person", "people");
irregular("man", "men");
irregular("child", "children");
irregular("sex", "sexes");
irregular("move", "moves");
uncountable(new String[] { "equipment", "information", "rice", "money", "species", "series", "fish", "sheep" });
}
public static Inflector getInstance() {
if (instance == null) {
instance = new Inflector();
}
return instance;
}
public String underscore(String camelCasedWord) {
String underscoredWord = UNDERSCORE_PATTERN_1.matcher(camelCasedWord).replaceAll("$1_$2");
underscoredWord = UNDERSCORE_PATTERN_2.matcher(underscoredWord).replaceAll("$1_$2");
underscoredWord = underscoredWord.replace('-', '_').toLowerCase();
return underscoredWord;
}
public String pluralize(String word) {
if (uncountables.contains(word.toLowerCase())) {
return word;
}
return replaceWithFirstRule(word, plurals);
}
public String singularize(String word) {
if (uncountables.contains(word.toLowerCase())) {
return word;
}
return replaceWithFirstRule(word, singulars);
}
private String replaceWithFirstRule(String word, List<RuleAndReplacement> ruleAndReplacements) {
for (RuleAndReplacement rar : ruleAndReplacements) {
String rule = rar.getRule();
String replacement = rar.getReplacement();
// Return if we find a match.
Matcher matcher = Pattern.compile(rule, Pattern.CASE_INSENSITIVE).matcher(word);
if (matcher.find()) {
return matcher.replaceAll(replacement);
}
}
return word;
}
public String tableize(String className) {
return pluralize(underscore(className));
}
public String tableize(Class<?> klass) {
String className = klass.getName().replace(klass.getPackage().getName() + ".", "");
return tableize(className);
}
public static void plural(String rule, String replacement) {
plurals.add(0, new RuleAndReplacement(rule, replacement));
}
public static void singular(String rule, String replacement) {
singulars.add(0, new RuleAndReplacement(rule, replacement));
}
public static void irregular(String singular, String plural) {
plural(singular, plural);
singular(plural, singular);
}
public static void uncountable(String... words) {
for (String word : words) {
uncountables.add(word);
}
}
}
class RuleAndReplacement {
private String rule;
private String replacement;
public RuleAndReplacement(String rule, String replacement) {
this.rule = rule;
this.replacement = replacement;
}
public String getReplacement() {
return replacement;
}
public void setReplacement(String replacement) {
this.replacement = replacement;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
}
\ No newline at end of file
package cn.ibizlab.util.helper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringAdvUtils {
/**
* Set the cache size (entry count) of the sanitizedNameCache, camelizedWordsCache and underscoreWordsCache.
*/
public static final String NAME_CACHE_SIZE_PROPERTY = "cn.ibizlab.codegen.utils.namecache.cachesize";
/**
* Set the cache expiry (in seconds) of the sanitizedNameCache, camelizedWordsCache and underscoreWordsCache.
*/
public static final String NAME_CACHE_EXPIRY_PROPERTY = "cn.ibizlab.codegen.utils.namecache.expireafter.seconds";
// A cache of camelized words. The camelize() method is invoked many times with the same
// arguments, this cache is used to optimized performance.
private static Cache<Pair<String, Boolean>, String> camelizedWordsCache;
// A cache of underscored words, used to optimize the performance of the underscore() method.
private static Cache<String, String> underscoreWordsCache;
// A cache of escaped words, used to optimize the performance of the escape() method.
private static Cache<EscapedNameOptions, String> escapedWordsCache;
static {
int cacheSize = 200;
int cacheExpiry = 5;
camelizedWordsCache = Caffeine.newBuilder()
.maximumSize(cacheSize)
.expireAfterAccess(cacheExpiry, TimeUnit.SECONDS)
.ticker(Ticker.systemTicker())
.build();
escapedWordsCache = Caffeine.newBuilder()
.maximumSize(cacheSize)
.expireAfterAccess(cacheExpiry, TimeUnit.SECONDS)
.ticker(Ticker.systemTicker())
.build();
underscoreWordsCache = Caffeine.newBuilder()
.maximumSize(cacheSize)
.expireAfterAccess(cacheExpiry, TimeUnit.SECONDS)
.ticker(Ticker.systemTicker())
.build();
}
private static Pattern capitalLetterPattern = Pattern.compile("([A-Z]+)([A-Z][a-z][a-z]+)");
private static Pattern lowercasePattern = Pattern.compile("([a-z\\d])([A-Z])");
private static Pattern pkgSeparatorPattern = Pattern.compile("\\.");
private static Pattern dollarPattern = Pattern.compile("\\$");
/**
* Underscore the given word.
* Copied from Twitter elephant bird
* https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java
*
* @param word The word
* @return The underscored version of the word
*/
public static String underscore(final String word) {
return underscoreWordsCache.get(word, wordToUnderscore -> {
String result;
String replacementPattern = "$1_$2";
// Replace package separator with slash.
result = pkgSeparatorPattern.matcher(wordToUnderscore).replaceAll("/");
// Replace $ with two underscores for inner classes.
result = dollarPattern.matcher(result).replaceAll("__");
// Replace capital letter with _ plus lowercase letter.
result = capitalLetterPattern.matcher(result).replaceAll(replacementPattern);
result = lowercasePattern.matcher(result).replaceAll(replacementPattern);
result = result.replace('-', '_');
// replace space with underscore
result = result.replace(' ', '_');
result = result.toLowerCase(Locale.ROOT);
return result;
});
}
/**
* Dashize the given word.
*
* @param word The word
* @return The dashized version of the word, e.g. "my-name"
*/
public static String dashize(String word) {
return underscore(word).replaceAll("[_ ]+", "-");
}
/**
* Camelize name (parameter, property, method, etc) with upper case for first letter
* copied from Twitter elephant bird
* https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java
*
* @param word string to be camelize
* @return camelized string
*/
public static String camelize(String word) {
return camelize(word, false);
}
public static String pascalcase(String word) {
return camelize(word, false);
}
public static String camelcase(String word) {
return camelize(word, true);
}
public static String spinalcase(String word) {
return dashize(word);
}
public static String snakecase(String word) {
return underscore(word);
}
public static String pluralize(String word) {
return Inflector.getInstance().pluralize(camelcase(word).toLowerCase());
}
private static Pattern camelizeSlashPattern = Pattern.compile("\\/(.?)");
private static Pattern camelizeUppercasePattern = Pattern.compile("(\\.?)(\\w)([^\\.]*)$");
private static Pattern camelizeUnderscorePattern = Pattern.compile("(_)(.)");
private static Pattern camelizeHyphenPattern = Pattern.compile("(-)(.)");
private static Pattern camelizeDollarPattern = Pattern.compile("\\$");
private static Pattern camelizeSimpleUnderscorePattern = Pattern.compile("_");
/**
* Camelize name (parameter, property, method, etc)
*
* @param inputWord string to be camelize
* @param lowercaseFirstLetter lower case for first letter if set to true
* @return camelized string
*/
public static String camelize(final String inputWord, boolean lowercaseFirstLetter) {
Pair<String, Boolean> key = new ImmutablePair<>(underscore(inputWord), lowercaseFirstLetter);
return camelizedWordsCache.get(key, pair -> {
String word = pair.getKey();
Boolean lowerFirstLetter = pair.getValue();
// Replace all slashes with dots (package separator)
Matcher m = camelizeSlashPattern.matcher(word);
while (m.find()) {
word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/);
m = camelizeSlashPattern.matcher(word);
}
// case out dots
String[] parts = word.split("\\.");
StringBuilder f = new StringBuilder();
for (String z : parts) {
if (z.length() > 0) {
f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1));
}
}
word = f.toString();
m = camelizeSlashPattern.matcher(word);
while (m.find()) {
word = m.replaceFirst(Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/);
m = camelizeSlashPattern.matcher(word);
}
// Uppercase the class name.
m = camelizeUppercasePattern.matcher(word);
if (m.find()) {
String rep = m.group(1) + m.group(2).toUpperCase(Locale.ROOT) + m.group(3);
rep = camelizeDollarPattern.matcher(rep).replaceAll("\\\\\\$");
word = m.replaceAll(rep);
}
// Remove all underscores (underscore_case to camelCase)
m = camelizeUnderscorePattern.matcher(word);
while (m.find()) {
String original = m.group(2);
String upperCase = original.toUpperCase(Locale.ROOT);
if (original.equals(upperCase)) {
word = camelizeSimpleUnderscorePattern.matcher(word).replaceFirst("");
} else {
word = m.replaceFirst(upperCase);
}
m = camelizeUnderscorePattern.matcher(word);
}
// Remove all hyphens (hyphen-case to camelCase)
m = camelizeHyphenPattern.matcher(word);
while (m.find()) {
word = m.replaceFirst(m.group(2).toUpperCase(Locale.ROOT));
m = camelizeHyphenPattern.matcher(word);
}
if (lowerFirstLetter && word.length() > 0) {
int i = 0;
char charAt = word.charAt(i);
while (i + 1 < word.length() && !((charAt >= 'a' && charAt <= 'z') || (charAt >= 'A' && charAt <= 'Z'))) {
i = i + 1;
charAt = word.charAt(i);
}
i = i + 1;
word = word.substring(0, i).toLowerCase(Locale.ROOT) + word.substring(i);
}
// remove all underscore
word = camelizeSimpleUnderscorePattern.matcher(word).replaceAll("");
return word;
});
}
private static class EscapedNameOptions {
public EscapedNameOptions(String name, Set<String> specialChars, List<String> charactersToAllow, String appendToReplacement) {
this.name = name;
this.appendToReplacement = appendToReplacement;
if (specialChars != null) {
this.specialChars = Collections.unmodifiableSet(specialChars);
} else {
this.specialChars = Collections.emptySet();
}
if (charactersToAllow != null) {
this.charactersToAllow = Collections.unmodifiableList(charactersToAllow);
} else {
this.charactersToAllow = Collections.emptyList();
}
}
private String name;
private String appendToReplacement;
private Set<String> specialChars;
private List<String> charactersToAllow;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EscapedNameOptions that = (EscapedNameOptions) o;
return Objects.equals(name, that.name) &&
Objects.equals(appendToReplacement, that.appendToReplacement) &&
Objects.equals(specialChars, that.specialChars) &&
Objects.equals(charactersToAllow, that.charactersToAllow);
}
@Override
public int hashCode() {
return Objects.hash(name, appendToReplacement, specialChars, charactersToAllow);
}
}
/**
* Return the name with escaped characters.
*
* @param name the name to be escaped
* @param replacementMap map of replacement characters for non-allowed characters
* @param charactersToAllow characters that are not escaped
* @param appendToReplacement String to append to replaced characters.
* @return the escaped word
* <p>
* throws Runtime exception as word is not escaped properly.
*/
public static String escape(final String name, final Map<String, String> replacementMap,
final List<String> charactersToAllow, final String appendToReplacement) {
EscapedNameOptions ns = new EscapedNameOptions(name, replacementMap.keySet(), charactersToAllow, appendToReplacement);
return StringAdvUtils.escapedWordsCache.get(ns, wordToEscape -> {
String result = name.chars().mapToObj(c -> {
String character = String.valueOf((char) c);
if (charactersToAllow != null && charactersToAllow.contains(character)) {
return character;
} else if (replacementMap.containsKey(character)) {
return replacementMap.get(character) + (appendToReplacement != null ? appendToReplacement: "");
} else {
return character;
}
}).reduce( (c1, c2) -> c1 + c2).orElse(null);
if (result != null) return result;
throw new RuntimeException("Word '" + name + "' could not be escaped.");
});
}
}
......@@ -11,6 +11,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.sql.Timestamp;
import java.util.*;
......@@ -319,8 +320,27 @@ public class AuthenticationUser implements UserDetails
if(permissionList.getJSONArray("authorities")!=null){
authorities=new ArrayList<>();
permissionList.getJSONArray("authorities").
forEach(item->authorities.add(new SimpleGrantedAuthority(String.valueOf(item))));
forEach(item->{
if(item instanceof String)
authorities.add(new SimpleGrantedAuthority(String.valueOf(item)));
else if(item instanceof GrantedAuthority)
authorities.add((GrantedAuthority)item);
else
{
JSONObject json=(JSONObject)item;
if (json.getString("type").equals("OPPRIV")) {
authorities.add(JSONObject.parseObject(json.toString(), UAADEAuthority.class));
} else if (json.getString("type").equals("APPMENU")) {
authorities.add(JSONObject.parseObject(json.toString(), UAAMenuAuthority.class));
} else if (json.getString("type").equals("UNIRES")) {
authorities.add(JSONObject.parseObject(json.toString(), UAAUniResAuthority.class));
} else if (json.getString("type").equals("ROLE")) {
authorities.add(JSONObject.parseObject(json.toString(), UAARoleAuthority.class));
}
}
});
}
}
}
}
package cn.ibizlab.util.security;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Data
public class UAADEAuthority extends UAAGrantedAuthority {
private String entity;
private Integer enableorgdr;
private Integer enabledeptdr;
private Integer enabledeptbc;
private Long orgdr;
private Long deptdr;
private String deptbc;
private boolean dataset;
private String bscope;
private List<Map<String, String>> deAction = new ArrayList<>();
public UAADEAuthority(){
this.setType("OPPRIV");
}
@Override
public String getAuthority() {
return this.getName();
}
public void setAuthority(String name) {
}
}
package cn.ibizlab.util.security;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
@Data
public class UAAGrantedAuthority implements GrantedAuthority {
private String name;
private String type ;
private String systemid;
@Override
public String getAuthority() {
return null;
}
}
package cn.ibizlab.util.security;
import lombok.Data;
@Data
public class UAAMenuAuthority extends UAAGrantedAuthority {
private String menuTag;
public UAAMenuAuthority(){
this.setType("APPMENU");
}
@Override
public String getAuthority() {
return menuTag;
}
public void setAuthority(String menuTag) {
this.menuTag = menuTag;
}
}
package cn.ibizlab.util.security;
import lombok.Data;
@Data
public class UAARoleAuthority extends UAAGrantedAuthority {
private String roleTag;
public UAARoleAuthority(){
this.setType("ROLE");
}
@Override
public String getAuthority() {
return roleTag;
}
public void setAuthority(String roleTag) {
this.roleTag = roleTag;
}
}
package cn.ibizlab.util.security;
import lombok.Data;
@Data
public class UAAUniResAuthority extends UAAGrantedAuthority {
private String unionResTag;
public UAAUniResAuthority(){
this.setType("UNIRES");
}
@Override
public String getAuthority() {
return unionResTag;
}
public void setAuthority(String unionResTag) {
this.unionResTag = unionResTag;
}
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册