Commit 42065119 by s_guodong

init

parents
HELP.md
target/
out/
model/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea/*
!.idea/artifacts
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
<?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>
<groupId>com.brilliance.report</groupId>
<artifactId>rmb-report-generator</artifactId>
<version>1.0-SNAPSHOT</version>
<name>generator</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<commons-io_version>2.4</commons-io_version>
<junit_version>4.11</junit_version>
</properties>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.62</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io_version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit_version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.brilliance.report.rmb.generator.util;
import cn.hutool.core.thread.GlobalThreadPool;
import org.apache.velocity.app.VelocityEngine;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
public class DZXTTemplateUtil {
public static VelocityEngine ve = null;
private static ExecutorService executorService;
public static CountDownLatch latch;
public static final String resource=Thread.currentThread().getContextClassLoader().getResource("").getPath();
private static void init(int size) throws IOException {
ve = new VelocityEngine();
ve.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, resource);
ve.setProperty("input.encoding", "UTF-8");
ve.setProperty("output.encoding", "UTF-8");
ve.init();
executorService = GlobalThreadPool.getExecutor();
latch=new CountDownLatch(size);
}
/**
* @param args
*/
public static void main(String[] args) {
try {
List<Map<String, Object>> sheets = ModelGenerator.init();
if(sheets.size()>0){
init(sheets.size());
Function<Map<String, Object>, Callable<Boolean>> task= sheet->()-> {
return ModelGenerator.generator(sheet);
};
sheets.forEach(sheet -> {
executorService.submit(task.apply(sheet));
});
latch.await();
}
} catch (Throwable e) {
e.printStackTrace();
}finally {
if(executorService!=null){
executorService.shutdownNow();
}
}
}
}
package com.brilliance.report.rmb.generator.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import java.util.List;
public class FastJsonUtil {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = {
SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
};
/**
* 转换成字符串
*
* @param object
* @return
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object, config);
}
/**
* 转换成字符串
*
* @param object
* @return
*/
public static String toJSONString(Object object,SimplePropertyPreFilter filter) {
return JSON.toJSONString(object, filter, new SerializerFeature[]{});
}
/**
* 转换成字符串 ,带有过滤器
*
* @param object
* @return
*/
public static String toJSONWithFeatures(Object object) {
return JSON.toJSONString(object, config, features);
}
/**
* 转成bean对象
*
* @param text
* @return
*/
public static Object toBean(String text) {
return JSON.parseObject(text);
}
/**
* 转成具体的泛型bean对象
*
* @param text
* @param clazz
* @param <T>
* @return
*/
public static <T> T toBean(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
/**
* 转换为数组Array
*
* @param text
* @param <T>
* @return
*/
public static <T> Object[] toArray(String text) {
return JSON.parseArray(text).toArray();
}
/**
* 转换为具体的泛型数组Array
*
* @param text
* @param clazz
* @param <T>
* @return
*/
public static <T> Object[] toArray(String text, Class<T> clazz) {
return JSON.parseArray(text, clazz).toArray();
}
/**
* 转换为具体的泛型List
* @param text
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> toList(String text, Class<T> clazz) {
return JSON.parseArray(text, clazz);
}
}
package com.brilliance.report.rmb.generator.util;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class ModelGenerator {
public static final URL excel = ModelGenerator.class.getClassLoader().getResource("msgstruct.xlsx");
private static final String TEMPLATENAM = "bean.vm";
private static final String MSG_PACKAGE = "com.brilliance.report.rmb.model";
private static final String COL_TAG = "tag";
private static final String COL_NAM = "nam";
private static final String COL_TYP = "typ";
private static final String COL_LEN = "len";
private static final String COL_RMK = "rmk";
private static final String COL_OPT = "opt";
private static final String COL_KEY = "key";
private static final String COL_CLASS = "class";
private static final String DES = "import com.brilliance.report.rmb.model.Desc;\n";
private static final String LEN = "import com.brilliance.report.rmb.model.Len;\n";
private static final String UNSIG = "import com.brilliance.report.rmb.model.UnSig;\n";
private static final String XJTA = "import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\n";
private static final String ACAA = "import com.brilliance.report.rmb.model.ActiveCurrencyAndAmount;\n";
private static final String NEED = "import com.brilliance.report.rmb.model.Need;\n";
private static final String LIST = "import java.util.List;\n";
private static final String HEAD = "import com.brilliance.report.rmb.model.HEAD;\n";
private static final String NODE_NAME = "obj";
private static final String LIST_NAME = "list";
private static final String TYPE_INTEGER = "Integer";
private static String outPth = System.getProperty("user.dir") + "/model/";
private static ThreadLocal<String> parentPth = new ThreadLocal<String>();
/**
* 读取msgstruc.xlsx文件,筛选出需要创建模型的sheet
*
* @return List 返回需要生成模型的sheet集合
*/
public static List<Map<String, Object>> init() throws IOException {
ExcelReader reader = ExcelUtil.getReader(excel.openStream(), 0);
List<Map<String, Object>> readAll = reader.readAll();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String cur = sdf.format(new Date());
List<Map<String, Object>> task = readAll.stream().filter(item -> {
if (item.get("create") != null && cur.equals(item.get("create").toString()) && StringUtils.isNotEmpty(item.get("name").toString())) {
return true;
}
return false;
}).collect(Collectors.toList());
return task;
}
public static Boolean generator(Map<String, Object> map) {
String sheet = null;
try {
// 报文类型
String type = map.get("type").toString();
// 文件名
sheet = map.get("name").toString();
// 生成主类
produceMainClass(type, sheet, map);
ExcelReader reader = ExcelUtil.getReader(excel.openStream(), sheet);
List<Map<String, Object>> readAll = reader.readAll();
List<Map<String, Object>> list = new ArrayList<>();
String clazzName = "";
for (int i = 0; i < readAll.size(); i++) {
Map<String, Object> item = readAll.get(i);
Object clazzNameObj = item.get(COL_CLASS);
if (clazzNameObj != null) {
if (StringUtil.isEmpty(clazzName)) {
clazzName = ((String) clazzNameObj).trim();
}
if (list.size() != 0) {
Map<String, Object> temPlateData = doGenerator(list, clazzName);
temPlateData.put("packagename", MSG_PACKAGE + "." + type.replaceAll("\\.", "_"));
temPlateData.put("classnameanno", clazzName);
createBean(temPlateData);
System.out.println("创建模型成功=" + FastJsonUtil.toJSONString(temPlateData));
list = new ArrayList<>();
clazzName = ((String) clazzNameObj).trim();
}
continue;
}
list.add(item);
}
if (list.size() != 0) {
Map<String, Object> temPlateData = doGenerator(list, clazzName);
temPlateData.put("packagename", MSG_PACKAGE + "." + type.replaceAll("\\.", "_"));
temPlateData.put("classnameanno", clazzName);
createBean(temPlateData);
System.out.println("创建模型成功=" + FastJsonUtil.toJSONString(temPlateData));
}
} catch (Throwable e) {
System.err.println(sheet + "执行时出现异常:" + e.getMessage());
e.printStackTrace();
return false;
} finally {
if (DZXTTemplateUtil.latch != null) {
DZXTTemplateUtil.latch.countDown();
}
System.out.println(sheet + "处理完");
}
return true;
}
private static Map<String, Object> doGenerator(List<Map<String, Object>> readAll, String sheet) {
Map<String, Object> temPlateData = generatorTemplateData(readAll, sheet);
if (temPlateData.isEmpty()) {
System.out.println(sheet + "数据为空,创建模型失败");
return null;
}
return temPlateData;
}
@SuppressWarnings("Duplicates")
private static Map<String, Object> generatorTemplateData(List<Map<String, Object>> raw, String rawClazNam) {
Map<String, Object> temPlateData = new HashMap<String, Object>();
List<Map<String, Object>> fields = new LinkedList<Map<String, Object>>();
String classname = rawClazNam.replaceAll("\\.", "_");
String packagename = MSG_PACKAGE + "." + classname;
StringBuilder sb = new StringBuilder();
classname = classname.substring(0, 1).toUpperCase()
+ classname.substring(1);
Map<String, Object> field = null;
for (int i = 0; i < raw.size(); i++) {
Map<String, Object> item = raw.get(i);
// 字段tag
String tag = item.get(COL_TAG).toString().trim();
// 字段类型
String fieldtype = item.get(COL_TYP) != null ? item.get(COL_TYP).toString().trim() : "";
// 字段中文名
String fieldCNName = item.get(COL_NAM) != null ? item.get(COL_NAM).toString().trim() : "";
// 字段是否必输信息
String opt = item.get(COL_OPT) != null ? item.get(COL_OPT).toString() : "";
// 字段备注
String rmk = item.get(COL_RMK) != null ? item.get(COL_RMK).toString().trim() : "";
// 字段长度
String len = item.get(COL_LEN) != null ? item.get(COL_LEN).toString().trim() : "";
field = new HashMap<>();
// 抓取字段注解
field.put("fieldannotation", new HashSet<String>());
// 抓取字段名
field.put("fieldname", tag);
if (tag.equals("HEAD") && sb.indexOf(HEAD) == -1) {
sb.append(HEAD);
}
// 抓取字段类型信息
if (NODE_NAME.equalsIgnoreCase(fieldtype)) {
field.put("fieldtyp", tag);
} else if (LIST_NAME.equalsIgnoreCase(fieldtype)) {
field.put("fieldtyp", "List<" + tag + ">");
if (sb.indexOf(LIST) == -1) {
sb.append(LIST);
}
} else if (TYPE_INTEGER.equalsIgnoreCase(fieldtype)) {
field.put("fieldtyp", "Integer");
} else {
field.put("fieldtyp", "String");
}
// 提取字段描述信息
((Set) field.get("fieldannotation")).add("@Desc(\"" + fieldCNName + "\")");
if (sb.indexOf(DES) == -1) {
sb.append(DES);
}
// 抓取字段是否必输信息
if (StringUtils.isNotEmpty(opt)) {
if (opt.contains("M")) {
((Set) field.get("fieldannotation")).add("@Need");
if (sb.indexOf(NEED) == -1) {
sb.append(NEED);
}
}
}
// 提取字段长度信息
if (StringUtil.isNotEmpty(len)) {
if (len.contains("[")) {
String s = len.replaceAll("\\[", "").replaceAll("]", "");
String[] split = s.split(",");
((Set) field.get("fieldannotation")).add("@Len(min = " + Integer.valueOf(split[0]) + ",max =" + Integer.valueOf(split[1]) + " )");
} else {
((Set) field.get("fieldannotation")).add("@Len(size =" + Integer.valueOf(len) + ")");
}
if (sb.indexOf(LEN) == -1) {
sb.append(LEN);
}
}
// 抓取字段备注信息
field.put("remark", rmk);
fields.add(field);
}
temPlateData.put("fields", fields);
temPlateData.put("packagename", packagename);
temPlateData.put("classname", classname);
temPlateData.put("fileName", classname + ".java");
if (sb.length() > 0) {
temPlateData.put("importpcg", sb.toString());
}
return temPlateData;
}
private static void createBean(Map<String, Object> cache) throws Exception {
createCode(TEMPLATENAM, cache);
}
private static void createCode(String tbp, Map<String, Object> cache)
throws IOException {
Template vt = DZXTTemplateUtil.ve.getTemplate(tbp);
VelocityContext context = new VelocityContext();
context.put("vm", cache);
StringWriter sw = new StringWriter();
vt.merge(context, sw);
writeToFile(sw.toString(), cache);
}
private static void writeToFile(String content, Map<String, Object> cache)
throws IOException {
FileWriter fw = null;
BufferedWriter bufWriter = null;
String secpth = cache.get("packagename").toString()
.replaceAll("\\.", "/");
String filePath = outPth + secpth + "/" + cache.get("fileName");
System.out.println("生成文件=" + filePath);
try {
File tmp = new File(filePath);
if (!tmp.getParentFile().exists()) {
tmp.getParentFile().mkdirs();
} else {
tmp.delete();
tmp.createNewFile();
}
fw = new FileWriter(filePath);
bufWriter = new BufferedWriter(fw);
bufWriter.append(content).flush();
} finally {
if (null != bufWriter) {
bufWriter.close();
}
if (null != fw) {
fw.close();
}
}
}
private static void produceMainClass(String type, String clazzName, Map map) throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put(COL_TAG, "HEAD");
map1.put(COL_TYP, NODE_NAME);
map1.put(COL_NAM, "报文头");
map1.put(COL_OPT, "M");
Map<String, Object> map2 = new HashMap<>();
map2.put(COL_TAG, "MSG");
map2.put(COL_TYP, NODE_NAME);
map2.put(COL_NAM, "报文体");
map2.put(COL_OPT, "M");
list.add(map1);
list.add(map2);
Map<String, Object> temPlateData = doGenerator(list, clazzName);
temPlateData.put("packagename", MSG_PACKAGE + "." + type.replaceAll("\\.", "_"));
temPlateData.put("classnameanno", "CFX");
Object nosign = map.get("nosign");
if (nosign != null && "√".equals(((String) nosign).trim())) {
temPlateData.put("nosign", map.get("nosign").toString());
temPlateData.put("importpcg", temPlateData.get("importpcg") + UNSIG);
}
createBean(temPlateData);
System.out.println("创建主模型成功=" + FastJsonUtil.toJSONString(temPlateData));
}
}
package com.brilliance.report.rmb.generator.util;
import org.bouncycastle.util.encoders.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class StringUtil {
private static final char[] DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final int Max = Integer.MAX_VALUE;
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static String file2Base64Str(String FilePath, String charset) throws UnsupportedEncodingException {
byte[] fileBytes = file2Bytes(FilePath);
String fileStr = null;
if (fileBytes != null) {
fileStr = new String(Base64.encode(fileBytes), charset);
}
return fileStr;
}
public static void base64Str2File(String base64Str, String FilePath) {
byte[] fileBytes = Base64.decode(base64Str);
writeBytes2File(fileBytes, FilePath, false);
}
private static void writeBytes2File(byte[] fileBytes, String filePath, boolean isAppend) {
File file = createFile(filePath);
FileOutputStream out = null;
try {
out = new FileOutputStream(file, isAppend);
out.write(fileBytes, 0, fileBytes.length);
out.flush();
} catch (IOException e1) {
throw new RuntimeException(e1);
} finally {
if (null != out) {
try {
out.close();
} catch (Exception e2) {
}
}
}
}
private static byte[] file2Bytes(String filePath) {
File file = createFile(filePath);
long len = file.length();
if (len >= Max) {
throw new RuntimeException("File is larger then max array size");
} else {
byte[] bytes = new byte[(int) len];
FileInputStream in = null;
try {
in = new FileInputStream(file);
int readLength = in.read(bytes);
if ((long) readLength < len) {
throw new IOException(String.format("File length is [%d] but read [%d]!", new Object[]{len, readLength}));
}
} catch (Exception e1) {
throw new RuntimeException(e1);
} finally {
if (null != in) {
try {
in.close();
} catch (Exception e2) {
}
}
}
return bytes;
}
}
private static File createFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
File parentFile = file.getParentFile();
if (null != parentFile && !parentFile.exists()) {
parentFile.mkdirs();
}
try {
file.createNewFile();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return file;
}
public static String md5Hex(String data, String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(data.getBytes(charset));
byte[] md5Bytes = md5.digest();
return encodeHexStr(md5Bytes);
}
public static String encodeHexStr(byte[] data) {
return new String(encodeHex(data));
}
public static char[] encodeHex(byte[] data) {
int len = data.length;
char[] out = new char[len << 1];
int i = 0;
for (int j = 0; i < len; ++i) {
out[j++] = DIGITS_LOWER[(data[i] >>> 4) & 0xF];
out[j++] = DIGITS_LOWER[0xF & data[i]];
}
return out;
}
}
#parse("util.vm")
package $vm.packagename;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#if($vm.importpcg)$vm.importpcg#end
@XmlType(propOrder = {#foreach($field in $vm.fields) "$field.fieldname"#if($foreach.hasNext),#end#end})
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "$vm.classnameanno")
#if($vm.nosign == '√')
@UnSig
#end
public class $vm.classname {
#foreach($field in $vm.fields)
#if($field.remark!='')
/**
* ${field.remark}
*/
#end
#foreach($fieldannotation in $field.fieldannotation)
$fieldannotation
#end
public ${field.fieldtyp} $field.fieldname;
#end
public $vm.classname () {
}
public $vm.classname (#foreach($field in $vm.fields)$field.fieldtyp $field.fieldname #if($foreach.hasNext),#end#end){
#foreach($field in $vm.fields)
this.$field.fieldname=$field.fieldname;
#end
}
}
\ No newline at end of file
##首字母大写
#macro(initUpperCase $field)$field.toUpperCase().substring(0,1)$field.substring(1)#end
##类名称简写,去掉类名前面的类路径
#macro(shortName $fullClassName)
#set($index = $fullClassName.lastIndexOf(".") + 1)
$fullClassName.substring($index)
#end
##全部小写
#macro(toLowerCase $field)$field.toLowerCase()#end
##全部大写
#macro(toUpperCase $field)$field.toUpperCase()#end
##首字母大写
#macro(initLowerCase $field)$field.toLowerCase().substring(0,1)$field.substring(1)#end
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment