一、前言
最近负责各式各样三方接口对接,从百度,阿里,腾讯,网易再到各种小三方,调三方接口难度不大,但是封装大量的参数让人不胜其烦,于是,在下一寻思,何不写个自动生成工具?
说干就干,根据阅读三方文档的经验来看,他们提供的参数信息一般是以表格形式展示,那么我的技术需求,首先的就是解析表单,接着,得到参数后,如果有合适的模版,不就可以了生成目标实体了么,vm模版,决定就是你了。
########注意
本工具类暂时只支持docx格式生成java实体类,其他的操作,后续补充。。。。。。。。
二、环境准备
1、引入所需pom文件
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、编写vm模版
package ${package}.${moduleName}.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
#if(${hasBigDecimal})
import java.math.BigDecimal;
#end
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class ${className} {
private static final long serialVersionUID = 1L;
#foreach ($property in $properties)
/**
* $property.comments
*/
#if($property.required == true)
@NonNull
#end
private $property.attrType $property.lowerAttrName;
#end
}
三、逻辑实现
public ResponseEntity<byte[]> genEntity(MultipartFile file, Entity entity) throws IOException {
//设置文件下载请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"",entity.getClassName().concat(".java")));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
//创建模版实例
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
// 载入(获取)模板对象
Template t = ve.getTemplate("Entity.java.vm");
VelocityContext ctx = new VelocityContext();
// 域对象加入参数值
ctx.put("author", entity.getAuthor());
ctx.put("datetime", (new Date()).toLocaleString());
ctx.put("package", entity.getPackageName());
ctx.put("moduleName", entity.getModuleName());
ctx.put("className", entity.getClassName());
ctx.put("comments", entity.getComments());
// list集合
List<Property> temp = new ArrayList<>();
// BufferedReader br = new BufferedReader(new FileReader(file));
XWPFDocument document = new XWPFDocument(file.getInputStream());
// 获取所有表格
int paramName = -1;
int paramType = -1;
int paramNeed = -1;
int paramConmment = -1;
List<XWPFTable> tables = document.getTables();
for (XWPFTable table : tables) {
// 获取表格的行
List<XWPFTableRow> rows = table.getRows();
//第一行为表格说明
List<XWPFTableCell> cells = rows.get(0).getTableCells();
rows.remove(0);
for (int i = 0; i < cells.size(); i++) {
String content = cells.get(i).getText();
if (content.matches("(.*字段)|(.*参数)")) {
paramName = i;
}else if (content.matches(".*类型")) {
paramType = i;
}else if (content.matches("(.*说明)|(.*描述)|(.*解释)")) {
paramConmment = i;
}else if (content.matches("是否.*")) {
paramNeed = i;
}
}
for (XWPFTableRow row : rows) {
// 获取表格的每个单元格
List<XWPFTableCell> tableCells = row.getTableCells();
Property p = new Property();
//将过长的说明合并为一行
if (paramConmment == -1) {
p.setComments("");
}else {
p.setComments(tableCells.get(paramConmment).getText().replaceAll("\\s",""));
}
if (paramType == -1) {
p.setAttrType("String");
}else {
p.setAttrType(tableCells.get(1).getText());
}
if (paramName == -1) {
return null;
}
p.setLowerAttrName(tableCells.get(0).getText());
if (paramNeed == -1) {
p.setRequired(false);
} else {
if ("是".equals(tableCells.get(2).getText()) || "true".equals(tableCells.get(2).getText())) {
p.setRequired(true);
} else {
p.setRequired(false);
}
}
temp.add(p);
}
}
//以下为读取txt格式的文档
/* String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split("\\s");
System.out.println(Arrays.toString(arr));
Property p = new Property();
p.setComments(arr[3]);
p.setAttrType(arr[1]);
p.setLowerAttrName(arr[0]);
if ("是".equals(arr[2]) || "true".equals(arr[2])) {
p.setRequired(true);
}else {
p.setRequired(false);
}
temp.add(p);
}*/
ctx.put("properties", temp);
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
System.out.println(sw.toString());
return ResponseEntity.ok().headers(headers)
.contentLength(sw.toString().getBytes().length).contentType(MediaType.parseMediaType
("application/octet-stream"))
.body(sw.toString().getBytes());
}
四、测试
1、准备docx文档数据
2、填充表格参数
3、获取实体类
五、资源
1、测试路径:http://106.12.121.80:8080/
2、项目下载:传送门