代码初始化提交。

This commit is contained in:
wangzhijiang
2024-02-20 09:33:24 +08:00
parent c66445edd4
commit 8abe03b22a
2184 changed files with 718173 additions and 0 deletions
@@ -0,0 +1,28 @@
<?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">
<parent>
<artifactId>laws-base</artifactId>
<groupId>com.jero.boot</groupId>
<version>2.5.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<description>代码生成核心模块</description>
<artifactId>laws-base-generater-core</artifactId>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.version}</version>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,23 @@
package com.jero.codegenerate.database;
import com.jero.codegenerate.properties.CodeConfigProperties;
public class CodegenDatasourceConfig {
private CodegenDatasourceConfig() {
}
/**
* 加载配置
* @date 2021/4/2 10:29
* @param driverName 驱动
* @param url 地址
* @param username 用户名
* @param password 密码
* @return void
*/
public static void initDbConfig(String driverName, String url, String username, String password) {
CodeConfigProperties.driverName = driverName;
CodeConfigProperties.databaseUrl = url;
CodeConfigProperties.username = username;
CodeConfigProperties.password = password;
}
}
@@ -0,0 +1,581 @@
package com.jero.codegenerate.database;
import com.jero.codegenerate.database.util.CodeStringUtils;
import com.jero.codegenerate.database.util.DbConvertDef;
import com.jero.codegenerate.generate.pojo.ColumnVo;
import com.jero.codegenerate.generate.util.TableConvert;
import com.jero.codegenerate.properties.CodeConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import java.sql.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class DbReadTableUtil {
private DbReadTableUtil() {
}
private static final String CONNECT_DATABASE_NAME = " connect databaseName : ";
private static final String COLUMN_GET_FIELD_NAME = "columnt.getFieldName() -------------";
public static void main(String[] args) throws SQLException {
try {
List<ColumnVo> list = listColumns("demo");
for (ColumnVo columnVo : list) {
log.info(columnVo.getFieldName());
}
} catch (Exception e) {
e.printStackTrace();
}
new DbReadTableUtil();
log.info(ArrayUtils.toString(listTableName()));
}
/**
* 获取所有表名的集合
* @date 2021/4/2 4:29
* @param
* @return java.util.List<java.lang.String>
*/
public static List<String> listTableName() throws SQLException {
String sqlStr = null;
ArrayList<String> list = new ArrayList<>(0);
Connection connection = null;
Statement statement = null;
try {
Class.forName(CodeConfigProperties.driverName);
connection = DriverManager.getConnection(CodeConfigProperties.databaseUrl, CodeConfigProperties.username, CodeConfigProperties.password);
statement = connection.createStatement(1005, 1007);
// 表格所属的库
String catalog = connection.getCatalog();
log.info(CONNECT_DATABASE_NAME + catalog);
if (CodeConfigProperties.databaseType.equals(DbConvertDef.MYSQL)) {
// mysql查询所有表的sql
sqlStr = MessageFormat.format(DbConvertDef.MYSQL_ALLTABLES_SQL, TableConvert.formatStr(catalog));
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.ORACLE)) {
// oracle查询所有表的sql
sqlStr = DbConvertDef.ORACLE_ALLTABLES_SQL;
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.POSTGRESQL)) {
// postgresql查询所有表的sql
sqlStr = DbConvertDef.POSTGRESQL_ALLTABLES_SQL;
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.SQLSERVER)) {
// sqlserver查询所有表的sql
sqlStr = DbConvertDef.SQLSERVER_ALLTABLES_SQL;
}
log.debug("--------------sql-------------" + sqlStr);
ResultSet resultSet = statement.executeQuery(sqlStr);
while(resultSet.next()) {
String tableName = resultSet.getString(1);
list.add(tableName);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
/**
* 获取一个表的所有列(字段)信息集合
* @date 2021/4/2 9:29
* @param tableName
* @return java.util.List<com.jero.codegenerate.generate.pojo.ColumnVo>
*/
public static List<ColumnVo> listColumns(String tableName) throws SQLException, ClassNotFoundException {
String sqlStr = null;
ArrayList<ColumnVo> list = new ArrayList<>();
Connection connection = null;
Statement statement = null;
int row;
try {
Class.forName(com.jero.codegenerate.properties.CodeConfigProperties.driverName);
connection = DriverManager.getConnection(com.jero.codegenerate.properties.CodeConfigProperties.databaseUrl, com.jero.codegenerate.properties.CodeConfigProperties.username, com.jero.codegenerate.properties.CodeConfigProperties.password);
statement = connection.createStatement(1005, 1007);
// 表格所属的库
String catalog = connection.getCatalog();
log.info(CONNECT_DATABASE_NAME + catalog);
sqlStr = getSqlStr(tableName, sqlStr, catalog);
log.debug("--------------sql-------------" + sqlStr);
ResultSet resultSet = statement.executeQuery(sqlStr);
// 游标指向结果集末尾
resultSet.last();
// 返回结果是当前数据集的行号,而不是结果的行数
row = resultSet.getRow();
if (row <= 0) {
throw new IllegalArgumentException("该表不存在或者表中没有字段");
}
ColumnVo columnVo = new ColumnVo();
setColumn(resultSet, columnVo);
columnVo.setFieldDbName(resultSet.getString(1).toUpperCase());
columnVo.setFieldType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
columnVo.setFieldDbType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
columnVo.setPrecision(resultSet.getString(4));
columnVo.setScale(resultSet.getString(5));
columnVo.setCharmaxLength(resultSet.getString(6));
columnVo.setNullable(TableConvert.getNullable(resultSet.getString(7)));
setupColumnVo(columnVo);
columnVo.setFiledComment(StringUtils.isBlank(resultSet.getString(3)) ? columnVo.getFieldName() : resultSet.getString(3));
log.debug(COLUMN_GET_FIELD_NAME + columnVo.getFieldName());
String[] pageFilterFieldsStrings = new String[0];
if (com.jero.codegenerate.properties.CodeConfigProperties.pageFilterFields != null) {
pageFilterFieldsStrings = com.jero.codegenerate.properties.CodeConfigProperties.pageFilterFields.toLowerCase().split(",");
}
// 字段名不等与表id名&&查询字段不包括数据库名
if (!com.jero.codegenerate.properties.CodeConfigProperties.dbTableId.equals(columnVo.getFieldName()) && !CodeStringUtils.isPageFilterFieldsContainDbName(columnVo.getFieldDbName().toLowerCase(), pageFilterFieldsStrings)) {
list.add(columnVo);
}
while(resultSet.previous()) {
ColumnVo columnVo1 = new ColumnVo();
setColumn(resultSet, columnVo1);
columnVo1.setFieldDbName(resultSet.getString(1).toUpperCase());
log.debug(COLUMN_GET_FIELD_NAME + columnVo1.getFieldName());
getList(list, resultSet, pageFilterFieldsStrings, columnVo1);
}
log.debug("读取表成功");
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
ArrayList<ColumnVo> result = new ArrayList<>();
for(row = list.size() - 1; row >= 0; --row) {
ColumnVo columnVo = list.get(row);
result.add(columnVo);
}
return result;
}
private static void getList(ArrayList<ColumnVo> list, ResultSet resultSet, String[] pageFilterFieldsStrings, ColumnVo columnVo1) throws SQLException {
if (!CodeConfigProperties.dbTableId.equals(columnVo1.getFieldName()) && !CodeStringUtils.isPageFilterFieldsContainDbName(columnVo1.getFieldDbName().toLowerCase(), pageFilterFieldsStrings)) {
columnVo1.setFieldType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
columnVo1.setFieldDbType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
log.debug("-----po.setFieldType------------" + columnVo1.getFieldType());
columnVo1.setPrecision(resultSet.getString(4));
columnVo1.setScale(resultSet.getString(5));
columnVo1.setCharmaxLength(resultSet.getString(6));
columnVo1.setNullable(TableConvert.getNullable(resultSet.getString(7)));
setupColumnVo(columnVo1);
columnVo1.setFiledComment(StringUtils.isBlank(resultSet.getString(3)) ? columnVo1.getFieldName() : resultSet.getString(3));
list.add(columnVo1);
}
}
/**
* 获取该表下原本所有列(字段)信息的集合
* @date 2021/4/2 10:02
* @param tableName
* @return java.util.List<com.jero.codegenerate.generate.pojo.ColumnVo>
*/
public static List<ColumnVo> listOriginalColumns(String tableName) throws SQLException, ClassNotFoundException {
ResultSet resultSet;
String sqlStr = null;
ArrayList<ColumnVo> list = new ArrayList<>();
Connection connection = null;
Statement statement = null;
int row;
try {
Class.forName(com.jero.codegenerate.properties.CodeConfigProperties.driverName);
connection = DriverManager.getConnection(com.jero.codegenerate.properties.CodeConfigProperties.databaseUrl, com.jero.codegenerate.properties.CodeConfigProperties.username, com.jero.codegenerate.properties.CodeConfigProperties.password);
statement = connection.createStatement(1005, 1007);
// 表格所属的库
String catalog = connection.getCatalog();
log.info(CONNECT_DATABASE_NAME + catalog);
sqlStr = getSqlStr(tableName, sqlStr, catalog);
resultSet = statement.executeQuery(sqlStr);
// 游标指向结果集末尾
resultSet.last();
// 返回结果是当前数据集的行号,而不是结果的行数
row = resultSet.getRow();
if (row <= 0) {
throw new IllegalArgumentException("该表不存在或者表中没有字段");
}
ColumnVo columnVo = new ColumnVo();
setColumn(resultSet, columnVo);
columnVo.setFieldDbName(resultSet.getString(1).toUpperCase());
columnVo.setPrecision(TableConvert.isFieldValueBlank(resultSet.getString(4)));
columnVo.setScale(TableConvert.isFieldValueBlank(resultSet.getString(5)));
columnVo.setCharmaxLength(TableConvert.isFieldValueBlank(resultSet.getString(6)));
columnVo.setNullable(TableConvert.getNullable(resultSet.getString(7)));
columnVo.setFieldType(getFieldType(resultSet.getString(2).toLowerCase(), columnVo.getPrecision(), columnVo.getScale()));
columnVo.setFieldDbType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
setupColumnVo(columnVo);
columnVo.setFiledComment(StringUtils.isBlank(resultSet.getString(3)) ? columnVo.getFieldName() : resultSet.getString(3));
log.debug(COLUMN_GET_FIELD_NAME + columnVo.getFieldName());
list.add(columnVo);
while(true) {
if (!resultSet.previous()) {
log.debug("读取表成功");
break;
}
ColumnVo columnVo1 = new ColumnVo();
setColumn(resultSet, columnVo1);
columnVo1.setFieldDbName(resultSet.getString(1).toUpperCase());
columnVo1.setPrecision(TableConvert.isFieldValueBlank(resultSet.getString(4)));
columnVo1.setScale(TableConvert.isFieldValueBlank(resultSet.getString(5)));
columnVo1.setCharmaxLength(TableConvert.isFieldValueBlank(resultSet.getString(6)));
columnVo1.setNullable(TableConvert.getNullable(resultSet.getString(7)));
columnVo1.setFieldType(getFieldType(resultSet.getString(2).toLowerCase(), columnVo1.getPrecision(), columnVo1.getScale()));
columnVo1.setFieldDbType(convertFieldNameToCamelCase(resultSet.getString(2).toLowerCase()));
setupColumnVo(columnVo1);
columnVo1.setFiledComment(StringUtils.isBlank(resultSet.getString(3)) ? columnVo1.getFieldName() : resultSet.getString(3));
list.add(columnVo1);
}
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
ArrayList<ColumnVo> result = new ArrayList<>();
for(row = list.size() - 1; row >= 0; --row) {
ColumnVo columnVo = list.get(row);
result.add(columnVo);
}
return result;
}
private static void setColumn(ResultSet resultSet, ColumnVo columnVo1) throws SQLException {
if (CodeConfigProperties.dbFiledConvert) {
columnVo1.setFieldName(convertFieldNameToCamelCase(resultSet.getString(1).toLowerCase()));
} else {
columnVo1.setFieldName(resultSet.getString(1).toLowerCase());
}
}
private static String getSqlStr(String tableName, String sqlStr, String catalog) {
if (CodeConfigProperties.databaseType.equals(DbConvertDef.MYSQL)) {
// mysql查询表的所有列信息sql
sqlStr = MessageFormat.format(DbConvertDef.MYSQL_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName), TableConvert.formatStr(catalog));
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.ORACLE)) {
// oracle查询表的所有列信息sql
sqlStr = MessageFormat.format(DbConvertDef.ORACLE_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName.toUpperCase()));
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.POSTGRESQL)) {
// postgresql查询表的所有列信息sql
sqlStr = MessageFormat.format(DbConvertDef.POSTGRESQL_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName), TableConvert.formatStr(tableName));
}
if (CodeConfigProperties.databaseType.equals(DbConvertDef.SQLSERVER)) {
// sqlserver查询表的所有列信息sql
sqlStr = MessageFormat.format(DbConvertDef.SQLSERVER_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName));
}
return sqlStr;
}
/**
* 查询是否该表不存在或没有字段
* @date 2021/4/2 9:18
* @param tableName
* @return boolean
*/
public static boolean c(String tableName) {
String sqlStr = null;
Connection connection = null;
Statement statement = null;
try {
log.debug("数据库驱动: " + com.jero.codegenerate.properties.CodeConfigProperties.driverName);
Class.forName(com.jero.codegenerate.properties.CodeConfigProperties.driverName);
connection = DriverManager.getConnection(com.jero.codegenerate.properties.CodeConfigProperties.databaseUrl, com.jero.codegenerate.properties.CodeConfigProperties.username, com.jero.codegenerate.properties.CodeConfigProperties.password);
statement = connection.createStatement(1005, 1007);
// 表格所属的库
String catalog = connection.getCatalog();
log.info(CONNECT_DATABASE_NAME + catalog);
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.MYSQL)) {
// mysql获取表的列信息sql
sqlStr = "select column_name,data_type,column_comment,0,0 from information_schema.columns where table_name = '" + tableName + "' and table_schema = '" + catalog + "'";
}
// oracle获取表的列信息sql
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.ORACLE)) {
sqlStr = "select colstable.column_name column_name, colstable.data_type data_type, commentstable.comments column_comment from user_tab_cols colstable inner join user_col_comments commentstable on colstable.column_name = commentstable.column_name where colstable.table_name = commentstable.table_name and colstable.table_name = '" + tableName.toUpperCase() + "'";
}
// postgresql获取表的列信息sql
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.POSTGRESQL)) {
sqlStr = MessageFormat.format(DbConvertDef.POSTGRESQL_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName), TableConvert.formatStr(tableName));
}
// sqlserver获取表的列信息sql
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.SQLSERVER)) {
sqlStr = MessageFormat.format(DbConvertDef.SQLSERVER_ALLCOLUMNS_SQL, TableConvert.formatStr(tableName));
}
ResultSet resultSet = statement.executeQuery(sqlStr);
// 游标指向结果集末尾
resultSet.last();
// 返回结果是当前数据集的行号,而不是结果的行数
int row = resultSet.getRow();
return row > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 转换字段名破折号间隔命名为驼峰命名
* @date 2021/4/2 9:35
* @param fieldName 字段名
* @return java.lang.String
*/
private static String convertFieldNameToCamelCase(String fieldName) {
String[] fieldNameArray = fieldName.split("_");
fieldName = "";
int i = 0;
for(int length = fieldNameArray.length; i < length; ++i) {
if (i > 0) {
String fieldNameWord = fieldNameArray[i].toLowerCase();
fieldNameWord = fieldNameWord.substring(0, 1).toUpperCase() + fieldNameWord.substring(1, fieldNameWord.length());
fieldName = fieldName + fieldNameWord;
} else {
fieldName = fieldName + fieldNameArray[i].toLowerCase();
}
}
return fieldName;
}
/**
* 将外键字符串下划线间隔命名转换为驼峰命名
* @date 2021/4/2 10:52
* @param foreignKey
* @return java.lang.String
*/
public static String convertForeignKeyToCamelCase(String foreignKey) {
String[] foreignKeyWords = foreignKey.split("_");
foreignKey = "";
int i = 0;
for(int length = foreignKeyWords.length; i < length; ++i) {
if (i > 0) {
String foreignKeyLowerCase = foreignKeyWords[i].toLowerCase();
foreignKeyLowerCase = foreignKeyLowerCase.substring(0, 1).toUpperCase() + foreignKeyLowerCase.substring(1, foreignKeyLowerCase.length());
foreignKey = foreignKey + foreignKeyLowerCase;
} else {
foreignKey = foreignKey + foreignKeyWords[i].toLowerCase();
}
}
foreignKey = foreignKey.substring(0, 1).toUpperCase() + foreignKey.substring(1);
return foreignKey;
}
/**
* 设置ColumnVo
* @date 2021/4/6 13:45
* @param columnVo
* @return void
*/
private static void setupColumnVo(ColumnVo columnVo) {
String fieldType = columnVo.getFieldType();
String scale = columnVo.getScale();
columnVo.setClassType("inputxt");
if ("N".equals(columnVo.getNullable())) {
columnVo.setOptionType("*");
}
if (!"datetime".equals(fieldType) && !fieldType.contains("time")) {
setColumnVo(columnVo, fieldType, scale);
} else {
columnVo.setClassType("easyui-datetimebox");
}
}
private static void setColumnVo(ColumnVo columnVo, String fieldType, String scale) {
if ("date".equals(fieldType)) {
columnVo.setClassType("easyui-datebox");
} else if (fieldType.contains("int")) {
columnVo.setOptionType("n");
} else if ("number".equals(fieldType)) {
if (StringUtils.isNotBlank(scale) && Integer.parseInt(scale) > 0) {
columnVo.setOptionType("d");
}
} else if (!"float".equals(fieldType) && !"double".equals(fieldType) && !"decimal".equals(fieldType)) {
if ("numeric".equals(fieldType)) {
columnVo.setOptionType("d");
}
} else {
columnVo.setOptionType("d");
}
}
/**
* 返回字段类型
* @date 2021/4/6 13:43
* @param value
* @param precision
* @param scale
* @return java.lang.String
*/
private static String getFieldType(String value, String precision, String scale) {
String bigDecimal = "java.math.BigDecimal";
if (value.contains("char")) {
value = "java.lang.String";
} else if (value.contains("int")) {
value = "java.lang.Integer";
} else if (value.contains("float")) {
value = "java.lang.Float";
} else if (value.contains("double")) {
value = "java.lang.Double";
} else if (value.contains("number")) {
value = getString(precision, scale, bigDecimal);
} else if (value.contains("decimal")) {
value = bigDecimal;
} else if (value.contains("date")) {
value = "java.util.Date";
} else if (value.contains("time")) {
value = "java.util.Date";
} else if (value.contains("blob")) {
value = "byte[]";
} else if (value.contains("clob")) {
value = "java.sql.Clob";
} else if (value.contains("numeric")) {
value = bigDecimal;
} else {
value = "java.lang.Object";
}
return value;
}
private static String getString(String precision, String scale, String bigDecimal) {
String value;
if (StringUtils.isNotBlank(scale) && Integer.parseInt(scale) > 0) {
value = bigDecimal;
} else if (StringUtils.isNotBlank(precision) && Integer.parseInt(precision) > 10) {
value = "java.lang.Long";
} else {
value = "java.lang.Integer";
}
return value;
}
//通过表名获取表备注
public String remarks(String tableName) throws SQLException, ClassNotFoundException {
Connection connection = null;
Statement statement = null;
try {
Class.forName(com.jero.codegenerate.properties.CodeConfigProperties.driverName);
connection = DriverManager.getConnection(com.jero.codegenerate.properties.CodeConfigProperties.databaseUrl, com.jero.codegenerate.properties.CodeConfigProperties.username, com.jero.codegenerate.properties.CodeConfigProperties.password);
statement = connection.createStatement(1005, 1007);
String sqlStr = "";
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.MYSQL)) {
// mysql获取表的列信息sql
sqlStr = "SELECT table_comment FROM information_schema.TABLES WHERE table_name = " + "'"+tableName+"'";
}
// oracle获取表的列信息sql
if (com.jero.codegenerate.properties.CodeConfigProperties.databaseType.equals(DbConvertDef.ORACLE)) {
sqlStr = "SELECT comments FROM user_tab_comments WHERE table_name = '" + tableName.toUpperCase() + "'";
}
ResultSet resultSet = statement.executeQuery(sqlStr);
while(resultSet.next()) {
String name = resultSet.getString(1);
return name;
}
}catch (ClassNotFoundException | SQLException e){
throw e;
}finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return "";
}
}
@@ -0,0 +1,102 @@
package com.jero.codegenerate.database.util;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class CodeStringUtils {
private CodeStringUtils() {
}
/**
* Comma:逗号 将字符串数组转换为逗号间隔字符串
* @date 2021/4/6 13:37
* @param stringArray 字符串数组
* @return java.lang.String
*/
public static String joinComma(String[] stringArray) {
StringBuilder sb = new StringBuilder();
String[] array = stringArray;
int length = stringArray.length;
for(int i = 0; i < length; ++i) {
String s = array[i];
if (StringUtils.isNotBlank(s)) {
sb.append(",");
sb.append("'");
sb.append(s.trim());
sb.append("'");
}
}
return sb.toString().substring(1);
}
/**
* 首字母大写字符串
* @param word 字符串
* @return java.lang.String
*/
public static String convertFirstWordToLower(String word) {
if (StringUtils.isNotBlank(word)) {
word = word.substring(0, 1).toLowerCase() + word.substring(1);
}
return word;
}
/**
* 判断并获取整型
* @date 2021/4/6 13:39
* @param integer 整型数
* @return java.lang.Integer
*/
public static Integer checkIntegerAndGet(Integer integer) {
return integer == null ? 0 : integer;
}
/**
* 是否查询字段数组包含数据库名
* @date 2021/4/2 9:48
* @param dbName 数据库名
* @param pageFilterFieldsStrings 查询字段数组
* @return boolean
*/
public static boolean isPageFilterFieldsContainDbName(String dbName, String[] pageFilterFieldsStrings) {
if (pageFilterFieldsStrings != null && pageFilterFieldsStrings.length != 0) {
for(int i = 0; i < pageFilterFieldsStrings.length; ++i) {
String pageFilterFieldsString = pageFilterFieldsStrings[i];
if (pageFilterFieldsString.equals(dbName)) {
return true;
}
}
return false;
} else {
return false;
}
}
/**
* 字符串集合是否包含目标字符串
* @date 2021/4/2 10:18
* @param target
* @param stringList
* @return boolean
*/
public static boolean isListContainString(String target, List<String> stringList) {
String[] stringArray = new String[0];
if (stringList != null) {
stringArray = stringList.toArray(new String[0]);
}
if (stringArray != null && stringArray.length != 0) {
for(int i = 0; i < stringArray.length; ++i) {
String s = stringArray[i];
if (s.equals(target)) {
return true;
}
}
return false;
} else {
return false;
}
}
}
@@ -0,0 +1,22 @@
package com.jero.codegenerate.database.util;
public class DbConvertDef {
private DbConvertDef(){
}
public static final String Y = "Y";
public static final String N = "N";
public static final String MYSQL = "mysql";
public static final String ORACLE = "oracle";
public static final String SQLSERVER = "sqlserver";
public static final String POSTGRESQL = "postgresql";
public static final String MYSQL_ALLCOLUMNS_SQL = "select column_name,data_type,column_comment,numeric_precision,numeric_scale,character_maximum_length,is_nullable nullable from information_schema.columns where table_name = {0} and table_schema = {1} order by ORDINAL_POSITION";
public static final String ORACLE_ALLCOLUMNS_SQL = " select colstable.column_name column_name, colstable.data_type data_type, commentstable.comments column_comment, colstable.Data_Precision column_precision, colstable.Data_Scale column_scale,colstable.Char_Length,colstable.nullable from user_tab_cols colstable inner join user_col_comments commentstable on colstable.column_name = commentstable.column_name where colstable.table_name = commentstable.table_name and colstable.table_name = {0}";
public static final String SQLSERVER_ALLCOLUMNS_SQL = "select distinct cast(a.name as varchar(50)) column_name, cast(b.name as varchar(50)) data_type, cast(e.value as NVARCHAR(200)) comment, cast(ColumnProperty(a.object_id,a.Name,'''Precision''') as int) num_precision, cast(ColumnProperty(a.object_id,a.Name,'''Scale''') as int) num_scale, a.max_length, (case when a.is_nullable=1 then '''y''' else '''n''' end) nullable,column_id from sys.columns a left join sys.types b on a.user_type_id=b.user_type_id left join (select top 1 * from sys.objects where type = '''U''' and name ={0} order by name) c on a.object_id=c.object_id left join sys.extended_properties e on e.major_id=c.object_id and e.minor_id=a.column_id and e.class=1 where c.name={0} order by a.column_id";
public static final String POSTGRESQL_ALLCOLUMNS_SQL = "select icm.column_name as field,icm.udt_name as type,fieldtxt.descript as comment, icm.numeric_precision_radix as column_precision ,icm.numeric_scale as column_scale ,icm.character_maximum_length as Char_Length,icm.is_nullable as attnotnull from information_schema.columns icm, (SELECT A.attnum,( SELECT description FROM pg_catalog.pg_description WHERE objoid = A.attrelid AND objsubid = A.attnum ) AS descript,A.attname FROM\tpg_catalog.pg_attribute A WHERE A.attrelid = ( SELECT oid FROM pg_class WHERE relname = {0} ) AND A.attnum > 0 AND NOT A.attisdropped ORDER BY\tA.attnum ) fieldtxt where icm.table_name={1} and fieldtxt.attname = icm.column_name";
public static final String MYSQL_ALLTABLES_SQL = "select distinct table_name from information_schema.columns where table_schema = {0}";
public static final String ORACLE_ALLTABLES_SQL = "select distinct colstable.table_name as table_name from user_tab_cols colstable order by colstable.table_name";
public static final String SQLSERVER_ALLTABLES_SQL = "select distinct c.name as table_name from sys.objects c where c.type = 'U' ";
public static final String POSTGRESQL_ALLTABLES_SQL = "select tablename from pg_tables where schemaname='public'";
}
@@ -0,0 +1,14 @@
package com.jero.codegenerate.generate;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public interface IGenerate {
Map<String, Object> getCodeGenerateConfig() throws SQLException, ClassNotFoundException;
List<String> generateCodeFile(String var1) throws SQLException, ClassNotFoundException, IOException;
List<String> generateCodeFile(String var1, String var2, String var3) throws SQLException, IOException, ClassNotFoundException;
}
@@ -0,0 +1,100 @@
package com.jero.codegenerate.generate.config;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class CreateFileConfig {
private String templatePath;
private List<File> templateRootDirs = new ArrayList<>();
private String stylePath;
public CreateFileConfig(String templatePath) {
log.debug("----templatePath-----------------" + templatePath);
log.debug("----stylePath-----------------" + this.stylePath);
this.templatePath = templatePath;
}
/**
* 设置 fileList
* @date 2021/4/6 13:47
* @param file
* @return void
*/
private void setFileList(File file) {
this.convertArrToList(file);
}
/**
* 将文件数组转换为文件集合
* @date 2021/4/2 10:30
* @param files
* @return void
*/
private void convertArrToList(File... files) {
this.templateRootDirs = Arrays.asList(files);
}
/**
* 获取stylePath
* @date 2021/4/6 13:47
* @param
* @return java.lang.String
*/
public String getStylePath() {
return this.stylePath;
}
/**
* 设置 stylePath
* @date 2021/4/6 13:46
* @param stylePath
* @return void
*/
public void setStylePath(String stylePath) {
this.stylePath = stylePath;
}
/**
* 返回模板目录集合
* @date 2021/4/2 14:45
* @param
* @return java.util.List<java.io.File>
*/
public List<File> listTemplateRootDirs() throws UnsupportedEncodingException {
String file = this.getClass().getResource(this.templatePath).getFile();
// 对中文路径进行处理
file = URLDecoder.decode(file.replace("%20", " "), "UTF-8");
log.debug("-------classpath-------" + file);
if (file.indexOf("/BOOT-INF/classes!") != -1 || file.indexOf("/BOOT-INF/lib/") != -1) {
// 当前工程路径
file = System.getProperty("user.dir") + File.separator + "config/jero/code-template-online/".replace("/", File.separator);
log.debug("---JAR--config--classpath-------" + file);
}
this.setFileList(new File(file));
return this.templateRootDirs;
}
/**
* 设置fileList
* @date 2021/4/6 15:39
* @param files 文件集合
* @return void
*/
public void setFileList(List<File> files) {
this.templateRootDirs = files;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\"templateRootDirs\":\"");
sb.append(this.templateRootDirs);
sb.append("\",\"stylePath\":\"");
sb.append(this.stylePath);
sb.append("\"} ");
return sb.toString();
}
}
@@ -0,0 +1,117 @@
package com.jero.codegenerate.generate.impl;
import com.jero.codegenerate.database.DbReadTableUtil;
import com.jero.codegenerate.generate.IGenerate;
import com.jero.codegenerate.generate.config.CreateFileConfig;
import com.jero.codegenerate.generate.impl.base.BaseCodeGenerate;
import com.jero.codegenerate.generate.pojo.ColumnVo;
import com.jero.codegenerate.generate.pojo.TableVo;
import com.jero.codegenerate.generate.util.NonceUtils;
import com.jero.codegenerate.properties.CodeConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class CodeGenerateOne extends BaseCodeGenerate implements IGenerate {
private TableVo tableVo;
private List<ColumnVo> columns;
private List<ColumnVo> originalColumns;
public CodeGenerateOne(TableVo tableVo) {
this.tableVo = tableVo;
}
public CodeGenerateOne(TableVo tableVo, List<ColumnVo> columns, List<ColumnVo> originalColumns) {
this.tableVo = tableVo;
this.columns = columns;
this.originalColumns = originalColumns;
}
@Override
public Map<String, Object> getCodeGenerateConfig() throws SQLException, ClassNotFoundException {
HashMap<String, Object> var1 = new HashMap<>();
var1.put("bussiPackage", com.jero.codegenerate.properties.CodeConfigProperties.packageName);
var1.put("entityPackage", this.tableVo.getEntityPackage());
var1.put("entityName", this.tableVo.getEntityName());
var1.put("tableName", this.tableVo.getTableName());
var1.put("primaryKeyField", com.jero.codegenerate.properties.CodeConfigProperties.dbTableId);
if (this.tableVo.getFieldRequiredNum() == null) {
this.tableVo.setFieldRequiredNum(StringUtils.isNotEmpty(com.jero.codegenerate.properties.CodeConfigProperties.fieldRequiredNum) ? Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.fieldRequiredNum) : -1);
}
if (this.tableVo.getSearchFieldNum() == null) {
this.tableVo.setSearchFieldNum(StringUtils.isNotEmpty(com.jero.codegenerate.properties.CodeConfigProperties.pageSearchFieldNum) ? Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.pageSearchFieldNum) : -1);
}
if (this.tableVo.getFieldRowNum() == null) {
this.tableVo.setFieldRowNum(Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.fieldRowNum));
}
var1.put("tableVo", this.tableVo);
try {
if (this.columns == null || this.columns.isEmpty()) {
this.columns = DbReadTableUtil.listColumns(this.tableVo.getTableName());
}
var1.put("columns", this.columns);
if (this.originalColumns == null || this.originalColumns.isEmpty()) {
this.originalColumns = DbReadTableUtil.listOriginalColumns(this.tableVo.getTableName());
}
var1.put("originalColumns", this.originalColumns);
for (ColumnVo var3 : this.originalColumns) {
if (var3.getFieldName().equalsIgnoreCase(CodeConfigProperties.dbTableId)) {
var1.put("primaryKeyPolicy", var3.getFieldType());
}
}
} catch (SQLException | ClassNotFoundException throwAbles) {
throw throwAbles;
}
long var5 = NonceUtils.getSecureRandomLong() + NonceUtils.getCurrentTimeMillis();
var1.put("serialVersionUID", String.valueOf(var5));
log.info("load template data: " + var1.toString());
return var1;
}
@Override
public List<String> generateCodeFile(String stylePath) throws SQLException, ClassNotFoundException, IOException {
log.debug("----jero---Code----Generation----[单表模型:" + this.tableVo.getTableName() + "]------- 生成中。。。");
String projectPath = com.jero.codegenerate.properties.CodeConfigProperties.projectPath;
Map<String, Object> codeGenerateConfig = this.getCodeGenerateConfig();
String templateUrl = com.jero.codegenerate.properties.CodeConfigProperties.templateUrl;
if (dealAndGetTemplateUrl(templateUrl, "/").equals("jero/code-template")) {
templateUrl = "/" + dealAndGetTemplateUrl(templateUrl, "/") + "/one";
com.jero.codegenerate.properties.CodeConfigProperties.setTemplateUrl(templateUrl);
}
CreateFileConfig createFileConfig = new CreateFileConfig(templateUrl);
createFileConfig.setStylePath(stylePath);
this.createProject(createFileConfig, projectPath, codeGenerateConfig);
log.info(" ----- jero-boot ---- generate code success =======> 表名:" + this.tableVo.getTableName() + " ");
return this.messageList;
}
@Override
public List<String> generateCodeFile(String projectPath, String templatePath, String stylePath) throws SQLException, IOException, ClassNotFoundException {
if (projectPath != null && !"".equals(projectPath)) {
com.jero.codegenerate.properties.CodeConfigProperties.setProjectPath(projectPath);
}
if (templatePath != null && !"".equals(templatePath)) {
com.jero.codegenerate.properties.CodeConfigProperties.setTemplateUrl(templatePath);
}
this.generateCodeFile(stylePath);
return this.messageList;
}
}
@@ -0,0 +1,168 @@
package com.jero.codegenerate.generate.impl;
import com.jero.codegenerate.database.DbReadTableUtil;
import com.jero.codegenerate.generate.IGenerate;
import com.jero.codegenerate.generate.config.CreateFileConfig;
import com.jero.codegenerate.generate.impl.base.BaseCodeGenerate;
import com.jero.codegenerate.generate.pojo.ColumnVo;
import com.jero.codegenerate.generate.pojo.onetomany.MainTableVo;
import com.jero.codegenerate.generate.pojo.onetomany.SubTableVo;
import com.jero.codegenerate.generate.util.NonceUtils;
import com.jero.codegenerate.properties.CodeConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class CodeGenerateOneToMany extends BaseCodeGenerate implements IGenerate {
// 主表vo
private MainTableVo mainTableVo;
private List<ColumnVo> mainColumns;
private List<ColumnVo> originalMainColumns;
// 从表集合
private List<SubTableVo> subTables;
public CodeGenerateOneToMany(MainTableVo mainTableVo, List<SubTableVo> subTables) {
this.subTables = subTables;
this.mainTableVo = mainTableVo;
}
public CodeGenerateOneToMany(MainTableVo mainTableVo, List<ColumnVo> mainColums, List<ColumnVo> originalMainColumns, List<SubTableVo> subTables) {
this.mainTableVo = mainTableVo;
this.mainColumns = mainColums;
this.originalMainColumns = originalMainColumns;
this.subTables = subTables;
}
/**
* 获取代码生成器的配置 map
* @date 2021/4/2 10:39
* @param
* @return java.util.Map<java.lang.String,java.lang.Object>
*/
@Override
public Map<String, Object> getCodeGenerateConfig() throws SQLException, ClassNotFoundException {
HashMap<String,Object> hashMap = new HashMap<>();
// 包名
hashMap.put("bussiPackage", com.jero.codegenerate.properties.CodeConfigProperties.packageName);
// 实体包名
hashMap.put("entityPackage", this.mainTableVo.getEntityPackage());
// 实体名
hashMap.put("entityName", this.mainTableVo.getEntityName());
// 表名
hashMap.put("tableName", this.mainTableVo.getTableName());
hashMap.put("ftl_description", this.mainTableVo.getFtlDescription());
// 主键名
hashMap.put("primaryKeyField", com.jero.codegenerate.properties.CodeConfigProperties.dbTableId);
if (this.mainTableVo.getFieldRequiredNum() == null) {
this.mainTableVo.setFieldRequiredNum(StringUtils.isNotEmpty(com.jero.codegenerate.properties.CodeConfigProperties.fieldRequiredNum) ? Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.fieldRequiredNum) : -1);
}
if (this.mainTableVo.getSearchFieldNum() == null) {
this.mainTableVo.setSearchFieldNum(StringUtils.isNotEmpty(com.jero.codegenerate.properties.CodeConfigProperties.pageSearchFieldNum) ? Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.pageSearchFieldNum) : -1);
}
if (this.mainTableVo.getFieldRowNum() == null) {
this.mainTableVo.setFieldRowNum(Integer.parseInt(com.jero.codegenerate.properties.CodeConfigProperties.fieldRowNum));
}
// put主表
hashMap.put("tableVo", this.mainTableVo);
try {
if (this.mainColumns == null || this.mainColumns.isEmpty()) {
this.mainColumns = DbReadTableUtil.listColumns(this.mainTableVo.getTableName());
}
if (this.originalMainColumns == null || this.originalMainColumns.isEmpty()) {
this.originalMainColumns = DbReadTableUtil.listOriginalColumns(this.mainTableVo.getTableName());
}
hashMap.put("columns", this.mainColumns);
hashMap.put("originalColumns", this.originalMainColumns);
for (ColumnVo columnVo : this.originalMainColumns) {
// 主键类型
if (columnVo.getFieldName().equalsIgnoreCase(CodeConfigProperties.dbTableId)) {
hashMap.put("primaryKeyPolicy", columnVo.getFieldType());
}
}
setSubTableVo();
// put从表集合
hashMap.put("subTables", this.subTables);
} catch (SQLException | ClassNotFoundException throwAbles) {
throw throwAbles;
}
long serialVersionUID = NonceUtils.getSecureRandomLong() + NonceUtils.getCurrentTimeMillis();
hashMap.put("serialVersionUID", String.valueOf(serialVersionUID));
log.info("code template data: " + hashMap.toString());
return hashMap;
}
private void setSubTableVo() throws SQLException, ClassNotFoundException {
for (SubTableVo subTableVo : this.subTables) {
// 从表(局部变量)
List<ColumnVo> originalColumns;
if (subTableVo.getColums() == null || subTableVo.getColums().isEmpty()) {
originalColumns = DbReadTableUtil.listColumns(subTableVo.getTableName());
subTableVo.setColums(originalColumns);
}
if (subTableVo.getOriginalColumns() == null || subTableVo.getOriginalColumns().isEmpty()) {
originalColumns = DbReadTableUtil.listOriginalColumns(subTableVo.getTableName());
subTableVo.setOriginalColumns(originalColumns);
}
// 从表外键
String[] foreignKeys = subTableVo.getForeignKeys();
// 存储外键的集合
ArrayList<String> list = new ArrayList<>();
String[] foreignKeys1 = foreignKeys;
int length = foreignKeys.length;
for (int i = 0; i < length; ++i) {
String foreignKey = foreignKeys1[i];
list.add(DbReadTableUtil.convertForeignKeyToCamelCase(foreignKey));
}
// put外键数组
subTableVo.setForeignKeys(list.toArray(new String[0]));
subTableVo.setOriginalForeignKeys(foreignKeys);
}
}
@Override
public List<String> generateCodeFile(String stylePath) throws SQLException, ClassNotFoundException, IOException {
String projectPath = com.jero.codegenerate.properties.CodeConfigProperties.projectPath;
Map<String, Object> configMap = this.getCodeGenerateConfig();
String templateUrl = com.jero.codegenerate.properties.CodeConfigProperties.templateUrl;
if (dealAndGetTemplateUrl(templateUrl, "/").equals("jero/code-template")) {
templateUrl = "/" + dealAndGetTemplateUrl(templateUrl, "/") + "/onetomany";
com.jero.codegenerate.properties.CodeConfigProperties.setTemplateUrl(templateUrl);
}
CreateFileConfig createFileConfig = new CreateFileConfig(templateUrl);
createFileConfig.setStylePath(stylePath);
this.createProject(createFileConfig, projectPath, configMap);
log.info("----- jero-boot ---- generate code success =======> 主表名:" + this.mainTableVo.getTableName());
return this.messageList;
}
@Override
public List<String> generateCodeFile(String projectPath, String templatePath, String stylePath) throws SQLException, IOException, ClassNotFoundException {
if (projectPath != null && !"".equals(projectPath)) {
com.jero.codegenerate.properties.CodeConfigProperties.setProjectPath(projectPath);
}
if (templatePath != null && !"".equals(templatePath)) {
com.jero.codegenerate.properties.CodeConfigProperties.setTemplateUrl(templatePath);
}
this.generateCodeFile(stylePath);
return this.messageList;
}
}
@@ -0,0 +1,318 @@
package com.jero.codegenerate.generate.impl.base;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.jero.codegenerate.generate.config.CreateFileConfig;
import com.jero.codegenerate.generate.util.FileHelper;
import com.jero.codegenerate.generate.util.FreemarkerHelper;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BaseCodeGenerate {
protected static String characterSet = "UTF-8";
protected List<String> messageList = new ArrayList<>();
/**
* 生成项目文件
* @date 2021/4/2 14:32
* @param createFileConfig 配置类
* @param projectPath 项目生成路径
* @param configMap 代码配置map
* @return void
*/
protected void createProject(CreateFileConfig createFileConfig, String projectPath, Map<String, Object> configMap) throws IOException {
log.debug("--------generate----projectPath--------" + projectPath);
for(int i = 0; i < createFileConfig.listTemplateRootDirs().size(); ++i) {
// 获取一个模板根目录
File templateRootDir = createFileConfig.listTemplateRootDirs().get(i);
this.createOutPutFile(projectPath, templateRootDir, configMap, createFileConfig);
}
}
/**
* 生成输出目录的文件
* @author 马志朝
* @date 2021/4/6 14:25
* @param projectPath 项目路径
* @param templateRootDir 模板根目录
* @param configMap 表配置
* @param createFileConfig 生成文件配置
* @return void
*/
protected void createOutPutFile(String projectPath, File templateRootDir, Map<String, Object> configMap, CreateFileConfig createFileConfig) throws IOException {
// 模板目录为空
if (templateRootDir == null) {
throw new IllegalStateException("'templateRootDir' must be not null");
} else {
log.info(" load template from templateRootDir = '" + templateRootDir.getAbsolutePath() + "',stylePath ='" + createFileConfig.getStylePath() + "', out GenerateRootDir:" + com.jero.codegenerate.properties.CodeConfigProperties.projectPath);
// 获取模板目录下的模板
List<File> templateFileList = FileHelper.listFileAndSort(templateRootDir);
log.debug("----srcFiles----size-----------" + templateFileList.size());
log.debug("----srcFiles----list------------" + templateFileList.toString());
for(int i = 0; i < templateFileList.size(); ++i) {
// 获取一个模板文件
File srcFile = templateFileList.get(i);
this.createOutPutFile(projectPath, templateRootDir, configMap, srcFile, createFileConfig);
}
}
}
/**
* 生成输出目录的文件
* @date 2021/4/6 14:33
* @param projectPath 项目路径
* @param templateRootDir 模板根目录
* @param configMap 表配置
* @param srcFile 一个模板文件
* @param createFileConfig 生成文件配置
* @return void
*/
protected void createOutPutFile(String projectPath, File templateRootDir, Map<String, Object> configMap, File srcFile, CreateFileConfig createFileConfig) {
log.debug("-------templateRootDir--" + templateRootDir.getPath());
log.debug("-------srcFile--" + srcFile.getPath());
String templateFilePath = FileHelper.getDirExcludeRootDir(templateRootDir, srcFile);
try {
log.debug("-------templateFile--" + templateFilePath);
if (createFileConfig.getStylePath() != null && !"".equals(createFileConfig.getStylePath()) && !templateFilePath.replace(File.separator, ".").startsWith(createFileConfig.getStylePath())) {
return;
}
//模板文件目录
String outputFilepath = getTemplatePath(configMap, templateFilePath, createFileConfig);
if(Objects.isNull(outputFilepath)){
return;
}
log.debug("-------outputFilepath--" + outputFilepath);
String packageDir;
// 输出文件路径以 java 开头
if (outputFilepath.startsWith("java")) {
// 生成目录位置
packageDir = projectPath + File.separator + com.jero.codegenerate.properties.CodeConfigProperties.sourceRootPackage.replace(".", File.separator);
outputFilepath = outputFilepath.substring("java".length());
outputFilepath = packageDir + outputFilepath;
log.debug("-------java----outputFilepath--" + outputFilepath);
// 生成文件
this.createOutPutFile(templateFilePath, outputFilepath, configMap, createFileConfig);
// 输出文件路径以 webapp 开头
} else if (outputFilepath.startsWith("webapp")) {
// 生成目录位置
packageDir = projectPath + File.separator + com.jero.codegenerate.properties.CodeConfigProperties.webrootPackage.replace(".", File.separator);
outputFilepath = outputFilepath.substring("webapp".length());
outputFilepath = packageDir + outputFilepath;
log.debug("-------webapp---outputFilepath---" + outputFilepath);
// 生成文件
this.createOutPutFile(templateFilePath, outputFilepath, configMap, createFileConfig);
}
} catch (Exception exception) {
log.error(exception.toString(), exception);
}
}
/**
* 生成输出目录的文件
* @date 2021/4/6 14:14
* @param templateFilePath 模板相对路径
* @param outputFilepath 输出文件路径
* @param configMap 表配置
* @param createFileConfig 生成文件配置
* @return void
*/
protected void createOutPutFile(String templateFilePath, String outputFilepath, Map<String, Object> configMap, CreateFileConfig createFileConfig) throws IOException, TemplateException {
if (outputFilepath.endsWith("i")) {
//将末尾的'i'去除
outputFilepath = outputFilepath.substring(0, outputFilepath.length() - 1);
}
// 根据模板文件路径获取指定模板
Template template = this.getTemplate(templateFilePath, createFileConfig);
template.setOutputEncoding(characterSet);
// 生成文件
File file = FileHelper.createFile(outputFilepath);
log.info("[generate]\t template:" + templateFilePath + " ==> " + outputFilepath);
//根据template写入数据
FreemarkerHelper.fillDataIntoFileByTemplate(template, configMap, file, characterSet);
// 文件名开头是否非法
if (!this.isStartWithSpecialStr(file)) {
this.messageList.add("生成成功:" + outputFilepath);
}
// 是否以指定字符串开头
if (this.isStartWithSpecialStr(file)) {
this.splitFileAndGenerate(file, "#segment#");
}
}
/**
* 根据templateFilePath获得对应的模板类
* @date 2021/4/2 16:54
* @param templateFilePath 目标模板路径
* @param createFileConfig 生成文件配置
* @return freemarker.template.Template
*/
protected Template getTemplate(String templateFilePath, CreateFileConfig createFileConfig) throws IOException {
return FreemarkerHelper.getConfiguration(createFileConfig.listTemplateRootDirs(), characterSet, templateFilePath).getTemplate(templateFilePath);
}
/**
* 是否文件名以【1-n】字符开头,来分割文件生成多个
* @date 2021/4/2 17:18
* @param file 文件
* @return boolean
*/
protected boolean isStartWithSpecialStr(File file) {
return file.getName().startsWith("[1-n]");
}
/**
* 读取一对多文件内容以指定字符串分割生成各个文件
* @date 2021/4/6 15:08
* @param file 文件
* @param str 开头字符串
* @return void
*/
protected void splitFileAndGenerate(File file, String str) {
ArrayList<OutputStreamWriter> list = new ArrayList<>();
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), characterSet);
BufferedReader bf = new BufferedReader(isr);){
boolean b = false;
OutputStreamWriter osw = null;
while(true) {
String s;
while((s = bf.readLine()) != null) {
// 若以指定str开头,长度大于0
if (s.trim().length() > 0 && s.startsWith(str)) {
// 截取指定str后
String substring = s.substring(str.length());
// 父目录
String parentPath = file.getParentFile().getAbsolutePath();
// 文件路径
substring = parentPath + File.separator + substring;
log.info("[generate]\t split file:" + file.getAbsolutePath() + " ==> " + substring);
osw = new OutputStreamWriter(new FileOutputStream(substring), characterSet);
list.add(osw);
this.messageList.add("生成成功:" + substring);
b = true;
} else if (b) {
osw.append(s).append("\r\n");
}
}
for(int j = 0; j < list.size(); ++j) {
((Writer)list.get(j)).close();
}
log.debug("[generate]\t delete file:" + file.getAbsolutePath());
// 删除文件
delFile(file);
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeList(list);
}
}
private void closeList(ArrayList<OutputStreamWriter> list) {
try {
if (!list.isEmpty()) {
for(int var12 = 0; var12 < list.size(); ++var12) {
if (list.get(var12) != null) {
((Writer)list.get(var12)).close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取生成文件的项目路径
* @date 2021/4/2 16:28
* @param configMap 实体配置
* @param templateFilePath 模板文件路径
* @param createFileConfig 生成文件配置
* @return java.lang.String
*/
protected static String getTemplatePath(Map<String, Object> configMap, String templateFilePath, CreateFileConfig createFileConfig) throws IOException {
String templateFilePath1 = templateFilePath;
int i;
// ascii 64 = @
if ((i = templateFilePath.indexOf(64)) != -1) {
templateFilePath1 = templateFilePath.substring(0, i);
// 截取@后的字符串
String substring = templateFilePath.substring(i + 1);
Object o = configMap.get(substring);
if (o == null) {
log.error("[not-generate] WARN: test expression is null by key:[" + substring + "] on template:[" + templateFilePath + "]");
return null;
}
if (!"true".equals(String.valueOf(o))) {
log.error("[not-generate]\t test expression '@" + substring + "' is false,template:" + templateFilePath);
return null;
}
}
Configuration configuration = FreemarkerHelper.getConfiguration(createFileConfig.listTemplateRootDirs(), characterSet, "/");
templateFilePath1 = FreemarkerHelper.getFillTemplateString(templateFilePath1, configMap, configuration);
String stylePath = createFileConfig.getStylePath();
if (stylePath != null && !"".equals(stylePath)) {
templateFilePath1 = templateFilePath1.substring(stylePath.length() + 1);
}
// 后缀名
String suffix = templateFilePath1.substring(templateFilePath1.lastIndexOf("."));
String path = templateFilePath1.substring(0, templateFilePath1.lastIndexOf(".")).replace(".", File.separator);
templateFilePath1 = path + suffix;
return templateFilePath1;
}
/**
* 删除文件
* @date 2021/4/6 15:03
* @param file
* @return boolean
*/
protected static boolean delFile(File file) throws IOException {
boolean flag = false;
for(int i = 0; !flag && i++ < 10;flag = Files.deleteIfExists(file.toPath())) {
log.info("");
}
return flag;
}
/**
* 处理TemplateUrl并返回,使这个字符串不能以分割符开头和结尾
* @date 2021/4/1 17:29
* @param templateUrl
* @param separator 传入的分隔符
* @return java.lang.String
*/
protected static String dealAndGetTemplateUrl(String templateUrl, String separator) {
boolean flag1 = true;
boolean flag2 = true;
do {
// 若第一个分隔符位于第一位,长度截取加一位
int start = templateUrl.indexOf(separator) == 0 ? 1 : 0;
// 若最后的分隔符位置为最后一位,长度截取到前一位
int end = templateUrl.lastIndexOf(separator) + 1 == templateUrl.length() ? templateUrl.lastIndexOf(separator) : templateUrl.length();
templateUrl = templateUrl.substring(start, end);
// 开头是否为分隔符,若是则为true
flag1 = templateUrl.indexOf(separator) == 0;
// 结尾是否为分隔符,若是则为true
flag2 = templateUrl.lastIndexOf(separator) + 1 == templateUrl.length();
} while(flag1 || flag2);
return templateUrl;
}
}
@@ -0,0 +1,171 @@
package com.jero.codegenerate.generate.pojo;
public class CgFormColumnExtendVo {
protected Integer fieldLength;
protected String fieldHref;
protected String fieldValidType;
protected String fieldDefault;
protected String fieldShowType;
protected Integer fieldOrderNum;
protected String isKey;
protected String isShow;
protected String isShowList;
protected String isQuery;
protected String queryMode;
protected String dictField;
protected String dictTable;
protected String dictText;
protected String sort = "N";
protected String readonly = "N";
protected String defaultVal;
protected String uploadnum;
public String getUploadnum() {
return this.uploadnum;
}
public void setUploadnum(String uploadnum) {
this.uploadnum = uploadnum;
}
public String getDefaultVal() {
return this.defaultVal;
}
public void setDefaultVal(String defaultVal) {
this.defaultVal = defaultVal;
}
public String getSort() {
return this.sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getReadonly() {
return this.readonly;
}
public void setReadonly(String readonly) {
this.readonly = readonly;
}
public String getIsKey() {
return this.isKey;
}
public void setIsKey(String isKey) {
this.isKey = isKey;
}
public String getFieldDefault() {
return this.fieldDefault;
}
public void setFieldDefault(String fieldDefault) {
this.fieldDefault = fieldDefault;
}
public String getIsShow() {
return this.isShow;
}
public void setIsShow(String isShow) {
this.isShow = isShow;
}
public String getIsShowList() {
return this.isShowList;
}
public void setIsShowList(String isShowList) {
this.isShowList = isShowList;
}
public String getIsQuery() {
return this.isQuery;
}
public void setIsQuery(String isQuery) {
this.isQuery = isQuery;
}
public Integer getFieldLength() {
return this.fieldLength;
}
public void setFieldLength(Integer fieldLength) {
this.fieldLength = fieldLength;
}
public String getFieldHref() {
return this.fieldHref;
}
public void setFieldHref(String fieldHref) {
this.fieldHref = fieldHref;
}
public String getFieldValidType() {
return this.fieldValidType;
}
public void setFieldValidType(String fieldValidType) {
this.fieldValidType = fieldValidType;
}
public String getQueryMode() {
return this.queryMode;
}
public void setQueryMode(String queryMode) {
this.queryMode = queryMode;
}
public String getDictField() {
return this.dictField;
}
public void setDictField(String dictField) {
this.dictField = dictField;
}
public String getDictTable() {
return this.dictTable;
}
public void setDictTable(String dictTable) {
this.dictTable = dictTable;
}
public String getDictText() {
return this.dictText;
}
public void setDictText(String dictText) {
this.dictText = dictText;
}
public String getFieldShowType() {
return this.fieldShowType;
}
public void setFieldShowType(String fieldShowType) {
this.fieldShowType = fieldShowType;
}
public Integer getFieldOrderNum() {
return this.fieldOrderNum;
}
public void setFieldOrderNum(Integer fieldOrderNum) {
this.fieldOrderNum = fieldOrderNum;
}
public String toString() {
return "{}";
}
}
@@ -0,0 +1,119 @@
package com.jero.codegenerate.generate.pojo;
public class ColumnVo extends CgFormColumnExtendVo {
public static final String OPTION_REQUIRED = "required:true";
public static final String OPTION_NUMBER_INSEX = "precision:2,groupSeparator:','";
private String fieldDbName;
private String fieldName;
private String filedComment = "";
private String fieldType = "";
private String fieldDbType = "";
private String charmaxLength = "";
private String precision;
private String scale;
private String nullable;
private String classType = "";
private String classType_row = "";
private String optionType = "";
public String getFieldDbType() {
return this.fieldDbType;
}
public void setFieldDbType(String fieldDbType) {
this.fieldDbType = fieldDbType;
}
public String getNullable() {
return this.nullable;
}
public void setNullable(String nullable) {
this.nullable = nullable;
}
public String getPrecision() {
return this.precision;
}
public String getScale() {
return this.scale;
}
public void setPrecision(String precision) {
this.precision = precision;
}
public void setScale(String scale) {
this.scale = scale;
}
public String getOptionType() {
return this.optionType;
}
public void setOptionType(String optionType) {
this.optionType = optionType;
}
public String getClassType() {
return this.classType;
}
public void setClassType(String classType) {
this.classType = classType;
}
public String getFieldType() {
return this.fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFiledComment() {
return this.filedComment;
}
public void setFiledComment(String filedComment) {
this.filedComment = filedComment;
}
public String getClassType_row() {
return this.classType != null && this.classType.contains("easyui-") ? this.classType.replace("easyui-", "") : this.classType_row;
}
public void setClassType_row(String classType_row) {
this.classType_row = classType_row;
}
public String getCharmaxLength() {
return this.charmaxLength != null && !"0".equals(this.charmaxLength) ? this.charmaxLength : "";
}
public void setCharmaxLength(String charmaxLength) {
this.charmaxLength = charmaxLength;
}
public String getFieldDbName() {
return this.fieldDbName;
}
public void setFieldDbName(String fieldDbName) {
this.fieldDbName = fieldDbName;
}
@Override
public String toString() {
return "{\"fieldDbName\":\"" + this.fieldDbName + "\",\"fieldName\":\"" + this.fieldName + "\",\"filedComment\":\"" + this.filedComment + "\",\"fieldType\":\"" + this.fieldType + "\",\"fieldDbType\":\"" + this.fieldDbType + "\",\"classType\":\"" + this.classType + "\",\"classType_row\":\"" + this.classType_row + "\",\"optionType\":\"" + this.optionType + "\",\"charmaxLength\":\"" + this.charmaxLength + "\",\"precision\":\"" + this.precision + "\",\"scale\":\"" + this.scale + "\",\"nullable\":\"" + this.nullable + "\",\"fieldLength\":\"" + this.fieldLength + "\",\"fieldHref\":\"" + this.fieldHref + "\",\"fieldValidType\":\"" + this.fieldValidType + "\",\"fieldDefault\":\"" + this.fieldDefault + "\",\"fieldShowType\":\"" + this.fieldShowType + "\",\"fieldOrderNum\":\"" + this.fieldOrderNum + "\",\"isKey\":\"" + this.isKey + "\",\"isShow\":\"" + this.isShow + "\",\"isShowList\":\"" + this.isShowList + "\",\"isQuery\":\"" + this.isQuery + "\",\"uploadnum\":\"" + this.uploadnum + "\",\"defaultVal\":\"" + this.defaultVal + "\",\"sort\":\"" + this.sort + "\",\"readonly\":\"" + this.readonly + "\",\"queryMode\":\"" + this.queryMode + "\",\"dictField\":\"" + this.dictField + "\",\"dictTable\":\"" + this.dictTable + "\",\"dictText\":\"" + this.dictText + "\"}";
}
}
@@ -0,0 +1,101 @@
package com.jero.codegenerate.generate.pojo;
import java.util.Map;
public class TableVo {
private String tableName;
private String ftlDescription;
private String primaryKeyPolicy;
private String sequenceCode;
private String entityPackage;
private String entityName;
private Integer fieldRowNum;
private Integer searchFieldNum;
private Integer fieldRequiredNum;
private Map<String, Object> extendParams;
public String getEntityPackage() {
return this.entityPackage;
}
public String getTableName() {
return this.tableName;
}
public String getEntityName() {
return this.entityName;
}
public String getFtlDescription() {
return this.ftlDescription;
}
public void setEntityPackage(String entityPackage) {
this.entityPackage = entityPackage;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public void setFtlDescription(String ftlDescription) {
this.ftlDescription = ftlDescription;
}
public String getPrimaryKeyPolicy() {
return this.primaryKeyPolicy;
}
public String getSequenceCode() {
return this.sequenceCode;
}
public void setPrimaryKeyPolicy(String primaryKeyPolicy) {
this.primaryKeyPolicy = primaryKeyPolicy;
}
public void setSequenceCode(String sequenceCode) {
this.sequenceCode = sequenceCode;
}
public Integer getFieldRowNum() {
return this.fieldRowNum;
}
public void setFieldRowNum(Integer fieldRowNum) {
this.fieldRowNum = fieldRowNum;
}
public Integer getSearchFieldNum() {
return this.searchFieldNum;
}
public void setSearchFieldNum(Integer searchFieldNum) {
this.searchFieldNum = searchFieldNum;
}
public Integer getFieldRequiredNum() {
return this.fieldRequiredNum;
}
public void setFieldRequiredNum(Integer fieldRequiredNum) {
this.fieldRequiredNum = fieldRequiredNum;
}
public Map<String, Object> getExtendParams() {
return this.extendParams;
}
public void setExtendParams(Map<String, Object> extendParams) {
this.extendParams = extendParams;
}
public String toString() {
return "{\"tableName\":\"" + this.tableName + "\",\"ftlDescription\":\"" + this.ftlDescription + "\",\"primaryKeyPolicy\":\"" + this.primaryKeyPolicy + "\",\"sequenceCode\":\"" + this.sequenceCode + "\",\"entityPackage\":\"" + this.entityPackage + "\",\"entityName\":\"" + this.entityName + "\",\"fieldRowNum\":\"" + this.fieldRowNum + "\",\"searchFieldNum\":\"" + this.searchFieldNum + "\",\"fieldRequiredNum\":\"" + this.fieldRequiredNum + "\"}";
}
}
@@ -0,0 +1,121 @@
package com.jero.codegenerate.generate.pojo.onetomany;
import java.util.List;
import java.util.Map;
public class MainTableVo {
private String entityPackage;
private String tableName;
private String entityName;
private String ftlDescription;
private String primaryKeyPolicy;
private String sequenceCode;
private String ftl_mode = "A";
List<SubTableVo> subTables;
public Integer fieldRowNum;
public Integer searchFieldNum;
public Integer fieldRequiredNum;
private Map<String, Object> extendParams;
public Map<String, Object> getExtendParams() {
return this.extendParams;
}
public void setExtendParams(Map<String, Object> extendParams) {
this.extendParams = extendParams;
}
public Integer getFieldRowNum() {
return this.fieldRowNum;
}
public void setFieldRowNum(Integer fieldRowNum) {
this.fieldRowNum = fieldRowNum;
}
public Integer getSearchFieldNum() {
return this.searchFieldNum;
}
public void setSearchFieldNum(Integer searchFieldNum) {
this.searchFieldNum = searchFieldNum;
}
public Integer getFieldRequiredNum() {
return this.fieldRequiredNum;
}
public void setFieldRequiredNum(Integer fieldRequiredNum) {
this.fieldRequiredNum = fieldRequiredNum;
}
public List<SubTableVo> getSubTables() {
return this.subTables;
}
public void setSubTables(List<SubTableVo> subTables) {
this.subTables = subTables;
}
public String getEntityPackage() {
return this.entityPackage;
}
public String getTableName() {
return this.tableName;
}
public String getEntityName() {
return this.entityName;
}
public String getFtlDescription() {
return this.ftlDescription;
}
public void setEntityPackage(String entityPackage) {
this.entityPackage = entityPackage;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public void setFtlDescription(String ftlDescription) {
this.ftlDescription = ftlDescription;
}
public String getFtl_mode() {
return this.ftl_mode;
}
public void setFtl_mode(String ftl_mode) {
this.ftl_mode = ftl_mode;
}
public String getPrimaryKeyPolicy() {
return this.primaryKeyPolicy;
}
public String getSequenceCode() {
return this.sequenceCode;
}
public void setPrimaryKeyPolicy(String primaryKeyPolicy) {
this.primaryKeyPolicy = primaryKeyPolicy;
}
public void setSequenceCode(String sequenceCode) {
this.sequenceCode = sequenceCode;
}
@Override
public String toString() {
return "{\"entityPackage\":\"" + this.entityPackage + "\",\"tableName\":\"" + this.tableName + "\",\"entityName\":\"" + this.entityName + "\",\"ftlDescription\":\"" + this.ftlDescription + "\",\"primaryKeyPolicy\":\"" + this.primaryKeyPolicy + "\",\"sequenceCode\":\"" + this.sequenceCode + "\",\"ftl_mode\":\"" + this.ftl_mode + "\",\"subTables\":" + this.subTables + ",\"fieldRowNum\":\"" + this.fieldRowNum + "\",\"searchFieldNum\":\"" + this.searchFieldNum + "\",\"fieldRequiredNum\":\"" + this.fieldRequiredNum + "\"}";
}
}
@@ -0,0 +1,140 @@
package com.jero.codegenerate.generate.pojo.onetomany;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.jero.codegenerate.generate.pojo.ColumnVo;
public class SubTableVo {
private String entityPackage;
private String tableName;
private String entityName;
private String primaryKeyPolicy;
private String sequenceCode;
private String ftlDescription;
private String[] originalForeignKeys;
private String[] originalForeignMainKeys;
private String[] foreignKeys;
private String[] foreignMainKeys;
private String foreignRelationType;
private List<ColumnVo> colums;
private List<ColumnVo> originalColumns;
private Map<String, Object> extendParams;
public Map<String, Object> getExtendParams() {
return this.extendParams;
}
public void setExtendParams(Map<String, Object> extendParams) {
this.extendParams = extendParams;
}
public String getEntityPackage() {
return this.entityPackage;
}
public String getTableName() {
return this.tableName;
}
public String getEntityName() {
return this.entityName;
}
public String[] getOriginalForeignMainKeys() {
return this.originalForeignMainKeys;
}
public void setOriginalForeignMainKeys(String[] originalForeignMainKeys) {
this.originalForeignMainKeys = originalForeignMainKeys;
}
public String[] getForeignMainKeys() {
return this.foreignMainKeys;
}
public void setForeignMainKeys(String[] foreignMainKeys) {
this.foreignMainKeys = foreignMainKeys;
}
public String getFtlDescription() {
return this.ftlDescription;
}
public List<ColumnVo> getColums() {
return this.colums;
}
public void setColums(List<ColumnVo> colums) {
this.colums = colums;
}
public void setEntityPackage(String entityPackage) {
this.entityPackage = entityPackage;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public void setFtlDescription(String ftlDescription) {
this.ftlDescription = ftlDescription;
}
public String[] getForeignKeys() {
return this.foreignKeys;
}
public void setForeignKeys(String[] foreignKeys) {
this.foreignKeys = foreignKeys;
}
public String getPrimaryKeyPolicy() {
return this.primaryKeyPolicy;
}
public String getSequenceCode() {
return this.sequenceCode;
}
public void setPrimaryKeyPolicy(String primaryKeyPolicy) {
this.primaryKeyPolicy = primaryKeyPolicy;
}
public void setSequenceCode(String sequenceCode) {
this.sequenceCode = sequenceCode;
}
public List<ColumnVo> getOriginalColumns() {
return this.originalColumns;
}
public void setOriginalColumns(List<ColumnVo> originalColumns) {
this.originalColumns = originalColumns;
}
public String[] getOriginalForeignKeys() {
return this.originalForeignKeys;
}
public void setOriginalForeignKeys(String[] originalForeignKeys) {
this.originalForeignKeys = originalForeignKeys;
}
public String getForeignRelationType() {
return this.foreignRelationType;
}
public void setForeignRelationType(String foreignRelationType) {
this.foreignRelationType = foreignRelationType;
}
public String toString() {
return "{\"entityPackage\":\"" + this.entityPackage + "\",\"tableName\":\"" + this.tableName + "\",\"entityName\":\"" + this.entityName + "\",\"primaryKeyPolicy\":\"" + this.primaryKeyPolicy + "\",\"sequenceCode\":\"" + this.sequenceCode + "\",\"ftlDescription\":\"" + this.ftlDescription + "\",\"originalForeignKeys\":\"" + Arrays.toString(this.originalForeignKeys) + "\",\"foreignKeys\":\"" + Arrays.toString(this.foreignKeys) + "\",\"colums\":" + this.colums + ",\"originalColumns\":" + this.originalColumns + "}";
}
}
@@ -0,0 +1,171 @@
package com.jero.codegenerate.generate.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
@Slf4j
public class FileHelper {
private FileHelper(){
}
public static List<String> dirNameList = new ArrayList<>();
public static List<String> fileSuffixList = new ArrayList<>();
static {
dirNameList.add(".svn");
dirNameList.add("CVS");
dirNameList.add(".cvsignore");
dirNameList.add(".copyarea.db");
dirNameList.add("SCCS");
dirNameList.add("vssver.scc");
dirNameList.add(".DS_Store");
dirNameList.add(".git");
dirNameList.add(".gitignore");
fileSuffixList.add(".ftl");
}
/**
* 获取文件目录下的所有文件排序后的集合
* @date 2021/4/2 11:30
* @param dir
* @return java.util.List<java.io.File>
*/
public static List<File> listFileAndSort(File dir) throws IOException {
ArrayList<File> list = new ArrayList<>();
dfsAndAddFile(dir, list);
Collections.sort(list, (var1, var2) -> var1.getAbsolutePath().compareTo(var2.getAbsolutePath()));
return list;
}
/**
* 深度优先搜索目录下的文件
* @date 2021/4/2 11:31
* @param dir 目录
* @param list 存放文件的集合
* @return void
*/
public static void dfsAndAddFile(File dir, List<File> list) throws IOException {
log.debug("---------dir------------path: " + dir.getPath() + " -- isHidden --: " + dir.isHidden() + " -- isDirectory --: " + dir.isDirectory());
if (!dir.isHidden() && dir.isDirectory() && !isContainDir(dir)) {
File[] files = dir.listFiles();
for(int i = 0; i < files.length; ++i) {
dfsAndAddFile(files[i], list);
}
} else if (!isSuffixContain(dir) && !isContainDir(dir)) {
list.add(dir);
}
}
/**
* 除去模板根目录后的子目录路径
* @date 2021/4/2 15:04
* @param templateRootDir 模板根目录
* @param srcFile 模板文件
* @return java.lang.String
*/
public static String getDirExcludeRootDir(File templateRootDir, File srcFile) {
if (templateRootDir.equals(srcFile)) {
return "";
} else {
return templateRootDir.getParentFile() == null ? srcFile.getAbsolutePath().substring(templateRootDir.getAbsolutePath().length()) : srcFile.getAbsolutePath().substring(templateRootDir.getAbsolutePath().length() + 1);
}
}
/**
* 是否为一个文件
* @date 2021/4/2 13:59
* @param file
* @return boolean
*/
public static boolean isFile(File file) {
return !file.isDirectory() && isSuffixNotBlank(file.getName());
}
/**
* 后缀名是否为空白
* @date 2021/4/2 13:40
* @param fileName
* @return boolean
*/
public static boolean isSuffixNotBlank(String fileName) {
return !StringUtils.isBlank(getSuffix(fileName));
}
/**
* 获取后缀名
* @date 2021/4/2 13:20
* @param fileName
* @return java.lang.String
*/
public static String getSuffix(String fileName) {
if (fileName == null) {
return null;
} else {
int index = fileName.indexOf(".");
return index == -1 ? "" : fileName.substring(index + 1);
}
}
/**
* 创建文件以及父目录
* @date 2021/4/2 13:57
* @param file
* @return java.io.File
*/
public static File createFile(String file) {
if (file == null) {
throw new IllegalArgumentException("file must be not null");
} else {
File file1 = new File(file);
createParentFile(file1);
return file1;
}
}
/**
* 创建父目录
* @date 2021/4/2 13:58
* @param file
* @return void
*/
public static void createParentFile(File file) {
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
}
/**
* 是否目录集合包含指定目录
* @date 2021/4/2 11:22
* @param dir
* @return boolean
*/
private static boolean isContainDir(File dir) {
for(int i = 0; i < dirNameList.size(); ++i) {
if (dir.getName().equals(dirNameList.get(i))) {
return true;
}
}
return false;
}
/**
* 是否后缀名集合包含指定文件后缀名
* @date 2021/4/2 11:21
* @param file
* @return boolean
*/
private static boolean isSuffixContain(File file) {
for(int i = 0; i < fileSuffixList.size(); ++i) {
if (file.getName().endsWith(fileSuffixList.get(i))) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,124 @@
package com.jero.codegenerate.generate.util;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
@Slf4j
public class FreemarkerHelper {
private FreemarkerHelper(){
}
/**
* 获取配置类
* @date 2021/4/2 15:47
* @param templateRootDirs 模板根目录集合
* @param characterSet 字符集
* @param separator 分隔符
* @return freemarker.template.Configuration
*/
public static Configuration getConfiguration(List<File> templateRootDirs, String characterSet, String separator) throws IOException {
Configuration configuration = new Configuration();
log.debug(" FileTemplateLoader[] size " + templateRootDirs.size());
log.debug(" templateRootDirs templateName " + separator);
FileTemplateLoader[] fileTemplateLoaders = new FileTemplateLoader[templateRootDirs.size()];
for(int i = 0; i < templateRootDirs.size(); ++i) {
File file = templateRootDirs.get(i);
log.debug(" FileTemplateLoader " + file.getAbsolutePath());
fileTemplateLoaders[i] = new FileTemplateLoader(file);
}
MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(fileTemplateLoaders);
configuration.setTemplateLoader(multiTemplateLoader);
configuration.setNumberFormat("###############");
configuration.setBooleanFormat("true,false");
configuration.setDefaultEncoding(characterSet);
return configuration;
}
public static List<String> a(String var0, String var1) {
String[] var2 = b(var0, "\\/");
ArrayList<String> var3 = new ArrayList<>();
var3.add(var1);
var3.add(File.separator + var1);
String var4 = "";
for(int var5 = 0; var5 < var2.length; ++var5) {
var4 = var4 + File.separator + var2[var5];
var3.add(var4 + File.separator + var1);
}
return var3;
}
public static String[] b(String var0, String var1) {
if (var0 == null) {
return new String[0];
} else {
StringTokenizer var2 = new StringTokenizer(var0, var1);
ArrayList<String> var3 = new ArrayList<>();
while(var2.hasMoreElements()) {
Object var4 = var2.nextElement();
var3.add(var4.toString());
}
return var3.toArray(new String[var3.size()]);
}
}
/**
* 使用配置对象(map),对模板路径字符串进行填充并返回
* @date 2021/4/2 16:02
* @param templateFilePath
* @param configMap
* @param configuration
* @return java.lang.String
*/
public static String getFillTemplateString(String templateFilePath, Map<String, Object> configMap, Configuration configuration) {
StringWriter stringWriter = new StringWriter();
try {
// 指定使用的模板文件,使用配置类创建模板
Template template = new Template("templateString...", new StringReader(templateFilePath), configuration);
// 将数据模型(map)通过StringWriter填充到模板文件
template.process(configMap, stringWriter);
return stringWriter.toString();
} catch (Exception e) {
throw new IllegalStateException("cannot process templateString:" + templateFilePath + " cause:" + e, e);
}
}
/**
* 对根据模板生成的文件进行数据填充
* @date 2021/4/2 17:04
* @param template 模板
* @param configMap 数据配置
* @param file 输出文件
* @param characterSet 字符集
* @return void
*/
public static void fillDataIntoFileByTemplate(Template template, Map<String, Object> configMap, File file, String characterSet) throws IOException, TemplateException {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), characterSet));
configMap.put("Format", new SimpleFormat());
//填充文件
template.process(configMap, bufferedWriter);
bufferedWriter.close();
}
}
@@ -0,0 +1,139 @@
package com.jero.codegenerate.generate.util;
import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
/**
* Nonce Number Once 只使用一次的数字相关工具类
*/
@Slf4j
public class NonceUtils {
private static final String[] NUMBER_STRINGS = new String[]{"0", "00", "0000", "00000000"};
private static Date date;
private static int count = 0;
/**
* 生成指定长度随机字符串
* @date 2021/4/6 9:01
* @param count 长度
* @return java.lang.String
*/
public static String getRandomString(int count) {
return RandomStringUtils.randomAlphanumeric(count);
}
/**
* 生成真随机数整型
* @date 2021/4/6 9:06
* @return int
*/
public static int getSecureRandom() {
return (new SecureRandom()).nextInt();
}
/**
* 生成真随机整型数的16进制字符串
* @date 2021/4/6 9:08
* @return java.lang.String
*/
public static String getSecureRandomOfHexString() {
return Integer.toHexString(getSecureRandom());
}
/**
* 生成真随机数的长整型
* @date 2021/4/6 9:09
* @return long
*/
public static long getSecureRandomLong() {
return (new SecureRandom()).nextLong();
}
/**
* 生成真随机长整型数的16进制字符串
* @date 2021/4/6 9:10
* @return java.lang.String
*/
public static String getSecureRandomLongOfHexString() {
return Long.toHexString(getSecureRandomLong());
}
/**
* 生成uuid
* @date 2021/4/6 9:13
* @return java.lang.String
*/
public static String getUuid() {
return UUID.randomUUID().toString();
}
/**
* 获取当前格式化日期
* @date 2021/4/6 9:13
* @return java.lang.String
*/
public static String getNow() {
SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = new Date();
return SIMPLE_DATE_FORMAT.format(date);
}
/**
* 获取毫秒
* @date 2021/4/6 9:15
* @return long
*/
public static long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
/**
* 获取毫秒的16进制字符串
* @date 2021/4/6 9:17
* @return java.lang.String
*/
public static String getCurrentTimeMillisHexString() {
return Long.toHexString(getCurrentTimeMillis());
}
/**
* todo 待补充
* @date 2021/4/6 9:36
* @return java.lang.String
*/
public static synchronized String i() {
Date now = new Date();
if (now.equals(date)) {
++count;
} else {
date = now;
count = 0;
}
return Integer.toHexString(count);
}
/**
* todo 待补充
* @date 2021/4/6 9:39
* @param var0
* @param length
* @return java.lang.String
*/
public static String a(String var0, int length) {
int var2 = length - var0.length();
StringBuilder sb;
for(sb = new StringBuilder(); var2 >= 8; var2 -= 8) {
sb.append(NUMBER_STRINGS[3]);
}
for(int i = 2; i >= 0; --i) {
if ((var2 & 1 << i) != 0) {
sb.append(NUMBER_STRINGS[i]);
}
}
sb.append(var0);
return sb.toString();
}
public static void main(String[] args) throws IOException {
log.info(getSecureRandomLong() + getCurrentTimeMillis() + "");
}
}
@@ -0,0 +1,169 @@
package com.jero.codegenerate.generate.util;
import java.text.*;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class SimpleFormat {
/**
* 下划线字符串转换为驼峰字符串
* @date 2021/4/6 9:55
* @param str 字符串
* @return java.lang.String
*/
public static String underlineToHump(String str) {
StringBuilder sb = new StringBuilder();
String[] strArray = str.split("_");
String[] newStringArray = strArray;
int length = strArray.length;
for(int i = 0; i < length; ++i) {
String s = newStringArray[i];
// 原字符串不包含 -
if (!str.contains("_")) {
sb.append(s);
//首次添加不首字母大写
} else if (sb.length() == 0) {
sb.append(s.toLowerCase());
} else {
// 首字母大写
sb.append(s.substring(0, 1).toUpperCase());
sb.append(s.substring(1).toLowerCase());
}
}
return sb.toString();
}
/**
* 驼峰字符串转换为下划线字符串
* @date 2021/4/6 10:01
* @param str 字符串
* @return java.lang.String
*/
public static String humpToUnderline(String str) {
StringBuilder sb = new StringBuilder(str);
// 随着下划线的增加,偏移量也会增加
int addUnderlineCount = 0;
// 不包含下划线
if (!str.contains("_")) {
for(int i = 0; i < str.length(); ++i) {
// 如果字母大写
if (Character.isUpperCase(str.charAt(i))) {
sb.insert(i + addUnderlineCount, "_");
++addUnderlineCount;
}
}
}
return sb.toString().toLowerCase().startsWith("_") ? sb.toString().toLowerCase().substring(1) : sb.toString().toLowerCase();
}
/**
* 驼峰字符串转换为下划线字符串 ps:方法可能重复了
* @date 2021/4/6 10:17
* @param str 字符串
* @return java.lang.String
*/
public static String humpToShortbar(String str) {
StringBuilder sb = new StringBuilder(str);
int addUnderlineCount = 0;
if (!str.contains("-")) {
for(int i = 0; i < str.length(); ++i) {
if (Character.isUpperCase(str.charAt(i))) {
sb.insert(i + addUnderlineCount, "-");
++addUnderlineCount;
}
}
}
return sb.toString().toLowerCase().startsWith("-") ? sb.toString().toLowerCase().substring(1) : sb.toString().toLowerCase();
}
public String number(Object obj) {
obj = obj != null && obj.toString().length() != 0 ? obj : 0;
return obj.toString().equalsIgnoreCase("NaN") ? "NaN" : (new DecimalFormat("0.00")).format(Double.parseDouble(obj.toString()));
}
public String number(Object obj, String pattern) {
obj = obj != null && obj.toString().length() != 0 ? obj : 0;
return obj.toString().equalsIgnoreCase("NaN") ? "NaN" : (new DecimalFormat(pattern)).format(Double.parseDouble(obj.toString()));
}
public String round(Object obj) {
obj = obj != null && obj.toString().length() != 0 ? obj : 0;
return obj.toString().equalsIgnoreCase("NaN") ? "NaN" : (new DecimalFormat("0")).format(Double.parseDouble(obj.toString()));
}
public String currency(Object obj) {
obj = obj != null && obj.toString().length() != 0 ? obj : 0;
return NumberFormat.getCurrencyInstance(Locale.CHINA).format(obj);
}
/**
* timeStamp转换为日期格式化String
* @date 2021/4/6 10:22
* @param obj
* @param pattern
* @return java.lang.String
*/
public String timestampToString(Object obj, String pattern) {
if (obj == null) {
return "";
} else {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM月 -yy");
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat(pattern);
Date date = null;
try {
date = simpleDateFormat.parse(obj.toString());
} catch (ParseException e) {
e.printStackTrace();
return "error";
}
return simpleDateFormat1.format(date);
}
}
public String percent(Object obj) {
obj = obj != null && obj.toString().length() != 0 ? obj : 0;
return obj.toString().equalsIgnoreCase("NaN") ? "" : NumberFormat.getPercentInstance(Locale.CHINA).format(obj);
}
public String date(Object obj, String pattern) {
return obj == null ? "" : (new SimpleDateFormat(pattern)).format(obj);
}
public String date(Object obj) {
return obj == null ? "" : DateFormat.getDateInstance(1, Locale.CHINA).format(obj);
}
public String time(Object obj) {
return obj == null ? "" : DateFormat.getTimeInstance(3, Locale.CHINA).format(obj);
}
public String datetime(Object obj) {
return obj == null ? "" : DateFormat.getDateTimeInstance(1, 3, Locale.CHINA).format(obj);
}
/**
* 将字符串集合转换为 'string', 间隔格式的字符串
* @date 2021/4/6 9:41
* @param stringList 字符串集合
* @return java.lang.String
*/
public String getInStrs(List<String> stringList) {
StringBuilder sb = new StringBuilder();
for (String s : stringList) {
sb.append("'").append(s).append("',");
}
String string = sb.toString();
if ("".equals(string)) {
return null;
} else {
string = string.substring(0, string.length() - 1);
return string;
}
}
}
@@ -0,0 +1,43 @@
package com.jero.codegenerate.generate.util;
import org.apache.commons.lang.StringUtils;
public class TableConvert {
private TableConvert(){
}
/**
* 校验字段为 '是' 或 '否'
* @date 2021/4/6 10:46
* @param s
* @return java.lang.String
*/
public static String getNullable(String s) {
if (!"YES".equals(s) && !"yes".equals(s) && !"y".equals(s) && !"Y".equals(s) && !"f".equals(s)) {
return !"NO".equals(s) && !"N".equals(s) && !"no".equals(s) && !"n".equals(s) && !"t".equals(s) ? null : "N";
} else {
return "Y";
}
}
/**
* 校验字符串是否为空字符串
* @date 2021/4/6 10:44
* @param s 字符串
* @return java.lang.String
*/
public static String isFieldValueBlank(String s) {
return StringUtils.isBlank(s) ? "" : s;
}
/**
* 格式化字符串,加单引号
* @date 2021/4/6 10:45
* @param s 字符串
* @return java.lang.String
*/
public static String formatStr(String s) {
return "'" + s + "'";
}
}
@@ -0,0 +1,187 @@
package com.jero.codegenerate.properties;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
* 配置文件
* @date 2021/4/2 11:01
*/
@Slf4j
public class CodeConfigProperties {
private CodeConfigProperties(){
}
private static final String DATA_BASE_FILE_URL = "jero/jero_database";
private static final String CONFIG_FILE_URL = "jero/jero_config";
private static ResourceBundle databaseDatasourcePropties = getDatasourcePropties(CodeConfigProperties.DATA_BASE_FILE_URL);
private static ResourceBundle configDatasourcePropties = getDatasourcePropties(CodeConfigProperties.CONFIG_FILE_URL);
public static String databaseType;
public static String driverName;
public static String databaseUrl;
public static String username;
public static String password;
public static String projectPath;
public static String packageName;
public static String sourceRootPackage;
public static String webrootPackage;
public static String templateUrl;
public static boolean dbFiledConvert;
public static String dbTableId;
public static String fieldRequiredNum;
public static String pageSearchFieldNum;
public static String pageFilterFields;
public static String fieldRowNum;
public static final String MY_SQL = "mysql";
public static final String SQL_SERVER = "sqlserver";
private static ResourceBundle getDatasourcePropties(String url) {
String configPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + url + ".properties";
PropertyResourceBundle propertyResourceBundle = null;
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(configPath))){
propertyResourceBundle = new PropertyResourceBundle(bufferedInputStream);
log.info(" JAR方式部署,通过config目录读取配置:" + configPath);
} catch (IOException e) {
log.error(e.getMessage());
}
return propertyResourceBundle;
}
public static final String getDriverName() {
return databaseDatasourcePropties.getString("driver_name");
}
public static final String getDatabaseUrl() {
return databaseDatasourcePropties.getString("url");
}
public static final String getUsername() {
return databaseDatasourcePropties.getString("username");
}
public static final String getPassword() {
return databaseDatasourcePropties.getString("password");
}
public static final String getDatabaseName() {
return databaseDatasourcePropties.getString("database_name");
}
public static final boolean getDbFiledConvert() {
String dbFiledConvert = configDatasourcePropties.getString("db_filed_convert");
return !dbFiledConvert.equals("false");
}
private static String getBussiPackage() {
return configDatasourcePropties.getString("bussi_package");
}
private static String getTemplateUrl() {
return configDatasourcePropties.getString("template_path");
}
public static final String getSourceRootPackage() {
return configDatasourcePropties.getString("source_root_package");
}
public static final String getWebrootPackage() {
return configDatasourcePropties.getString("webroot_package");
}
public static final String getDBTableId() {
return configDatasourcePropties.getString("db_table_id");
}
public static final String getPageFilterFields() {
return configDatasourcePropties.getString("page_filter_fields");
}
public static final String getPageSearchFieldNum() {
return configDatasourcePropties.getString("page_search_filed_num");
}
public static final String getPageFieldRequiredNum() {
return configDatasourcePropties.getString("page_field_required_num");
}
public static String getProjectPath() {
String var0 = configDatasourcePropties.getString("project_path");
if (var0 != null && !"".equals(var0)) {
projectPath = var0;
}
return projectPath;
}
public static void setProjectPath(String projectPath) {
CodeConfigProperties.projectPath = projectPath;
}
public static void setTemplateUrl(String templateUrl) {
CodeConfigProperties.templateUrl = templateUrl;
}
static {
if (databaseDatasourcePropties == null) {
databaseDatasourcePropties = ResourceBundle.getBundle(CodeConfigProperties.DATA_BASE_FILE_URL);
}
if (configDatasourcePropties == null) {
configDatasourcePropties = ResourceBundle.getBundle(CodeConfigProperties.CONFIG_FILE_URL);
}
databaseType = MY_SQL;
driverName = "com.mysql.jdbc.Driver";
databaseUrl = "jdbc:mysql://localhost:3306/jero-boot?useUnicode=true&characterEncoding=UTF-8";
username = "root";
password = "root";
projectPath = "c:/workspace/jero";
packageName = "com.jero";
sourceRootPackage = "src";
webrootPackage = "WebRoot";
templateUrl = "/jero/code-template/";
dbFiledConvert = true;
fieldRequiredNum = "4";
pageSearchFieldNum = "3";
fieldRowNum = "1";
driverName = getDriverName();
databaseUrl = getDatabaseUrl();
username = getUsername();
password = getPassword();
sourceRootPackage = getSourceRootPackage();
webrootPackage = getWebrootPackage();
packageName = getBussiPackage();
templateUrl = getTemplateUrl();
projectPath = getProjectPath();
dbTableId = getDBTableId();
dbFiledConvert = getDbFiledConvert();
pageFilterFields = getPageFilterFields();
pageSearchFieldNum = getPageSearchFieldNum();
if (!databaseUrl.contains(MY_SQL) && !databaseUrl.contains("MYSQL")) {
if (!databaseUrl.contains("oracle") && !databaseUrl.contains("ORACLE")) {
if (!databaseUrl.contains("postgresql") && !databaseUrl.contains("POSTGRESQL")) {
if (databaseUrl.contains(SQL_SERVER) || databaseUrl.contains("sql server")) {
databaseType = SQL_SERVER;
}
} else {
databaseType = "postgresql";
}
} else {
databaseType = "oracle";
}
} else {
databaseType = MY_SQL;
}
sourceRootPackage = sourceRootPackage.replace(".", "/");
webrootPackage = webrootPackage.replace(".", "/");
}
}