提交 e8deedf2 authored 作者: HASEE's avatar HASEE

model layer init

上级 e69ff4ee
......@@ -27,6 +27,69 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>cn.hutool</groupId>-->
<!-- <artifactId>hutool-all</artifactId>-->
<!-- <version>5.5.8</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
......
......@@ -2,14 +2,17 @@ package com.tykj.workflowcore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
* 测试时的启动类
* @author admin
*/
@SpringBootApplication
@EnableJpaAuditing
public class WorkflowCoreApplication {
public static void main(String[] args) {
SpringApplication.run(WorkflowCoreApplication.class, args);
}
......
package com.tykj.workflowcore.model_layer.annotatiion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @ClassName WorkFlowCoreNoScan
* @Description TODO
* @Author WWW
* @Date 2021/3/1 14:19
* @Version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WorkFlowCoreNoScan {
String desc ="工作流核心不扫描!";
}
package com.tykj.workflowcore.model_layer.controller;
import com.tykj.workflowcore.model_layer.dao.ColumnInfoDao;
import com.tykj.workflowcore.model_layer.model.ColumnInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @ClassName ColumnController
* @Description TODO
* @Author WWW
* @Date 2021/2/24 14:33
* @Version 1.0
*/
@RestController
@RequestMapping("/Column")
public class ColumnController {
@Autowired
private ColumnInfoDao columnInfoDao;
@PostMapping("/addColumnInfo")
public ColumnInfo addColumnInfo(@RequestBody ColumnInfo columnInfo) {
ColumnInfo save = columnInfoDao.save(columnInfo);
if (save != null) {
return save;
}
return null;
}
@GetMapping("/getInfo")
public List<ColumnInfo> getAll() {
List<ColumnInfo> all = columnInfoDao.findAll();
return all;
}
@GetMapping("/getInfo/{id}")
public ColumnInfo getOne(@PathVariable("id") long id) {
ColumnInfo one = columnInfoDao.findById(id).get();
return one;
}
}
package com.tykj.workflowcore.model_layer.controller;
import com.tykj.workflowcore.model_layer.model.ColumnInfo;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import com.tykj.workflowcore.model_layer.model.TableVO;
import com.tykj.workflowcore.model_layer.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* @ClassName ModelController
* @Description TODO
* @Author WWW
* @Date 2021/2/26 13:35
* @Version 1.0
*/
@RestController
@RequestMapping("/model")
public class ModelController {
@Autowired
private ModelService modelService;
@RequestMapping("/getAllEntity")
public List<TableInfo> getAllEntity() {
List<TableInfo> tableInfos = null;
try {
tableInfos = modelService.ListAllEntities();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return tableInfos;
}
@GetMapping("/getAllField")
public List<ColumnInfo> getFields(String tableName) {
List<ColumnInfo> all = modelService.showModelFields(tableName);
return all;
}
@PostMapping("/addModel")
public ResponseEntity addModel(@RequestBody String jsonStr) throws Exception {
TableVO tableVO = modelService.addModel(jsonStr);
List<TableInfo> tableInfos = modelService.ListAllEntities();
for (TableInfo tableInfo : tableInfos) {
if (tableVO.getModelName()!=null&&tableVO.getModelName().equals(tableInfo.getName())){
return new ResponseEntity(HttpStatus.BAD_GATEWAY);
}
}
modelService.NewTable(tableVO);
return new ResponseEntity(HttpStatus.ACCEPTED);
}
@PostMapping("/insertValues")
public int insertValues(@RequestBody Map<String,Object> map){
int i = modelService.putValueByEntityName(map);
return i;
}
}
package com.tykj.workflowcore.model_layer.controller;
import com.tykj.workflowcore.model_layer.dao.TableInfoDao;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName TableInfoController
* @Description TODO
* @Author WWW
* @Date 2021/2/24 13:46
* @Version 1.0
*/
@RestController
@RequestMapping("/table")
public class TableInfoController {
@Autowired
private TableInfoDao tableInfoDao;
@PostMapping("/addTable")
public TableInfo addTable(@RequestParam("tableName") String tableName) {
TableInfo tableInfo = new TableInfo();
tableInfo.setName(tableName);
TableInfo save = tableInfoDao.save(tableInfo);
if (save!=null){
return save;
}
return null;
}
}
package com.tykj.workflowcore.model_layer.dao;
import com.tykj.workflowcore.model_layer.model.ColumnInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @ClassName ColumnInfoDao
* @Description TODO
* @Author WWW
* @Date 2021/2/24 11:22
* @Version 1.0
*/
public interface ColumnInfoDao extends JpaRepository<ColumnInfo,Long>, JpaSpecificationExecutor<ColumnInfo> {
}
package com.tykj.workflowcore.model_layer.dao;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @ClassName TableInfoDao
* @Description TODO
* @Author WWW
* @Date 2021/2/24 11:20
* @Version 1.0
*/
public interface TableInfoDao extends JpaRepository<TableInfo,Long>, JpaSpecificationExecutor<TableInfo> {
}
package com.tykj.workflowcore.model_layer.model;
import com.tykj.workflowcore.model_layer.annotatiion.WorkFlowCoreNoScan;
import lombok.Data;
import javax.persistence.*;
/**
* @ClassName ColumnInfo
* @Description TODO
* @Author WWW
* @Date 2021/2/24 11:14
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Entity
@Table(name = "column_info")
@Data
public class ColumnInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long Id;
@Column(name = "name")
private String Name;
@Column(name = "cn_name")
private String CnName;
@Column(name = "type")
private String Type;
@Column(name = "length")
private int Length;
@Column(name = "db_name")
private String DbName;
@Column(name = "db_id")
private Long DbId;
}
package com.tykj.workflowcore.model_layer.model;
import com.tykj.workflowcore.model_layer.annotatiion.WorkFlowCoreNoScan;
import lombok.Data;
/**
* @ClassName ColumnVO
* @Description TODO
* @Author WWW
* @Date 2021/3/1 9:58
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Data
public class ColumnVO {
private String filedType;
private String fieldName;
private String filedDescription;
private int filedLength;
}
package com.tykj.workflowcore.model_layer.model;
import com.tykj.workflowcore.model_layer.annotatiion.WorkFlowCoreNoScan;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
/**
* @ClassName TableInfo
* @Description TODO
* @Author WWW
* @Date 2021/2/24 11:05
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "table_info")
@Data
public class TableInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long Id;
@Column(nullable = false,name = "name")
private String Name;
@Column(nullable = false,name = "cn_name")
private String CnName;
@Column(name = "description")
private String Desc;
@Column(name = "type")
private String Type;
@Column(name = "reviser")
private String Reviser;
@Lob
@Column(name = "xml",columnDefinition="TEXT")
private String XML;
@LastModifiedDate
@Column(nullable = false,name = "update_time")
private Date updateTime;
@CreatedDate
@Column(nullable = false, updatable = false,name = "create_time")
private Date createTime;
}
package com.tykj.workflowcore.model_layer.model;
import com.tykj.workflowcore.model_layer.annotatiion.WorkFlowCoreNoScan;
import lombok.Data;
import java.util.List;
/**
* @ClassName tableVO
* @Description TODO
* @Author WWW
* @Date 2021/3/1 9:56
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Data
public class TableVO {
private String modelTitle;
private String modelName;
private List<ColumnVO> dataList;
}
package com.tykj.workflowcore.model_layer.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.tykj.workflowcore.model_layer.model.ColumnInfo;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import com.tykj.workflowcore.model_layer.model.TableVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* @ClassName ModelService
* @Description TODO
* @Author WWW
* @Date 2021/2/26 13:36
* @Version 1.0
*/
@Transactional
@Service
public interface ModelService {
List<TableInfo> ListAllEntities() throws SQLException;
List<ColumnInfo> showModelFields(String ModelName);
TableVO addModel(String tableVO) throws JsonProcessingException;
TableVO NewTable(TableVO tableVO);
int putValueByEntityName(Map<String ,Object> map );
}
package com.tykj.workflowcore.model_layer.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tykj.workflowcore.model_layer.dao.ColumnInfoDao;
import com.tykj.workflowcore.model_layer.dao.TableInfoDao;
import com.tykj.workflowcore.model_layer.model.ColumnInfo;
import com.tykj.workflowcore.model_layer.model.ColumnVO;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import com.tykj.workflowcore.model_layer.model.TableVO;
import com.tykj.workflowcore.model_layer.service.ModelService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.internal.SessionImpl;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import javax.xml.crypto.Data;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @ClassName MoedelImpl
* @Description TODO
* @Author WWW
* @Date 2021/2/26 13:39
* @Version 1.0
*/
@Transactional
@Service
public class ModelImpl implements ModelService {
@Autowired
private Map<String, Object> cacheMap;
@Autowired
private EntityManagerFactory entityManagerFactory;
@Autowired
private TableInfoDao tableInfoDao;
@Autowired
private ColumnInfoDao columnInfoDao;
@Override
public List<TableInfo> ListAllEntities() {
List<TableInfo> all = tableInfoDao.findAll();
return all;
}
@Override
public List<ColumnInfo> showModelFields(String TableName) {
Specification specification = (Specification) (root, criteriaQuery, criteriaBuilder) -> {
Path db_name = root.get("DbName");
Predicate equal = criteriaBuilder.equal(db_name, TableName);
return equal;
};
List<ColumnInfo> all = columnInfoDao.findAll(specification);
return all;
}
@Override
public TableVO addModel(String jsonStr) {
ObjectMapper mapper = new ObjectMapper();
TableVO tableVO = null;
try {
tableVO = mapper.readValue(jsonStr, TableVO.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return tableVO;
}
@Override
public TableVO NewTable(TableVO tableVO) {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
sessionFactory.getSessionFactoryOptions();
List<ColumnVO> dataList = tableVO.getDataList();
String XML_MAPPING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE hibernate-mapping PUBLIC\n" +
" \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n" +
" \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">\n" +
"<hibernate-mapping>\n" +
" <class entity-name=\"" + tableVO.getModelName() + "\" table=\"" + tableVO.getModelName() + "\">\n";
XML_MAPPING += " <id name=\"id\" type=\"java.lang.Long\" length=\"64\" unsaved-value=\"null\">\n" +
" <generator class=\"identity\" />\n" +
" </id>";
for (ColumnVO columnVO : dataList) {
XML_MAPPING +=
" <property type=\"" + columnVO.getFiledType() + "\" name=\"" + columnVO.getFieldName() +
"\" column=\"" + columnVO.getFieldName() + "\"/>\n";
}
XML_MAPPING += " </class>" +
"</hibernate-mapping>";
metadataSources.addInputStream(new ByteArrayInputStream(XML_MAPPING.getBytes()));
Metadata metadata = metadataSources.buildMetadata();
//更新数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
SchemaUpdate schemaUpdate = new SchemaUpdate();
schemaUpdate.execute(EnumSet.of(TargetType.DATABASE), metadata, serviceRegistry);
metadata = metadataSources.buildMetadata();
//创建会话工厂
SessionFactory newSessionFactory = metadata.buildSessionFactory();
//保存对象
Session newSession = newSessionFactory.openSession();
// Map<String, Object> entity = new HashMap<>();
// for (ColumnVO columnVO : dataList) {
// entity.put( columnVO.getFieldName(),"2222");
// }
// newSession.save(tableVO.getModuleName(), entity);
cacheMap.put("tableName", tableVO.getModelName());
cacheMap.put("xml", XML_MAPPING);
TableInfo tableInfo = new TableInfo();
tableInfo.setName(tableVO.getModelName());
tableInfo.setCnName(tableVO.getModelTitle());
tableInfo.setXML(XML_MAPPING);
tableInfoDao.save(tableInfo);
for (ColumnVO columnVO : dataList) {
ColumnInfo columnInfo = new ColumnInfo();
columnInfo.setName(columnVO.getFieldName());
columnInfo.setType(columnVO.getFiledType());
columnInfo.setLength(columnVO.getFiledLength());
columnInfo.setCnName(columnVO.getFiledDescription());
columnInfo.setDbName(tableInfo.getCnName());
columnInfo.setDbId(tableInfo.getId());
columnInfoDao.save(columnInfo);
}
//关闭会话
newSession.close();
return tableVO;
}
@Override
public int putValueByEntityName(Map<String, Object> map) {
for (String tableName:
map.keySet()) {
//查找对应的表
Specification spec = (Specification) (root, criteriaQuery, criteriaBuilder) -> {
Predicate equal = null;
if (StringUtils.isEmpty("Name")) {
Path name = root.get("Name");
equal = criteriaBuilder.equal(name, tableName);
}
return equal;
};
Optional one = tableInfoDao.findOne(spec);
TableInfo tableInfo = null;
if (one.isPresent()){
tableInfo = (TableInfo) one.get();
}
Object values = map.get(tableName);
if (values instanceof Map){
//插入数据
insertValue(tableInfo.getName(),tableInfo.getXML(), (Map) values);
}else {
//循环插入数据
List valuesList = (List) values;
for (int i = 0; i < valuesList.size(); i++) {
insertValue(tableInfo.getName(),tableInfo.getXML(), (Map) valuesList.get(i));
}
}
}
return 0;
}
public void insertValue(String tableName,String xml,Map map){
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
sessionFactory.getSessionFactoryOptions();
metadataSources.addInputStream(new ByteArrayInputStream(xml.getBytes()));
Metadata metadata = metadataSources.buildMetadata();
//更新数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
SchemaUpdate schemaUpdate = new SchemaUpdate();
schemaUpdate.execute(EnumSet.of(TargetType.DATABASE), metadata, serviceRegistry);
metadata = metadataSources.buildMetadata();
//创建会话工厂
SessionFactory newSessionFactory = metadata.buildSessionFactory();
//保存对象
Session newSession = newSessionFactory.openSession();
newSession.saveOrUpdate(tableName,map);
}
}
package com.tykj.workflowcore.model_layer.utils;
import sun.net.www.protocol.jar.JarURLConnection;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @ClassName ClassScan
* @Description TODO
* @Author WWW
* @Date 2021/2/22 13:44
* @Version 1.0
*/
public class ClassScanUtil {
// /**
// * 扫描给定的基包下的所有的类(包括子包)。
// * @param basePackageName 基包的名称
// * @return 所有在基包下的类的全名
// */
// public static Set<String> scanBasePackage(String basePackageName){
// String packageDirName = basePackageName.replace(".", "/");
// URL url = Thread.currentThread().getContextClassLoader().getResource(packageDirName);
// System.out.println(url);
// File targetFile = new File(url.getFile());
// if(!targetFile.exists() || targetFile.isFile()){
// throw new RuntimeException(basePackageName + "不是一个包名或者该包名不存在");
// }
// Set<String> classNames = new HashSet<String>();
// getAllClass(targetFile, basePackageName, classNames);
// return classNames;
//
// }
/**
* 得到所有在parentFile目录下的class文件名称
* @param parentFile
* @param classNames
* @param basePackageName
*/
private static void getAllClass(File parentFile, String basePackageName, Set<String> classNames){
File[] files = parentFile.listFiles();
for(File file : files){
String path = file.getPath();
if(file.isFile()){
if(path.endsWith(".class")){
classNames.add(
basePackageName + "." +
path.substring(
path.lastIndexOf('\\') + 1, path.lastIndexOf('.')
)
);
}
}else{
basePackageName = basePackageName + path.substring(path.lastIndexOf('\\') + 1);
getAllClass(file, basePackageName, classNames);
}
}
}
public static Set<Class<?>> getClasses(String pack){
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try{
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()){
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
}else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try{
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()){
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
System.out.println(packageName+"666666666666");
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try{
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
}catch (ClassNotFoundException e){
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
}catch (IOException e){
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
}catch (IOException e){
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(
String packageName,
String packagePath,
final boolean recursive,
Set<Class<?>> classes){
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory()) || (file.getName().endsWith(".class")));
// 循环所有文件
for (File file : dirfiles){
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
}else{
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try{
// 添加到集合中去
// classes.add(Class.forName(packageName + '.' +
// className));
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
}catch (ClassNotFoundException e){
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
package com.tykj.workflowcore.model_layer.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Entity;
import java.lang.reflect.Field;
/**
* @ClassName JugdeSwagger
* @Description TODO
* @Author WWW
* @Date 2021/2/26 9:53
* @Version 1.0
*/
public class SwaggerUtil {
public static void Swagger(Class<?> aClass) {
if (aClass.isAnnotationPresent(Entity.class)) {
if (aClass.isAnnotationPresent(ApiModel.class)) {
ApiModel annotation = aClass.getAnnotation(ApiModel.class);
StringBuilder APiModelDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
APiModelDocument.append(aClass + "的文档:value=" + annotation.value().toString() + ".");
}
if (annotation.description() != null && !annotation.description().equals("")) {
APiModelDocument.append("description=" + annotation.description().toString() + ".");
}
System.out.println(APiModelDocument.toString());
}
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(ApiModelProperty.class)) {
ApiModelProperty annotation = declaredField.getAnnotation(ApiModelProperty.class);
StringBuilder ApiModelPropertyDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
// System.out.println(declaredField+"的文档是"+annotation.value());
ApiModelPropertyDocument.append(declaredField + "的文档:value=" + annotation.value() + ".");
}
if (annotation.example() != null && !annotation.example().equals("")) {
// System.out.println(declaredField+"的文档是"+annotation.value());
ApiModelPropertyDocument.append("example=" + annotation.example() + ".");
}
System.out.println(ApiModelPropertyDocument.toString());
}
}
}
}
public static boolean isSwagger(Class<?> aClass) {
if (aClass.isAnnotationPresent(Entity.class)) {
if (aClass.isAnnotationPresent(ApiModel.class)) {
return true;
}
}
return false;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论