1、SpringbootService

Former-commit-id: ed6e1b99dcdf2ad65c2cd3898b46ba93a7620e3e
master
wangbing 4 years ago
parent 3ed179c49c
commit ac3f17b734

@ -120,12 +120,18 @@
<version>3.21.0.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.oracle.driver</groupId>-->
<!--<artifactId>odbc</artifactId>-->
<!--<version>1.0.0</version>-->
<!--<scope>system</scope>-->
<!--<systemPath>${project.basedir}/src/main/resources/lib/ojdbc7-12.1.0.2.jar</systemPath>-->
<!--</dependency>-->
<dependency>
<groupId>com.oracle.driver</groupId>
<artifactId>odbc</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/ojdbc7-12.1.0.2.jar</systemPath>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

@ -183,6 +183,22 @@ public class MainController {
Dialog.showVue();
}
@FXML
public void generateService(ActionEvent actionEvent) {
this.modelSave(null);
if (dBmanger.doCheck()) {
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setInitialDirectory(dBmanger.getPath());
Stage stage = new Stage();
File file = directoryChooser.showDialog(stage);
if (file != null) {
System.out.println("生成目录:" + file.getAbsolutePath());
dBmanger.generateService(ManagerFactory.getProjectManager().getProject(), file);
}
}
}
@FXML
public void generateApi(ActionEvent actionEvent) {
Dialog.showApi();

@ -1,15 +1,16 @@
package xyz.wbsite.dbtool.javafx.manger;
import org.springframework.boot.system.ApplicationHome;
import xyz.wbsite.dbtool.javafx.po.FieldType;
import xyz.wbsite.dbtool.javafx.manger.callable.AndroidCallable;
import xyz.wbsite.dbtool.javafx.manger.callable.ApiCallable;
import xyz.wbsite.dbtool.javafx.manger.callable.SpringBootCallable;
import xyz.wbsite.dbtool.javafx.manger.callable.SpringBootServiceCallable;
import xyz.wbsite.dbtool.javafx.manger.callable.VueCallable;
import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper;
import xyz.wbsite.dbtool.javafx.po.AndroidOption;
import xyz.wbsite.dbtool.javafx.po.Api;
import xyz.wbsite.dbtool.javafx.po.Field;
import xyz.wbsite.dbtool.javafx.po.FieldType;
import xyz.wbsite.dbtool.javafx.po.Module;
import xyz.wbsite.dbtool.javafx.po.MySQLDBmapper;
import xyz.wbsite.dbtool.javafx.po.OracleDBmapper;
@ -349,6 +350,36 @@ public class ProjectManager {
});
}
/**
*
*
* @param root
*/
public void generateService(Project project, final File root) {
if (!root.exists()) {
Dialog.showTimedDialog(1000, "目录不存在!");
}
Dialog.showProgress("生成中...");
service.execute(new Runnable() {
@Override
public void run() {
Callable callback = new SpringBootServiceCallable(project, path);
Future submit = service.submit(callback);
try {
submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Dialog.stopPopup();
Dialog.showSuccess("生成完毕.");
}
});
}
public void generateApi(File module, File api, List<String> domainList, List<Api> apis) {
if (module.exists()) {
Dialog.showProgress("生成中...");

@ -1,10 +1,10 @@
package xyz.wbsite.dbtool.javafx.manger.callable;
import xyz.wbsite.dbtool.javafx.po.DataBase;
import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager;
import xyz.wbsite.dbtool.javafx.manger.ManagerFactory;
import xyz.wbsite.dbtool.javafx.manger.XmlManager;
import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper;
import xyz.wbsite.dbtool.javafx.po.DataBase;
import xyz.wbsite.dbtool.javafx.po.Module;
import xyz.wbsite.dbtool.javafx.po.MySQLDBmapper;
import xyz.wbsite.dbtool.javafx.po.OracleDBmapper;
@ -49,7 +49,6 @@ public class SpringBootCallable implements Callable {
}
}
public Boolean call() throws Exception {
// 创建项目文件夹
File projectDir = Tool.createPath(root, project.getProjectName());
@ -325,10 +324,9 @@ public class SpringBootCallable implements Callable {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".java"), "SpringBoot/java/module/mpr/mapper.java", ctx);
if (table.getSys()) {
// freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), dataBase.name() + "_" + Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBoot/java/module/mpr/" + dataBase.name() + "_mapper.xml", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBoot/java/module/mpr/" + project.getDatabase().name() + "_mapper.xml", ctx);
} else {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBoot/java/module/mpr/Nosys_mapper.xml", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBoot/java/module/mpr/" + project.getDatabase().name() + "_NSYS_mapper.xml", ctx);
}
}
}
@ -673,10 +671,10 @@ public class SpringBootCallable implements Callable {
}
}
if (DataBase.Oracle.name().equals(project.getDatabase().name())) {
File lib = Tool.createPath(root.getAbsolutePath(), "lib");
Tool.outputResource("SpringBoot/resources/lib/ojdbc7-12.1.0.2.jar", Tool.createFile(lib.getAbsolutePath(), "ojdbc7-12.1.0.2.jar"));
}
// if (DataBase.Oracle.name().equals(project.getDatabase().name())) {
// File lib = Tool.createPath(root.getAbsolutePath(), "lib");
// Tool.outputResource("SpringBoot/resources/lib/ojdbc7-12.1.0.2.jar", Tool.createFile(lib.getAbsolutePath(), "ojdbc7-12.1.0.2.jar"));
// }
if (DataBase.SQLite.name().equals(project.getDatabase().name())) {
File dbFile = Tool.createFile(root.getAbsolutePath(), project.getProjectName() + ".db");

@ -0,0 +1,723 @@
package xyz.wbsite.dbtool.javafx.manger.callable;
import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager;
import xyz.wbsite.dbtool.javafx.manger.ManagerFactory;
import xyz.wbsite.dbtool.javafx.manger.XmlManager;
import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper;
import xyz.wbsite.dbtool.javafx.po.DataBase;
import xyz.wbsite.dbtool.javafx.po.Module;
import xyz.wbsite.dbtool.javafx.po.MySQLDBmapper;
import xyz.wbsite.dbtool.javafx.po.OracleDBmapper;
import xyz.wbsite.dbtool.javafx.po.Project;
import xyz.wbsite.dbtool.javafx.po.SQLiteDBmapper;
import xyz.wbsite.dbtool.javafx.po.Table;
import xyz.wbsite.dbtool.javafx.tool.Tool;
import xyz.wbsite.dbtool.web.frame.utils.FileUtil;
import xyz.wbsite.dbtool.web.frame.utils.ResourceUtil;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.Callable;
public class SpringBootServiceCallable implements Callable {
private File root;
private Project project;
private AbstractDBmapper dBmapper;
private FreeMarkerManager freeMarkerManager;
public SpringBootServiceCallable(Project project, File root) {
this.root = root;
this.project = project;
this.freeMarkerManager = ManagerFactory.getFreeMarkerManager();
// 根据配置获取数据库处理器
if (project.getDatabase().name().equals(DataBase.MySQL.name())) {
this.dBmapper = new MySQLDBmapper();
} else if (project.getDatabase().name().equals(DataBase.Oracle.name())) {
this.dBmapper = new OracleDBmapper();
} else if (project.getDatabase().name().equals(DataBase.SQLite.name())) {
this.dBmapper = new SQLiteDBmapper();
} else {
this.dBmapper = new MySQLDBmapper();
}
}
public Boolean call() throws Exception {
// 创建项目文件夹
File projectDir = Tool.createPath(root, project.getProjectName());
// 清空内容
Tool.clear(projectDir);
// 生成java目录
File javaDir = Tool.createPath(projectDir.getAbsolutePath(), "src", "main", "java");
// 生成资源目录
File resourcesDir = Tool.createPath(projectDir.getAbsolutePath(), "src", "main", "resources");
// 生成域名目录
File domainDir = javaDir;
for (String s : project.getProjectBasePackage().split("\\.")) {
domainDir = Tool.createPath(domainDir.getAbsolutePath(), s);
}
// 生成单元测试java目录
File testJavaDir = Tool.createPath(projectDir.getAbsolutePath(), "src", "test", "java");
File testDomainDir = testJavaDir;
for (String s : project.getProjectBasePackage().split("\\.")) {
testDomainDir = Tool.createPath(testDomainDir.getAbsolutePath(), s);
}
// 生成单元测试resources目录
File testResourcesDir = Tool.createPath(projectDir.getAbsolutePath(), "src", "test", "resources");
// 生成POM
generatePom(projectDir, project);
{//生成java文件
//生成 Controller
System.out.println("生成模块:action");
generateController(Tool.createPath(domainDir.getAbsolutePath(), "action"), project);
// 生成 Config
System.out.println("生成模块:config");
generateConfig(Tool.createPath(domainDir.getAbsolutePath(), "config"), project);
{// 模块
for (Module module : project.getModules()) {// 业务模块
module.setProjectAuthor(project.getProjectAuthor());
module.setProjectBasePackage(project.getProjectBasePackage());
module.setProjectName(project.getProjectName());
File moduleDir = Tool.createPath(domainDir.getAbsolutePath(), "module", module.getModuleName());
System.out.println("生成模块:Entity");
generateEntity(Tool.createPath(moduleDir.getAbsolutePath(), "ent"), module);
System.out.println("生成模块:Mapper");
generateMapper(Tool.createPath(moduleDir.getAbsolutePath(), "mpr"), module);
System.out.println("生成模块:Manager");
generateManager(Tool.createPath(moduleDir.getAbsolutePath(), "mgr"), module);
System.out.println("生成模块:Request");
generateRequest(Tool.createPath(moduleDir.getAbsolutePath(), "req"), module);
System.out.println("生成模块:Response");
generateResponse(Tool.createPath(moduleDir.getAbsolutePath(), "rsp"), module);
}
}
// frame等内容
System.out.println("生成模块:frame");
generateFrame(Tool.createPath(domainDir.getAbsolutePath(), "frame"), project);
// Task
System.out.println("生成模块:task");
generateTask(Tool.createPath(domainDir.getAbsolutePath(), "task"), project);
// Application
System.out.println("生成模块:Application");
generateApplication(Tool.createPath(domainDir.getAbsolutePath()), project);
}
{//生成resources文件
System.out.println("生成模块:Resources");
generateResources(resourcesDir, project);
System.out.println("生成模块:Static");
System.out.println("生成模块:Templates");
}
{//生成Test
System.out.println("生成模块:Test");
generateTest(testDomainDir, project);
}
{//生成Test Resources
System.out.println("生成模块:Test Resources");
generateTestResources(testResourcesDir, project);
}
System.out.println("finish");
return true;
}
/**
* POM.xml
*
* @param root
* @param project
*/
public void generatePom(File root, Project project) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("projectName", project.getProjectName());
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("dataBase", project.getDatabase().toString());
ctx.put("project", project);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "pom.xml"), "SpringBootService/pom.ftl", ctx);
}
/**
* Controller
*
* @param root
* @param project
*/
public void generateController(File root, Project project) {
Tool.clear(root);
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
ctx.put("modules", project.getModules());
{
File ajax = Tool.createPath(root.getAbsolutePath(), "ajax");
if (project.isNeedSys()) {//生成系统模块
File system = Tool.createPath(ajax.getAbsolutePath(), "system");
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/action/ajax/system/")) {
freeMarkerManager.outputTemp(Tool.createFile(system.getAbsolutePath(), name), "SpringBootService/java/action/ajax/system/" + name, ctx);
}
}
}
{
File api = Tool.createPath(root.getAbsolutePath(), "api");
for (Module module : project.getModules()) {
File m = Tool.createPath(api.getAbsolutePath(), module.getModuleName());
for (Table table : module.getTables()) {
HashMap<String, Object> ctxss = new HashMap<String, Object>();
ctxss.put("basePackage", project.getProjectBasePackage());
ctxss.put("module", module.getModuleName());
ctxss.put("author", project.getProjectAuthor());
ctxss.put("date", new Date());
ctxss.put("table", table);
freeMarkerManager.outputTemp(Tool.createFile(m.getAbsolutePath(), table.getCName() + "Api.java"), "SpringBootService/java/action/api/Api.java", ctxss);
}
}
if (project.isNeedSys()) {//生成系统模块
File system = Tool.createPath(api.getAbsolutePath(), "system");
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/action/api/system/")) {
freeMarkerManager.outputTemp(Tool.createFile(system.getAbsolutePath(), name), "SpringBootService/java/action/api/system/" + name, ctx);
}
}
}
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "GlobalController.java"), "SpringBootService/java/action/GlobalController.java", ctx);
}
public void generateConfig(File root, Project project) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("projectName", project.getProjectName());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
//config
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "ActionConfig.java"), "SpringBootService/java/config/ActionConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "CacheConfig.java"), "SpringBootService/java/config/CacheConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "SecurityConfig.java"), "SpringBootService/java/config/SecurityConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "ScheduleConfig.java"), "SpringBootService/java/config/ScheduleConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "ThreadPoolConfig.java"), "SpringBootService/java/config/ThreadPoolConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "WebMvcConfig.java"), "SpringBootService/java/config/WebMvcConfig.java", ctx);
if (project.getDatabase().name().equals(DataBase.SQLite.name())) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "SQLiteConfig.java"), "SpringBootService/java/config/SQLiteConfig.java", ctx);
}
if (project.isNeedMoreDB()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "MapperMainConfig.java"), "SpringBootService/java/config/MapperMainConfig.java", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "MapperTwoConfig.java"), "SpringBootService/java/config/MapperTwoConfig.java", ctx);
}
}
/**
* entity
*
* @param root
* @param md
*/
public void generateEntity(File root, Module md) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
for (Table table : md.getTables()) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("table", table);
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
File file = Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + ".java");
freeMarkerManager.outputTemp(file, "SpringBootService/java/module/ent/entity.ftl", ctx);
}
}
/**
* Mapper
*
* @param root
* @param md
*/
public void generateMapper(File root, Module md) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("module", md);
ctx.put("dataBase", project.getDatabase().toString());
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
for (Table table : md.getTables()) {
ctx.put("table", table);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".java"), "SpringBootService/java/module/mpr/mapper.java", ctx);
if (table.getSys()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBootService/java/module/mpr/" + project.getDatabase().name() + "_mapper.xml", ctx);
} else {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), "SpringBootService/java/module/mpr/" + project.getDatabase().name() + "_NSYS_mapper.xml", ctx);
}
}
}
public void generateManager(File root, Module md) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("module", md);
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
for (Table table : md.getTables()) {
ctx.put("table", table);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Manager" + ".java"), "SpringBootService/java/module/mgr/manager.ftl", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "ManagerImpl" + ".java"), "SpringBootService/java/module/mgr/managerImpl.ftl", ctx);
}
}
/**
* Request
*
* @param root
* @param md
*/
public void generateRequest(File root, Module md) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("module", md);
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
if (md.getModuleName().equals("api")) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "ApiExampleRequest" + ".java"), "SpringBootService/java/module/req/ApiExampleRequest.java", ctx);
}
for (Table table : md.getTables()) {
ctx.put("table", table);
if (table.getCreate()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "CreateRequest" + ".java"), "SpringBootService/java/module/req/createRequestClass.ftl", ctx);
}
if (table.getDelete()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "DeleteRequest" + ".java"), "SpringBootService/java/module/req/deleteRequestClass.ftl", ctx);
}
if (table.getUpdate()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "UpdateRequest" + ".java"), "SpringBootService/java/module/req/updateRequestClass.ftl", ctx);
}
if (table.getFind()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "FindRequest" + ".java"), "SpringBootService/java/module/req/findRequestClass.ftl", ctx);
}
if (table.getGet()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetRequest" + ".java"), "SpringBootService/java/module/req/getRequestClass.ftl", ctx);
}
if (table.getSearch()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "SearchRequest" + ".java"), "SpringBootService/java/module/req/searchRequestClass.ftl", ctx);
}
}
}
/**
*
*
* @param root
* @param md
*/
public void generateResponse(File root, Module md) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("module", md);
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
if (md.getModuleName().equals("api")) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "ApiExampleResponse" + ".java"), "SpringBootService/java/module/rsp/ApiExampleResponse.java", ctx);
}
for (Table table : md.getTables()) {
ctx.put("table", table);
if (table.getCreate()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "CreateResponse" + ".java"), "SpringBootService/java/module/rsp/createResponseClass.ftl", ctx);
}
if (table.getDelete()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "DeleteResponse" + ".java"), "SpringBootService/java/module/rsp/deleteResponseClass.ftl", ctx);
}
if (table.getUpdate()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "UpdateResponse" + ".java"), "SpringBootService/java/module/rsp/updateResponseClass.ftl", ctx);
}
if (table.getFind()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "FindResponse" + ".java"), "SpringBootService/java/module/rsp/findResponseClass.ftl", ctx);
}
if (table.getGet()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetResponse" + ".java"), "SpringBootService/java/module/rsp/getResponseClass.ftl", ctx);
}
if (table.getSearch()) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "SearchResponse" + ".java"), "SpringBootService/java/module/rsp/searchResponseClass.ftl", ctx);
}
}
}
/**
* frame
*
* @param root
* @param project
*/
public void generateFrame(File root, Project project) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("timestamp", new Date().getTime());
File auth = Tool.createPath(root.getAbsolutePath(), "auth");
File base = Tool.createPath(root.getAbsolutePath(), "base");
File excel = Tool.createPath(root.getAbsolutePath(), "excel");
File excelannotation = Tool.createPath(excel.getAbsolutePath(), "annotation");
File excelconverter = Tool.createPath(excel.getAbsolutePath(), "converter");
File exception = Tool.createPath(excel.getAbsolutePath(), "exception");
File excelstyle = Tool.createPath(excel.getAbsolutePath(), "style");
File schedule = Tool.createPath(root.getAbsolutePath(), "schedule");
File utils = Tool.createPath(root.getAbsolutePath(), "utils");
File validation = Tool.createPath(root.getAbsolutePath(), "validation");
//auth
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/auth/")) {
freeMarkerManager.outputTemp(Tool.createFile(auth.getAbsolutePath(), name), "SpringBootService/java/frame/auth/" + name, ctx);
}
//base
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/base/")) {
freeMarkerManager.outputTemp(Tool.createFile(base.getAbsolutePath(), name), "SpringBootService/java/frame/base/" + name, ctx);
}
//excel
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/excel/")) {
freeMarkerManager.outputTemp(Tool.createFile(excel.getAbsolutePath(), name), "SpringBootService/java/frame/excel/" + name, ctx);
}
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/excel/annotation/")) {
freeMarkerManager.outputTemp(Tool.createFile(excelannotation.getAbsolutePath(), name), "SpringBootService/java/frame/excel/annotation/" + name, ctx);
}
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/excel/converter/")) {
freeMarkerManager.outputTemp(Tool.createFile(excelconverter.getAbsolutePath(), name), "SpringBootService/java/frame/excel/converter/" + name, ctx);
}
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/excel/exception/")) {
freeMarkerManager.outputTemp(Tool.createFile(exception.getAbsolutePath(), name), "SpringBootService/java/frame/excel/exception/" + name, ctx);
}
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/excel/style/")) {
freeMarkerManager.outputTemp(Tool.createFile(excelstyle.getAbsolutePath(), name), "SpringBootService/java/frame/excel/style/" + name, ctx);
}
//schedule
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/schedule/")) {
freeMarkerManager.outputTemp(Tool.createFile(schedule.getAbsolutePath(), name), "SpringBootService/java/frame/schedule/" + name, ctx);
}
//utils
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/utils/")) {
ArrayList<String> filters = new ArrayList<>();
filters.add("MailUtil.java");
if (filters.contains(name)) {
if (project.isNeedEMail()) {
freeMarkerManager.outputTemp(Tool.createFile(utils.getAbsolutePath(), name), "SpringBootService/java/frame/utils/" + name, ctx);
}
} else {
freeMarkerManager.outputTemp(Tool.createFile(utils.getAbsolutePath(), name), "SpringBootService/java/frame/utils/" + name, ctx);
}
}
//validation
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/frame/validation/")) {
freeMarkerManager.outputTemp(Tool.createFile(validation.getAbsolutePath(), name), "SpringBootService/java/frame/validation/" + name, ctx);
}
}
/**
* frame
*
* @param root
* @param project
*/
public void generateTask(File root, Project project) {
if (!root.exists()) {
root.mkdirs();
} else {
Tool.clear(root);
}
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("timestamp", new Date().getTime());
//task
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/java/task/")) {
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), name), "SpringBootService/java/task/" + name, ctx);
}
}
/**
* base
*
* @param root
* @param project
*/
public void generateApplication(File root, Project project) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("project", project);
ctx.put("timestamp", new Date().getTime());
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "Application.java"), "SpringBootService/java/Application.ftl", ctx);
}
/**
* properties
*
* @param root
* @param project
*/
public void generateResources(File root, Project project) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("tool", Tool.class);
ctx.put("dataBase", project.getDatabase().toString());
ctx.put("author", project.getProjectAuthor());
ctx.put("dBmapper", dBmapper);
ctx.put("date", new Date());
ctx.put("author", project.getProjectAuthor());
ctx.put("projectName", project.getProjectName());
ctx.put("project", project);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "start-dev.bat"), "SpringBootService/resources/start-dev.bat", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "start-prod.bat"), "SpringBootService/resources/start-prod.bat", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "application-dev.properties"), "SpringBootService/resources/application-dev.ftl", ctx);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "application-prod.properties"), "SpringBootService/resources/application-prod.ftl", ctx);
Tool.outputResource("SpringBootService/resources/logback-spring.xml", Tool.createFile(root.getAbsolutePath(), "logback-spring.xml"));
File dbtool = Tool.createPath(root.getAbsolutePath(), "dbtool");
{
XmlManager xmlManager = ManagerFactory.getXmlManager();
xmlManager.saveAs(dbtool, project);
}
for (Module module : project.getModules()) {
ctx.put("moduleName", module.getModuleName());
ctx.put("module", module);
File tableDir = Tool.createPath(dbtool.getAbsolutePath(), module.getModuleName() + "_table");
for (Table table : module.getTables()) {
ctx.put("table", table);
freeMarkerManager.outputTemp(Tool.createFile(tableDir.getAbsolutePath(), project.getDatabase().name() + "_" + table.getTableName() + ".sql"), "SpringBootService/resources/dbtool/table.ftl", ctx);
}
freeMarkerManager.outputTemp(Tool.createFile(tableDir.getAbsolutePath(), project.getDatabase().name() + "_ALL_TABLE" + ".sql"), "SpringBootService/resources/dbtool/tableAll.ftl", ctx);
}
if (project.isNeedSys()) {//生成系统模块
File system = Tool.createPath(dbtool.getAbsolutePath(), "system_table");
for (String name : ResourceUtil.getResourceFiles("/modules/SpringBootService/resources/dbtool/system/")) {
if (name.contains(project.getDatabase().name())) {
freeMarkerManager.outputTemp(Tool.createFile(system.getAbsolutePath(), name), "SpringBootService/resources/dbtool/system/" + name, ctx);
}
}
}
if (DataBase.SQLite.name().equals(project.getDatabase().name())) {
File dbFile = Tool.createFile(root.getAbsolutePath(), project.getProjectName() + ".db");
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile.getAbsolutePath());
for (File fileModule : dbtool.listFiles()) {
if (!fileModule.isDirectory()) {
continue;
}
for (File file : fileModule.listFiles()) {
if (!file.getName().startsWith("SQLite_ALL_") && file.getName().endsWith(".sql")) {
statement = connection.createStatement();
String sql = FileUtil.readFileToString(file);
statement.execute(sql);
statement.close();
}
}
}
} catch (ClassNotFoundException | SQLException | IOException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (Exception e) {
}
}
}
}
public void generateTestResources(File root, Project project) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("projectName", project.getProjectName());
ctx.put("tool", Tool.class);
ctx.put("dataBase", project.getDatabase().toString());
ctx.put("author", project.getProjectAuthor());
ctx.put("dBmapper", dBmapper);
ctx.put("date", new Date());
ctx.put("project", project);
freeMarkerManager.outputTemp(Tool.createFile(root.getAbsolutePath(), "application.properties"), "SpringBootService/test/application.ftl", ctx);
Tool.outputResource("SpringBootService/test/logback-spring.xml", Tool.createFile(root.getAbsolutePath(), "logback-spring.xml"));
}
public void generateTest(File root, Project project) {
{
File config = Tool.createPath(root.getAbsolutePath(), "config");
config.mkdirs();
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
File file = Tool.createFile(config.getAbsolutePath(), "TestConfig" + ".java");
freeMarkerManager.outputTemp(file, "SpringBootService/test/TestConfig.ftl", ctx);
}
{
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
File file = Tool.createFile(root.getAbsolutePath(), "UtilTest" + ".java");
freeMarkerManager.outputTemp(file, "SpringBootService/test/UtilTest.java", ctx);
}
for (Module md : project.getModules()) {
File module = Tool.createPath(root.getAbsolutePath(), md.getModuleName());
for (Table table : md.getTables()) {
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("module", md);
ctx.put("basePackage", md.getProjectBasePackage());
ctx.put("moduleName", md.getModuleName());
ctx.put("table", table);
ctx.put("author", md.getProjectAuthor());
ctx.put("date", new Date());
File file = Tool.createFile(module.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Test" + ".java");
freeMarkerManager.outputTemp(file, "SpringBootService/test/test.ftl", ctx);
}
}
if (project.isNeedSys()) {//生成系统模块
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
File system = Tool.createPath(root.getAbsolutePath(), "system");
for (String apiFile : ResourceUtil.getResourceFiles("/modules/SpringBootService/test/system/")) {
freeMarkerManager.outputTemp(Tool.createFile(system.getAbsolutePath(), apiFile), "SpringBootService/test/system/" + apiFile, ctx);
}
}
{//数据初始化
HashMap<String, Object> ctx = new HashMap<String, Object>();
ctx.put("tool", Tool.class);
ctx.put("basePackage", project.getProjectBasePackage());
ctx.put("moduleName", project.getProjectName());
ctx.put("author", project.getProjectAuthor());
ctx.put("date", new Date());
File system = Tool.createPath(root.getAbsolutePath(), "datainit");
for (String apiFile : ResourceUtil.getResourceFiles("/modules/SpringBootService/test/datainit/")) {
freeMarkerManager.outputTemp(Tool.createFile(system.getAbsolutePath(), apiFile), "SpringBootService/test/datainit/" + apiFile, ctx);
}
}
}
}

@ -207,4 +207,12 @@ public class Table extends TreeItem {
}
return false;
}
public boolean hasSeachKey() {
for (Field field : fields) {
if (field.getIsSearch()) {
return true;
}
}
return false;
}
}

@ -37,6 +37,7 @@
<MenuItem mnemonicParsing="false" onAction="#generateApi" text="生成Api"/>
<MenuItem mnemonicParsing="false" onAction="#generateVue" text="生成Vue"/>
<MenuItem mnemonicParsing="false" onAction="#generateAndroid" text="生成Android"/>
<MenuItem mnemonicParsing="false" onAction="#generateService" text="生成Service"/>
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">

@ -61,6 +61,34 @@
</#list>
</select>
<select id="search" resultMap="${table.getFName()}">
SELECT
<include refid="entityColumnList"/>
FROM
<include refid="table"/>
WHERE
1 = 1
<#if table.hasSeachKey()>
<if test="request.keyword != null and request.keyword != ''">
1 = 1
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
OR "${f.fieldName}" LIKE '%'||${r"#{"}request.keyword}||'%'
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
OR `${f.fieldName}` LIKE CONCAT(CONCAT('%',${r"#{"}request.keyword}),'%')
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</select>
<insert id="insert">
INSERT INTO
<include refid="table"/>

@ -4,22 +4,10 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${basePackage}.module.${moduleName}.mpr.${table.getCName()}Mapper">
<#if dataBase == 'Oracle'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
<#elseif dataBase='MySQL'>
<sql id="table">`${module.modulePrefix?default("")}${table.tableName}`</sql>
<#elseif dataBase='SQLite'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
</#if>
<sql id="entityColumnList">
<#if dataBase == 'Oracle'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>`${f.fieldName}`<#if f_has_next>,</#if></#list>
<#elseif dataBase='SQLite'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
</#if>
</sql>
<resultMap id="${table.getFName()}" type="${basePackage}.module.${moduleName}.ent.${table.getCName()}">
@ -34,67 +22,10 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
<#elseif dataBase='SQLite'>
"IS_DELETED" = 0
</#if>
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Byte">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Short">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Integer">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Long">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Float">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Double">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Character">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Date">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND to_char("${f.fieldName}",'yyyy-MM-dd HH24:mi:ss') = to_char(${r"#{"}request.${f.getFName()}},'yyyy-MM-dd HH24:mi:ss')
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
@ -145,58 +76,6 @@
AND DATE_FORMAT(`${f.fieldName}`,"%Y-%m-%d %T") = DATE_FORMAT(${r"#{"}request.${f.getFName()}},"%Y-%m-%d %T")
</if>
</#if>
<#elseif dataBase='SQLite'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Byte">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Short">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Integer">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Long">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Float">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Double">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Character">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Date">
<if test="request.${f.getFName()} != null">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
</select>
@ -207,23 +86,13 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
</#if>
<if test="request.keyword != null and request.keyword != ''">
1 = 2
<#list table.fields as f>
<#if f.isSearch>
<#if dataBase == 'Oracle'>
OR "${f.fieldName}" LIKE CONCAT(CONCAT('%',${r"#{"}request.keyword}),'%')
<#elseif dataBase='MySQL'>
OR `${f.fieldName}` LIKE CONCAT('%',${r"#{request.keyword}"},'%')
</#if>
<#elseif dataBase='SQLite'>
OR ${f.fieldName} LIKE CONCAT('%',${r"#{request.keyword}"},'%')
</#if>
</#list>
</if>
</select>
@ -245,7 +114,7 @@
0,
0,
${r"#{"}token.userId,jdbcType=NUMERIC},
<#if dataBase == 'Oracle'>sysdate<#elseif dataBase == 'MySQL'>sysdate()<#elseif dataBase == 'SQLite'>datetime('now','localtime')</#if>,
sysdate(),
NULL,
NULL
)
@ -269,7 +138,7 @@
0,
0,
${r"#{"}token.userId,jdbcType=NUMERIC},
<#if dataBase == 'Oracle'>sysdate<#elseif dataBase == 'MySQL'>sysdate()<#elseif dataBase == 'SQLite'>datetime('now','localtime')</#if>,
sysdate(),
NULL,
NULL
)
@ -279,33 +148,15 @@
<update id="delete">
UPDATE
<include refid="table"/>
<#if dataBase == 'Oracle'>
SET "IS_DELETED" = 1
WHERE "IS_DELETED" = 0
AND "ID" = ${r"#{"}request.id}
<#elseif dataBase='MySQL'>
SET `IS_DELETED` = 1
WHERE `IS_DELETED` = 0
AND `ID` = ${r"#{"}request.id}
</#if>
</update>
<update id="update">
UPDATE
<include refid="table"/>
SET
<#if dataBase == 'Oracle'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
"${f.fieldName}" = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}},
</#if>
</#if>
</#list>
"ROW_VERSION" = "ROW_VERSION" + 1,
"LAST_UPDATE_BY" = ${r"#{"}token.userId},
"LAST_UPDATE_TIME" = sysdate
<#elseif dataBase='MySQL'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
@ -316,32 +167,10 @@
`ROW_VERSION` = `ROW_VERSION` + 1,
`LAST_UPDATE_BY` = ${r"#{"}token.userId},
`LAST_UPDATE_TIME` = sysdate()
<#elseif dataBase='SQLite'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
${f.fieldName} = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}},
</#if>
</#if>
</#list>
ROW_VERSION = ROW_VERSION + 1,
LAST_UPDATE_BY = ${r"#{"}token.userId},
LAST_UPDATE_TIME = datetime('now','localtime')
</#if>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
AND "ID" = ${r"#{"}request.id}
AND "ROW_VERSION" = ${r"#{"}request.rowVersion}
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
AND `ID` = ${r"#{"}request.id}
AND `ROW_VERSION` = ${r"#{"}request.rowVersion}
<#elseif dataBase='SQLite'>
IS_DELETED = 0
AND ID = ${r"#{"}request.id}
AND ROW_VERSION = ${r"#{"}request.rowVersion}
</#if>
</update>
<select id="get" resultMap="${table.getFName()}">
@ -350,15 +179,7 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
AND "ID" = ${r"#{request.id}"}
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
AND `ID` = ${r"#{request.id}"}
<#elseif dataBase='SQLite'>
IS_DELETED = 0
AND ID = ${r"#{request.id}"}
</#if>
</select>
</mapper>

@ -0,0 +1,191 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${basePackage}.module.${moduleName}.mpr.${table.getCName()}Mapper">
<#if dataBase == 'Oracle'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
<#elseif dataBase='MySQL'>
<sql id="table">`${module.modulePrefix?default("")}${table.tableName}`</sql>
</#if>
<sql id="entityColumnList">
<#if dataBase == 'Oracle'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>`${f.fieldName}`<#if f_has_next>,</#if></#list>
</#if>
</sql>
<resultMap id="${table.getFName()}" type="${basePackage}.module.${moduleName}.ent.${table.getCName()}">
<#list table.fields as f>
<result column="${f.fieldName}" jdbcType="${f.fieldType.jdbcType()}" property="${f.getFName()}"/>
</#list>
</resultMap>
<select id="find" resultMap="${table.getFName()}">
SELECT
<include refid="entityColumnList"/>
FROM
<include refid="table"/>
WHERE
1 = 1
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
</select>
<select id="search" resultMap="${table.getFName()}">
SELECT
<include refid="entityColumnList"/>
FROM
<include refid="table"/>
WHERE
1 = 1
<#if table.hasSeachKey()>
<if test="request.keyword != null and request.keyword != ''">
1 = 1
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
OR "${f.fieldName}" LIKE '%'||${r"#{"}request.keyword}||'%'
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
OR `${f.fieldName}` LIKE CONCAT(CONCAT('%',${r"#{"}request.keyword}),'%')
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</select>
<insert id="insert">
INSERT INTO
<include refid="table"/>
(
<include refid="entityColumnList"/>
)
VALUES
(
<#list table.fields as f>
${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
)
</insert>
<delete id="delete">
DELETE FROM
<include refid="table"/>
WHERE
<#if table.hasPrimaryKey()>
1 = 1
<#list table.fields as f>
<#if f.isPrimaryKey>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</delete>
<update id="update">
UPDATE
<include refid="table"/>
SET
<#if dataBase == 'Oracle'>
<#list table.fields as f>
"${f.fieldName}" = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>
`${f.fieldName}` = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
</#if>
WHERE
<#if table.hasPrimaryKey()>
1 = 1
<#list table.fields as f>
<#if f.isPrimaryKey>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</update>
</mapper>

@ -4,22 +4,10 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${basePackage}.module.${moduleName}.mpr.${table.getCName()}Mapper">
<#if dataBase == 'Oracle'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
<#elseif dataBase='MySQL'>
<sql id="table">`${module.modulePrefix?default("")}${table.tableName}`</sql>
<#elseif dataBase='SQLite'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
</#if>
<sql id="entityColumnList">
<#if dataBase == 'Oracle'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>`${f.fieldName}`<#if f_has_next>,</#if></#list>
<#elseif dataBase='SQLite'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
</#if>
</sql>
<resultMap id="${table.getFName()}" type="${basePackage}.module.${moduleName}.ent.${table.getCName()}">
@ -34,16 +22,9 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
<#elseif dataBase='SQLite'>
"IS_DELETED" = 0
</#if>
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
@ -94,109 +75,6 @@
AND to_char("${f.fieldName}",'yyyy-MM-dd HH24:mi:ss') = to_char(${r"#{"}request.${f.getFName()}},'yyyy-MM-dd HH24:mi:ss')
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Byte">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Short">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Integer">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Long">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Float">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Double">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Character">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Date">
<if test="request.${f.getFName()} != null">
AND DATE_FORMAT(`${f.fieldName}`,"%Y-%m-%d %T") = DATE_FORMAT(${r"#{"}request.${f.getFName()}},"%Y-%m-%d %T")
</if>
</#if>
<#elseif dataBase='SQLite'>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Byte">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Short">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Integer">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Long">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Float">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Double">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != 0">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Character">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Date">
<if test="request.${f.getFName()} != null">
AND ${f.fieldName} = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
</select>
@ -207,23 +85,12 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
</#if>
<if test="request.keyword != null and request.keyword != ''">
1 = 2
<#list table.fields as f>
<#if f.isSearch>
<#if dataBase == 'Oracle'>
OR "${f.fieldName}" LIKE CONCAT(CONCAT('%',${r"#{"}request.keyword}),'%')
<#elseif dataBase='MySQL'>
OR `${f.fieldName}` LIKE CONCAT('%',${r"#{request.keyword}"},'%')
</#if>
<#elseif dataBase='SQLite'>
OR ${f.fieldName} LIKE CONCAT('%',${r"#{request.keyword}"},'%')
</#if>
OR "${f.fieldName}" LIKE '%'||${r"#{"}request.keyword}||'%'
</#list>
</if>
</select>
@ -245,7 +112,7 @@
0,
0,
${r"#{"}token.userId,jdbcType=NUMERIC},
<#if dataBase == 'Oracle'>sysdate<#elseif dataBase == 'MySQL'>sysdate()<#elseif dataBase == 'SQLite'>datetime('now','localtime')</#if>,
sysdate,
NULL,
NULL
)
@ -269,7 +136,7 @@
0,
0,
${r"#{"}token.userId,jdbcType=NUMERIC},
<#if dataBase == 'Oracle'>sysdate<#elseif dataBase == 'MySQL'>sysdate()<#elseif dataBase == 'SQLite'>datetime('now','localtime')</#if>,
sysdate,
NULL,
NULL
)
@ -279,22 +146,15 @@
<update id="delete">
UPDATE
<include refid="table"/>
<#if dataBase == 'Oracle'>
SET "IS_DELETED" = 1
WHERE "IS_DELETED" = 0
AND "ID" = ${r"#{"}request.id}
<#elseif dataBase='MySQL'>
SET `IS_DELETED` = 1
WHERE `IS_DELETED` = 0
AND `ID` = ${r"#{"}request.id}
</#if>
</update>
<update id="update">
UPDATE
<include refid="table"/>
SET
<#if dataBase == 'Oracle'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
@ -305,43 +165,10 @@
"ROW_VERSION" = "ROW_VERSION" + 1,
"LAST_UPDATE_BY" = ${r"#{"}token.userId},
"LAST_UPDATE_TIME" = sysdate
<#elseif dataBase='MySQL'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
`${f.fieldName}` = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}},
</#if>
</#if>
</#list>
`ROW_VERSION` = `ROW_VERSION` + 1,
`LAST_UPDATE_BY` = ${r"#{"}token.userId},
`LAST_UPDATE_TIME` = sysdate()
<#elseif dataBase='SQLite'>
<#list table.fields as f>
<#if !f.isPrimaryKey>
<#if !f.isSystem || f.fieldName == 'ID'>
${f.fieldName} = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}},
</#if>
</#if>
</#list>
ROW_VERSION = ROW_VERSION + 1,
LAST_UPDATE_BY = ${r"#{"}token.userId},
LAST_UPDATE_TIME = datetime('now','localtime')
</#if>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
AND "ID" = ${r"#{"}request.id}
AND "ROW_VERSION" = ${r"#{"}request.rowVersion}
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
AND `ID` = ${r"#{"}request.id}
AND `ROW_VERSION` = ${r"#{"}request.rowVersion}
<#elseif dataBase='SQLite'>
IS_DELETED = 0
AND ID = ${r"#{"}request.id}
AND ROW_VERSION = ${r"#{"}request.rowVersion}
</#if>
</update>
<select id="get" resultMap="${table.getFName()}">
@ -350,15 +177,7 @@
FROM
<include refid="table"/>
WHERE
<#if dataBase == 'Oracle'>
"IS_DELETED" = 0
AND "ID" = ${r"#{request.id}"}
<#elseif dataBase='MySQL'>
`IS_DELETED` = 0
AND `ID` = ${r"#{request.id}"}
<#elseif dataBase='SQLite'>
IS_DELETED = 0
AND ID = ${r"#{request.id}"}
</#if>
</select>
</mapper>

@ -0,0 +1,191 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${basePackage}.module.${moduleName}.mpr.${table.getCName()}Mapper">
<#if dataBase == 'Oracle'>
<sql id="table">"${module.modulePrefix?default("")}${table.tableName}"</sql>
<#elseif dataBase='MySQL'>
<sql id="table">`${module.modulePrefix?default("")}${table.tableName}`</sql>
</#if>
<sql id="entityColumnList">
<#if dataBase == 'Oracle'>
<#list table.fields as f>"${f.fieldName}"<#if f_has_next>,</#if></#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>`${f.fieldName}`<#if f_has_next>,</#if></#list>
</#if>
</sql>
<resultMap id="${table.getFName()}" type="${basePackage}.module.${moduleName}.ent.${table.getCName()}">
<#list table.fields as f>
<result column="${f.fieldName}" jdbcType="${f.fieldType.jdbcType()}" property="${f.getFName()}"/>
</#list>
</resultMap>
<select id="find" resultMap="${table.getFName()}">
SELECT
<include refid="entityColumnList"/>
FROM
<include refid="table"/>
WHERE
1 = 1
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
</select>
<select id="search" resultMap="${table.getFName()}">
SELECT
<include refid="entityColumnList"/>
FROM
<include refid="table"/>
WHERE
1 = 1
<#if table.hasSeachKey()>
<if test="request.keyword != null and request.keyword != ''">
1 = 1
<#list table.fields as f>
<#if f.isQuery>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
OR "${f.fieldName}" LIKE '%'||${r"#{"}request.keyword}||'%'
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
OR `${f.fieldName}` LIKE CONCAT(CONCAT('%',${r"#{"}request.keyword}),'%')
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</select>
<insert id="insert">
INSERT INTO
<include refid="table"/>
(
<include refid="entityColumnList"/>
)
VALUES
(
<#list table.fields as f>
${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
)
</insert>
<delete id="delete">
DELETE FROM
<include refid="table"/>
WHERE
<#if table.hasPrimaryKey()>
1 = 1
<#list table.fields as f>
<#if f.isPrimaryKey>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</delete>
<update id="update">
UPDATE
<include refid="table"/>
SET
<#if dataBase == 'Oracle'>
<#list table.fields as f>
"${f.fieldName}" = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
<#elseif dataBase='MySQL'>
<#list table.fields as f>
`${f.fieldName}` = ${r"#{"}request.${f.getFName()},jdbcType=${f.fieldType.jdbcType()}}<#if f_has_next>,</#if>
</#list>
</#if>
WHERE
<#if table.hasPrimaryKey()>
1 = 1
<#list table.fields as f>
<#if f.isPrimaryKey>
<#if dataBase == 'Oracle'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND "${f.fieldName}" = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#elseif dataBase='MySQL'>
<#if f.fieldType.javaType() == "String">
<if test="request.${f.getFName()} != null and request.${f.getFName()} != ''">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
<#if f.fieldType.javaType() == "Boolean">
<if test="request.${f.getFName()} != null">
AND `${f.fieldName}` = ${r"#{"}request.${f.getFName()}}
</if>
</#if>
</#if>
</#if>
</#list>
<#else>
1 = 2
</#if>
</update>
</mapper>

@ -140,12 +140,17 @@
<#if dataBase == 'Oracle'>
<dependency>
<groupId>${basePackage}</groupId>
<artifactId>ojdbc</artifactId>
<version>0.0.1</version>
<scope>system</scope>
<systemPath>${r'${project.basedir}/src/main/resources/lib/ojdbc7-12.1.0.2.jar'}</systemPath>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<#--<dependency>-->
<#--<groupId>${basePackage}</groupId>-->
<#--<artifactId>ojdbc</artifactId>-->
<#--<version>0.0.1</version>-->
<#--<scope>system</scope>-->
<#--<systemPath>${r'${project.basedir}/src/main/resources/lib/ojdbc7-12.1.0.2.jar'}</systemPath>-->
<#--</dependency>-->
</#if>
</dependencies>

@ -0,0 +1,29 @@
package ${basePackage};
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
<#if project.needMoreDB>
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
</#if>
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import ${basePackage}.frame.auth.LocalData;
@SpringBootApplication
<#if project.needMoreDB>
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
<#else>
@EnableAutoConfiguration
</#if>
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
LocalData.setApplicationContext(SpringApplication.run(Application.class, args));
}
}

@ -0,0 +1,454 @@
package ${basePackage}.action;
import com.fasterxml.jackson.core.TreeNode;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import ${basePackage}.config.ActionConfig;
import ${basePackage}.frame.auth.LocalData;
import ${basePackage}.frame.base.BaseRequest;
import ${basePackage}.frame.base.BaseResponse;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.base.Screen;
import ${basePackage}.frame.auth.Token;
import ${basePackage}.frame.utils.AESUtil;
import ${basePackage}.frame.utils.LogUtil;
import ${basePackage}.frame.utils.MD5Util;
import ${basePackage}.frame.utils.MapperUtil;
import ${basePackage}.frame.utils.RequestUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ControllerController
* htm{@link GlobalController#action(Model, HttpServletRequest, HttpServletResponse)}
* ajax{@link GlobalController#ajax(String, String, String, HttpServletRequest, HttpServletResponse, String, MultipartFile)}
* {@link GlobalController#exceptionHandler(HttpServletRequest, HttpServletResponse, Model, Exception)}
* {@link GlobalController#sse(String)}
* <p>
* Request
* Api#Example#Request ==> ##Request
*
* @author author
* @version 0.0.1
* @since 2017-01-01
*/
@Controller
@ControllerAdvice
public class GlobalController implements ErrorController {
@Value("${r'${server.servlet.context-path}'}")
private String context;
@Value("${r'${web.url.index}'}")
private String homePage;
@Value("${r'${web.url.login}'}")
private String loginPage;
@Autowired
private FreeMarkerViewResolver viewResolver;
/**
*
*
* @param request
* @param response
* @param exception
* @return
*/
@ExceptionHandler(Exception.class)
public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Model model, Exception exception) {
StringBuffer msg = new StringBuffer("");
if (exception != null) {
msg = new StringBuffer("");
String message = exception.toString();
int length = exception.getStackTrace().length;
if (length > 0) {
msg.append("<a>").append(message).append("</a><br>");
for (int i = 0; i < length; i++) {
msg.append("<a>").append(exception.getStackTrace()[i]).append("</a><br>");
}
} else {
msg.append(message);
}
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
model.addAttribute("msg", msg.toString());
return "500";
}
private final static String ERROR_PATH = "/error";
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String error(HttpServletRequest request, HttpServletResponse response) {
switch (response.getStatus()) {
case 404:
return "404";
case 403:
String errorUrl = RequestUtil.getErrorUrl(request);
errorUrl = errorUrl.replaceFirst(context, "");
if ((errorUrl.equals(homePage) || errorUrl.equals("/")) && LocalData.getToken() == null) {
try {
response.sendRedirect(context + loginPage);
} catch (IOException e) {
e.printStackTrace();
}
}
return "403";
case 500:
return "500";
default:
return "403";
}
}
@RequestMapping("/")
public String home() {
Token token = LocalData.getToken();
if (token == null) {
return "redirect:" + loginPage;
} else {
return "redirect:" + homePage;
}
}
/**
* layoutscreen
* 使layoutViewNameTranslator
*
* @param model
* @param request
*/
@RequestMapping({"/**/*.htm"})
public String action(Model model, HttpServletRequest request, HttpServletResponse response) {
String servletPath = request.getServletPath();// /**/*.htm
String layout = "/layout/default";
String action = LocalData.getAction();// **/*
Pattern compile = Pattern.compile("^/(.+)\\.htm");
Matcher matcher = compile.matcher(servletPath);
if (matcher.find()) {
action = matcher.group(1);
LocalData.setAction(action);
}
try {
LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
Locale locale = localeResolver.resolveLocale(request);
{//查询screen
String[] split = action.split("/");
StringBuilder sb = new StringBuilder("");
sb.append("screen");
for (int i = 0; i < split.length; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
layout = sb.toString();
View view = viewResolver.resolveViewName(layout, locale);
if (view == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,"");
return null;
}
// 尝试执行Screen执行器(服务器渲染),并返回视图模板
try {
String beanClassName = (ActionConfig.SCREEN_PREFIX + action).toLowerCase();
Screen screenExec = LocalData.getApplicationContext().getBean(beanClassName, Screen.class);
screenExec.exec(model, request, response);
if (response.getStatus() != HttpServletResponse.SC_OK) {
response.sendError(response.getStatus(),"");
return null;
}
} catch (BeansException e) {
}
}
{//查找layout
String[] split = action.split("/");
int lt = split.length;
while (lt > 0) {
StringBuilder sb = new StringBuilder("");
sb.append("layout");
for (int i = 0; i < lt - 1; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
layout = sb.toString() + File.separator + split[split.length - 1];
View view = viewResolver.resolveViewName(layout, locale);
//无法找到对应layout使用默认layout
if (view == null) {
layout = sb.toString() + File.separator + "default";
View defaultView = viewResolver.resolveViewName(layout, locale);
if (null == defaultView && lt == 1) {
System.err.println("can not find layout/default.ftl");
} else if (null == defaultView) {
lt--;
} else {
break;
}
} else {
break;
}
}
}
} catch (Exception e) {
return exceptionHandler(request, response, model, e);
}
// todo 可在此获取共性数据(也可以在全局拦截器GlobalHandlerInterceptor、拦截器作用域比此更高)
// todo 例如用户信息等。其他业务数据在页面渲染后通过Ajax请求
return layout;
}
@RequestMapping("/ajax/{module}/{target}/{method}")
@ResponseBody
public Object ajax(
@PathVariable String module,
@PathVariable String target,
@PathVariable String method,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
@RequestBody(required = false) String data,
@RequestParam(name = "file", required = false) MultipartFile file) {
try {
String beanClassName = (ActionConfig.AJAX_PREFIX + module + "/" + target).toLowerCase();
Object ajax = LocalData.getApplicationContext().getBean(beanClassName);
Class ajaxClass = ajax.getClass();
Method[] methods = ajaxClass.getDeclaredMethods();
Method methodC = null;
for (Method meth : methods) {
if (meth.getName().equals(method)) {
methodC = meth;
}
}
if (methodC == null) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "未找到对应的方法!");
return baseResponse;
}
Parameter[] parameters = methodC.getParameters();
Object[] arg = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (parameter.getType() == HttpServletRequest.class) {
arg[i] = httpServletRequest;
} else if (parameter.getType() == HttpServletResponse.class) {
arg[i] = httpServletResponse;
} else if (parameter.getType() == TreeNode.class) {
arg[i] = MapperUtil.toTree(data);
} else if (parameter.getType() == String.class) {
arg[i] = data;
} else if (parameter.getType() == MultipartFile.class) {
arg[i] = file;
} else if (BaseRequest.class.isAssignableFrom(parameter.getType())) {
arg[i] = MapperUtil.toJava(data, parameter.getType());
} else if (parameter.getType() == Token.class) {
arg[i] = LocalData.getToken();
} else {
arg[i] = null;
}
}
return methodC.invoke(ajax, arg);
} catch (BeansException e) {
e.printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "未找到对应的目标!");
return baseResponse;
} catch (IllegalAccessException e) {
e.printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "方法执必须公开!");
return baseResponse;
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "方法执行错误[" + e.getTargetException().getMessage() + "]");
return baseResponse;
}
}
@RequestMapping(path = "/api/{module}/{target}/{method}", method = RequestMethod.POST)
@ResponseBody
public String api(
@PathVariable String module,
@PathVariable String target,
@PathVariable String method,
@RequestParam(required = false) String appKey,
@RequestParam(required = false) String sign,
@RequestParam(required = false) Long timestamp,
@RequestParam(required = false) String token,
@RequestParam(required = false) String encryptData,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
BaseResponse response = new BaseResponse();
if (appKey == null) {
response.addError(ErrorType.BUSINESS_ERROR, "应用码参数[appKey]不存在!");
return MapperUtil.toJson(response);
} else if (sign == null) {
response.addError(ErrorType.BUSINESS_ERROR, "签名参数[sign]不存在!");
return MapperUtil.toJson(response);
} else if (timestamp == null) {
response.addError(ErrorType.BUSINESS_ERROR, "时间戳参数[timestamp]不存在!");
return MapperUtil.toJson(response);
}
String data = null;
String appSecret = "1234567890123456";
// 解码
try {
data = AESUtil.decrypt2String(encryptData, appSecret);
} catch (Exception e) {
response.addError(ErrorType.BUSINESS_ERROR, "解码失败,请确认编码是否正确!");
return MapperUtil.toJson(response);
}
// 验证签名
String sign_ = MD5Util.encode(appSecret + data + timestamp);
if (!sign_.equals(sign)) {
response.addError(ErrorType.BUSINESS_ERROR, "签名验证失败!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 时效性验证
long currentTime = System.currentTimeMillis();
if (currentTime - timestamp > 2 * 60 * 1000) {
response.addError(ErrorType.BUSINESS_ERROR, "请求过期, 或本地时间错误!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 权限验证
if (!LocalData.getToken().hasRes(httpServletRequest.getServletPath())) {
response.addError(ErrorType.BUSINESS_ERROR, "[" + httpServletRequest.getServletPath() + "]未授权的资源!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 开始处理业务
try {
String beanClassName = (ActionConfig.API_PREFIX + module + "/" + target).toLowerCase();
Object ajax = LocalData.getApplicationContext().getBean(beanClassName);
Class ajaxClass = ajax.getClass();
Method[] methods = ajaxClass.getDeclaredMethods();
Method methodC = null;
for (Method meth : methods) {
if (meth.getName().equals(method)) {
methodC = meth;
}
}
if (methodC == null) {
response.addError(ErrorType.BUSINESS_ERROR, "未找到对应的方法!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
Parameter[] parameters = methodC.getParameters();
Object[] arg = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (parameter.getType() == HttpServletRequest.class) {
arg[i] = httpServletRequest;
} else if (parameter.getType() == HttpServletResponse.class) {
arg[i] = httpServletResponse;
} else if (BaseRequest.class.isAssignableFrom(parameter.getType())) {
arg[i] = MapperUtil.toJava(data, parameter.getType());
} else if (parameter.getType() == TreeNode.class) {
arg[i] = MapperUtil.toTree(data);
} else if (parameter.getType() == Token.class) {
arg[i] = LocalData.getToken();
} else {
arg[i] = null;
}
}
response = (BaseResponse) methodC.invoke(ajax, arg);
} catch (BeansException e) {
e.printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "未找到对应的目标!");
} catch (IllegalAccessException e) {
e.printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "方法执必须公开!");
} catch (InvocationTargetException e) {
LogUtil.dumpException(e.getTargetException());
e.getTargetException().printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "方法执行错误[" + e.getTargetException().getMessage() + "]");
}
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
private static ConcurrentHashMap<String, SseEmitter> sseMap = new ConcurrentHashMap();
/**
* Ssejs
* Sse{@link GlobalController#sseMap}
* Sse{@link GlobalController#pushAll}
*/
@RequestMapping(value = "/sse/{userId}", produces = "text/event-stream;charset=UTF-8")
public SseEmitter sse(@PathVariable String userId) {
SseEmitter sseEmitter = new SseEmitter(10000000L);
if (sseMap.get(userId) != null) {
sseMap.remove(userId);
}
sseMap.put(userId, sseEmitter);
return sseEmitter;
}
/**
* Sse
*
* @param data
*/
public static void pushAll(Object data) {
for (String s : sseMap.keySet()) {
try {
sseMap.get(s).send(MapperUtil.toJson(data), MediaType.APPLICATION_JSON);
} catch (IOException e) {
sseMap.remove(s);
}
}
}
}

@ -0,0 +1,49 @@
package ${basePackage}.action.api.${module};
import ${basePackage}.frame.auth.LocalData;
import ${basePackage}.module.${module}.mgr.${table.getCName()}Manager;
import ${basePackage}.module.${module}.req.*;
import ${basePackage}.module.${module}.rsp.*;
import org.springframework.beans.factory.annotation.Autowired;
public class ${table.getCName()}Api{
@Autowired
private ${table.getCName()}Manager ${table.getFName()}Manager;
<#if table.getCreate()>
public ${table.getCName()}CreateResponse create(${table.getCName()}CreateRequest request) {
return ${table.getFName()}Manager.create(request, LocalData.getToken());
}
</#if>
<#if table.getDelete()>
public ${table.getCName()}DeleteResponse delete(${table.getCName()}DeleteRequest request) {
return ${table.getFName()}Manager.delete(request, LocalData.getToken());
}
</#if>
<#if table.getUpdate()>
public ${table.getCName()}UpdateResponse update(${table.getCName()}UpdateRequest request) {
return ${table.getFName()}Manager.update(request, LocalData.getToken());
}
</#if>
<#if table.getFind()>
public ${table.getCName()}FindResponse find(${table.getCName()}FindRequest request) {
return ${table.getFName()}Manager.find(request, LocalData.getToken());
}
</#if>
<#if table.getGet()>
public ${table.getCName()}GetResponse get(${table.getCName()}GetRequest request) {
return ${table.getFName()}Manager.get(request, LocalData.getToken());
}
</#if>
<#if table.getSearch()>
public ${table.getCName()}SearchResponse search(${table.getCName()}SearchRequest request) {
return ${table.getFName()}Manager.search(request, LocalData.getToken());
}
</#if>
}

@ -0,0 +1,75 @@
package ${basePackage}.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import ${basePackage}.frame.utils.LogUtil;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ScreenControl
* <p>
* Screen {@link ActionConfig#registryScreen}
* Control {@link ActionConfig#registryControl}
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Configuration
public class ActionConfig implements BeanDefinitionRegistryPostProcessor {
public static String AJAX_PREFIX = "/ajax/";
public static String API_PREFIX = "/api/";
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
String aPackage = this.getClass().getPackage().getName();
Pattern compile = Pattern.compile("(.*)\\.config");
Matcher matcher = compile.matcher(aPackage);
if (matcher.find()) {
String basePackage = matcher.group(1);
registryApi(basePackage + ".action.api", beanDefinitionRegistry);
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
private int registryApi(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.addIncludeFilter(new TypeFilter() {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
return true;
}
});
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanClassName.endsWith("Api")) {
beanClassName = beanClassName.substring(0, beanClassName.length() - 3);
}
String beamName = beanClassName.replaceAll(basePackage + ".", API_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry api " + beamName);
return beamName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
}

@ -0,0 +1,45 @@
package ${basePackage}.config;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.DiskStoreConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
public static final String TOKEN_CACHE = "tokenCache";
@Bean
public EhCacheCacheManager getCacheManager() {
net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
// todo 需根据服务器物理内存配置
configuration.setMaxBytesLocalHeap("128M");
configuration.updateCheck(false);
configuration.addDiskStore(new DiskStoreConfiguration().path("java.io.tmpdir"));
CacheManager cacheManager = CacheManager.create(configuration);
// 添加token缓存
cacheManager.addCache(buildTokenCache());
return new EhCacheCacheManager(cacheManager);
}
/**
* TokenCache
*
* @return
*/
private Cache buildTokenCache() {
CacheConfiguration config = new CacheConfiguration();
config.setMemoryStoreEvictionPolicy("LFU");//最少使用
config.setTimeToLiveSeconds(60 * 60);//最长有效时间
config.setTimeToIdleSeconds(60 * 60);//无访问最长有效时间
config.setName(TOKEN_CACHE);
return new Cache(config);
}
}

@ -0,0 +1,41 @@
package ${basePackage}.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"${basePackage}.*.mainMpr"}, sqlSessionFactoryRef = "mainSqlSessionFactory")
public class MapperMainConfig {
@Bean(name = "mainDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.main")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "mainTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("mainDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Primary
@Bean(name = "mainSqlSessionFactory")
public SqlSessionFactory basicSqlSessionFactory(@Qualifier("mainDataSource") DataSource basicDataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(basicDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:**/mainMpr/*.xml"));
return factoryBean.getObject();
}
}

@ -0,0 +1,37 @@
package ${basePackage}.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"${basePackage}.*.twoMpr"}, sqlSessionFactoryRef = "twoSqlSessionFactory")
public class MapperTwoConfig {
@Bean(name = "TwoDataSource")
@ConfigurationProperties(prefix = "spring.datasource.two")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "twoTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("twoDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "twoSqlSessionFactory")
public SqlSessionFactory basicSqlSessionFactory(@Qualifier("twoDataSource") DataSource basicDataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(basicDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:**/twoMpr/*.xml"));
return factoryBean.getObject();
}
}

@ -0,0 +1,32 @@
package ${basePackage}.config;
import ${basePackage}.frame.utils.ResourceUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Configuration
public class SQLiteConfig {
@Value("${r'${spring.datasource.url}'}")
private String url;
@PostConstruct
public void generateDB() {
Pattern compile = Pattern.compile("jdbc:sqlite:(.*.db).*");
Matcher matcher = compile.matcher(url);
if (matcher.find()) {
String group = matcher.group(1);
File file = new File(group);
if (!file.exists()) {
File path = file.getAbsoluteFile().getParentFile();
if (!path.exists()) path.mkdirs();
ResourceUtil.copyResource2File("${projectName}.db", file);
}
}
}
}

@ -0,0 +1,91 @@
package ${basePackage}.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import ${basePackage}.frame.schedule.RunTask;
import ${basePackage}.frame.utils.LogUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ,
* :@Profile("dev") ()
*/
@Configuration
@Component
public class ScheduleConfig extends ThreadPoolTaskScheduler implements BeanDefinitionRegistryPostProcessor {
private Map<String, Class<RunTask>> classMap;
private Map<String, ScheduledFuture<?>> futureMap;
public ScheduleConfig() {
classMap = new HashMap<>();
futureMap = new HashMap<>();
setPoolSize(4);
initialize();
}
public boolean createOrRepeat(RunTask task) {
if (futureMap.containsKey(task.taskId())) {
ScheduledFuture<?> scheduledFuture = futureMap.get(task.taskId());
scheduledFuture.cancel(false);
}
classMap.put(task.taskId(), (Class<RunTask>) task.getClass());
futureMap.put(task.taskId(), task.schedule(this));
return true;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
String aPackage = this.getClass().getPackage().getName();
Pattern compile = Pattern.compile("(.*)\\.config");
Matcher matcher = compile.matcher(aPackage);
if (matcher.find()) {
String basePackage = matcher.group(1);
registryTask(basePackage, beanDefinitionRegistry);
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
private int registryTask(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.resetFilters(false);
classPathBeanDefinitionScanner.addIncludeFilter(new AssignableTypeFilter(RunTask.class));
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
try {
Class<?> aClass = Class.forName(beanClassName);
Object instance = aClass.newInstance();
RunTask task = (RunTask) instance;
ScheduleConfig.this.createOrRepeat(task);
} catch (Exception e) {
e.printStackTrace();
}
LogUtil.i("registry task " + beanClassName);
return beanClassName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
}

@ -0,0 +1,137 @@
package ${basePackage}.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import ${basePackage}.frame.auth.LocalData;
import ${basePackage}.frame.auth.Token;
import ${basePackage}.frame.utils.CookieUtil;
import ${basePackage}.module.system.mgr.TokensManager;
import ${basePackage}.module.system.req.TokensBuildRequest;
import ${basePackage}.module.system.rsp.TokensBuildResponse;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${r'${web.url.auth.included}'}")
private String[] included;
@Value("${r'${web.url.auth.excluded}'}")
private String[] excluded;
@Value("${r'${spring.mvc.static-path-pattern}'}")
private String[] staticPath;
@Value("${r'${web.url.login}'}")
private String loginPage;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().mvcMatchers(staticPath);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(new TokenFilter(), FilterSecurityInterceptor.class)// 过滤器用于处理Token
.authorizeRequests()
.antMatchers(excluded).permitAll()// 放行排除的URL
.antMatchers(included).access("@Authorization.hasPermission(request,authentication)")// 需要权限的URL
.and().cors()
.and().headers().frameOptions().disable()
.and().csrf().disable();
}
/**
*
* <p>
* Using generated security password: f6b42a66-71b1-4c31-b6a8-942838c81408
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
public static class TokenFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = request.getParameter("token");
if (token == null || token.isEmpty()) {
token = CookieUtil.getCookieValue(request.getCookies(), "token");
}
// 组装Token ~ 这边根据实际的业务组装Token
if (token != null) {
TokensManager tokensManager = LocalData.getBean(TokensManager.class);
TokensBuildRequest tokensBuildRequest = new TokensBuildRequest();
tokensBuildRequest.setToken(token);
TokensBuildResponse tokensBuildResponse = tokensManager.build(tokensBuildRequest, LocalData.getSysToken());
LocalData.setToken(tokensBuildResponse.getToken());
} else {
LocalData.setToken(null);
}
// Action
String servletPath = request.getServletPath().toLowerCase();
Pattern compile = Pattern.compile("^/(.+)\\.htm");
Matcher matcher = compile.matcher(servletPath);
if (matcher.find()) {
LocalData.setAction(matcher.group(1));
}
try {
filterChain.doFilter(servletRequest, servletResponse);
} catch (AccessDeniedException e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
@Bean("Authorization")
public Object getAuthorization() {
return new Object() {
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Token token_ = LocalData.getToken();
if (token_ == null) {
return false;
}
String path = request.getServletPath();
if (token_.hasRes(path)) {
return true;
}
return false;
}
};
}
}

@ -0,0 +1,56 @@
package ${basePackage}.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
private ThreadPoolTaskExecutor executor;
private int corePoolSize = 10;//线程池维护线程的最少数量
private int maxPoolSize = 30;//线程池维护线程的最大数量
private int queueCapacity = 8; //缓存队列
private int keepAlive = 60;//允许的空闲时间
@Nullable
@Override
public Executor getAsyncExecutor() {
executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("mqExecutor-");
// rejection-policy当pool已经达到max size的时候如何处理新任务
// CALLER_RUNS不在新线程中执行任务而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(keepAlive);
executor.initialize();
return executor;
}
@Nullable
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
System.out.println("-------------》》》捕获线程异常信息");
}
};
}
}

@ -0,0 +1,68 @@
package ${basePackage}.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import ${basePackage}.frame.utils.LogUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${r'${web.url.index}'}")
private String homePage;
@Value("${r'${spring.mvc.static-path-pattern}'}")
private String[] staticPath;
/**
*
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 全局异常收集拦截器
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
if (ex != null) {
LogUtil.dumpException(ex);
}
}
}).addPathPatterns("/**").excludePathPatterns(staticPath);
}
/**
* Jackson
* <p>
* 1LonglongStringjavascriptNumber
*
* @param converters
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
}
}
}
}

@ -0,0 +1,95 @@
package ${basePackage}.frame.auth;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import ${basePackage}.frame.auth.Token;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* LocalData -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class LocalData {
private static ApplicationContext applicationContext = null;
private static Token system = null;
static {
// 组装系统Token
system = new Token();
system.setId(0);
system.setUserId(0);
system.setUserName("system");
system.putRes(".*");
}
public static Token getSysToken() {
return system;
}
/**
* target = '/aa/bb'
*/
private static final ThreadLocal<String> actionHolder = new ThreadLocal();
public static String getAction() {
return actionHolder.get();
}
public static void setAction(String action) {
actionHolder.set(action);
}
/**
*
*/
private static final ThreadLocal<Token> tokenHolder = new ThreadLocal();
public static Token getToken() {
return tokenHolder.get();
}
public static void setToken(Token token) {
tokenHolder.set(token);
}
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
public static ApplicationContext getApplicationContext() {
return LocalData.applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext) {
LocalData.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> t) {
if (getApplicationContext() == null) {
return null;
}
try {
return getApplicationContext().getBean(t);
} catch (BeansException ignored) {
return null;
}
}
public static Environment getEnvironment() {
return getBean(Environment.class);
}
}

@ -0,0 +1,128 @@
package ${basePackage}.frame.auth;
import ${basePackage}.frame.utils.IDgenerator;
import ${basePackage}.module.system.ent.Res;
import ${basePackage}.module.system.mgr.ResManager;
import ${basePackage}.module.system.req.ResCreateRequest;
import ${basePackage}.module.system.req.ResFindRequest;
import ${basePackage}.module.system.rsp.ResFindResponse;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Token -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Token implements Serializable {
private static final Long serialVersionUID = 1L;
/**
* ID
*/
private long id;
/**
* TOKEN
*/
private String token;
/**
* ID
*/
private long userId;
/**
*
*/
private String userName;
private Set<String> resSet = new HashSet<>();
public boolean hasRes(String res) {
{// todo 开发初期收集资源,后期删除
String[] profiles = LocalData.getEnvironment().getActiveProfiles();
for (String profile : profiles) {
if (profile.contains("dev")) {//测试环境捕获资源
ResFindRequest resFindRequest = new ResFindRequest();
resFindRequest.setPageSize(0);
resFindRequest.setResValue(res);
ResManager resManager = LocalData.getBean(ResManager.class);
ResFindResponse resFindResponse = resManager.find(resFindRequest, LocalData.getSysToken());
if (resFindResponse.getResult().size() == 0) {//资源不存在,主动收集资源
ResCreateRequest resCreateRequest = new ResCreateRequest();
resCreateRequest.setResCode(IDgenerator.nextUUID());
resCreateRequest.setResName("默认");
resCreateRequest.setResValue(res);
resCreateRequest.setValid(true);
resCreateRequest.setResType("");
resManager.create(resCreateRequest, LocalData.getSysToken());
}
}
}
}
for (String s : resSet) {
if (res.matches(s)) {
return true;
}
}
return false;
}
public void putRes(String resource) {
resSet.add(resource);
}
public void putRes(Set<String> resourceSet) {
this.resSet.addAll(resourceSet);
}
public void putRes(List<Res> resList) {
if (resList == null) return;
for (Res res : resList) {
this.resSet.add(res.getResValue());
}
}
public Set<String> getResSet() {
return resSet;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.auth;
import ${basePackage}.frame.validation.DictValidator;
import javax.validation.Constraint;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DictValidator.class)
public @interface Verification {
String name() default "";
}

@ -0,0 +1,110 @@
package ${basePackage}.frame.base;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Date;
/**
* Base -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseEntity implements Serializable {
/**
*
*/
private long id;
/**
*
*/
private long rowVersion;
/**
*
*/
@JsonIgnore
private long createBy;
/**
*
*/
private Date createTime;
/**
*
*/
@JsonIgnore
private long lastUpdateBy;
/**
*
*/
@JsonIgnore
private Date lastUpdateTime;
/**
*
*/
@JsonIgnore
private boolean isDeleted;
public long getRowVersion() {
return rowVersion;
}
public void setRowVersion(long rowVersion) {
this.rowVersion = rowVersion;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getCreateBy() {
return createBy;
}
public void setCreateBy(long createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public long getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(long lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(boolean deleted) {
isDeleted = deleted;
}
}

@ -0,0 +1,52 @@
package ${basePackage}.frame.base;
/**
* BaseFindRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseFindRequest extends BaseRequest {
private int pageNumber = 1;
private int pageSize = 10;
private String sortKey;
private SortType sortType;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getSortKey() {
return sortKey;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public SortType getSortType() {
return sortType;
}
public void setSortType(SortType sortType) {
this.sortType = sortType;
}
}

@ -0,0 +1,33 @@
package ${basePackage}.frame.base;
import java.util.List;
/**
* BaseFindResponse -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseFindResponse<T> extends BaseResponse{
private List<T> result;
private Long totalCount;
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public Long getTotalCount() {
return totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
}

@ -0,0 +1,12 @@
package ${basePackage}.frame.base;
/**
* BaseRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseRequest {
}

@ -0,0 +1,38 @@
package ${basePackage}.frame.base;
import java.util.ArrayList;
import java.util.List;
/**
* BaseResponse -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseResponse {
private List<Error> errors = new ArrayList();
public void addError(Error error){
this.errors.add(error);
}
public void addError(ErrorType type,String message){
this.errors.add(new Error(type,message));
}
public void addErrors(List<Error> errors){
this.errors.addAll(errors);
}
public boolean hasError(){
return this.errors.size() > 0;
}
/**
*
*/
public List<Error> getErrors() {
return new ArrayList<Error>(errors);
}
}

@ -0,0 +1,24 @@
package ${basePackage}.frame.base;
/**
* BaseSearchRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseSearchRequest extends BaseFindRequest {
/**
*
*/
private String keyword;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}

@ -0,0 +1,24 @@
package ${basePackage}.frame.base;
/**
* BaseUpdateRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseUpdateRequest extends BaseRequest{
/**
*
*/
private long rowVersion;
public long getRowVersion() {
return rowVersion;
}
public void setRowVersion(long rowVersion) {
this.rowVersion = rowVersion;
}
}

@ -0,0 +1,10 @@
package ${basePackage}.frame.base;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Control {
public abstract void exec(Model model, HttpServletRequest request, HttpServletResponse response);
}

@ -0,0 +1,41 @@
package ${basePackage}.frame.base;
/**
* Error -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Error {
/*错误类型*/
private ErrorType type;
/*错误内容*/
private String message;
public Error() {
}
public Error(ErrorType type, String message) {
this.type = type;
this.message = message;
}
public ErrorType getType() {
return type;
}
public void setType(ErrorType type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.base;
/**
* ErrorType -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public enum ErrorType {
BUSINESS_ERROR,
SYSTEM_ERROR,
UNKNOWN_ERROR,
UNIQUENESS_ERROR,
EXPECTATION_NULL,
INVALID_PARAMETER
}

@ -0,0 +1,10 @@
package ${basePackage}.frame.base;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Screen {
public abstract void exec(Model model, HttpServletRequest request, HttpServletResponse response);
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.base;
/**
* SortTypeEnum -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public enum SortType {
//升序
ASC,
//降序
DESC
}

@ -0,0 +1,47 @@
package ${basePackage}.frame.excel;
import java.io.Serializable;
/**
* WCell - Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WCell implements Serializable {
/**
*
*/
private String value;
/**
* excel
*/
private String error;
public WCell() {
this.value = "";
}
public WCell(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}

@ -0,0 +1,146 @@
package ${basePackage}.frame.excel;
import ${basePackage}.frame.excel.converter.Converter;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* WColumn - Excel()
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WColumn implements Serializable {
/**
*
*/
private String name = "";
/**
*
*/
private int cellWidth = 8;
/**
*
*/
private boolean isRequired = false;
/**
*
*/
private String description = "";
/**
*
*/
private Converter converter;
/**
* Field
*/
private Field field;
/**
* set
*/
private Method setMethod;
/**
* get
*/
private Method getMethod;
/**
* ExcelType
*/
private int cellType = 1;
/**
*
*/
private String[] cellList;
public WColumn() {
this.name = "";
}
public WColumn(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public int getCellWidth() {
return cellWidth;
}
public void setCellWidth(int cellWidth) {
this.cellWidth = cellWidth;
}
public boolean isRequired() {
return isRequired;
}
public void setRequired(boolean isRequired) {
this.isRequired = isRequired;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
public int getCellType() {
return cellType;
}
public void setCellType(int cellType) {
this.cellType = cellType;
}
public Method getSetMethod() {
return setMethod;
}
public void setSetMethod(Method setMethod) {
this.setMethod = setMethod;
}
public Method getGetMethod() {
return getMethod;
}
public void setGetMethod(Method getMethod) {
this.getMethod = getMethod;
}
public String[] getCellList() {
return cellList;
}
public void setCellList(String[] cellList) {
this.cellList = cellList;
}
}

@ -0,0 +1,681 @@
package ${basePackage}.frame.excel;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.NumberToTextConverter;
import ${basePackage}.frame.excel.annotation.ColumnDescription;
import ${basePackage}.frame.excel.annotation.ColumnList;
import ${basePackage}.frame.excel.annotation.ColumnName;
import ${basePackage}.frame.excel.annotation.Convert;
import ${basePackage}.frame.excel.annotation.Ignore;
import ${basePackage}.frame.excel.annotation.ParentFirst;
import ${basePackage}.frame.excel.annotation.SheetName;
import ${basePackage}.frame.excel.converter.BooleanConverter;
import ${basePackage}.frame.excel.converter.ByteConverter;
import ${basePackage}.frame.excel.converter.CharacterConverter;
import ${basePackage}.frame.excel.converter.Converter;
import ${basePackage}.frame.excel.converter.DateConverter;
import ${basePackage}.frame.excel.converter.DoubleConverter;
import ${basePackage}.frame.excel.converter.FloatConverter;
import ${basePackage}.frame.excel.converter.IntegerConverter;
import ${basePackage}.frame.excel.converter.LongConverter;
import ${basePackage}.frame.excel.converter.ShortConverter;
import ${basePackage}.frame.excel.converter.StringConverter;
import ${basePackage}.frame.excel.exception.ReadErrorException;
import ${basePackage}.frame.excel.exception.TemplateNotMatchException;
import ${basePackage}.frame.excel.exception.ValueConverterException;
import ${basePackage}.frame.excel.style.DataCellStyle;
import ${basePackage}.frame.excel.style.ErrorCellStyle;
import ${basePackage}.frame.excel.style.HeadCellStyle;
import ${basePackage}.frame.excel.style.RedFont;
import ${basePackage}.frame.excel.style.SuccessCellStyle;
import ${basePackage}.frame.utils.ClassUtil;
import ${basePackage}.frame.utils.FileUtil;
import ${basePackage}.frame.utils.LogUtil;
import ${basePackage}.frame.utils.ValidationUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* WExcel - Excel
*
*
* new WExcel<Dept>(Dept.class).loadData(depts).toFile(file);<br>
*
*
* byte[] bytes = FileUtil.readFileToByteArray(new File("E:\\E.xlsx"));<br>
* WExcel check = new WExcel<Dept>(Dept.class).loadData(bytes);
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WExcel<T> implements Serializable, Cloneable {
/**
*
*/
private String name;
/**
*
*/
private boolean freezeFirst;
/**
*
*/
private Class<T> templateClass;
/**
*
*/
private List<WColumn> columnList = new ArrayList<>();
/**
*
*/
private List<WRow> rowList = new ArrayList<>();
/**
*
*/
public WExcel(Class<T> tClass) {
this.templateClass = tClass;
initColumns(tClass);
}
/**
* DataTable
*
* @return WColumn
*/
private List<WColumn> initColumns(Class<?> clazz) {
//获取工作簿名称,没有则以类名为默认工作簿名称
if (clazz.isAnnotationPresent(SheetName.class)) {
SheetName sheetName = clazz.getAnnotation(SheetName.class);
this.setName(sheetName.value());
this.setFreezeFirst(sheetName.freezeFirst());
} else {
this.setName(clazz.getSimpleName());
}
//是否关注父类属性
boolean parentFirst = clazz.isAnnotationPresent(ParentFirst.class) && clazz.getAnnotation(ParentFirst.class).value();
Field[] fields = ClassUtil.getFields(clazz, parentFirst);
for (Field field : fields) {
if (field.isAnnotationPresent(Ignore.class) && field.getAnnotation(Ignore.class).value()) {
continue;
}
WColumn WColumn = new WColumn();
WColumn.setField(field);
Method set = ClassUtil.setMethod(field.getName(), clazz, field.getType());
WColumn.setSetMethod(set);
Method get = ClassUtil.getMethod(field.getName(), clazz);
WColumn.setGetMethod(get);
//获取列名称
if (!field.isAnnotationPresent(ColumnName.class)) {
WColumn.setName(field.getName());
} else {
ColumnName columnColumnName = field.getAnnotation(ColumnName.class);
WColumn.setName(columnColumnName.value());
WColumn.setCellWidth(columnColumnName.width());
WColumn.setRequired(columnColumnName.required());
}
//获取列填写说明或描述
if (field.isAnnotationPresent(ColumnDescription.class)) {
WColumn.setDescription(field.getAnnotation(ColumnDescription.class).value());
}
//获取下拉列表
if (field.isAnnotationPresent(ColumnList.class)) {
WColumn.setCellList(field.getAnnotation(ColumnList.class).value());
}
//获取列类型
if (field.isAnnotationPresent(Convert.class)) {
Convert converter = field.getAnnotation(Convert.class);
Class target = converter.target();
try {
WColumn.setConverter((Converter) target.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
} else {
if (field.getType() == boolean.class || field.getType() == Boolean.class) {
WColumn.setConverter(new BooleanConverter());
WColumn.setCellType(Cell.CELL_TYPE_BOOLEAN);
} else if (field.getType() == byte.class || field.getType() == Byte.class) {
WColumn.setConverter(new ByteConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == char.class || field.getType() == Character.class) {
WColumn.setConverter(new CharacterConverter());
WColumn.setCellType(Cell.CELL_TYPE_STRING);
} else if (field.getType() == short.class || field.getType() == Short.class) {
WColumn.setConverter(new ShortConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == int.class || field.getType() == Integer.class) {
WColumn.setConverter(new IntegerConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == long.class || field.getType() == Long.class) {
WColumn.setConverter(new LongConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == float.class || field.getType() == Float.class) {
WColumn.setConverter(new FloatConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == double.class || field.getType() == Double.class) {
WColumn.setConverter(new DoubleConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == Date.class) {
WColumn.setConverter(new DateConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == String.class) {
WColumn.setConverter(new StringConverter());
WColumn.setCellType(Cell.CELL_TYPE_STRING);
} else {
throw new RuntimeException("Can not find Converter");
}
}
columnList.add(WColumn);
}
return columnList;
}
public WExcel loadData(List<T> list) {
return loadData(list, null);
}
/**
* <br/>
*
*
* @param list
*/
public WExcel loadData(List<T> list, Processor<T> processor) {
if (list.size() > 0) {
for (T t : list) {
WRow row = new WRow();
for (WColumn column : columnList) {
if (column == null) {
continue;
}
Method method = column.getGetMethod();
try {
Object value = method.invoke(t);
if (null == value) {
row.put(column.getName(), new WCell());
} else {
String string = column.getConverter().string(value);
row.put(column.getName(), new WCell(string));
}
} catch (IllegalAccessException e) {
LogUtil.w("can not invoke get method!");
} catch (InvocationTargetException e) {
LogUtil.w(method.getName() + " unexpected exception!");
}
// <2层检查>检查模板注解验证是否通过
row.addErrors(ValidationUtil.validate(t));
// <3层检查>如果没有错误,则可以执行处理器进行业务处理
if (!row.hasError() && processor != null) {
List<String> exec = processor.exec(t);
row.addErrors(exec != null ? exec : Collections.EMPTY_LIST);
}
}
this.rowList.add(row);
}
}
return this;
}
public WExcel loadData(File file) throws TemplateNotMatchException, ReadErrorException, IOException {
return loadData(FileUtil.readFileToByteArray(file), null);
}
public WExcel loadData(File file, Processor<T> processor) throws TemplateNotMatchException, ReadErrorException, IOException {
return loadData(FileUtil.readFileToByteArray(file), processor);
}
public WExcel loadData(byte[] bytes) throws TemplateNotMatchException, ReadErrorException {
return loadData(bytes, null);
}
/**
* Excel<br/>
* <br/>
*/
public WExcel loadData(byte[] bytes, Processor<T> processor) throws TemplateNotMatchException, ReadErrorException {
Workbook workbook = null;
InputStream is = null;
boolean flag;
try {
flag = true;
is = new ByteArrayInputStream(bytes); //读取文件流
workbook = new HSSFWorkbook(is);
} catch (Exception e) {
flag = false;
}
if (!flag) {
try {
flag = true;
is = new ByteArrayInputStream(bytes); //读取文件流
workbook = new XSSFWorkbook(is);
} catch (Exception e) {
flag = false;
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!flag) {
throw new ReadErrorException("读取Excel文件错误");
}
//第一张Sheet表
Sheet sheet = workbook.getSheetAt(0);
//获取Sheet名称
if (templateClass.isAnnotationPresent(SheetName.class)) {//如果模板存在注解则使用注解名称
SheetName sheetName = templateClass.getAnnotation(SheetName.class);
this.setName(sheetName.value());
} else {//将类名设为表名如果类名不存在将Excel表名设为表名
this.setName(sheet.getSheetName());
}
//读取表头
Row headRow = sheet.getRow(0);
//获取Excel列的总数
int columnSum = headRow.getPhysicalNumberOfCells();
//检查列数量
if (columnList.size() != columnSum) {
throw new TemplateNotMatchException("与模板列数量不同。");
} else {
for (int i = 0; i < columnList.size(); i++) {
WColumn wColumn = columnList.get(i);
Cell cell = headRow.getCell(i);
String headValue = getValue(cell);
headValue = headValue.replace("*", "");
headValue = headValue.replace(" ", "");
if (!wColumn.getName().equals(headValue)) {
throw new TemplateNotMatchException("第" + (i + 1) + "项,不匹配的列名," + wColumn.getName() + "和" + headValue);
}
}
}
//Excel文件的总行数
int maxRowNumber = sheet.getLastRowNum();
// 逐行读取导入文件的数据
for (int i = 0; i < maxRowNumber; i++) {
//Excel中的一行数据第0行为表头所以要加1
Row inputRow = sheet.getRow(i + 1);
WRow row = new WRow();
rowList.add(row);
if (null != inputRow) {
for (int j = 0; j < columnList.size(); j++) {
WColumn wcolumn = columnList.get(j);
/* 取得当前格子的值 */
Cell excelCell = inputRow.getCell(j);
WCell WCell = new WCell();
row.put(wcolumn.getName(), WCell);
String value = "";
if (null != excelCell) {
value = getValue(excelCell);
}
value = value.trim();
WCell.setValue(value);
}
}
try {
T t = templateClass.newInstance();
// <1层检查>检查数据格式是否正确
row.addErrors(transferMap(row, t));
// <2层检查>检查模板注解验证是否通过
row.addErrors(ValidationUtil.validate(t));
// <3层检查>如果没有错误,则可以执行处理器进行业务处理
if (!row.hasError() && processor != null) {
List<String> exec = processor.exec(t);
row.addErrors(exec != null ? exec : Collections.EMPTY_LIST);
}
} catch (InstantiationException | IllegalAccessException e) {
row.addError("模板对象默认构造函数错误");
}
}
return this;
}
/**
*
*
* @param row
* @param target
* @return
*/
public List<String> transferMap(WRow row, T target) {
List<String> err = new ArrayList<>();
for (String key : row.keySet()) {
for (WColumn column : columnList) {
String name = column.getName();
Method setMethod = column.getSetMethod();
if (key.equals(name)) {
WCell WCell = row.get(column.getName());
if (null != WCell) {
String value = WCell.getValue();
//获取转换器
Converter converter = column.getConverter();
try {
setMethod.invoke(target, converter.convert(value));
} catch (ValueConverterException e) {
e.printStackTrace();
err.add(e.getMessage());
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
err.add("[" + setMethod.getName() + "]执行错误");
}
}
break;
}
}
}
return err;
}
/**
*
*
* @return
*/
public String getName() {
return name;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
public boolean getFreezeFirst() {
return freezeFirst;
}
public void setFreezeFirst(boolean freezeFirst) {
this.freezeFirst = freezeFirst;
}
public final String toCSV() {
StringBuilder sb = new StringBuilder();
for (WColumn WColumn : this.columnList) {
if (WColumn != null) {
sb.append(WColumn.getName()).append(",");
}
}
sb.append("\n");
for (int i = 0; i < this.rowList.size(); i++) {
for (int j = 0; j < this.columnList.size(); j++) {
WColumn wColumn = this.columnList.get(j);
WCell wCell = this.rowList.get(i).get(wColumn.getName());
sb.append(wCell.getValue()).append(",");
}
sb.append("\n");
}
return sb.toString();
}
/**
* DataTable
*
* @return .
*/
public final boolean hasError() {
for (WRow wRow : rowList) {
if (wRow.hasError()) {
return true;
}
}
return false;
}
public byte[] getBytes() {
XSSFWorkbook workbook = getExcel();
if (workbook != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
workbook.write(outputStream);
} catch (IOException e) {
return null;
}
return outputStream.toByteArray();
}
return null;
}
public XSSFWorkbook getExcel() {
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个Sheet表
XSSFSheet sheet = workbook.createSheet(name);
sheet.setDefaultRowHeightInPoints(18);
Row firstRow = sheet.createRow(0); // 下标为0的行开始
XSSFDrawing drawing = sheet.createDrawingPatriarch();
int offset = 0;
// 添加结果和错误说明列
if (hasError()) {
offset++;
{// 第一栏结果栏
Cell firstCell = firstRow.createCell(0);
firstCell.setCellStyle(new HeadCellStyle(workbook).getStyle());
firstCell.setCellValue(new XSSFRichTextString("执行结果"));
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6);
XSSFComment comment = drawing.createCellComment(anchor);
comment.setString("此列为检查结果,导入时请处理完错误,并删除该列!");
firstCell.setCellComment(comment);
}
offset++;
{// 第二栏错误信息栏
Cell secondCell = firstRow.createCell(1);
secondCell.setCellStyle(new HeadCellStyle(workbook).getStyle());
secondCell.setCellValue(new XSSFRichTextString("结果说明"));
sheet.setColumnWidth(1, 18 * 256);
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6);
XSSFComment comment = drawing.createCellComment(anchor);
comment.setString("此列为检查结果信息列,导入时请处理完错误,并删除该列!");
secondCell.setCellComment(comment);
}
}
for (int j = 0; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(j);
Cell firstCell = firstRow.createCell(j + offset);
String columnName = column.getName();
XSSFRichTextString textString;
if (column.isRequired()) {
textString = new XSSFRichTextString("*" + columnName);
textString.applyFont(0, 1, new RedFont(workbook).getFont());
textString.applyFont(1, textString.length(), workbook.createFont());
} else {
textString = new XSSFRichTextString(columnName);
textString.applyFont(workbook.createFont());
}
StringBuilder sb = new StringBuilder();
sb.append(column.getDescription()).append("\n");
// 如果填写了注释信息
if (sb.length() > 1) {
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6);
XSSFComment comment = drawing.createCellComment(anchor);
comment.setString(sb.toString());
firstCell.setCellComment(comment);
}
firstCell.setCellValue(textString);
firstCell.setCellStyle(new HeadCellStyle(workbook).getStyle());
sheet.setColumnWidth(j + offset, (4 + column.getCellWidth()) * 256);
if (column.getCellList() != null){
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 65535, j+offset, j+offset);
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(column.getCellList());
DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
//处理Excel兼容性问题
if (dataValidation instanceof XSSFDataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
dataValidation.setEmptyCellAllowed(true);
dataValidation.setShowPromptBox(true);
dataValidation.createPromptBox("规则", "请选择下拉框里面的数据");
sheet.addValidationData(dataValidation);
}
}
// 冻结第一行
if (freezeFirst) {
sheet.createFreezePane(255, 1);
}
// 填充数据
for (int i = 0; i < this.rowList.size(); i++) {
WRow wRow = this.rowList.get(i);
Row row = sheet.createRow(i + 1);
if (offset > 0) {
if (this.rowList.get(i).hasError()) {
// 添加结果
List<String> errorList = wRow.getErrorList();
Cell resultCell = row.createCell(0);
resultCell.setCellStyle(new ErrorCellStyle(workbook).getStyle());
resultCell.setCellValue("错误");
// 添加错误信息详细说明
Cell errsCell = row.createCell(1);
errsCell.setCellStyle(new ErrorCellStyle(workbook).getStyle());
String join = String.join(";\n", errorList);
errsCell.setCellValue(new XSSFRichTextString(join));
} else {
// 添加结果
Cell resultCell = row.createCell(0);
resultCell.setCellStyle(new SuccessCellStyle(workbook).getStyle());
resultCell.setCellValue("成功");
// 添加错误信息详细说明
Cell errsCell = row.createCell(1);
errsCell.setCellStyle(new SuccessCellStyle(workbook).getStyle());
errsCell.setCellValue("");
}
}
for (int j = 0; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(j);
Cell xssfCell = row.createCell(j + offset);
WCell WCell = this.rowList.get(i).get(column.getName());
if (null == WCell) {
continue;
}
String value = WCell.getValue();
xssfCell.setCellType(column.getCellType());
if (column.getCellType() == Cell.CELL_TYPE_NUMERIC || column.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
xssfCell.setCellStyle(new DataCellStyle(workbook, CellStyle.ALIGN_RIGHT, wRow.hasError()).getStyle());
} else {
xssfCell.setCellStyle(new DataCellStyle(workbook, CellStyle.ALIGN_LEFT, wRow.hasError()).getStyle());
}
xssfCell.setCellValue(value);
}
}
return workbook;
}
/**
*
*
* @param cell
* @return
*/
public static String getValue(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case Cell.CELL_TYPE_BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date value = cell.getDateCellValue();
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else {
return NumberToTextConverter.toText(cell.getNumericCellValue());
}
default:
return cell.getStringCellValue();
}
}
public interface Processor<T> {
List<String> exec(T t);
}
public void toFile(File file) throws IOException {
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new RuntimeException("路径创建失败");
}
if (!file.exists() && !file.createNewFile()) {
throw new RuntimeException("文件创建失败");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getBytes());
fileOutputStream.close();
}
}

@ -0,0 +1,34 @@
package ${basePackage}.frame.excel;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* WRow - ExcelWCell<br>HashMap<String, WCell>,keyvalue
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WRow extends HashMap<String, WCell> implements Serializable {
private List<String> errorList = new ArrayList<>();
public final boolean hasError() {
return errorList.size() > 0;
}
public final void addError(String errorMsg) {
errorList.add(errorMsg);
}
public final void addErrors(List<String> errorMsgs) {
errorList.addAll(errorMsgs);
}
public List<String> getErrorList() {
return errorList;
}
}

@ -0,0 +1,22 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ColumnDescription - Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnDescription {
String value() default "";
}

@ -0,0 +1,25 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ColumnList -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnList {
/**
*
*/
String[] value();
}

@ -0,0 +1,40 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ColumnName - ExcelExcel使
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnName {
/**
*
*/
String value();
/**
*
*/
int width() default 8;
/**
* *
*/
boolean required() default false;
/**
*
*/
String dateFormat() default "yyyy-MM-dd";
}

@ -0,0 +1,21 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Converter - Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Convert {
Class target();
}

@ -0,0 +1,21 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Ignore - Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Ignore {
boolean value() default true;
}

@ -0,0 +1,21 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ParentFirst -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParentFirst {
boolean value() default true;
}

@ -0,0 +1,23 @@
package ${basePackage}.frame.excel.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* SheetName - Excel使Class
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SheetName {
String value();
boolean freezeFirst() default false;
}

@ -0,0 +1,46 @@
package ${basePackage}.frame.excel.converter;
import ${basePackage}.frame.excel.exception.ValueConverterException;
/**
* BooleanConverter - BooleanStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BooleanConverter implements Converter<Boolean> {
@Override
public Boolean convert(String var) throws ValueConverterException {
if (null == var || "".equals(var)) {
return false;
}
String lowerCase = var.toLowerCase();
if (lowerCase.matches("y|n")) {
return "y".equals(lowerCase);
} else if (lowerCase.matches("yes|no")) {
return "yes".equals(lowerCase);
} else if (lowerCase.matches("true|false")) {
return "true".equals(lowerCase);
} else if (lowerCase.matches("是|否")) {
return "是".equals(lowerCase);
} else if (lowerCase.matches("有|无")) {
return "有".equals(lowerCase);
} else if (lowerCase.matches("是|不是")) {
return "是".equals(lowerCase);
} else {
throw new ValueConverterException("[" + var + "] can not convert to Boolean");
}
}
@Override
public String string(Boolean var) {
if (var == null) {
return "";
}
return var ? "是" : "否";
}
}

@ -0,0 +1,28 @@
package ${basePackage}.frame.excel.converter;
/**
* ByteConverter - ByteStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ByteConverter implements Converter<Byte> {
@Override
public Byte convert(String var) {
try {
return Byte.parseByte(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Byte var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,28 @@
package ${basePackage}.frame.excel.converter;
/**
* CharacterConverter - CharacterStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class CharacterConverter implements Converter<Character> {
@Override
public Character convert(String var) {
if (var == null || var.equals("")) {
return '0';
} else {
return var.charAt(0);
}
}
@Override
public String string(Character var) {
if (var == null) {
return "";
}
return String.valueOf(var).trim();
}
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.excel.converter;
import ${basePackage}.frame.excel.exception.ValueConverterException;
/**
* Converter -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public interface Converter<T> {
T convert(String var) throws ValueConverterException;
String string(T var);
}

@ -0,0 +1,51 @@
package ${basePackage}.frame.excel.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* DateConverter - DateStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class DateConverter implements Converter<Date> {
@Override
public Date convert(String var) {
if (var == null) {
return null;
}
Date date = null;
try {
var = var.trim();
if (var.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(var);
} else if (var.matches("[0-9]{4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(var);
} else if (var.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = sdf.parse(var);
} else if (var.matches("[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日 [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
date = sdf.parse(var);
}
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
@Override
public String string(Date var) {
if (var == null) {
return "";
}
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(var);
}
}

@ -0,0 +1,28 @@
package ${basePackage}.frame.excel.converter;
/**
* DoubleConverter - DoubleStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class DoubleConverter implements Converter<Double> {
@Override
public Double convert(String var) {
try {
return Double.parseDouble(var);
} catch (Exception e) {
return 0d;
}
}
@Override
public String string(Double var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,33 @@
package ${basePackage}.frame.excel.converter;
/**
* FloatConverter - FloatStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class FloatConverter implements Converter<Float> {
@Override
public Float convert(String var) {
try {
//增加对1.0一类的的优化显示
if (var.matches("(\\d+)\\.0")) {
var = var.replaceAll("\\.0$", "");
}
return Float.parseFloat(var);
} catch (Exception e) {
return 0f;
}
}
@Override
public String string(Float var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,28 @@
package ${basePackage}.frame.excel.converter;
/**
* IntegerConverter - IntegerStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class IntegerConverter implements Converter<Integer> {
@Override
public Integer convert(String var) {
try {
return Integer.parseInt(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Integer var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,40 @@
package ${basePackage}.frame.excel.converter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* LongConverter - LongStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class LongConverter implements Converter<Long> {
@Override
public Long convert(String var) {
try {
//增加对1.0一类的的兼容性
if (var.matches("(\\d+)\\.(\\d*)")) {
Pattern compile = Pattern.compile("(\\d+)\\.(\\d*)");
Matcher matcher = compile.matcher(var);
if (matcher.find()) {
var = matcher.group(1);
}
}
return Long.parseLong(var);
} catch (Exception e) {
return 0L;
}
}
@Override
public String string(Long var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,28 @@
package ${basePackage}.frame.excel.converter;
/**
* ShortConverter - ShortStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ShortConverter implements Converter<Short> {
@Override
public Short convert(String var) {
try {
return Short.parseShort(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Short var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,24 @@
package ${basePackage}.frame.excel.converter;
/**
* StringConverter - StringStringString
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class StringConverter implements Converter<String> {
@Override
public String convert(String var) {
return var != null ? var.trim() : null;
}
@Override
public String string(String var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.excel.exception;
/**
* Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ReadErrorException extends Exception {
public ReadErrorException() {
}
public ReadErrorException(String s) {
super(s);
}
}

@ -0,0 +1,17 @@
package ${basePackage}.frame.excel.exception;
/**
* Excel
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class TemplateNotMatchException extends Exception {
public TemplateNotMatchException() {
}
public TemplateNotMatchException(String s) {
super(s);
}
}

@ -0,0 +1,15 @@
package ${basePackage}.frame.excel.exception;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ValueConverterException extends Exception {
public ValueConverterException(String s) {
super(s);
}
}

@ -0,0 +1,57 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class BaseCellStyle {
/**
*
*/
protected CellStyle style;
public BaseCellStyle(Workbook workbook) {
style = workbook.createCellStyle();
style.setFillPattern(CellStyle.NO_FILL);
//下边框
style.setBorderBottom(CellStyle.SOLID_FOREGROUND);
//下边框颜色
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//左边框
style.setBorderLeft(CellStyle.SOLID_FOREGROUND);
//左边框颜色
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
//右边框
style.setBorderRight(CellStyle.SOLID_FOREGROUND);
//右边框颜色
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
//上边框
style.setBorderTop(CellStyle.SOLID_FOREGROUND);
//上边框颜色
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中
style.setBorderBottom(CellStyle.SOLID_FOREGROUND); //下边框
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //下边框颜色
style.setBorderLeft(CellStyle.SOLID_FOREGROUND); //左边框
style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); //左边框颜色
style.setBorderRight(CellStyle.SOLID_FOREGROUND); //右边框
style.setRightBorderColor(IndexedColors.BLACK.getIndex()); //右边框颜色
style.setBorderTop(CellStyle.SOLID_FOREGROUND); //上边框
style.setTopBorderColor(IndexedColors.BLACK.getIndex()); //上边框颜色
}
public CellStyle getStyle() {
return style;
}
public void setStyle(CellStyle style) {
this.style = style;
}
}

@ -0,0 +1,29 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class BaseFont {
/**
*
*/
protected Font font;
public BaseFont(Workbook workbook) {
font = workbook.createFont();
}
public Font getFont() {
return font;
}
public void setFont(Font font) {
this.font = font;
}
}

@ -0,0 +1,29 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
public class DataCellStyle extends BaseCellStyle {
public DataCellStyle(Workbook workbook, short align, boolean error) {
super(workbook);
style.setAlignment(align);
if (error) {
style.setFillForegroundColor(HSSFColor.RED.index); //背景颜色红色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式
}
}
public DataCellStyle(Workbook workbook, short align) {
this(workbook, align, false);
}
public DataCellStyle(Workbook workbook, boolean error) {
this(workbook, CellStyle.ALIGN_LEFT, error);
}
public DataCellStyle(Workbook workbook) {
this(workbook, CellStyle.ALIGN_LEFT, false);
}
}

@ -0,0 +1,22 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
public class ErrorCellStyle extends BaseCellStyle {
public ErrorCellStyle(Workbook workbook) {
super(workbook);
style.setFillForegroundColor(HSSFColor.RED.index); //背景颜色红色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式
}
public CellStyle getStyle() {
return style;
}
public void setStyle(CellStyle style) {
this.style = style;
}
}

@ -0,0 +1,15 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
public class HeadCellStyle extends BaseCellStyle {
public HeadCellStyle(Workbook workbook) {
super(workbook);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); //背景颜色-灰色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式
style.setAlignment(CellStyle.ALIGN_CENTER); // 居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
/**
* .
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class NormalFont extends BaseFont {
public NormalFont(Workbook workbook) {
super(workbook);
font.setColor(HSSFColor.BLACK.index); //字体颜色-黑色
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
/**
* .
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class RedFont extends BaseFont {
public RedFont(Workbook workbook) {
super(workbook);
font.setColor(HSSFColor.RED.index); //字体颜色-黑色
}
}

@ -0,0 +1,22 @@
package ${basePackage}.frame.excel.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
public class SuccessCellStyle extends BaseCellStyle {
public SuccessCellStyle(Workbook workbook) {
super(workbook);
style.setFillForegroundColor(HSSFColor.GREEN.index); //背景颜色红色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式
}
public CellStyle getStyle() {
return style;
}
public void setStyle(CellStyle style) {
this.style = style;
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.schedule;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import java.util.concurrent.ScheduledFuture;
public abstract class RunCronTask extends RunTask {
abstract String cron();
@Override
public ScheduledFuture<?> schedule(ThreadPoolTaskScheduler poolTaskScheduler) {
Assert.notNull(poolTaskScheduler, "ThreadPoolTaskScheduler must not be null");
return poolTaskScheduler.schedule(this, new CronTrigger(cron()));
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.schedule;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.Assert;
import java.time.Duration;
import java.util.concurrent.ScheduledFuture;
public abstract class RunDelayRepeatTask extends RunTask {
public abstract Duration interval();
@Override
public ScheduledFuture<?> schedule(ThreadPoolTaskScheduler poolTaskScheduler) {
Assert.notNull(poolTaskScheduler, "ThreadPoolTaskScheduler must not be null");
return poolTaskScheduler.scheduleWithFixedDelay(this, interval());
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.schedule;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.Assert;
import java.time.Duration;
import java.util.concurrent.ScheduledFuture;
public abstract class RunFixRepeatTask extends RunTask {
public abstract Duration interval();
@Override
public ScheduledFuture<?> schedule(ThreadPoolTaskScheduler poolTaskScheduler) {
Assert.notNull(poolTaskScheduler, "ThreadPoolTaskScheduler must not be null");
return poolTaskScheduler.scheduleAtFixedRate(this, interval());
}
}

@ -0,0 +1,40 @@
package ${basePackage}.frame.schedule;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import ${basePackage}.frame.auth.LocalData;
import ${basePackage}.frame.utils.LogUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public abstract class RunSqlTask extends RunFixRepeatTask {
private Connection connection;
@Override
public void run() {
try {
if (connection == null || connection.isClosed()) {
SqlSessionFactory factory = LocalData.getBean(SqlSessionFactory.class);
SqlSession sqlSession = factory.openSession(true);
connection = sqlSession.getConnection();
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("schedule: get connection failed!");
return;
}
try {
PreparedStatement preparedStatement = connection.prepareStatement(getSql());
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
LogUtil.e("RunSqlTask exec failed! SQL:[" + getSql() + "]");
}
}
public abstract String getSql();
}

@ -0,0 +1,21 @@
package ${basePackage}.frame.schedule;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
public abstract class RunTask implements Runnable {
public abstract String taskId();
public abstract ScheduledFuture<?> schedule(ThreadPoolTaskScheduler poolTaskScheduler);
public void configChange(ThreadPoolTaskScheduler scheduler) {
ScheduledFuture<?> schedule = scheduler.schedule(this, new Date());
if (!schedule.cancel(true)) {
}
}
}

@ -0,0 +1,110 @@
package ${basePackage}.frame.utils;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* AESUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
/**
*
*
* @param data
* @param secret
* @return base64
*/
public static byte[] encrypt(byte[] data, String secret) {
try {
if (secret.length() != 16) {
throw new IllegalArgumentException("secret's length is not 16");
}
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
return cipher.doFinal(data);// 加密
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
* @param secret
* @return base64
*/
public static String encrypt2Base64(byte[] data, String secret) {
byte[] encrypt = encrypt(data, secret);
return Base64Util.encodeToString(encrypt, false);
}
/**
*
*
* @param data
* @param secret
* @return
*/
public static byte[] decrypt(byte[] data, String secret) {
try {
if (secret.length() != 16) {
throw new IllegalArgumentException("secret's length is not 16");
}
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptBase64(String base64Data, String secret) {
byte[] decode = Base64Util.decode(base64Data);
return decrypt(decode, secret);
}
public static String decrypt2String(String base64Data, String secret) {
byte[] bytes = decryptBase64(base64Data, secret);
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}

@ -0,0 +1,497 @@
package ${basePackage}.frame.utils;
import java.util.Arrays;
/**
* Base64Util
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Base64Util {
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
public final static String encodeToString(byte[] sArr) {
return new String(encodeToChar(sArr, false));
}
public final static char[] encodeToChar(byte[] sArr, boolean lineSep) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen; ) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/**
* Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static String encodeToString(byte[] sArr, boolean lineSep) {
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
/**
* Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen; ) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
public final static byte[] decode(char[] sArr) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i]] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0; )
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++]];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(byte[] sArr) {
// Check special case
int sLen = sArr.length;
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i] & 0xff] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0; )
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++] & 0xff];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(byte[] sArr) {
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
/**
* Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] sArr) {
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
/**
* Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
* and without line separators.<br>
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
*
* @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(String str) {
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
// Count '=' at end
int pad = 0;
for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0; )
if (str.charAt(i) == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[str.charAt(s++)];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param str The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String str) {
// Check special case
int sLen = str.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[str.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[str.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = str.charAt(eIx) == '=' ? (str.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (str.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[str.charAt(sIx++)] << 18 | IA[str.charAt(sIx++)] << 12 | IA[str.charAt(sIx++)] << 6 | IA[str.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[str.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
}

@ -0,0 +1,114 @@
package ${basePackage}.frame.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* ClassUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ClassUtil {
/**
*
*
* @param clazz
* @param parentFirst
* @return
*/
public static Field[] getFields(Class clazz, boolean parentFirst) {
Field[] fields = clazz.getDeclaredFields();
if (parentFirst) {
Field[] parentFields = getParentFields(clazz.getSuperclass());
return concat(fields, parentFields);
}
return fields;
}
/**
*
*
* @param clazz
* @return
*/
public static boolean isCollection(Class<?> clazz) {
return Collection.class.isAssignableFrom(clazz);
}
/**
* GET
*
* @param name
* @param pojoClass POJO
* @return
*/
public static Method getMethod(String name, Class<?> pojoClass) throws RuntimeException {
String getMethodName = "get" + StringUtil.upperFirstWord(name);
try {
return pojoClass.getMethod(getMethodName);
} catch (Exception e) {
getMethodName = "is" + StringUtil.upperFirstWord(name);
try {
return pojoClass.getMethod(getMethodName);
} catch (NoSuchMethodException e1) {
throw new RuntimeException("can not find[" + name + "]method");
}
}
}
/**
* SET
*
* @param name
* @param pojoClass POJO
* @return
*/
public static Method setMethod(String name, Class<?> pojoClass, Class<?> type) {
String setMethodName = "set" + StringUtil.upperFirstWord(name);
try {
return pojoClass.getMethod(setMethodName, type);
} catch (Exception e) {
return null;
}
}
public static boolean isJavaClass(Field field) {
Class<?> fieldType = field.getType();
boolean isBaseClass = false;
if (fieldType.isArray()) {
isBaseClass = false;
} else if (fieldType.isPrimitive() || fieldType.getPackage() == null
|| fieldType.getPackage().getName().equals("java.lang")
|| fieldType.getPackage().getName().equals("java.math")
|| fieldType.getPackage().getName().equals("java.sql")
|| fieldType.getPackage().getName().equals("java.util")) {
isBaseClass = true;
}
return isBaseClass;
}
public static Field[] getFields(Class clazz) {
return getFields(clazz, false);
}
private static Field[] getParentFields(Class parentClazz) {
if (parentClazz != null) {
Field[] fields = parentClazz.getDeclaredFields();
Field[] parentFields = getParentFields(parentClazz.getSuperclass());
return concat(fields, parentFields);
}
return new Field[0];
}
private static Field[] concat(Field[] f1, Field[] f2) {
Field[] fields = new Field[f1.length + f2.length];
System.arraycopy(f1, 0, fields, 0, f1.length);
System.arraycopy(f2, 0, fields, f1.length, f2.length);
return fields;
}
}

@ -0,0 +1,67 @@
package ${basePackage}.frame.utils;
import ${basePackage}.frame.auth.LocalData;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* CookieUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class CookieUtil {
/**
* Cookies
*
* @param cookies Cookies
* @return passportID
*/
public static String getCookieValue(Cookie[] cookies, String key) {
if (cookies != null) {
for (Cookie cookie : cookies) {
// Cookie中存放的为passport的id Cookie名称通过ConfigToolObject获取
if (cookie != null && cookie.getName().equals(key)) {
try {
return cookie.getValue();
} catch (Exception ignored) {
}
}
}
}
return null;
}
/**
* Cookie
*
* @param name
* @param value
*/
public static Cookie newCookie(String name, String value) {
HttpServletRequest request = LocalData.getRequest();
Cookie cookie = new Cookie(name, value);
cookie.setDomain(request.getServerName());
cookie.setMaxAge(-1);
cookie.setPath("/");
return cookie;
}
/**
* Cookie
*
* @param name
*/
public static void clearCookie(String name) {
HttpServletRequest request = LocalData.getRequest();
HttpServletResponse response = LocalData.getResponse();
Cookie cookie = new Cookie(name, null);
cookie.setDomain(request.getServerName());
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
}

@ -0,0 +1,242 @@
package ${basePackage}.frame.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
public static List<String> readFile2Lines(String fileName) {
List<String> returnString = new ArrayList<String>();
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
returnString.add(tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return returnString;
}
public static String readFileToString(File file) throws IOException {
byte[] bytes = readFileToByteArray(file);
return new String(bytes, "UTF-8");
}
public static byte[] readFileToByteArray(File file) throws IOException {
InputStream in = openInputStream(file);
Throwable var2 = null;
byte[] var5;
try {
long fileLength = file.length();
var5 = fileLength > 0L ? toByteArray(in, fileLength) : toByteArray(in);
} catch (Throwable var14) {
var2 = var14;
throw var14;
} finally {
if (in != null) {
if (var2 != null) {
try {
in.close();
} catch (Throwable var13) {
var2.addSuppressed(var13);
}
} else {
in.close();
}
}
}
return var5;
}
public static FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
} else if (!file.canRead()) {
throw new IOException("File '" + file + "' cannot be read");
} else {
return new FileInputStream(file);
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
}
public static byte[] toByteArray(InputStream input, long size) throws IOException {
if (size > 2147483647L) {
throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size);
} else {
return toByteArray(input, (int) size);
}
}
public static byte[] toByteArray(InputStream input, int size) throws IOException {
if (size < 0) {
throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
} else if (size == 0) {
return new byte[0];
} else {
byte[] data = new byte[size];
int offset;
int read;
for (offset = 0; offset < size && (read = input.read(data, offset, size - offset)) != -1; offset += read) {
;
}
if (offset != size) {
throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
} else {
return data;
}
}
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Throwable var2 = null;
byte[] var3;
try {
copy((InputStream) input, (OutputStream) output);
var3 = output.toByteArray();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (output != null) {
if (var2 != null) {
try {
output.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
output.close();
}
}
}
return var3;
}
public static int copy(InputStream input, OutputStream output) throws IOException {
long count = copyLarge(input, output);
return count > 2147483647L ? -1 : (int) count;
}
public static boolean copy(File in, File out) throws Exception {
try {
FileInputStream input = new FileInputStream(in);
FileOutputStream output = new FileOutputStream(out);
copy(input, output);
input.close();
output.close();
return true;
} catch (IOException ie) {
return false;
}
}
public static long copyLarge(InputStream input, OutputStream output) throws IOException {
return copy(input, output, 4096);
}
public static long copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
return copyLarge(input, output, new byte[bufferSize]);
}
public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
long count;
int n;
for (count = 0L; -1 != (n = input.read(buffer)); count += (long) n) {
output.write(buffer, 0, n);
}
return count;
}
public static boolean clearDirectory(File dir) {
if ((dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " + dir +
" is not a directory. ");
}
File[] entries = dir.listFiles();
int sz = entries.length;
for (int i = 0; i < sz; i++) {
if (entries[i].isDirectory()) {
if (!clearDirectory(entries[i])) {
return false;
}
} else {
if (!entries[i].delete()) {
return false;
}
}
}
if (!dir.delete()) {
return false;
}
return true;
}
/**
* DOS/WindowsUNIX/Linux
* "\"全部换为"/"便
* "/""\"DOS/Windows
*/
public static String toUNIXpath(String filePath) {
return filePath.replace('\\', '/');
}
public static void inputStream2File(InputStream is, File target) {
try {
if (!target.exists() && !target.createNewFile()) {
throw new RuntimeException(target.getName() + "not exists");
}
OutputStream outStream = new FileOutputStream(target);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,75 @@
package ${basePackage}.frame.utils;
import java.util.UUID;
/**
* IDgenerator - ID
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class IDgenerator {
private static long workerId = 1L;
private static long datacenterId = 1L;
private static long sequence = 0L;
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private static long twepoch = 1531130104852L;
// 机器标识位数
private static long workerIdBits = 2L;//分布应用可设置为5这里减少占位增加可支持时间
// 数据中心标识位数
private static long datacenterIdBits = 2L;//分布应用可设置为5这里减少占位增加可支持时间
// 机器ID最大值
private static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private static long sequenceBits = 12L;
// 机器ID偏左移12位
private static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static long sequenceMask = -1L ^ (-1L << sequenceBits);
// 上次生产id时间戳
private static long lastTimestamp = -1L;
public static synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
}
protected static long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected static long timeGen() {
return System.currentTimeMillis();
}
public static String nextUUID() {
return UUID.randomUUID().toString();
}
}

@ -0,0 +1,70 @@
package ${basePackage}.frame.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LogUtil -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class LogUtil {
//定义一个全局的记录器通过LoggerFactory获取
private final static Logger logger = LoggerFactory.getLogger(LogUtil.class);
/**
* info
* @param context
*/
public static void i(String context){
logger.info(context);
}
/**
* debug
* @param context
*/
public static void d(String context){
logger.debug(context);
}
/**
* warn
* @param context
*/
public static void w(String context){
logger.warn(context);
}
/**
* error
* @param context
*/
public static void e(String context){
logger.error(context);
}
/**
*
*/
public static void dumpException(Throwable e){
StringBuffer msg = new StringBuffer("null");
if (e != null) {
msg = new StringBuffer("");
String message = e.toString();
int length = e.getStackTrace().length;
if (length > 0) {
msg.append(message).append("\n");
for (int i = 0; i < length; i++) {
msg.append("\t").append(e.getStackTrace()[i]).append("\n");
}
} else {
msg.append(message);
}
}
logger.error(msg.toString());
}
}

@ -0,0 +1,91 @@
package ${basePackage}.frame.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5Util - MD5
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class MD5Util {
/**
*
*
* @param value
* @param salts
* @return
*/
public static String generatePwd(String value, String... salts) {
String pwd = encode(value);
for (String s : salts) {
pwd = encode(s + value + s);
}
return pwd;
}
/**
*
*
* @param value
* @return
*/
public static String generatePwd(String value) {
return generatePwd(value, "MD5");
}
/**
*
*
* @param value
* @return Hex
*/
public static String encode(String value) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] e = md.digest(value.getBytes());
return toHexString(e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return value;
}
}
/**
*
*
* @param bytes
* @return Hex
*/
public static String encode(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] e = md.digest(bytes);
return toHexString(e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
/**
* @param bytes
* @return Hex
*/
private static String toHexString(byte bytes[]) {
StringBuilder hs = new StringBuilder();
String stmp = "";
for (int n = 0; n < bytes.length; n++) {
stmp = Integer.toHexString(bytes[n] & 0xff);
if (stmp.length() == 1)
hs.append("0").append(stmp);
else
hs.append(stmp);
}
return hs.toString();
}
}

@ -0,0 +1,147 @@
package ${basePackage}.frame.utils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
*
* <p>
* : 使
* <dependency>
* <groupId>javax.mail</groupId>
* <artifactId>mail</artifactId>
* <version>1.4.7</version>
* </dependency>
* <p>
* : JavaMailSenderSpringboot
* JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
* javaMailSender.setDefaultEncoding(UTF-8);
* javaMailSender.setHost(smtp.example.com);
* javaMailSender.setUsername(**@example.com);
* javaMailSender.setPassword(******);
* javaMailSender.setPort(25);
* <p>
*
* MailUtil.sendSimpleMail(javaMailSender, username, "**@example.com", "标题", "内容");
* <p>
* HTML
* String html = "<html><body><h2>HTML邮件内容</h2><br><marquee>飞机飞走了.。。o O 0 ○~~~~~~~</marquee></body></html>";
* MailUtil.sendHtmlMail(javaMailSender, username, "**@example.com", "给你的", html);
* <p>
*
* MailUtil.sendAttachmentsMail(javaMailSender, username, "**@example.com", "给你的", html, "E:\\1.jpg");
* <p>
* HTML<img>
* String resId = "id_001";
* String html2 = "<html><body><h2>html邮件内容</h2><br><img src=\'cid:" + resId + "\'></img></body></html>";
* MailUtil.sendInlineResourceMail(javaMailSender, username, "**@example.com", "标题", html2, "E:\\1.jpg", resId);
*/
public class MailUtil {
/**
*
*
* @param sender
* @param from
* @param to
* @param subject
* @param content
*/
public static void sendSimpleMail(JavaMailSender sender, String from, String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(from);
sender.send(message);
}
/**
* HTML
*
* @param sender
* @param from
* @param to
* @param subject
* @param content
*/
public static void sendHtmlMail(JavaMailSender sender, String from, String to, String subject, String content) {
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setFrom(from);
helper.setSubject(subject);
helper.setText(content, true);
sender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
*
*
* @param sender
* @param from
* @param to
* @param subject
* @param content
* @param filePath
*/
public static void sendAttachmentsMail(JavaMailSender sender, String from, String to, String subject, String content, String filePath) {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setFrom(from);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
//此处可以添加多个附件
helper.addAttachment(fileName, file);
sender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
*
*
* @param sender
* @param from
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId ID
*/
public static void sendInlineResourceMail(JavaMailSender sender, String from, String to, String subject, String content, String rscPath, String rscId) {
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setFrom(from);
helper.setSubject(subject);
helper.setText(content, true);
//可以添加多个图片
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
sender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,145 @@
package ${basePackage}.frame.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import ${basePackage}.frame.auth.LocalData;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* MapUtil -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class MapperUtil {
private static ObjectMapper om;
private static Mapper mapper;
static {
try {// 优先获取SpringBoot默认配置
om = LocalData.getBean(ObjectMapper.class);
} catch (Exception e) {
e.printStackTrace();
}
if (null == om) {
//初始化
om = new ObjectMapper();
// 日期格式化
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//序列化时忽略null属性
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//序列化时排序
om.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
//反序列化是忽略多余字段
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//支持空类序列化时出错InvalidDefinitionException
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
mapper = new DozerBeanMapper();
}
public static TreeNode toTree(String json) {
try {
return om.readTree(json);
} catch (IOException e) {
e.printStackTrace();
return om.createObjectNode();
}
}
public static TreeNode toTree(Object json) {
return om.valueToTree(json);
}
public static String toJson(Object object) {
return toJson(object, false);
}
public static String toJson(Object object, boolean pretty) {
try {
if (pretty) {
return om.writerWithDefaultPrettyPrinter().writeValueAsString(object);
} else {
return om.writeValueAsString(object);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
return "{}";
}
}
public static String toJson(JsonNode jsonNode) {
return jsonNode.asText();
}
public static <T> T toJava(String json, Class<T> cls) {
try {
if (json == null || "".equals(json)) {
return cls.newInstance();
}
return om.readValue(json, cls);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
public static <T> T toJava(TreeNode treeNode, Class<T> cls) {
try {
return om.treeToValue(treeNode, cls);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static <T> T toJava(String json, TypeReference<T> valueTypeRef) {
try {
return om.readValue(json, valueTypeRef);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> List<T> toJavaList(String json, TypeReference<List<T>> reference) {
try {
return om.readValue(json, reference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> List<T> toJavaList(InputStream json, TypeReference<List<T>> reference) {
try {
return om.readValue(json, reference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T map(Object o, Class<T> aClass) {
return mapper.map(o, aClass);
}
public static void map(Object o, Object o1) {
mapper.map(o, o1);
}
}

@ -0,0 +1,20 @@
package ${basePackage}.frame.utils;
/**
* Message -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Message {
public static final String ERROR_500 = "服务器走了下神,稍后再试一次";
public static final String NOT_EXIST_METHOD = "调用的方法不存在";
public static String CREATE_FAILURE = "创建失败,请刷新后重新尝试";
public static String DELETE_FAILURE = "删除失败,请刷新后重新尝试";
public static String UPDATE_FAILURE = "更新失败,请刷新后重新尝试";
public static String FIND_FAILURE = "查询失败,请刷新后重新尝试";
public static String GET_FAILURE = "未获取相应内容";
public static String INSERT_DUPLICATE = "已经存在相同数据,返回列表页面确认";
}

@ -0,0 +1,117 @@
package ${basePackage}.frame.utils;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ProcessUtil {
/**
* windowsexe
* @param path exe
*/
public static void execExe(String path) {
Runtime rn = Runtime.getRuntime();
Process p = null;
try {
p = rn.exec(path);
} catch (Exception e) {
System.out.println("Error exec!");
}
}
/**
* windows
* @param path
*/
public static void execBat(String path) {
Runtime rn = Runtime.getRuntime();
Process p = null;
try {
p = rn.exec(path);
} catch (Exception e) {
System.out.println("Error exec!");
}
}
/**
* windows cmd
* @param command cmd
*/
public static String execCmd(String command) {
return exec("cmd /c " + command);
}
/**
*
* @param command cmd
*/
public static String exec(String command) {
StringBuilder build = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
build.append(line);
}
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return build.toString();
}
/**
* @throws IOException
* @desc
* @author zp
* @date 2018-3-29
*/
public static void killProc(String processName) throws IOException {
if (processName != null && !"".equals(processName)) {
execCmd("taskkill /F /IM " + processName);
}
}
/**
* @desc
* @author zp
* @date 2018-3-29
*/
public static boolean findProcess(String processName) {
BufferedReader bufferedReader = null;
try {
Process proc = Runtime.getRuntime().exec("tasklist -fi " + '"' + "imagename eq " + processName + '"');
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains(processName)) {
return true;
}
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
}
}
}

@ -0,0 +1,308 @@
package ${basePackage}.frame.utils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
/**
* RSAUtil - RSA
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class RSAUtil {
private static String cryptPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" +
"3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" +
"a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB";
private static String cryptPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" +
"DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" +
"RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" +
"gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" +
"CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" +
"6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" +
"r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" +
"+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" +
"1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" +
"M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" +
"UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" +
"3f3yq+a2OQ==";
private static String signPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" +
"3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" +
"a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB";
private static String signPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" +
"DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" +
"RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" +
"gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" +
"CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" +
"6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" +
"r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" +
"+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" +
"1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" +
"M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" +
"UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" +
"3f3yq+a2OQ==";
/**
*
*/
public static void createKey() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//公钥
RSAPublicKey aPublic = (RSAPublicKey) keyPair.getPublic();
//私钥
RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
//把密钥对象对应的字节转为Base64字符存储
System.err.println("publicKeyBase64-->" + Base64Util.encodeToString(aPublic.getEncoded()));
System.err.println("privateKeyBase64-->" + Base64Util.encodeToString(aPrivate.getEncoded()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static String encrypt2Base64(byte[] data) {
byte[] encrypt = encrypt(data);
return Base64Util.encodeToString(encrypt);
}
public static byte[] encrypt(String data) {
return encrypt(data.getBytes());
}
/**
*
*
* @param data
*/
public static byte[] encrypt(byte[] data) {
try {
//生成公钥对象
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Util.decode(cryptPublicKeyBase64));
PublicKey aPublic = keyFactory.generatePublic(x509EncodedKeySpec);
//分段加密开始
ByteArrayOutputStream bs = new ByteArrayOutputStream();
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, aPublic);
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 117, data.length)));
bs.write(bytes);
offset += 117;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
*/
public static byte[] encrypt(String data, PublicKey aPublic) {
try {
if (aPublic == null) {
System.err.println("PublicKey can not be null");
return null;
}
//分段加密开始
ByteArrayOutputStream bs = new ByteArrayOutputStream();
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, aPublic);
int offset = 0;
byte[] b = data.getBytes();
while (offset < b.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(b, offset, Math.min(offset + 117, b.length)));
bs.write(bytes);
offset += 117;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param base64String base64
* @return
*/
public static byte[] decrypt(String base64String) {
return decrypt(Base64Util.decode(base64String));
}
public static String decrypt2String(String base64String) {
byte[] decrypt = decrypt(Base64Util.decode(base64String));
try {
return new String(decrypt, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
*/
public static byte[] decrypt(byte[] data) {
try {
//生成私钥对象
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64Util.decode(cryptPrivateKeyBase64));
PrivateKey aPrivate = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, aPrivate);
//获得密文字节
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 128, data.length)));
bs.write(bytes);
offset += 128;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
* @param aPrivate
* @return
*/
public static byte[] decrypt(byte[] data, PublicKey aPrivate) {
try {
if (aPrivate == null) {
System.err.println("PublicKey can not be null");
return null;
}
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, aPrivate);
//获得密文字节
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 128, data.length)));
bs.write(bytes);
offset += 128;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String sign2Base64(byte[] data) {
return sign2Base64(data, signPrivateKeyBase64);
}
public static String sign2Base64(byte[] data, String privateKey) {
byte[] sign = sign(data, privateKey);
return Base64Util.encodeToString(sign);
}
/**
* RSA
*
* @param data
* @param privateKey
* @return
*/
public static byte[] sign(byte[] data, String privateKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
PrivateKey aPrivate = keyFactory.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(aPrivate);
signature.update(data);
return signature.sign();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA
*
* @param data
* @param sign base64
* @param publicKey
* @return
*/
public static boolean doCheck(byte[] data, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64Util.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(Base64Util.decode(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean doCheck(byte[] data, String sign) {
return doCheck(data, sign, signPublicKeyBase64);
}
public static PublicKey parsePublicKey(String cryptPublicKeyBase64) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Util.decode(cryptPublicKeyBase64));
return keyFactory.generatePublic(x509EncodedKeySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
public static PrivateKey parsePrivateKey(String cryptPrivateKeyBase64) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(cryptPrivateKeyBase64));
return keyFactory.generatePrivate(priPKCS8);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
}

@ -0,0 +1,79 @@
package ${basePackage}.frame.utils;
import javax.servlet.http.HttpServletRequest;
/**
* RequestUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class RequestUtil {
/**
* IP
*
* @param request
* @return
*/
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
/**
*
*
* @param request
* @return
*/
public static String getUserAgent(HttpServletRequest request) {
return request.getHeader("User-Agent");
}
/**
* URL
*
* @param request
* @return URL
*/
public static String getErrorUrl(HttpServletRequest request) {
if (request.getAttribute("javax.servlet.error.request_uri") != null) {
return (String) request.getAttribute("javax.servlet.error.request_uri");
} else {
return "";
}
}
}

@ -0,0 +1,144 @@
package ${basePackage}.frame.utils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Resource
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ResourceUtil extends ResourceUtils {
/**
* : /modules/dir/
*
* @param resourcePath
* @return
*/
public static List<String> getResourceFiles(String resourcePath) {
List<String> result = new ArrayList<>();
File applicationHome = getApplicationHome();
if (applicationHome.getAbsolutePath().endsWith(".jar")) {
try {
Pattern pattern = Pattern.compile(".*" + resourcePath + "(.+\\..+)");
JarFile jarFile = new JarFile(applicationHome);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.matches(".*" + resourcePath + "(.+\\..+)")) {
Matcher matcher = pattern.matcher(name);
if (matcher.find()) result.add(matcher.group(1));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
ClassPathResource cpr = new ClassPathResource(resourcePath);
File in = cpr.getFile();
for (File file : in.listFiles()) {
result.add(file.getName());
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* jar
*
* @return jar
*/
public static File getApplicationHome() {
ApplicationHome home = new ApplicationHome(ResourceUtil.class);
return home.getSource();
}
/**
* resource
*
* @return
*/
public static InputStream getResourceInput(String resource) {
try {
ClassPathResource classPathResource = new ClassPathResource(resource);
return classPathResource.getInputStream();
} catch (IOException e) {
return null;
}
}
/**
* jar
*
* @return
*/
public static boolean copyResource2File(String resource, File file) {
InputStream resourceInput = getResourceInput(resource);
FileOutputStream fileOutputStream = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
FileUtil.copy(resourceInput, fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fileOutputStream != null) fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
*
* @return
*/
public static byte[] getResourceBytes(String resource) {
InputStream is = null;
byte[] result = null;
try {
is = getResourceInput(resource);
result = new byte[is.available()];
is.read(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}

@ -0,0 +1,42 @@
package ${basePackage}.frame.utils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import ${basePackage}.frame.excel.WExcel;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* ResponseUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ResponseUtil {
/**
* ResponseEntity
*
* @param bytes
* @param fileName
* @return
*/
public static ResponseEntity<byte[]> apply(byte[] bytes, String fileName) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "utf-8"));
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (UnsupportedEncodingException e) {
return null;
}
}
public static ResponseEntity<byte[]> apply(WExcel sheet) {
return apply(sheet.getBytes(), sheet.getName() + ".xlsx");
}
}

@ -0,0 +1,87 @@
package ${basePackage}.frame.utils;
public class StringUtil {
public static int getByteLength(String str) {
int length = str.replaceAll("[^\\x00-\\xff]", "**").length();
return length;
}
public static String upperFirstWord(String str) {
String temp = str.substring(0, 1);
return temp.toUpperCase() + str.substring(1);
}
public static boolean isEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(value.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotEmpty(String value) {
return !isEmpty(value);
}
/**
* ,
*/
public static boolean isNumeric(Object obj) {
if (obj == null) {
return false;
}
char[] chars = obj.toString().toCharArray();
int length = chars.length;
if (length < 1)
return false;
int i = 0;
if (length > 1 && chars[0] == '-')
i = 1;
for (; i < length; i++) {
if (!Character.isDigit(chars[i])) {
return false;
}
}
return true;
}
/**
*
*/
public static String unicodeToChinese(String unicode) {
StringBuilder out = new StringBuilder();
if (!isEmpty(unicode)) {
for (int i = 0; i < unicode.length(); i++) {
out.append(unicode.charAt(i));
}
}
return out.toString();
}
public static String toUnderlineStyle(String name) {
StringBuilder newName = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (Character.isUpperCase(c)) {
if (i > 0) {
newName.append("_");
}
newName.append(Character.toLowerCase(c));
} else {
newName.append(c);
}
}
return newName.toString();
}
}

@ -0,0 +1,41 @@
package ${basePackage}.frame.utils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* Url
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Component
public class UrlUtil {
public String getUrl(String url) {
if (url == null) {
return "";
}
if (!url.startsWith("/")) {
return "/" + url;
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 协议
String scheme = request.getScheme();
// 域名
String serverName = request.getServerName();
// 端口
int serverPort = request.getServerPort();
// 上下文路径
String context = request.getContextPath();
return String.format(Locale.CHINA, "%s://%s:%d%s%s", scheme, serverName, serverPort, context, url);
}
}

@ -0,0 +1,72 @@
package ${basePackage}.frame.utils;
import ${basePackage}.frame.base.BaseRequest;
import ${basePackage}.frame.base.BaseResponse;
import ${basePackage}.frame.base.ErrorType;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ValidationUtil {
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
public static <T extends BaseResponse> T validate(BaseRequest req, T response) {
if (req == null) {
response.addError(ErrorType.EXPECTATION_NULL, "请求对象不能为空");
return response;
}
try {
Validator validator = factory.getValidator();
Set<ConstraintViolation<BaseRequest>> constraintViolations = validator.validate(req);
if (constraintViolations.size() > 0) {
for (ConstraintViolation<BaseRequest> violation : constraintViolations) {
response.addError(ErrorType.INVALID_PARAMETER, violation.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.dumpException(e);
response.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
}
return response;
}
public static List<String> validate(Object req) {
List<String> validResult = new ArrayList<>();
if (req == null) {
validResult.add("当前数据为空");
return validResult;
}
try {
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(req);
if (constraintViolations.size() > 0) {
for (ConstraintViolation<Object> violation : constraintViolations) {
validResult.add(violation.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
validResult.add("数据检查错误");
}
return validResult;
}
}

@ -0,0 +1,459 @@
package ${basePackage}.frame.utils;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* WebUtils - http访
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WebUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET";
//private static final Certificate verisign; //
private static boolean ignoreSSLCheck; // 忽略SSL检查
private static class TrustAllTrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
private WebUtils() {
}
public static void setIgnoreSSLCheck(boolean ignoreSSLCheck) {
WebUtils.ignoreSSLCheck = ignoreSSLCheck;
}
/**
* HTTP POST
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) throws IOException {
return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
}
/**
* HTTP POST
*
* @param url
* @param params
* @param charset UTF-8, GBK, GB2312
* @return
*/
public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout) throws IOException {
return doPost(url, params, charset, connectTimeout, readTimeout, null);
}
public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout, Map<String, String> headerMap) throws IOException {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap);
}
/**
* HTTP POST
*
* @param url
* @param ctype
* @param content
* @return
*/
public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException {
return _doPost(url, ctype, content, connectTimeout, readTimeout, null);
}
private static String _doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
try {
conn = getConnection(new URL(url), METHOD_POST, ctype, headerMap);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
} catch (IOException e) {
throw e;
}
try {
out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
} catch (IOException e) {
throw e;
}
} finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException {
StringBuilder entry = new StringBuilder();
entry.append("Content-Disposition:form-data;name=\"");
entry.append(fieldName);
entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
entry.append(fieldValue);
return entry.toString().getBytes(charset);
}
private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException {
StringBuilder entry = new StringBuilder();
entry.append("Content-Disposition:form-data;name=\"");
entry.append(fieldName);
entry.append("\";filename=\"");
entry.append(fileName);
entry.append("\"\r\nContent-Type:");
entry.append(mimeType);
entry.append("\r\n\r\n");
return entry.toString().getBytes(charset);
}
/**
* HTTP GET
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, String> params) throws IOException {
return doGet(url, params, DEFAULT_CHARSET);
}
/**
* HTTP GET
*
* @param url
* @param params
* @param charset UTF-8, GBK, GB2312
* @return
*/
public static String doGet(String url, Map<String, String> params, String charset) throws IOException {
HttpURLConnection conn = null;
String rsp = null;
try {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
try {
conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype, null);
} catch (IOException e) {
throw e;
}
try {
rsp = getResponseAsString(conn);
} catch (IOException e) {
throw e;
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection connHttps = (HttpsURLConnection) conn;
if (ignoreSSLCheck) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
throw new IOException(e);
}
} else {
try {
//SSLContext ctx = SSLContext.getInstance("TLS");
//ctx.init(null, new TrustManager[] { new VerisignTrustManager() }, new SecureRandom());
//connHttps.setSSLSocketFactory(ctx.getSocketFactory());
} catch (Exception e) {
throw new IOException(e);
}
}
conn = connHttps;
}
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "text/xml,text/javascript");
conn.setRequestProperty("User-Agent", "top-sdk-java");
conn.setRequestProperty("Content-Type", ctype);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return conn;
}
private static URL buildGetUrl(String strUrl, String query) throws IOException {
URL url = new URL(strUrl);
if (isEmpty(query)) {
return url;
}
if (isEmpty(url.getQuery())) {
if (strUrl.endsWith("?")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "?" + query;
}
} else {
if (strUrl.endsWith("&")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "&" + query;
}
}
return new URL(strUrl);
}
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
boolean hasParam = false;
for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
// 忽略参数名或参数值为空的参数
if (areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
}
public static boolean isEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(value.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
*
*/
public static boolean areNotEmpty(String... values) {
boolean result = true;
if (values == null || values.length == 0) {
result = false;
} else {
for (String value : values) {
result &= !isEmpty(value);
}
}
return result;
}
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
Reader reader = new InputStreamReader(stream, charset);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET;
if (!isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!isEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
/**
* 使UTF-8
*
* @param value
* @return
*/
public static String decode(String value) {
return decode(value, DEFAULT_CHARSET);
}
/**
* 使UTF-8
*
* @param value
* @return
*/
public static String encode(String value) {
return encode(value, DEFAULT_CHARSET);
}
/**
* 使
*
* @param value
* @param charset
* @return
*/
public static String decode(String value, String charset) {
String result = null;
if (!isEmpty(value)) {
try {
result = URLDecoder.decode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* 使
*
* @param value
* @param charset
* @return
*/
public static String encode(String value, String charset) {
String result = null;
if (!isEmpty(value)) {
try {
result = URLEncoder.encode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
private static Map<String, String> getParamsFromUrl(String url) {
Map<String, String> map = null;
if (url != null && url.indexOf('?') != -1) {
map = splitUrlQuery(url.substring(url.indexOf('?') + 1));
}
if (map == null) {
map = new HashMap<String, String>();
}
return map;
}
/**
* URL
*
* @param query URL
* @return
*/
public static Map<String, String> splitUrlQuery(String query) {
Map<String, String> result = new HashMap<String, String>();
String[] pairs = query.split("&");
if (pairs != null && pairs.length > 0) {
for (String pair : pairs) {
String[] param = pair.split("=", 2);
if (param != null && param.length == 2) {
result.put(param[0], param[1]);
}
}
}
return result;
}
}

@ -0,0 +1,145 @@
package ${basePackage}.frame.utils;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* ZipUtil - Zip
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ZipUtil {
/**
*
*
* @param zipFile Zip
* @param descDir
*/
public static void unZip(File zipFile, File descDir) {
if (!descDir.exists()) {
descDir.mkdirs();
}
ZipFile zip = null;
try {
zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
File dir = new File(descDir, entry.getName());
dir.mkdirs();
} else {
// 如果是文件就先创建一个文件然后用io流把内容copy过去
File targetFile = new File(descDir + "/" + entry.getName());
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zip.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
System.out.println("解压文件" + zipFile.getAbsolutePath() + "成功");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtil", e);
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
*
* @param src
* @param zip Zip
*/
public static void toZip(File src, File zip) {
ZipOutputStream zipOutputStream = null;
try {
if (!src.exists()) {
System.err.println("压缩文件或目录不存在");
return;
}
if (!zip.exists()) {
zip.createNewFile();
}
zipOutputStream = new ZipOutputStream(new FileOutputStream(zip));
compress(src, zipOutputStream, null);
zipOutputStream.close();
System.out.println("压缩文件" + zip.getAbsolutePath() + "成功");
} catch (IOException e) {
System.err.println("压缩失败");
e.printStackTrace();
} finally {
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param sourceFile
* @param zos Zip
* @param parentPath
* @throws IOException
*/
private static void compress(File sourceFile, ZipOutputStream zos, String parentPath) throws IOException {
byte[] buff = new byte[1024];
if (sourceFile.isDirectory()) {
//确保空文件夹也可以压缩进去
zos.putNextEntry(new ZipEntry((parentPath != null ? parentPath : "") + sourceFile.getName() + "/"));
zos.closeEntry();
//循环压缩子文件或文件夹
for (File file : sourceFile.listFiles()) {
compress(file, zos, (parentPath != null ? parentPath : "") + sourceFile.getName() + "/");
}
} else {
//压缩文件
zos.putNextEntry(new ZipEntry((parentPath != null ? parentPath : "") + sourceFile.getName()));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buff)) != -1) {
zos.write(buff, 0, len);
}
zos.closeEntry();
in.close();
}
}
public static void main(String[] args) {
//解压
unZip(new File("E:\\AAA.zip"), new File("E:\\AAA"));
//压缩
toZip(new File("E:\\AAA"), new File("E:\\AAA.zip"));
}
}

@ -0,0 +1,18 @@
package ${basePackage}.frame.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DictValidator.class)
public @interface Dict {
String message() default "字典验证错误";
String name() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save

Powered by TurnKey Linux.