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

重置

上级 58416c04
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>ibzdata</artifactId>
<groupId>cn.ibizlab</groupId>
<version>1.0.0.0</version>
</parent>
<artifactId>ibzdata-boot</artifactId>
<name>Ibzdata Dev Monolithic Boot</name>
<description>Ibzdata Boot</description>
<dependencies>
<dependency>
<groupId>cn.ibizlab</groupId>
<artifactId>ibzdata-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cn.ibizlab</groupId>
<artifactId>ibzdata-provider-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cn.ibizlab</groupId>
<artifactId>ibzdata-app-web</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<!--由于boot是通过dependency来关联所有子项目,页面和配置等信息都存在与子项目中,
所以您在对boot进行打包前,需要先将子项目install到maven仓库,以确保boot可以正常引用所有完整的子项目-->
<profiles>
<profile>
<id>boot</id>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<finalName>ibzdata</finalName>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
<mainClass>cn.ibizlab.DevBootApplication</mainClass>
<outputDirectory>../</outputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
......@@ -218,10 +218,10 @@ public class DOModel implements Serializable {
if(this.getSchema()!=null&&("mongodb".equals(name)))
{
POSchema defaultPOSchema= TransUtils.PojoSchema2PO(this.getSchema());
if(defaultPOSchema!=null) {
poSchemas.put("mongodb", defaultPOSchema);
return defaultPOSchema;
POSchema documentPOSchema= TransUtils.PojoSchema2DocumentPO(this.getSchema());
if(documentPOSchema!=null) {
poSchemas.put(name, documentPOSchema);
return documentPOSchema;
}
}
......
......@@ -222,18 +222,49 @@ public class BaseData extends DataObj
@JsonIgnore
@JSONField(serialize = false)
public Map<String,BaseData> getParentData()
public Map<String,BaseData> getParentDatas()
{
return parentDatas;
}
public BaseData setParentDatas(Map<String,BaseData> parentDatas)
{
this.parentDatas=parentDatas;
return this;
}
public BaseData addParentData(String entity,Map data)
{
if(StringUtils.isEmpty(entity)||ObjectUtils.isEmpty(data))
return this;
if(parentDatas==null)
parentDatas=new LinkedHashMap<>();
BaseData parent=null;
if(parentDatas.containsKey(entity))
parent=parentDatas.get(entity);
else {
parent = new BaseData();
parentDatas.put(entity,parent);
}
parent.setAll(data);
return this;
}
public BaseData addParent(String entity,String key)
{
if(StringUtils.isEmpty(entity)||StringUtils.isEmpty(key))
return this;
if(parentDatas==null)
parentDatas=new LinkedHashMap<>();
parentDatas.put(entity,new BaseData().setKey(key));
BaseData parent=null;
if(parentDatas.containsKey(entity))
parent=parentDatas.get(entity);
else {
parent = new BaseData();
parentDatas.put(entity,parent);
}
parent.setKey(key);
return this;
}
......
......@@ -247,7 +247,8 @@ public class DynamicModelService {
IPSLinkDEField linkDEField = (IPSLinkDEField)defield;
metaFieldModel.setRefFieldId(linkDEField.getRelatedPSDEField().getId())
.setRefFieldName(linkDEField.getRelatedPSDEField().getName()).setRelationId(linkDEField.getPSDER().getId())
.setRelationName(linkDEField.getPSDER().getName()).setRelationCodeName(linkDEField.getPSDER().getCodeName()).setRefEntityName(linkDEField.getPSDER().getMajorPSDataEntity().getName());
.setRelationName(linkDEField.getPSDER().getName()).setRelationCodeName(linkDEField.getPSDER().getCodeName()).setRefEntityName(linkDEField.getPSDER().getMajorPSDataEntity().getName())
.setRefFieldCodeName(linkDEField.getRelatedPSDEField().getCodeName());
}
if(!ObjectUtils.isEmpty(defield.getAllPSDEFSearchModes()))
......@@ -277,7 +278,8 @@ public class DynamicModelService {
MetaRelationshipModel metaRel=new MetaRelationshipModel();
metaRel.setId(der.getId()).setName(der.getName()).setRelationType(der.getDERType()).setCodeName(der.getCodeName()).setRefEntityId(der.getMajorPSDataEntity().getId())
.setRefEntityName(der.getMajorPSDataEntity().getName()).setEntityId(dataEntity.getId()).setEntityName(dataEntity.getName()).setNestedName(der.getMinorCodeName())
.setRefEntityName(der.getMajorPSDataEntity().getName()).setRefEntityCodeName(der.getMajorPSDataEntity().getCodeName())
.setEntityId(dataEntity.getId()).setEntityName(dataEntity.getName()).setEntityCodeName(dataEntity.getCodeName()).setNestedName(der.getMinorCodeName())
.setSystemId(iPSSystem.getCodeName());
if(der instanceof IPSDER1N)
......@@ -307,7 +309,8 @@ public class DynamicModelService {
MetaRelationshipModel metaRel=new MetaRelationshipModel();
metaRel.setId(der.getId()).setName(der.getName()).setRelationType(der.getDERType()).setCodeName(der.getCodeName()).setRefEntityId(der.getMajorPSDataEntity().getId())
.setRefEntityName(der.getMajorPSDataEntity().getName()).setEntityId(dataEntity.getId()).setEntityName(dataEntity.getName()).setNestedName(der.getMinorCodeName())
.setRefEntityName(der.getMajorPSDataEntity().getName()).setRefEntityCodeName(der.getMajorPSDataEntity().getCodeName())
.setEntityId(dataEntity.getId()).setEntityName(dataEntity.getName()).setEntityCodeName(dataEntity.getCodeName()).setNestedName(der.getMinorCodeName())
.setSystemId(iPSSystem.getCodeName());
if(der instanceof IPSDER1N)
......
......@@ -115,6 +115,13 @@ public class MetaFieldModel {
@JsonProperty("ref_field_name")
@ApiModelProperty("引用属性名称")
private String refFieldName;
/**
* 引用属性代码名称
*/
@JSONField(name = "ref_field_code_name")
@JsonProperty("ref_field_code_name")
@ApiModelProperty("引用属性代码名称")
private String refFieldCodeName;
/**
* 引用关系标识
*/
......
......@@ -69,6 +69,13 @@ public class MetaRelationshipModel implements Serializable {
@JsonProperty("entity_name")
@ApiModelProperty("实体名称")
private String entityName;
/**
* 实体代码名称
*/
@JSONField(name = "entity_code_name")
@JsonProperty("entity_code_name")
@ApiModelProperty("实体代码名称")
private String entityCodeName;
/**
* 引用实体标识
*/
......@@ -83,6 +90,13 @@ public class MetaRelationshipModel implements Serializable {
@JsonProperty("ref_entity_name")
@ApiModelProperty("引用实体名称")
private String refEntityName;
/**
* 引用实体代码名称
*/
@JSONField(name = "ref_entity_code_name")
@JsonProperty("ref_entity_code_name")
@ApiModelProperty("引用实体代码名称")
private String refEntityCodeName;
/**
* 嵌套代码名称
*/
......
......@@ -742,9 +742,10 @@ public class POSchema {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
if(!entry.getKey().equalsIgnoreCase(entry.getValue()))
{
Object obj=source.get(entry.getKey());
Object obj=source.get(entry.getKey().toLowerCase());
source.remove(entry.getKey().toLowerCase());
source.set(entry.getValue().toLowerCase(),obj);
if(obj!=null||source.get(entry.getValue().toLowerCase())==null)
source.set(entry.getValue().toLowerCase(),obj);
}
}
return source;
......@@ -769,9 +770,10 @@ public class POSchema {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
if(!entry.getKey().equalsIgnoreCase(entry.getValue()))
{
Object obj=source.get(entry.getValue());
Object obj=source.get(entry.getValue().toLowerCase());
source.remove(entry.getValue().toLowerCase());
source.set(entry.getKey().toLowerCase(),obj);
if(obj!=null||source.get(entry.getKey().toLowerCase())==null)
source.set(entry.getKey().toLowerCase(),obj);
}
}
return source;
......
......@@ -160,6 +160,14 @@ public class PojoOption extends DataObj
return this.set("ref_field_name",refFieldName);
}
public String getRefFieldCodeName() {
return this.getStringValue("ref_field_code_name");
}
public PojoOption setRefFieldCodeName(String refFieldCodeName) {
return this.set("ref_field_code_name",refFieldCodeName);
}
public Boolean isKeyField() {
return this.getBooleanValue("key_field");
}
......
......@@ -39,6 +39,7 @@ public class PojoSchema {
@JSONField(ordinal = 1)
private String id;
......@@ -210,64 +211,102 @@ public class PojoSchema {
return this;
}
@JsonIgnore
@JSONField(serialize = false)
private Map<String,PojoSchema> references;
private List<PojoSchema> references;
public List<PojoSchema> getReferences()
{
if(references==null)
{
references=new ArrayList<>();
getProperties().values().forEach(prop->{
if(Type.object.getCode().equalsIgnoreCase(prop.getType())&&prop.getOptions()!=null&&(!StringUtils.isEmpty(prop.getOptions().getRelationName()))) {
references.add(prop);
}
});
}
return references;
}
@JsonIgnore
@JSONField(serialize = false)
public Map<String,PojoSchema> getReferences()
private Map<String,PojoSchema> referenceMap;
@JsonIgnore
@JSONField(serialize = false)
public Map<String,PojoSchema> getReferenceMap()
{
if(references==null)
if(referenceMap==null)
{
references=new LinkedHashMap<>();
referenceMap=new LinkedHashMap<>();
getProperties().keySet().forEach(key->{
PojoSchema prop=getProperties().get(key);
if(Type.object.getCode().equalsIgnoreCase(prop.getType())&&prop.getOptions()!=null&&(!StringUtils.isEmpty(prop.getOptions().getRelationName()))) {
references.put(key, prop);
referenceMap.put(key, prop);
if(!key.equals(key.toLowerCase()))
references.put(key.toLowerCase(),prop);
references.put(prop.getOptions().getRelationName(),prop);
referenceMap.put(key.toLowerCase(),prop);
referenceMap.put(prop.getOptions().getRelationName(),prop);
if(!StringUtils.isEmpty(prop.getOptions().getEntityName())) {
if(!references.containsKey(prop.getOptions().getEntityName()))
references.put(prop.getOptions().getEntityName(), prop);
if(!references.containsKey(prop.getOptions().getEntityName().toLowerCase()))
references.put(prop.getOptions().getEntityName().toLowerCase(),prop);
if(!referenceMap.containsKey(prop.getOptions().getEntityName()))
referenceMap.put(prop.getOptions().getEntityName(), prop);
if(!referenceMap.containsKey(prop.getOptions().getEntityName().toLowerCase()))
referenceMap.put(prop.getOptions().getEntityName().toLowerCase(),prop);
}
if(!StringUtils.isEmpty(prop.getOptions().getCodeName())) {
if(!references.containsKey(prop.getOptions().getCodeName()))
references.put(prop.getOptions().getCodeName(), prop);
if(!references.containsKey(prop.getOptions().getCodeName().toLowerCase()))
references.put(prop.getOptions().getCodeName().toLowerCase(), prop);
if(!referenceMap.containsKey(prop.getOptions().getCodeName()))
referenceMap.put(prop.getOptions().getCodeName(), prop);
if(!referenceMap.containsKey(prop.getOptions().getCodeName().toLowerCase()))
referenceMap.put(prop.getOptions().getCodeName().toLowerCase(), prop);
}
String pluralize=Inflector.getInstance().pluralize(StringUtils.isEmpty(prop.getOptions().getCodeName())?prop.getOptions().getEntityName():prop.getOptions().getCodeName()).toLowerCase();
if(!references.containsKey(pluralize))
references.put(pluralize, prop);
if(!referenceMap.containsKey(pluralize))
referenceMap.put(pluralize, prop);
}
});
}
return references;
return referenceMap;
}
public PojoSchema getRefSchema(String tag)
{
if(getReferences()!=null)
if(getReferenceMap()!=null)
{
return this.getReferences().get(tag);
return this.getReferenceMap().get(tag);
}
return null;
}
public Map<String,PojoSchema> getRefProperties()
{
Map<String,PojoSchema> refProperties=new LinkedHashMap<>();
if(this.getOwner()!=null&&Type.object.getCode().equalsIgnoreCase(this.getType())&&this.getOptions()!=null&&(!StringUtils.isEmpty(this.getOptions().getRelationName())))
{
this.getOwner().getProperties().entrySet().forEach(entry-> {
String key=entry.getKey();
if(key.equals(this.getName()))
return;
PojoSchema prop = entry.getValue();
if(prop.getOptions()!=null&&(!StringUtils.isEmpty(prop.getOptions().getRelationName()))&&prop.getOptions().getRelationName().equals(this.getOptions().getRelationName()))
{
refProperties.put(key,prop);
}
});
}
return refProperties;
}
public Map<String,PojoSchema> getRefProperties(String tag)
{
Map<String,PojoSchema> refProperties=new LinkedHashMap<>();
PojoSchema refSchema=this.getRefSchema(tag);
if(refSchema!=null)
{
getProperties().keySet().forEach(key-> {
getProperties().entrySet().forEach(entry-> {
String key=entry.getKey();
if(key.equals(refSchema.getName()))
return;
PojoSchema prop = getProperties().get(key);
PojoSchema prop = entry.getValue();
if(prop.getOptions()!=null&&(!StringUtils.isEmpty(prop.getOptions().getRelationName()))&&prop.getOptions().getRelationName().equals(refSchema.getOptions().getRelationName()))
{
refProperties.put(key,prop);
......@@ -565,7 +604,7 @@ public class PojoSchema {
if(unionKeys.size()!=keys.length&&keyMap.size()>1)
return null;
if(unionKeys.size()!=keys.length)
if(unionKeys.size()==keys.length)
{
int i=0;
for(PojoSchema keySchema:unionKeys.values())
......@@ -592,36 +631,68 @@ public class PojoSchema {
public BaseData fillParentKey(BaseData data)
{
if(ObjectUtils.isEmpty(data.getParentData()))
this.getReferences().forEach(refSchema->{
Object obj=data.get(refSchema.getName().toLowerCase());
if(obj!=null&&obj instanceof Map)
{
data.addParentData(refSchema.getName(),(Map)obj);
}
});
if(ObjectUtils.isEmpty(data.getParentDatas()))
{
return data;
}
data.getParentData().entrySet().forEach(entry->{
String refSchema=entry.getKey();
BaseData parent=entry.getValue();
for(Map.Entry<String,PojoSchema> keyset:this.getRefProperties(refSchema).entrySet())
Map<String,BaseData> parentDatas=new LinkedHashMap();
data.getParentDatas().entrySet().forEach(entry->{
String refSchemaKey=entry.getKey();
PojoSchema refSchema=this.getRefSchema(refSchemaKey);
if(refSchema!=null)
{
PojoSchema prop=keyset.getValue();
if(prop.getOptions()!=null)
BaseData parent=entry.getValue();
if(parent.keySet().size()==0)
return;
Map<String,PojoSchema> refProperties = refSchema.getRefProperties();
for(Map.Entry<String,PojoSchema> entrySet:refProperties.entrySet())
{
if("PICKUP".equalsIgnoreCase(prop.getOptions().getFieldType())) {
data.set(keyset.getKey().toLowerCase(), parent.getKey());
break;
PojoSchema prop=entrySet.getValue();
if(prop.getOptions()!=null)
{
if("PICKUP".equalsIgnoreCase(prop.getOptions().getFieldType())) {
if(!ObjectUtils.isEmpty(parent.getKey()))
data.set(entrySet.getKey().toLowerCase(), parent.getKey());
if(parent.keySet().size()==1)
break;
}
String refFieldCodeName=prop.getOptions().getRefFieldCodeName();
if((!StringUtils.isEmpty(refFieldCodeName))&&parent.get(refFieldCodeName.toLowerCase())!=null)
data.set(entrySet.getKey().toLowerCase(), parent.get(refFieldCodeName.toLowerCase()));
}
}
}
if(refProperties.size()>1)
{
if(!parentDatas.containsKey(refSchema.getName()))
parentDatas.put(refSchema.getName(),parent);
else
parentDatas.get(refSchema.getName()).setAll(parent);
}
}
});
data.setParentDatas(parentDatas);
return data;
}
public FilterData fillParentFilter(FilterData data)
{
if(ObjectUtils.isEmpty(data.getParentData()))
if(ObjectUtils.isEmpty(data.getParentDatas()))
{
return data;
}
data.getParentData().entrySet().forEach(entry->{
data.getParentDatas().entrySet().forEach(entry->{
String refSchema=entry.getKey();
BaseData parent=entry.getValue();
for(Map.Entry<String,PojoSchema> keyset:this.getRefProperties(refSchema).entrySet())
......
......@@ -323,6 +323,106 @@ public class TransUtils {
public static POSchema PojoSchema2DocumentPO(PojoSchema pojoSchema)
{
POSchema poSchema=new POSchema().setName(pojoSchema.getCodeName().toLowerCase()).setDefaultDataSource(pojoSchema.getDefaultDataSoruce())
.setRemarks(pojoSchema.getTitle()).setLogicVal(pojoSchema.getOptions().getLogicVal()).setLogicDelVal(pojoSchema.getOptions().getLogicDelVal());
for(String name:pojoSchema.getProperties().keySet())
{
PojoSchema sub=pojoSchema.getProperties().get(name);
String dataType=sub.getOptions().getDataType();
Integer length=sub.getOptions().getDataLength();
Integer precision=sub.getOptions().getDataPreci();
POSchema.Column column=new POSchema.Column().setName(name).setAlias(name).setRemarks(sub.getTitle()).setDefaultValue(sub.getOptions().getDefaultValue()).setPredefined(sub.getOptions().getPredefined()).setLength(length);
if(PojoSchema.Type.object.getCode().equals(sub.getType())||PojoSchema.Type.array.getCode().equals(sub.getType()))
{
if(!sub.getOptions().isPhysicalField())
continue;
if(StringUtils.isEmpty(dataType))dataType="TEXT";
column.setType(dataType);
column.setLength(null);
}
else if(PojoSchema.Type.string.getCode().equals(sub.getType())&&(!StringUtils.isEmpty(sub.getFormat())))
{
if(StringUtils.isEmpty(dataType)&&(sub.getFormat().indexOf("date")>=0))
dataType="DATETIME";
else
dataType="VARCHAR";
column.setType(dataType);
}
else if(PojoSchema.Type.integer.getCode().equals(sub.getType()) )
{
if(StringUtils.isEmpty(dataType))dataType="INT";
column.setType(dataType);
}
else if(PojoSchema.Type.number.getCode().equals(sub.getType()) )
{
if(StringUtils.isEmpty(dataType))dataType="NUMBER";
column.setType(dataType);
}
else {
if(StringUtils.isEmpty(dataType))dataType="VARCHAR";
column.setType(dataType);
}
if(column.isNumber())
column.setPrecision(precision);
if((pojoSchema.getRequired()!=null&&pojoSchema.getRequired().contains(name))||(!pojoSchema.getOptions().isNullable()))
column.getConstraints(true).setNullable(false);
if(pojoSchema.getKeyMap()!=null&&pojoSchema.getKeyMap().containsKey(column.getName())) {
String primaryKeyName="PK_"+poSchema.getName().toUpperCase()+"_"+ column.getName().toUpperCase();
column.getConstraints(true).setPrimaryKey(true).setPrimaryKeyName(primaryKeyName);
}
if(sub.getOptions().isLogicValidField())
{
if(!StringUtils.isEmpty(pojoSchema.getOptions().getLogicVal()))
column.setDefaultValue(pojoSchema.getOptions().getLogicVal());
else
column.setDefaultValue("1");
}
if(!StringUtils.isEmpty(sub.getOptions().getSearchModes()))
column.putSearchModes(sub.getOptions().getSearchModes());
if("PICKUP".equals(sub.getOptions().getFieldType())&&sub.getOptions().isPhysicalField())
{
PojoSchema relationshipModel=pojoSchema.getRefSchema(sub.getOptions().getRelationName());
String fkName=sub.getOptions().getRelationName().toUpperCase();
if((!StringUtils.isEmpty(relationshipModel.getOptions().getRefTableName()))&&(!StringUtils.isEmpty(fkName))) {
column.getConstraints(true).setReferencedTableName(relationshipModel.getOptions().getRefTableName()).setReferencedColumnNames(sub.getOptions().getRefFieldName()).setForeignKeyName(fkName);
poSchema.addForeignKeyConstraint(new POSchema.ForeignKeyConstraint().setConstraintName(fkName).setBaseTableName(poSchema.getName()).setBaseColumnNames(column.getName()).setReferencedTableName(relationshipModel.getOptions().getRefTableName()).setReferencedColumnNames(sub.getOptions().getRefFieldName()));
}
}
else if((!StringUtils.isEmpty(sub.getOptions().getRelationName()))) {
PojoSchema relationshipModel=pojoSchema.getRefSchema(sub.getOptions().getRelationName());
if(relationshipModel!=null&&(!StringUtils.isEmpty(relationshipModel.getOptions().getTableName()))) {
column.getConstraints(true).setReferencedTableName(relationshipModel.getOptions().getTableName())
.setReferencedColumnNames(sub.getOptions().getRefFieldName());
}
}
if(!sub.getOptions().isPhysicalField())
poSchema.addTransient(column.setComputed(true));
else
poSchema.addColumn(column);
}
String defaultQueryScript=pojoSchema.getOptions().getDefaultQueryScript();
if(!StringUtils.isEmpty(defaultQueryScript))
poSchema.setDefaultQueryScriptSQL(defaultQueryScript);
return poSchema;
}
public static POSchema EntityModelModel2PO(EntityModel entityModel,String dsType) {
final String dataSourceType=dsType.toLowerCase();
......
......@@ -15,12 +15,11 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Component
public class DynamicMongoContextHolder
{
private static final Map<String, MongoDbFactory> MONGO_CLIENT_DB_FACTORY_MAP = new HashMap<>();
private static final ThreadLocal<MongoDbFactory> MONGO_DB_FACTORY_THREAD_LOCAL =
public static final Map<String, MongoDbFactory> MONGO_CLIENT_DB_FACTORY_MAP = new HashMap<>();
public static final ThreadLocal<MongoDbFactory> MONGO_DB_FACTORY_THREAD_LOCAL =
new ThreadLocal<>();
public static MongoDbFactory getMongoDbFactory() {
......@@ -50,27 +49,6 @@ public class DynamicMongoContextHolder
MONGO_CLIENT_DB_FACTORY_MAP.remove(ds);
}
@Value("${spring.data.mongodb.uri:mongodb://localhost:27017/admin}")
private String uri;
@PostConstruct
public void init() {
if (!StringUtils.isEmpty(uri)) {
addFactory("master",uri);
}
}
@Bean(name = "mongoTemplate")
@Lazy(true)
public DynamicMongoTemplate dynamicMongoTemplate() {
Iterator<MongoDbFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
return new DynamicMongoTemplate(iterator.next());
}
@Bean(name = "mongoDbFactory")
@Lazy(true)
public MongoDbFactory mongoDbFactory() {
Iterator<MongoDbFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
return iterator.next();
}
}
package cn.ibizlab.core.data.mongodb;
package cn.ibizlab.core.data.repository;
import cn.ibizlab.core.data.dto.BaseData;
import cn.ibizlab.core.data.dto.FilterData;
import cn.ibizlab.core.data.model.POSchema;
import cn.ibizlab.core.data.mongodb.DynamicMongoContextHolder;
import cn.ibizlab.util.errors.BadRequestAlertException;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
......@@ -19,26 +21,34 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;
@Slf4j
@Component
public abstract class MongoDataRepository {
public class MongoDataRepository {
@Autowired
@Lazy
private MongoTemplate mongoTemplate;
/**
* 反射获取泛型类型
*
* @return
*/
protected abstract Class<BaseData> getEntityClass();
protected Class<BaseData> getEntityClass()
{
return BaseData.class;
}
/**
......@@ -112,12 +122,12 @@ public abstract class MongoDataRepository {
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
this.mongoTemplate.save(data, schema.getName());
return 1;
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
......@@ -125,31 +135,31 @@ public abstract class MongoDataRepository {
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
this.mongoTemplate.insert(list, schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public int updateData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
Query query = getKeyQuery(schema,data);
Update update = getUpdateByObject(data);
return (int)this.mongoTemplate.updateFirst(query, update, schema.getName()).getModifiedCount();
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public void updateBathData(String ds,POSchema schema, List<BaseData> list){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
list.forEach(data -> {
Query query = getKeyQuery(schema,data);
Update update = getUpdateByObject(data);
......@@ -157,49 +167,49 @@ public abstract class MongoDataRepository {
});
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public int removeData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return (int)this.mongoTemplate.remove(getKeyQuery(schema,data),schema.getName()).getDeletedCount();
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public int removeBathData(String ds,POSchema schema, List list){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return (int)mongoTemplate.remove(getKeyQuery(schema,list),schema.getName()).getDeletedCount();
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public int saveData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
Query query = getKeyQuery(schema,data);
Update update = getUpdateByObject(data);
return (int)this.mongoTemplate.upsert(query, update, schema.getName()).getModifiedCount();
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public void saveBatchData(String ds,POSchema schema, List<BaseData> list){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
list.forEach(data -> {
Query query = getKeyQuery(schema,data);
Update update = getUpdateByObject(data);
......@@ -207,40 +217,40 @@ public abstract class MongoDataRepository {
});
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public int countData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return (int)mongoTemplate.count(getQueryByObject(data),schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public List<BaseData> getData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return mongoTemplate.find(getKeyQuery(schema,data),getEntityClass(),schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public List<BaseData> getBatchData(String ds,POSchema schema, List<BaseData> list){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return mongoTemplate.find(getKeyQuery(schema,list),getEntityClass(),schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
......@@ -249,18 +259,18 @@ public abstract class MongoDataRepository {
public List<BaseData> selectData(String ds,POSchema schema, BaseData data){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
return mongoTemplate.find(getQueryByObject(data),getEntityClass(),schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public Page<BaseData> selectData(String ds,POSchema schema, BaseData data, Pageable page){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
if(page==null)
page= PageRequest.of(0,20, Sort.unsorted());
Query query = getQueryByObject(data);
......@@ -269,26 +279,26 @@ public abstract class MongoDataRepository {
return new PageImpl<BaseData>(list,page,total);
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public List<BaseData> queryData(String ds,POSchema schema, String sql, FilterData context){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
Query query = new BasicQuery(context.getQueryBuilder().get().toString());
return mongoTemplate.find(query,BaseData.class,schema.getName());
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
public Page<BaseData> queryData(String ds,POSchema schema, String sql, FilterData context, Pageable page){
try
{
DynamicDataSourceContextHolder.push(ds);
DynamicMongoContextHolder.push(ds);
if(page==null)
page=context.getPageable();
else
......@@ -299,7 +309,7 @@ public abstract class MongoDataRepository {
return new PageImpl<BaseData>(list,page,total);
}
finally {
DynamicDataSourceContextHolder.poll();
DynamicMongoContextHolder.poll();
}
}
......
......@@ -6,26 +6,29 @@ import cn.ibizlab.core.data.dto.RequestData;
import cn.ibizlab.core.data.dto.ResponseData;
import cn.ibizlab.core.data.service.IDataService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.security.AuthenticationUser;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.*;
@Slf4j
@Api(tags = {"数据" })
@RestController("api-data")
@RequestMapping({"/ibiz-repository/{system}/{scope}","/ibiz-repo/{system}",
"/ibiz-repository/{system}/{scope}/{parentEntity}/{parentKey}","/ibiz-repo/{system}/parentEntity}/{parentKey}",
"/ibiz-repository/{system}/{scope}/{parentEntity}/{parentKey}","/ibiz-repo/{system}/{parentEntity}/{parentKey}",
"/ibiz-repository/{system}/{scope}/{parentEntity}/{parentKey}/{parentEntity2}/{parentKey2}","/ibiz-repo/{system}/{parentEntity}/{parentKey}/{parentEntity2}/{parentKey2}"})
public class DataResource
{
......@@ -599,5 +602,47 @@ public class DataResource
}
@Value("${ibiz.enablePermissionValid:false}")
boolean enablePermissionValid; //是否开启权限校验
@RequestMapping(method = RequestMethod.GET, value = {"/appdata"})
public ResponseEntity<JSONObject> getAppData(@PathVariable(name = "system",required = true) String systemId) {
JSONObject appData = new JSONObject() ;
Set<String> appMenu = new HashSet();
Set<String> uniRes = new HashSet();
AuthenticationUser curUser = AuthenticationUser.getAuthenticationUser();
if(enablePermissionValid){
Collection<GrantedAuthority> authorities=curUser.getAuthorities();
Iterator it = authorities.iterator();
while(it.hasNext()) {
GrantedAuthority authority = (GrantedAuthority)it.next();
String strAuthority=authority.getAuthority();
if(strAuthority.startsWith("UNIRES_"+systemId)) {
uniRes.add(strAuthority.substring(systemId.length()+8));
}
else if(strAuthority.startsWith("APPMENU_"+systemId)){
appMenu.add(strAuthority.substring(systemId.length()+9));
}
}
}
Map<String,Object> context = new HashMap<>();
context.putAll(curUser.getSessionParams());
context.put("srfusername",curUser.getPersonname());
appData.put("context",context);
appData.put("unires",uniRes);
appData.put("appmenu",appMenu);
appData.put("enablepermissionvalid",enablePermissionValid);
if(curUser.getSuperuser()==1){
appData.put("enablepermissionvalid",false);
}
else{
appData.put("enablepermissionvalid",enablePermissionValid);
}
return ResponseEntity.status(HttpStatus.OK).body(appData);
}
}
......@@ -3,12 +3,14 @@ package cn.ibizlab.core.data.service.impl;
import cn.ibizlab.core.data.domain.DOModel;
import cn.ibizlab.core.data.dto.*;
import cn.ibizlab.core.data.model.DSLink;
import cn.ibizlab.core.data.model.PojoSchema;
import cn.ibizlab.core.data.service.IDOModelService;
import cn.ibizlab.core.data.service.IDSSettingService;
import cn.ibizlab.core.data.service.IDataService;
import cn.ibizlab.core.data.service.ModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
......@@ -18,6 +20,7 @@ import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 实体[业务实体] 无存储服务对象接口实现
......@@ -37,6 +40,7 @@ public class BaseDataService implements IDataService {
private DbDataServiceImpl dbProxyService;
@Autowired
@Lazy
private MongoDataServiceImpl mongoProxyService;
@Autowired
......@@ -212,7 +216,48 @@ public class BaseDataService implements IDataService {
public BaseData getDraft(DOModel model, String scope, String datasource, BaseData et)
{
if(StringUtils.isEmpty(datasource))datasource=model.getDefaultDataSource();
return getProxyService(datasource).getDraft(model,scope,datasource,et);
model.fillParentKey(et);
if(!ObjectUtils.isEmpty(et.getParentDatas()))
{
et.getParentDatas().entrySet().forEach(entry->{
String refSchemaKey=entry.getKey();
BaseData parent=entry.getValue();
if(parent.keySet().size()==0)
return;
PojoSchema refSchema=model.getSchema().getRefSchema(refSchemaKey);
Map<String,PojoSchema> refProperties=refSchema.getRefProperties();
if(refProperties.size()<=1)
return;
if((!StringUtils.isEmpty(refSchema.getName()))&&(!StringUtils.isEmpty(parent.getKey())))
{
String system=StringUtils.isEmpty(refSchema.getSystem())?model.getSystemId():refSchema.getSystem();
try{
BaseData parentData=this.getByMap(system,scope,refSchema.getOptions().getEntityName(),"",parent);
if(parentData!=null)
{
refProperties.entrySet().forEach(propEntry->{
PojoSchema prop=propEntry.getValue();
if(prop.getOptions()!=null)
{
String refFieldCodeName=prop.getOptions().getRefFieldCodeName();
if((!StringUtils.isEmpty(refFieldCodeName))&&parentData.get(refFieldCodeName.toLowerCase())!=null)
et.set(propEntry.getKey().toLowerCase(), parentData.get(refFieldCodeName.toLowerCase()));
}
});
}
}catch (Exception ex){log.error("填充上级数据失败"+refSchema.getOptions().getEntityName());}
}
});
}
return et;
}
@Override
......
......@@ -5,6 +5,7 @@ import cn.ibizlab.core.data.dto.*;
import cn.ibizlab.core.data.mapper.DbDataMapper;
import cn.ibizlab.core.data.model.DSLink;
import cn.ibizlab.core.data.model.POSchema;
import cn.ibizlab.core.data.model.PojoSchema;
import cn.ibizlab.core.data.service.IDSSettingService;
import cn.ibizlab.core.data.service.IDataService;
import cn.ibizlab.core.data.service.ModelService;
......@@ -248,6 +249,28 @@ public class DbDataServiceImpl implements IDataService {
@Override
public BaseData getDraft(DOModel model, String scope, String datasource, BaseData et)
{
model.fillParentKey(et);
if(!ObjectUtils.isEmpty(et.getParentDatas()))
{
et.getParentDatas().entrySet().forEach(entry->{
String refSchemaKey=entry.getKey();
BaseData parent=entry.getValue();
if(parent.keySet().size()==0)
return;
PojoSchema refSchema=model.getSchema().getRefSchema(refSchemaKey);
Map<String,PojoSchema> refProperties=refSchema.getRefProperties();
if(refProperties.size()<=1)
return;
if((!StringUtils.isEmpty(refSchema.getName()))&&(!StringUtils.isEmpty(parent.getKey())))
{
}
});
}
return et;
}
......
......@@ -7,16 +7,14 @@ import cn.ibizlab.core.data.dto.RequestData;
import cn.ibizlab.core.data.dto.ResponseData;
import cn.ibizlab.core.data.model.DSLink;
import cn.ibizlab.core.data.model.POSchema;
import cn.ibizlab.core.data.mongodb.MongoDataRepository;
import cn.ibizlab.core.data.repository.MongoDataRepository;
import cn.ibizlab.core.data.service.IDSSettingService;
import cn.ibizlab.core.data.service.IDataService;
import cn.ibizlab.core.data.service.ModelService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
......@@ -24,9 +22,7 @@ import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 实体[业务实体] 无存储服务对象接口实现
......@@ -38,7 +34,6 @@ public class MongoDataServiceImpl implements IDataService
@Autowired
@Lazy
private MongoDataRepository mongoDataRepository;
......@@ -184,7 +179,7 @@ public class MongoDataServiceImpl implements IDataService
if(StringUtils.isEmpty(datasource))datasource=model.getDefaultDataSource();
DSLink link=dsSettingService.getDataSource(datasource);
POSchema poSchema=model.getPOSchema(link.getType());
List<BaseData> list=mongoDataRepository.getData(link.getName(),poSchema,poSchema.trans2PO(et));
List<BaseData> list= mongoDataRepository.getData(link.getName(),poSchema,poSchema.trans2PO(et));
if(ObjectUtils.isEmpty(list)||list.size()>1)
throw new BadRequestAlertException("未找到数据",model.getName(),key.toString());
return poSchema.trans(list.get(0));
......@@ -223,7 +218,7 @@ public class MongoDataServiceImpl implements IDataService
if(StringUtils.isEmpty(datasource))datasource=model.getDefaultDataSource();
DSLink link=dsSettingService.getDataSource(datasource);
POSchema poSchema=model.getPOSchema(link.getType());
List<BaseData> list=mongoDataRepository.getData(link.getName(),poSchema,poSchema.trans2PO(et));
List<BaseData> list= mongoDataRepository.getData(link.getName(),poSchema,poSchema.trans2PO(et));
if(ObjectUtils.isEmpty(list)||list.size()>1)
throw new BadRequestAlertException("未找到数据",model.getName(),key.toString());
return poSchema.trans(list.get(0));
......@@ -245,7 +240,7 @@ public class MongoDataServiceImpl implements IDataService
if(StringUtils.isEmpty(datasource))datasource=model.getDefaultDataSource();
DSLink link=dsSettingService.getDataSource(datasource);
POSchema poSchema=model.getPOSchema(link.getType());
int cnt=mongoDataRepository.countData(link.getName(),poSchema,poSchema.trans2PO(et));
int cnt= mongoDataRepository.countData(link.getName(),poSchema,poSchema.trans2PO(et));
return cnt==1;
}
......@@ -300,7 +295,7 @@ public class MongoDataServiceImpl implements IDataService
if(StringUtils.isEmpty(datasource))datasource=model.getDefaultDataSource();
DSLink link=dsSettingService.getDataSource(datasource);
POSchema poSchema=model.getPOSchema(link.getType());
Page<BaseData> pages=mongoDataRepository.selectData(link.getName(),poSchema,poSchema.trans2PO(et),pageable);
Page<BaseData> pages= mongoDataRepository.selectData(link.getName(),poSchema,poSchema.trans2PO(et),pageable);
poSchema.trans(pages.getContent());
return pages;
}
......
package cn.ibizlab.core.util.config;
import cn.ibizlab.core.data.mongodb.DynamicMongoContextHolder;
import cn.ibizlab.core.data.mongodb.DynamicMongoTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@Configuration
public class MongoDBConfig {
@Value("${spring.data.mongodb.uri:mongodb://localhost:27017/admin}")
private String uri;
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
......@@ -25,6 +38,22 @@ public class MongoDBConfig {
return new MongoCustomConversions(converterList);
}
@Bean(name = "mongoTemplate")
@Lazy
public DynamicMongoTemplate mongoTemplate() {
if(DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.size()==0)
DynamicMongoContextHolder.addFactory("master",uri);
Iterator<MongoDbFactory> iterator = DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
return new DynamicMongoTemplate(iterator.next());
}
@Bean(name = "mongoDbFactory")
@Lazy
public MongoDbFactory mongoDbFactory() {
Iterator<MongoDbFactory> iterator = DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
return iterator.next();
}
public static class JSR310DateConverters {
private JSR310DateConverters() {
......
package cn.ibizlab.util.security;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
......@@ -239,6 +240,10 @@ public class AuthenticationUser implements UserDetails
if(userDetails instanceof AuthenticationUser ) {
authuserdetail= (AuthenticationUser)userDetails;
}
else if (userDetails!=null)
{
authuserdetail= JSON.parseObject(JSON.toJSONString(userDetails),AuthenticationUser.class);
}
else {
authuserdetail=new AuthenticationUser();
}
......
package cn.ibizlab.util.helper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DataObject {
final static public DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final static public DateFormat datetimeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
final static public DateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
final static public String getStringValue(Object objValue, String strDefault) {
if (objValue == null) {
return strDefault;
}
if (objValue instanceof String) {
return (String) objValue;
}
if (objValue instanceof java.sql.Timestamp||objValue instanceof java.sql.Date||objValue instanceof java.util.Date) {
String rt=datetimeFormat.format(objValue);
if(rt.endsWith(" 00:00:00")) {
rt=dayFormat.format(objValue);
}
return rt;
}
if(objValue instanceof BigDecimal)
{
return getBigDecimalValue(objValue,BigDecimal.ZERO).toString();
}
return objValue.toString();
}
public static <T> Object objectValueOf(Class<T> type,Object fieldValue) {
if(fieldValue==null) {
return null;
}
Object resultValue=fieldValue;
String targetType=type.getSimpleName();
if(targetType.equals(fieldValue.getClass().getSimpleName())){
return resultValue;
}
if(targetType.equals("Boolean")){
resultValue=getBooleanValue(fieldValue,false);
}
else if(targetType.equals("Character")){
resultValue=getCharacterValue(fieldValue,null);
}
else if(targetType.equals("Byte")){
resultValue=getBinaryValue(fieldValue,null);
}
else if(targetType.equals("Short")){
resultValue=Short.valueOf(fieldValue.toString());
}
else if(targetType.equals("Integer")){
resultValue= getIntegerValue(fieldValue,null);
}
else if(targetType.equals("Long")){
resultValue=getLongValue(fieldValue,null);
}
else if(targetType.equals("Float")){
resultValue= getFloatValue(fieldValue,null);
}
else if(targetType.equals("Double")){
resultValue= getDoubleValue(fieldValue,null);
}
else if(targetType.equals("BigDecimal")){
resultValue= getBigDecimalValue(fieldValue,null);
}
else if(targetType.equals("BigInteger")){
resultValue= getBigIntegerValue(fieldValue,null);
}
else if(targetType.equals("Timestamp")){
resultValue= getTimestampValue(fieldValue,null);
}
else if(targetType.equals("String")) {
resultValue= getStringValue(fieldValue,null);
}
if(resultValue==null) {
return null;
}
return resultValue;
}
public static <T> T valueOf(Class<T> type,Object fieldValue) {
return (T)objectValueOf(type,fieldValue);
}
final static public JSONObject getJSONObjectValue(Object objValue, JSONObject jDefault) {
if (objValue == null) {
return jDefault;
}
if(objValue instanceof JSONObject) {
return (JSONObject)objValue;
}
String strValue = objValue.toString();
try {
return JSONObject.parseObject(strValue);
}
catch (Exception ex)
{
return jDefault;
}
}
final static public JSONArray getJSONArrayValue(Object objValue, JSONArray jDefault) {
if (objValue == null) {
return jDefault;
}
if(objValue instanceof JSONArray) {
return (JSONArray)objValue;
}
String strValue = objValue.toString();
try {
return JSONArray.parseArray(strValue);
}
catch (Exception ex)
{
return jDefault;
}
}
final static public List<String> getListValue(Object objValue) {
if (objValue == null) {
return new ArrayList<String>();
}
JSONArray arr=(getJSONArrayValue(objValue,null));
if(arr!=null)
{
List<String> chk1=new ArrayList<>();
for(int i=0;i<arr.size();i++)
{
if(arr.get(i) instanceof String) {
chk1.add(arr.getString(i));
}
}
return chk1;
}
else
{
return new ArrayList<String>();
}
}
final static public Boolean getBooleanValue(Object objValue,Boolean bDefault) {
if (objValue == null) {
return bDefault;
}
if (objValue instanceof Boolean) {
return (Boolean) objValue;
}
return DataObject.getStringValue(objValue,"").equalsIgnoreCase("true")||objValue.toString().equals("1")||objValue.toString().equalsIgnoreCase("y");
}
final static public char[] getCharacterValue(Object objValue,char[] cDefault) {
if (objValue == null) {
return cDefault;
}
return objValue.toString().toCharArray();
}
final static public Double getDoubleValue(Object objValue,Double dDefault) {
if (objValue == null) {
return dDefault;
}
if (objValue instanceof Double) {
return (Double) objValue;
}
String strValue = objValue.toString();
if (StringUtils.isEmpty(strValue)) {
return null;
}
strValue = strValue.replace(",", "");
return Double.parseDouble(strValue);
}
final static public Integer getIntegerValue( Object objValue, Integer nDefault) {
if (objValue == null) {
return nDefault;
}
if(objValue instanceof Integer) {
return (Integer)objValue;
}
if (objValue instanceof Double) {
return ((Double) objValue).intValue();
}
if (objValue instanceof BigDecimal) {
return ((BigDecimal) objValue).intValue();
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue)) {
return nDefault;
}
strValue = strValue.replace(",", "");
return Integer.parseInt(strValue);
}
final static public Float getFloatValue( Object objValue, Float fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof Float) {
return (Float)objValue;
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue)) {
return fDefault;
}
strValue = strValue.replace(",", "");
return Float.parseFloat(strValue);
} catch (Exception ex) {
return fDefault;
}
}
final static public BigDecimal getBigDecimalValue( Object objValue, BigDecimal fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof BigDecimal){
return ((BigDecimal)(objValue)).stripTrailingZeros();
}
if(objValue instanceof Double){
return BigDecimal.valueOf((Double)objValue).stripTrailingZeros();
}
if(objValue instanceof Long){
return BigDecimal.valueOf((Long)objValue).stripTrailingZeros();
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue)) {
return fDefault;
}
strValue = strValue.replace(",", "");
return BigDecimal.valueOf(Double.parseDouble(strValue)).stripTrailingZeros();
} catch (Exception ex) {
return fDefault;
}
}
final static public BigInteger getBigIntegerValue( Object objValue, BigInteger fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof BigInteger){
return (BigInteger)(objValue);
}
else {
Long l=getLongValue(objValue,null);
if(l!=null) {
return BigInteger.valueOf(l);
}
}
} catch (Exception ex) {
}
return fDefault;
}
final static public Long getLongValue( Object objValue, Long nDefault) {
if (objValue == null) {
return nDefault;
}
try {
if (objValue instanceof Long) return (Long) objValue;
if (objValue instanceof Integer) {
return ((Integer) objValue).longValue();
}
if (objValue instanceof Double) {
return ((Double) objValue).longValue();
}
if (objValue instanceof BigDecimal) {
return ((BigDecimal) objValue).longValue();
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue)) {
return nDefault;
}
strValue = strValue.replace(",", "");
return Long.parseLong(strValue);
} catch (Exception ex) {
return nDefault;
}
}
final static public byte[] getBinaryValue(Object objValue, byte[] def) {
if (objValue == null) {
return def;
}
if(objValue instanceof byte[]){
return (byte[])objValue;
}
if (objValue instanceof String){
return Base64.getDecoder().decode((String) objValue);
}
return def;
}
/**
* 转换对象值到时间值
*
* @param objValue
* @return
* @
*/
final static public java.sql.Timestamp getTimestampValue(Object objValue,java.sql.Timestamp tDefault) {
if (objValue == null) {
return tDefault;
}
if (objValue instanceof java.sql.Timestamp) {
java.sql.Timestamp ti = (java.sql.Timestamp) objValue;
return ti;
}
if (objValue instanceof java.sql.Date) {
java.sql.Date date = (java.sql.Date) objValue;
return new java.sql.Timestamp(date.getTime());
}
if (objValue instanceof java.util.Date) {
java.util.Date date = (java.util.Date) objValue;
return new java.sql.Timestamp(date.getTime());
}
if (objValue instanceof String) {
String strValue = (String) objValue;
strValue = strValue.trim();
if (StringUtils.isEmpty(strValue)) {
return null;
}
try {
java.util.Date date = parse((String) objValue);
return new java.sql.Timestamp(date.getTime());
}
catch (Exception ex)
{
return tDefault;
}
}
if(objValue instanceof Long)
{
Long lValue = (Long)objValue;
return new java.sql.Timestamp(lValue);
}
if(objValue instanceof oracle.sql.TIMESTAMP)
{
try {
oracle.sql.TIMESTAMP tValue = (oracle.sql.TIMESTAMP)objValue;
return tValue.timestampValue();
} catch (SQLException e) {
return tDefault;
}
}
return tDefault;
}
public static Object testDateTime(String strInput) throws Exception{
return testDateTime(strInput, null);
}
/**
* 转换文本值到日期时间
*
* @param strInput
* @param timeZone
* @return
* @
*/
public static Object testDateTime(String strInput, TimeZone timeZone) throws Exception{
if (StringUtils.isEmpty(strInput)) {
return null;
}
Date dtDate = parse(strInput, timeZone);
java.sql.Timestamp retDate = new java.sql.Timestamp(dtDate.getTime());
return retDate;
}
/**
* 转换字符串到时间对象
*
* @param strTimeString
* @return
* @throws ParseException
* @
*/
public static Date parse(String strTimeString) throws ParseException, Exception {
return parse(strTimeString, null);
}
/**
* 分析时间串
*
* @param strTimeString MM/dd/yy yy-MM-dd HH:mm:ss 格式
* @param timeZone
* @return
* @throws ParseException
* @
*/
public static Date parse(String strTimeString, TimeZone timeZone) throws ParseException, Exception {
strTimeString = strTimeString.trim();
if(StringUtils.isEmpty(strTimeString)){
throw new Exception("unknown date(time) string");
}
if(strTimeString.indexOf("Z")!=-1){
//有时区
String[] parts = strTimeString.split("[Z]");
if(parts.length>=1){
strTimeString = parts[0];
}
if(parts.length>=2){
if(timeZone == null){
if(!StringUtils.isEmpty(parts[1])){
timeZone = TimeZone.getTimeZone(parts[1]);
}
}
}
}
// 判断是长数据还是短数据
String strPart[] = null;
if(strTimeString.indexOf("T")!=-1){
strPart = strTimeString.split("[T]");
}
else{
strPart = strTimeString.split(" ");
}
if (strPart.length == 2) {
// 两个部分
String strDate = "";
String strTime = "";
if (strPart[0].indexOf(":") != -1) {
strTime = strPart[0];
strDate = strPart[1];
} else {
strTime = strPart[1];
strDate = strPart[0];
}
strDate = strDate.trim();
strTime = strTime.trim();
strDate = getFormatDateString(strDate);
strTime = getFormatTimeString(strTime);
DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strDate + " " + strTime);
} else {
// 一个部分
if (strTimeString.indexOf(":") != -1) {
// 时间
strTimeString = getFormatTimeString(strTimeString);
DateFormat dtFormat = new SimpleDateFormat("HH:mm:ss");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strTimeString);
} else {
// 作为日期处理
strTimeString = getFormatDateString(strTimeString);
DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strTimeString);
}
}
}
/**
* 获取时间格式化串
*
* @param strOrigin
* @return
*/
private static String getFormatTimeString(String strOrigin) {
int nDotPos = strOrigin.indexOf(".");
if (nDotPos != -1) {
strOrigin = strOrigin.substring(0, nDotPos);
}
Object Time[] = new Object[3];
Time[0] = 0;
Time[1] = 0;
Time[2] = 0;
String timepart[] = strOrigin.split(":");
int nTimePartLength = timepart.length;
if (nTimePartLength > 3) {
nTimePartLength = 3;
}
for (int i = 0; i < nTimePartLength; i++) {
Time[i] = Integer.parseInt(timepart[i]);
}
return String.format("%1$02d:%2$02d:%3$02d", Time);
}
/**
* 获取时日期格式化串
*
* @param strOrigin
* @return
* @
*/
private static String getFormatDateString(String strOrigin) throws Exception{
return getFormatDateString(strOrigin, true);
}
/**
* 获取时日期格式化串
*
* @param strOrigin
* @param bAdv
* @return
* @
*/
private static String getFormatDateString(String strOrigin, boolean bAdv) throws Exception{
Object Date[] = new Object[3];
Date[0] = 1970;
Date[1] = 1;
Date[2] = 1;
if (strOrigin.indexOf("-") != -1) {
String datePart[] = strOrigin.split("-");
if (datePart.length >= 1) {
Date[0] = Integer.parseInt(datePart[0]);
}
if (datePart.length >= 2) {
Date[1] = Integer.parseInt(datePart[1]);
}
if (datePart.length >= 3) {
Date[2] = Integer.parseInt(datePart[2]);
}
}
else if (strOrigin.indexOf("/") != -1) {
String datePart[] = strOrigin.split("/");
if (datePart.length >= 1) {
Date[1] = Integer.parseInt(datePart[0]);
}
if (datePart.length >= 2) {
Date[2] = Integer.parseInt(datePart[1]);
}
if (datePart.length >= 3) {
Date[0] = Integer.parseInt(datePart[2]);
}
} else {
if (bAdv) {
strOrigin = strOrigin.replace(".", "-");
strOrigin = strOrigin.replace("日", "");
strOrigin = strOrigin.replace("天", "");
strOrigin = strOrigin.replace("年", "-");
strOrigin = strOrigin.replace("月", "-");
return getFormatDateString(strOrigin, false);
} else
throw new Exception("无法识别的时间字符串,"+strOrigin);
}
return String.format("%1$04d-%2$02d-%3$02d", Date);
}
public static Timestamp getBeginDate()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
cl.set(1900,1,1);
return new Timestamp(cl.getTime().getTime());
}
public static Timestamp getEndDate()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
cl.set(2100,12,31,23,59,59);
return new Timestamp(cl.getTime().getTime());
}
public static Timestamp getNow()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
return new Timestamp(cl.getTime().getTime());
}
}
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.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import java.util.*;
@RestController
@RequestMapping(value = "")
public class AppController {
@Value("${ibiz.enablePermissionValid:false}")
boolean enablePermissionValid; //是否开启权限校验
@Value("${ibiz.systemid:ibzdata}")
private String systemId;
@Autowired
private AuthenticationUserService userDetailsService;
@RequestMapping(method = RequestMethod.GET, value = {"/ibiz-repository/{system}/{scope}/appdata","/ibiz-repo/{system}/appdata","/appdata"})
public ResponseEntity<JSONObject> getAppData() {
JSONObject appData = new JSONObject() ;
Set<String> appMenu = new HashSet();
Set<String> uniRes = new HashSet();
AuthenticationUser curUser = AuthenticationUser.getAuthenticationUser();
if(enablePermissionValid){
Collection<GrantedAuthority> authorities=curUser.getAuthorities();
Iterator it = authorities.iterator();
while(it.hasNext()) {
GrantedAuthority authority = (GrantedAuthority)it.next();
String strAuthority=authority.getAuthority();
if(strAuthority.startsWith("UNIRES_"+systemId)) {
uniRes.add(strAuthority.substring(systemId.length()+8));
}
else if(strAuthority.startsWith("APPMENU_"+systemId)){
appMenu.add(strAuthority.substring(systemId.length()+9));
}
}
}
Map<String,Object> context = new HashMap<>();
context.putAll(curUser.getSessionParams());
context.put("srfusername",curUser.getPersonname());
appData.put("context",context);
appData.put("unires",uniRes);
appData.put("appmenu",appMenu);
appData.put("enablepermissionvalid",enablePermissionValid);
if(curUser.getSuperuser()==1){
appData.put("enablepermissionvalid",false);
}
else{
appData.put("enablepermissionvalid",enablePermissionValid);
}
fillAppData(appData);
return ResponseEntity.status(HttpStatus.OK).body(appData);
}
@RequestMapping(method = RequestMethod.GET, value = "${ibiz.auth.logoutpath:v7/logout}")
public void logout() {
if(AuthenticationUser.getAuthenticationUser()!=null){
userDetailsService.resetByUsername(AuthenticationUser.getAuthenticationUser().getUsername());
}
}
@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(StringUtils.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(StringUtils.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 (StringUtils.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){
}
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册