update codegen

This commit is contained in:
东皇 2018-06-25 21:08:53 +08:00
parent ac55d7891b
commit eaa3fbd0cd
27 changed files with 249 additions and 469 deletions

View File

@ -47,7 +47,6 @@
<module>tigon-service-api</module>
<module>tigon-service-support</module>
<module>tigon-extjs</module>
<module>tigon-freemarker-support</module>
<module>tigon-codegen</module>
</modules>
@ -159,7 +158,6 @@
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
@ -169,8 +167,6 @@
<configuration>
<addResources>true</addResources>
<layout>ZIP</layout>
<!--<skip>false</skip>-->
<!--<fork>true</fork>-->
</configuration>
<executions>
<execution>

View File

@ -24,9 +24,12 @@
<dependencies>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-freemarker-support</artifactId>
<version>0.0.1-SNAPSHOT</version>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
@ -50,6 +53,16 @@
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-mybatis</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@ -71,6 +84,7 @@
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>false</skip>
<fork>true</fork>
</configuration>
</plugin>
</plugins>

View File

@ -1,5 +1,6 @@
package me.chyxion.tigon.codegen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -8,13 +9,15 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* chyxion@163.com <br>
* Jun 24, 2018 20:43:36
*/
@Slf4j
@SpringBootApplication
public class TigonCodeGen {
/**
* @param args start args
*/
public static void main(String[] args) {
public static void main(final String[] args) {
log.info("Startup args [{}].", args);
SpringApplication.run(TigonCodeGen.class, args);
}
}

View File

@ -10,6 +10,8 @@ import com.alibaba.fastjson.JSONArray;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import javax.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import me.chyxion.tigon.codegen.service.CodeGenService;
@ -35,11 +37,16 @@ public class CodeGenController {
private CodeGenService service;
@Autowired
private CodeGenBaseTool tool;
@Value("${codegen.components:}")
private String genComponents;
@RequestMapping(method = GET)
public ModelAndView index() {
return new ModelAndView("webapp/views/codegen")
.addObject("pkg", tool.getPkg());
.addObject("pkg", tool.getPkg())
.addObject("components",
StringUtils.isNotBlank(genComponents) ?
JSON.toJSONString(genComponents.split("\\s*[,;]\\s*")) : "[]");
}
@RequestMapping(value = "/tables")

View File

@ -1,8 +1,7 @@
package me.chyxion.tigon.freemarker;
package me.chyxion.tigon.codegen.freemarker;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
@ -13,9 +12,8 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
* chyxion@163.com <br>
* Dec 5, 2014 2:31:39 PM
*/
@Slf4j
public class FreeMarkerViewResolverExt extends FreeMarkerViewResolver {
private static final Logger log =
LoggerFactory.getLogger(FreeMarkerViewResolverExt.class);
/**
* {@inheritDoc}
@ -24,6 +22,6 @@ public class FreeMarkerViewResolverExt extends FreeMarkerViewResolver {
public View resolveViewName(String viewName, Locale locale)
throws Exception {
log.debug("Try to resolve view name [{}], locale [{}] as freemarker view.", viewName, locale);
return super.resolveViewName(viewName.replaceAll("(?i)(^\\s*ftl\\:)|(\\.ftl\\s*$)", ""), locale);
return super.resolveViewName(viewName.replaceAll("(?i)(^\\s*ftl:)|(\\.ftl\\s*$)", ""), locale);
}
}

View File

@ -1,41 +1,25 @@
package me.chyxion.tigon.codegen.service;
import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import org.slf4j.Logger;
import java.util.TreeSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.*;
import java.io.FileWriter;
import java.sql.ResultSet;
import org.w3c.dom.Element;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import java.util.LinkedList;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.io.FileInputStream;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.sql.DatabaseMetaData;
import com.alibaba.fastjson.JSON;
import java.io.InputStreamReader;
import me.chyxion.tigon.model.M1;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import javax.annotation.PostConstruct;
import org.apache.commons.io.FileUtils;
import me.chyxion.tigon.util.WordUtils;
import java.nio.charset.StandardCharsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.CharEncoding;
import me.chyxion.tigon.codegen.utils.DbTool;
import javax.xml.parsers.DocumentBuilderFactory;
import me.chyxion.tigon.codegen.util.DbTool;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.dao.DataAccessException;
@ -46,7 +30,6 @@ import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import static org.springframework.context.ConfigurableApplicationContext.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
/**
@ -56,92 +39,21 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
* chyxion@163.com <br>
* Dec 3, 2014 11:25:17 AM
*/
@Slf4j
public class CodeGenBaseTool {
private static final Logger log =
LoggerFactory.getLogger(CodeGenBaseTool.class);
@Autowired
private FreeMarkerConfigurer fmCfg;
@Autowired(required = false)
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTpl;
@Value("#{systemProperties['project.basedir']}")
@Value("${project.base-dir}")
private String projDir;
private String groupId;
@Value("${project.base-package}")
private String pkg;
private Properties config = new Properties();
private Set<String> baseCols = new HashSet<String>();
@Value("${codegen.table-prefix:}")
private String tablePrefix;
/**
* @param col
* @return true if col is base col
*/
public boolean isBaseCol(String col) {
return baseCols.contains(col);
}
/**
* @param key
* @return
*/
public String getConfig(String key) {
return config.getProperty(key);
}
/**
* @param key
* @param defaultValue
* @return
*/
public String getConfig(String key, String defaultValue) {
return config.getProperty(key, defaultValue);
}
/**
* get config
* @param key
* @param defaultValue
* @return
*/
public boolean getConfig(String key, boolean defaultValue) {
return Boolean.valueOf(getConfig(key, String.valueOf(defaultValue)));
}
/**
* @param key
* @param defaultValue
* @return
*/
public int getConfig(String key, int defaultValue) {
return Integer.valueOf(getConfig(key, String.valueOf(defaultValue)));
}
/**
* @param key
* @param defaultValue
* @return
*/
public long getConfig(String key, long defaultValue) {
return Long.valueOf(getConfig(key, String.valueOf(defaultValue)));
}
/**
* @param key
* @param defaultValue
* @return
*/
public double getConfig(String key, double defaultValue) {
return Double.valueOf(getConfig(key, String.valueOf(defaultValue)));
}
/**
* @param key
* @param defaultValue
* @return
*/
public float getConfig(String key, float defaultValue) {
return Float.valueOf(getConfig(key, String.valueOf(defaultValue)));
}
private Set<String> baseCols = new HashSet<>();
/**
* @return the projDir
@ -150,13 +62,6 @@ public class CodeGenBaseTool {
return projDir;
}
/**
* @return the groupId
*/
public String getGroupId() {
return groupId;
}
/**
* @return the groupId
*/
@ -193,63 +98,6 @@ public class CodeGenBaseTool {
}
}
/**
* init config
*/
@PostConstruct
void init() {
// disable cache
log.info("Disable FreeMarker Cache In Dev Mode.");
fmCfg.getConfiguration().setTemplateUpdateDelayMilliseconds(0);
if (dataSource != null) {
jdbcTpl = new JdbcTemplate(dataSource, true);
}
try {
log.info("Parse Group ID From [{}/pom.xml].", projDir);
Element root = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new File(projDir, "pom.xml"))
.getDocumentElement();
root.normalize();
groupId = root.getElementsByTagName("groupId").item(0).getTextContent().trim();
log.info("Group ID [{}] Found.", groupId);
}
catch (Exception e) {
throw new IllegalStateException(
"Parse [groupId] From Maven POM File [" + projDir + "/pom.xml] Error Caused", e);
}
InputStream cfgIns = CodeGenBaseTool.class
.getResourceAsStream("/codegen/config.properties");
if (cfgIns != null) {
try {
config.load(cfgIns);
log.info("Code Gen Config [{}] Found.", config);
}
catch (IOException e) {
throw new IllegalStateException(
"Load Code Gen Config Error Caused", e);
}
finally {
IOUtils.closeQuietly(cfgIns);
}
}
baseCols.add("id");
String baseColsProp = config.getProperty("base.cols");
if (StringUtils.isNotBlank(baseColsProp)) {
log.info("Code Gen Base Cols [{}] Found.", baseColsProp);
baseCols.addAll(Arrays.asList(
org.springframework.util.StringUtils
.tokenizeToStringArray(
baseColsProp, CONFIG_LOCATION_DELIMITERS, true, true)));
}
log.info("Code Gen Base Cols [{}] Result.", baseCols);
pkg = config.getProperty("base.package", groupId);
log.info("Code Gen Package [{}].", pkg);
}
/**
* list all model generated
* @return
@ -270,7 +118,7 @@ public class CodeGenBaseTool {
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
mapData = JSON.parseObject(IOUtils.toString(fin, CharEncoding.UTF_8));
mapData = JSON.parseObject(IOUtils.toString(fin, StandardCharsets.UTF_8));
}
catch (IOException e) {
log.info("Parse JSON File [{}] ERROR Caused.", file.getName());
@ -284,7 +132,7 @@ public class CodeGenBaseTool {
// backup data file
IOUtils.copy(fin,
new FileWriter(new File(projDir, backupFileName)),
CharEncoding.UTF_8);
StandardCharsets.UTF_8);
}
}
catch (IOException e1) {
@ -296,8 +144,8 @@ public class CodeGenBaseTool {
}
}
if (mapData == null) {
mapData = new HashMap<String, Object>();
mapData.put("items", new LinkedList<Object>());
mapData = new HashMap<>();
mapData.put("items", new LinkedList<>());
}
return mapData;
}
@ -309,7 +157,7 @@ public class CodeGenBaseTool {
FileUtils.write(file, JSON.toJSONStringWithDateFormat(storeData,
"yyyy-MM-dd HH:mm:ss",
SerializerFeature.PrettyFormat),
CharEncoding.UTF_8);
StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException("Write Data To File [" + file.getAbsolutePath() + "] ERROR Caused.", e);
@ -371,7 +219,7 @@ public class CodeGenBaseTool {
execSQL("drop table " + item.get("table"));
}
catch (Exception e) {
log.info("Drop Table Error Caused.", e);
log.info("Drop table error caused.", e);
}
}
it.remove();
@ -392,7 +240,7 @@ public class CodeGenBaseTool {
return FreeMarkerTemplateUtils.processTemplateIntoString(
new Template(ftl, new InputStreamReader(
CodeGenBaseTool.class.getResourceAsStream(ftl),
CharEncoding.UTF_8), fmCfg.getConfiguration()), model);
StandardCharsets.UTF_8), fmCfg.getConfiguration()), model);
}
catch (Exception e) {
throw new RuntimeException("Code Generate Render ERROR, [" + e.getMessage() + "].", e);
@ -410,9 +258,6 @@ public class CodeGenBaseTool {
try {
DatabaseMetaData md = conn.getMetaData();
rs = md.getTables(null, null, "%", new String[] {"TABLE"});
String tablePrefix =
config.getProperty("table.prefix", "")
.toLowerCase();
while (rs.next()) {
Map<String, Object> mapTable = new HashMap<String, Object>();
String table = rs.getString(3).toLowerCase();
@ -422,7 +267,7 @@ public class CodeGenBaseTool {
String[] tableNameParts = null;
if (StringUtils.isNotBlank(tablePrefix) &&
table.startsWith(tablePrefix + "_")) {
log.info("Table Prefix [{}] Found, Trim.", tablePrefix);
log.info("Table prefix [{}] found, trim.", tablePrefix);
tableNameParts =
table.substring(tablePrefix.length() + 1)
.split("_");
@ -451,7 +296,7 @@ public class CodeGenBaseTool {
}
});
}
return new LinkedList<Map<String, Object>>();
return Collections.emptyList();
}
// --

View File

@ -1,38 +1,42 @@
package me.chyxion.tigon.codegen.service.support;
import me.chyxion.tigon.mybatis.Table;
import me.chyxion.tigon.service.BaseCrudService;
import me.chyxion.tigon.service.BaseService;
import me.chyxion.tigon.service.support.BaseCrudServiceSupport;
import me.chyxion.tigon.util.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Locale;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import me.chyxion.tigon.codegen.controller.CodeGenController.GenForm;
import me.chyxion.tigon.codegen.service.CodeGenBaseTool;
import me.chyxion.tigon.codegen.service.CodeGenService;
import me.chyxion.tigon.codegen.service.CodeGenerator;
import me.chyxion.tigon.mybatis.BaseMapper;
import java.text.DateFormat;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.model.M1;
import me.chyxion.tigon.model.M2;
import me.chyxion.tigon.model.M3;
import me.chyxion.tigon.webmvc.test.ControllerTestTool;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Modifier;
import me.chyxion.tigon.mybatis.Table;
import me.chyxion.tigon.util.WordUtils;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.BaseMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ClassUtils;
import me.chyxion.tigon.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import me.chyxion.tigon.service.BaseCrudService;
import org.springframework.util.ReflectionUtils;
import me.chyxion.tigon.codegen.service.CodeGenerator;
import me.chyxion.tigon.webmvc.test.ControllerTestTool;
import me.chyxion.tigon.codegen.service.CodeGenService;
import me.chyxion.tigon.codegen.service.CodeGenBaseTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import me.chyxion.tigon.service.support.BaseCrudServiceSupport;
import me.chyxion.tigon.codegen.controller.CodeGenController.GenForm;
/**
* @version 0.0.1
@ -41,8 +45,8 @@ import org.springframework.beans.factory.annotation.Autowired;
* chyxion@163.com <br>
* Oct 6, 2014 1:10:02 PM
*/
@Slf4j
public class CodeGenServiceSupport implements CodeGenService {
private static final Logger log = LoggerFactory.getLogger(CodeGenServiceSupport.class);
private static final Map<String, String> TYPE_PACKAGES = new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
@ -54,6 +58,14 @@ public class CodeGenServiceSupport implements CodeGenService {
private CodeGenBaseTool baseTool;
@Autowired
private List<CodeGenerator> codeGen;
@Value("${codegen.mapper.cache-enabled:false}")
private boolean cacheEnabled;
@Value("${codegen.model.super-class.name:}")
private String modelSuperClassName;
@Value("${codegen.model.super-class.import-name:}")
private String modelSuperClassImportName;
@Value("${codegen.model.super-class.import-required:true}")
private boolean modelSuperClassImportRequired;
/**
* {@inheritDoc}
@ -88,7 +100,7 @@ public class CodeGenServiceSupport implements CodeGenService {
fmDataModel.put("table", table.toLowerCase());
fmDataModel.put("notNull", false);
fmDataModel.put("notBlank", false);
fmDataModel.put("cacheEnabled", baseTool.getConfig("cache.enabled", false));
fmDataModel.put("cacheEnabled", cacheEnabled);
fmDataModel.put("useGeneratedKeys", false);
// collect col names
@ -102,65 +114,87 @@ public class CodeGenServiceSupport implements CodeGenService {
if (ArrayUtils.contains(
new String[] {"int", "long", "boolean", "double", "byte"},
javaType)) {
javaType = StringUtils.capitalize(javaType);
javaType = "int".equals(javaType) ?
Integer.class.getSimpleName() :
StringUtils.capitalize(javaType);
}
idType = javaType;
}
}
String baseModelName = null;
String baseModelFullName = null;
Collection<String> baseCols = null;
if (colNames.containsAll(new M3<String, String>().cols())) {
final String baseModelName;
final String baseModelFullName;
final Collection<String> baseCols;
// custom super class
if (StringUtils.isNotBlank(modelSuperClassName)) {
Assert.state(StringUtils.isNotBlank(modelSuperClassImportName ),
"config 'codegen.model.super-class.import-name' required");
baseModelName = modelSuperClassName;
baseModelFullName = modelSuperClassImportRequired ?
modelSuperClassImportName : null;
try {
baseCols = new HashSet<>();
ReflectionUtils.doWithFields(ClassUtils.getClass(modelSuperClassImportName), field -> {
log.info("Super model field [{}] found.", field);
final int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
final String fieldName = field.getName();
log.info("Add super model filed [{}] to base cols.", fieldName);
baseCols.add(WordUtils.convertCamelCase(fieldName, "_").toLowerCase());
}
});
}
catch (final ClassNotFoundException e) {
throw new IllegalStateException(
"No model super class [" + modelSuperClassImportName + "] found", e);
}
log.info("Base cols [{}] extracted.", baseCols);
}
else if (colNames.containsAll(new M3<String, String>().cols())) {
baseModelName = M3.class.getSimpleName() +
"<" + idType + ", " + idType + ">";
baseModelFullName = M3.class.getName();
baseCols = new M3<String, String>().cols();
log.info("Base cols [{}] read from M3.", baseCols);
}
else if (colNames.containsAll(new M2<String>().cols())) {
baseModelName = M2.class.getSimpleName() + "<" + idType + ">";
baseModelFullName = M2.class.getName();
baseCols = new M2<String>().cols();
log.info("Base cols [{}] read from M2.", baseCols);
}
else if (colNames.containsAll(new M1<String>().cols())) {
baseModelName = M1.class.getSimpleName() + "<" + idType + ">";
baseModelFullName = M1.class.getName();
baseCols = new M1<String>().cols();
log.info("Base cols [{}] read from M1.", baseCols);
}
else {
baseModelName = M0.class.getSimpleName();
baseModelFullName = M0.class.getName();
baseCols = new M0<String>().cols();
}
// custom config
String cfgBaseModelName = baseTool.getConfig("super.base.model.name");
if (StringUtils.isNotBlank(cfgBaseModelName)) {
baseCols = baseTool.getBaseCols();
log.info("Base cols [{}] read from M0.", baseCols);
}
String cfgBaseModelFullName =
baseTool.getConfig("super.base.model.full.name");
fmDataModel.put("baseModelName",
baseTool.getConfig("super.base.model.name", baseModelName));
fmDataModel.put("baseModelFullName",
"NONE".equalsIgnoreCase(cfgBaseModelFullName) ? null :
StringUtils.isNotBlank(cfgBaseModelFullName) ?
cfgBaseModelFullName : baseModelFullName);
fmDataModel.put("baseModelFullName", baseModelFullName);
fmDataModel.put("baseModelName", baseModelName);
fmDataModel.put("tableAnnotationClassName", Table.class.getName());
fmDataModel.put("tableAnnotationName", Table.class.getSimpleName());
Set<String> imports = new HashSet<String>();
List<Map<String, Object>> colsWithoutBase =
final Set<String> imports = new HashSet<>();
final List<Map<String, Object>> colsWithoutBase =
(List<Map<String, Object>>) columns;
Iterator<Map<String, Object>> colIt =
final Iterator<Map<String, Object>> colIt =
colsWithoutBase.iterator();
while (colIt.hasNext()) {
Map<String, Object> col = colIt.next();
// col name
String colName = ((String) col.get("col")).toLowerCase();
final String colName = ((String) col.get("col")).toLowerCase();
log.info("Process model col [{}].", colName);
if (!baseCols.contains(colName)) {
// prop name
String propName = (String) col.get("name");
@ -175,13 +209,14 @@ public class CodeGenServiceSupport implements CodeGenService {
}
}
// imports
String p = TYPE_PACKAGES.get(col.get("javaType"));
if (StringUtils.isNotBlank(p)) {
imports.add(p);
final String imp = TYPE_PACKAGES.get(col.get("javaType"));
if (StringUtils.isNotBlank(imp)) {
imports.add(imp);
}
}
// remove base col
else {
log.info("Remove base col [{}].", colName);
colIt.remove();
}
}

View File

@ -4,7 +4,6 @@ import java.io.File;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import me.chyxion.tigon.codegen.model.CodeGenArgs;
@ -17,7 +16,7 @@ import me.chyxion.tigon.codegen.service.CodeGenerator;
* chyxion@163.com <br>
* Oct 7, 2014 12:23:13 PM
*/
@Order(Ordered.LOWEST_PRECEDENCE)
@Order
public class TableCodeGen extends CodeGenerator {
private static final Logger log = LoggerFactory.getLogger(TableCodeGen.class);
@ -35,7 +34,7 @@ public class TableCodeGen extends CodeGenerator {
@Override
public String process(Map<String, Object> dataModel, String module, String model) {
String table = (String) dataModel.get("table");
log.info("Process Generate Table [{}] SQL File.", table);
log.info("Process generate table [{}] SQL file.", table);
StringBuilder filePath = new StringBuilder(resourcesDir)
.append("db/");
if (StringUtils.isNotBlank(module)) {
@ -51,21 +50,21 @@ public class TableCodeGen extends CodeGenerator {
if (!Boolean.FALSE.equals(dataModel.get("createTable"))) {
// ignore drop table error
try {
log.info("Execute Drop Table [{}].", table);
log.info("Execute drop table [{}].", table);
baseTool.execSQL("drop table " + table);
}
catch (Exception e) {
log.info("Drop Table Failed, Error Message [{}], Ingore.",
log.info("Drop table failed, error message [{}], ignore.",
e.getMessage());
}
// ignore execute sql error
try {
log.info("Execut Create Table SQL File [{}].", filePath);
log.info("Execute create table SQL file [{}].", filePath);
baseTool.execSQL(new File(baseTool.getProjDir(), filePath
.toString()));
}
catch (Exception e) {
log.warn("Database Create Table Error, Ingore.", e);
log.warn("Database create table error, ignore.", e);
}
}
return filePath.toString();

View File

@ -1,4 +1,4 @@
package me.chyxion.tigon.codegen.utils;
package me.chyxion.tigon.codegen.util;
import java.io.IOException;
import java.io.LineNumberReader;

View File

@ -1,13 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="me.chyxion.tigon.codegen.controller" />
<!-- Tool -->
<bean class="me.chyxion.tigon.codegen.service.CodeGenBaseTool" />
@ -23,4 +20,40 @@
<bean class="me.chyxion.tigon.codegen.service.support.TableCodeGen" />
<bean class="me.chyxion.tigon.codegen.service.support.ViewCodeGen" />
<!-- FreeMarker Config -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPaths="/WEB-INF/views/, classpath:/, classpath:/webapp/views/"
p:defaultEncoding="utf-8"
p:preferFileSystemAccess="false">
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">${tigon.codegen.freemarker.cache.expire:36000}</prop>
<prop key="output_encoding">utf-8</prop>
<prop key="locale">en_US</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<!-- avoid 000.00 -->
<prop key="number_format">#</prop>
</props>
</property>
</bean>
<bean class="me.chyxion.tigon.codegen.freemarker.FreeMarkerViewResolverExt"
p:suffix=".ftl"
p:contentType="text/html; charset=utf-8"
p:exposeRequestAttributes="true"
p:order="16"
/>
<bean class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg>
<bean class="com.alibaba.druid.pool.DruidDataSource"
init-method="init"
destroy-method="close"
p:url="jdbc:mysql://${datasource.host}:${datasource.port}/${datasource.database-name}?useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull"
p:username="${datasource.username}"
p:password="${datasource.password}"
/>
</constructor-arg>
</bean>
</beans>

View File

@ -86,13 +86,6 @@ Ext.define ('Tigon.views.CodeGen', {
form = rc.down('form');
form.getForm().setValues(rec.getData());
form.down('grid').getStore().loadData(rec.get('cols'));
// show demo grid
// var dg = rc.down('container[name=demo_grid]');
// dg.removeAll();
// load view
// dg.add(Ext.create('App.views.' +
// (rec.get('module') ? rec.get('module') + '.' : '') +
// rec.get('model') + '.List'));
}
}
}
@ -121,13 +114,6 @@ Ext.define ('Tigon.views.CodeGen', {
createTable: false
}));
form.down('grid').getStore().loadData(rec.get('cols'));
// show demo grid
// var dg = rc.down('container[name=demo_grid]');
// dg.removeAll();
// load view
// dg.add(Ext.create('App.views.' +
// (rec.get('module') ? rec.get('module') + '.' : '') +
// rec.get('model') + '.List'));
}
}
}
@ -215,34 +201,30 @@ Ext.define ('Tigon.views.CodeGen', {
fieldLabel: 'Options',
xtype: 'checkboxgroup',
defaults: {
checked: true,
checked: false,
xtype: 'checkbox',
inputValue: true
},
columns: 3,
items: [{
boxLabel: 'Gen controller',
checked: components.indexOf('controller') > -1,
name: 'genController'
}, {
boxLabel: 'Gen service',
name: 'genService'
}, {
boxLabel: 'Gen mapper',
checked: components.indexOf('mapper') > -1,
name: 'genMapper'
}, {
boxLabel: 'Gen model',
checked: components.indexOf('model') > -1,
name: 'genModel'
}, {
boxLabel: 'Gen table',
name: 'genTable'
}, {
boxLabel: 'Gen form',
checked: false,
checked: components.indexOf('form') > -1,
name: 'genView'
}, {
boxLabel: 'Create table',
checked: false,
name: 'createTable'
}]
}, {
xtype: 'fieldcontainer',

View File

@ -16,7 +16,7 @@
items: [{
xtype: 'box',
region: 'north',
html: '<h1>Super Super Code!</h1>'
html: '<h1>Tigon Code Gen!</h1>'
},
Ext.create('Tigon.views.CodeGen', {
region: 'center'
@ -26,6 +26,7 @@
Ext.create('Tigon.views.ThemesBar').show();
});
var pkg = '${pkg}';
var components = ${components};
</script>
<title>Auto Code</title>
</head>

View File

@ -1 +0,0 @@
# tigon-freemarker-support

View File

@ -1,54 +0,0 @@
<?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>
<artifactId>tigon-freemarker-support</artifactId>
<packaging>jar</packaging>
<name>Tigon FreeMarker Support</name>
<description>Tigon FreeMarker Support</description>
<parent>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- FreeMarker Config -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPaths="/WEB-INF/views/, classpath:/, classpath:/webapp/views/"
p:defaultEncoding="utf-8"
p:preferFileSystemAccess="false">
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">${freemarker.cache.expire:36000}</prop>
<prop key="output_encoding">utf-8</prop>
<prop key="locale">en_US</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<!-- avoid 000.00 -->
<prop key="number_format">#</prop>
</props>
</property>
</bean>
<bean class="me.chyxion.tigon.freemarker.FreeMarkerViewResolverExt"
p:suffix=".ftl"
p:contentType="text/html; charset=utf-8"
p:exposeRequestAttributes="true"
p:order="16"
/>
</beans>

View File

@ -1,20 +0,0 @@
package me.chyxion.tigon.freemarker.test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Jan 27, 2015 3:27:08 PM
*/
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/controller-test.xml")
public class SiteControllerTest {
}

View File

@ -1,13 +0,0 @@
log4j.rootLogger=debug, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.Encoding=utf-8
log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%F:%L] %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%F:%L] %m%n
log4j.appender.file.File=${log.dir}/${project.artifactId}-test.log
log4j.appender.file.Encoding=utf-8

View File

@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Scan Mock -->
<context:component-scan base-package="me.chyxion.tigon.freemarker.test"
use-default-filters="false">
<context:include-filter type="annotation"
expression="me.chyxion.tigon.webmvc.stereotype.Mock" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
</beans>

View File

@ -10,11 +10,11 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank;
* chyxion@163.com <br>
* Oct 8, 2016 6:26:19 PM
*/
@Getter
public class FC2<CreatorId> extends FC1 {
private static final long serialVersionUID = 1L;
private transient boolean __lock = true;
@Getter
@NotNullOrBlank
protected CreatorId createdBy;

View File

@ -1,7 +1,6 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.validation.annotation.NotNullOrBlank;
/**
@ -11,12 +10,12 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank;
* chyxion@163.com <br>
* Oct 8, 2016 6:26:36 PM
*/
@Getter
public class FU2<EditorId, Id>
extends FU1<Id> {
private static final long serialVersionUID = 1L;
private transient boolean __lock = true;
@Getter
@NotNullOrBlank
private EditorId updatedBy;

View File

@ -38,6 +38,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public String getId() {
return id;
}
@ -45,6 +46,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public int getSize() {
final Long size = hashOp.size(id);
log.info("Get redis cache [{}] size [{}].", id, size);
@ -54,6 +56,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public void putObject(final Object key, final Object value) {
log.debug("Put redis cache [{}] object key [{}], value [{}].", id, key, value);
hashOp.put(id, keyMd5(key), value);
@ -62,6 +65,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public Object getObject(final Object key) {
final Object value = hashOp.get(id, keyMd5(key));
log.debug("Get redis cache object key [{}], value [{}].", key, value);
@ -71,6 +75,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public Object removeObject(final Object key) {
log.info("Remove redis cache [{}] object key [{}].", id, key);
return hashOp.delete(id, keyMd5(key));
@ -79,6 +84,7 @@ public final class RedisCache implements Cache {
/**
* {@inheritDoc}
*/
@Override
public void clear() {
log.info("Clear redis cache [{}].", id);
redisTpl.delete(id);
@ -108,7 +114,7 @@ public final class RedisCache implements Cache {
* @param key cache key
* @return prefixed key
*/
private String keyMd5(Object key) {
private String keyMd5(final Object key) {
final String md5Hex = DigestUtils.md5Hex(key instanceof String ? (String) key : String.valueOf(key));
log.debug("Get redis cache [{}] key [{}] md5 hex [{}].", id, key, md5Hex);
return md5Hex;

View File

@ -34,11 +34,4 @@ public class RedisCacheConfig {
public RedisTemplate<String, Object> getRedisTpl() {
return redisTpl;
}
/**
* @param redisTpl the redisTpl to set
*/
public void setRedisTpl(RedisTemplate<String, Object> redisTpl) {
this.redisTpl = redisTpl;
}
}

View File

@ -1,7 +1,6 @@
package me.chyxion.tigon.mybatis.cache.support;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import javax.annotation.PostConstruct;
import org.apache.ibatis.session.Configuration;
@ -16,9 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
* chyxion@163.com <br>
* Aug 26, 2015 10:58:58 AM
*/
@Slf4j
public class CacheToolSupport implements CacheTool {
private static final Logger log =
LoggerFactory.getLogger(CacheToolSupport.class);
@Autowired
private SqlSessionFactory ssf;
@ -29,13 +27,13 @@ public class CacheToolSupport implements CacheTool {
*/
@Override
public void clearCache(Class<?> mapper) {
log.info("Clear Cache [{}].", mapper);
Cache cache = getCache(mapper);
log.info("Clear mybatis cache [{}].", mapper);
final Cache cache = getCache(mapper);
if (cache != null) {
cache.clear();
}
else {
log.warn("No Cache [{}] Found.", mapper);
log.warn("No mybatis cache [{}] found.", mapper);
}
}

View File

@ -1,8 +1,9 @@
package me.chyxion.tigon.service;
import java.util.List;
import javax.validation.constraints.Min;
import java.util.function.Function;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
@ -89,14 +90,14 @@ public interface BaseQueryService<PrimaryKey,
* scan model of all
* @param scanner scanner
*/
Model scan(@NotNull Scanner<Model> scanner);
Model scan(@NotNull Function<Model, Boolean> scanner);
/**
* scan model by search
* @param search search
* @param scanner scanner
*/
Model scan(Search search, @NotNull Scanner<Model> scanner);
Model scan(Search search, @NotNull Function<Model, Boolean> scanner);
/**
* scan model by search
@ -104,15 +105,11 @@ public interface BaseQueryService<PrimaryKey,
* @param search search
* @param scanner scanner
*/
Model scan(@Min(1) int batchSize, Search search, @NotNull Scanner<Model> scanner);
Model scan(@Min(1) int batchSize, Search search, @NotNull Function<Model, Boolean> scanner);
interface Scanner<T> {
/**
* scan model
* @param model model
* @return false to break
*/
boolean found(T model);
}
<Model> Model scan(@Min(1) int batchSize,
Search search,
@NotNull Function<Search, List<Model>> dataQuerier,
@NotNull Function<Search, Integer> countQuerier,
@NotNull Function<Model, Boolean> scanner);
}

View File

@ -2,8 +2,9 @@ package me.chyxion.tigon.service.support;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.BaseModel;
import java.util.function.Function;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import me.chyxion.tigon.mybatis.BaseMapper;
@ -24,7 +25,7 @@ public class BaseQueryServiceSupport
extends BaseServiceSupport<PrimaryKey, Model, Mapper>
implements BaseQueryService<PrimaryKey, Model> {
@Value("${default.query.batch.size:256}")
@Value("${tigon.query.batch.size:32}")
private int scanBatchSize;
/**
@ -59,7 +60,7 @@ public class BaseQueryServiceSupport
*/
@Override
public ListResult<Model> listPage(Search search) {
log.debug("LIST MODELS PAGE BY SEARCH [{}].", search);
log.debug("List models page by search [{}].", search);
return new ListResult<>(list(search), count(search));
}
@ -77,7 +78,7 @@ public class BaseQueryServiceSupport
*/
@Override
public ViewModel<Model> findViewModel(Search search) {
log.debug("Find view model by search [{}].", search);
log.debug("Find View Model By Search [{}].", search);
Model model = find(search);
return model != null ? toViewModel(model) : null;
}
@ -116,7 +117,7 @@ public class BaseQueryServiceSupport
* {@inheritDoc}
*/
@Override
public Model scan(Scanner<Model> scanner) {
public Model scan(Function<Model, Boolean> scanner) {
return scan(null, scanner);
}
@ -124,7 +125,7 @@ public class BaseQueryServiceSupport
* {@inheritDoc}
*/
@Override
public Model scan(Search search, Scanner<Model> scanner) {
public Model scan(Search search, Function<Model, Boolean> scanner) {
return scan(scanBatchSize(), search, scanner);
}
@ -132,25 +133,37 @@ public class BaseQueryServiceSupport
* {@inheritDoc}
*/
@Override
public Model scan(int batchSize, Search search, Scanner<Model> scanner) {
public Model scan(int batchSize, Search search, Function<Model, Boolean> scanner) {
return scan(batchSize, search, this::list, this::count, scanner);
}
/**
* {@inheritDoc}
*/
@Override
public <Model> Model scan(final int batchSize,
Search search,
final Function<Search, List<Model>> dataQuerier,
final Function<Search, Integer> countQuerier,
final Function<Model, Boolean> scanner) {
log.info("Scan model by search [{}].", search);
int total = count(search);
int total = countQuerier.apply(search);
if (total > 0) {
if (search == null) {
log.debug("Scan search is null, use default.");
search = new Search();
}
for (int start = 0; start < total; start += batchSize) {
for (Model model : list(
for (Model model : dataQuerier.apply(
search.offset(start)
.limit(Math.min(batchSize, total - start)))) {
if (scanner.found(model)) {
log.info("Model [{}] found by scanner.", model);
if (scanner.apply(model)) {
log.info("Model [{}] found by scanner, stop scan.", model);
return model;
}
}
}
log.debug("No matched model found by scanner.");
log.info("Scan completed, no matched model found by scanner.");
}
else {
log.info("No model to scan by search [{}].", search);
@ -161,6 +174,7 @@ public class BaseQueryServiceSupport
/**
* @return the mapper
*/
@Override
public Mapper getMapper() {
return mapper;
}
@ -168,6 +182,7 @@ public class BaseQueryServiceSupport
/**
* @param mapper the mapper to set
*/
@Override
public void setMapper(Mapper mapper) {
this.mapper = mapper;
}