根据Table内容自动生成实体类

匿名 (未验证) 提交于 2019-12-02 23:03:14

一、前言

最近负责各式各样三方接口对接,从百度,阿里,腾讯,网易再到各种小三方,调三方接口难度不大,但是封装大量的参数让人不胜其烦,于是,在下一寻思,何不写个自动生成工具?

说干就干,根据阅读三方文档的经验来看,他们提供的参数信息一般是以表格形式展示,那么我的技术需求,首先的就是解析表单,接着,得到参数后,如果有合适的模版,不就可以了生成目标实体了么,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文档数据

参数

类型

是否必填

最大长度

描述

示例值

app_id

String

32

支付宝分配给开发者的应用ID

2014072300007148

method

String

128

接口名称

alipay.trade.fastpay.refund.query

format

String

40

仅支持JSON

JSON

charset

String

10

请求使用的编码格式,如utf-8,gbk,gb2312等

utf-8

sign_type

String

10

商户生成签

名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2

RSA2

sign

String

344

商户请求参数的签名串,详见签名

详见示例

timestamp

String

19

发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"

2014-07-24 03:07:50

version

String

3

调用的接口版本,固定为:1.0

1.0

app_auth_token

String

40

详见应用授权概述

biz_content

String

请求参数的集合,最大长度不限,除公共参数外所有请求参数都必须放在这个参数中传递,具体参照各产品快速接入文档

2、运行项目,并请求

3、获取实体类

五、资源

1、测试路径http://106.12.121.80:8080/

2、项目下载:传送门

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!