From 1d87d635003a6dcf4308162dac081de61279248c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8A=E5=B1=B1=E6=89=93=E8=80=81=E8=99=8E?= <251878350@qq.com> Date: Mon, 9 Sep 2019 16:27:56 +0800 Subject: [PATCH 01/46] =?UTF-8?q?=20=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=95=B0=E6=8D=AE=E5=BA=93=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=AD=97=E5=85=B8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E4=B8=8D=E5=90=8C=E7=9A=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=EF=BC=8C=E5=BE=97=E5=88=B0=E8=AF=A5=E5=BA=93=E7=9B=B8?= =?UTF-8?q?=E5=BA=94=E7=9A=84=E6=89=80=E6=9C=89=E8=A1=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=88=97=E8=A1=A8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?PDF=E6=96=87=E4=BB=B6=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 84b3d92..9f4006b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ #### 介绍 鉴于企业开发过程中数据字典难维护,我们团队参考阿里云数据库管理中的数据字典展示,进行了一个克隆。当前 3.0 版本支持 MySQL SQLSERVER ORACLE DB2 PG 数据库的数据字典生成,关联您的数据库后,可以自动生成 PDF和markdown 文件格式的数据字典文档,也可以直接运行项目支持在线 -同步数据库数据字典。 +同步数据库数据字典,支持在线选择不同的数据库,得到该库相应的所有表信息列表,支持在线PDF文件下载。 码云下载地址:https://gitee.com/cdtrh_group/database-dictionary 官方QQ群:256612400 #### 使用说明 @@ -13,6 +13,8 @@ PDF格式数据字典效果展示如下: 在线markdown展示效果如下: ![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112014_0b8fa0f0_1447662.png "WEB.png") ![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112029_5a4ac06f_1447662.png "web2.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/162454_a496b28b_1447662.png "v4.png") ![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112039_0ac187ce_1447662.png "web3.png") ![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112048_4bc293df_1447662.png "web4.png") + -- Gitee From e5d1dfe866d2c082dd920a126286353162ba6e4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8A=E5=B1=B1=E6=89=93=E8=80=81=E8=99=8E?= <251878350@qq.com> Date: Mon, 9 Sep 2019 16:41:02 +0800 Subject: [PATCH 02/46] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=95=B0=E6=8D=AE=E5=BA=93=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=AD=97=E5=85=B8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E4=B8=8D=E5=90=8C=E7=9A=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=EF=BC=8C=E5=BE=97=E5=88=B0=E8=AF=A5=E5=BA=93=E7=9B=B8?= =?UTF-8?q?=E5=BA=94=E7=9A=84=E6=89=80=E6=9C=89=E8=A1=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=88=97=E8=A1=A8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?PDF=E6=96=87=E4=BB=B6=E4=B8=8B=E8=BD=BD=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f4006b..c7c3c76 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # database-dictionary #### 介绍 -鉴于企业开发过程中数据字典难维护,我们团队参考阿里云数据库管理中的数据字典展示,进行了一个克隆。当前 3.0 版本支持 MySQL SQLSERVER ORACLE DB2 PG 数据库的数据字典生成,关联您的数据库后,可以自动生成 PDF和markdown 文件格式的数据字典文档,也可以直接运行项目支持在线 +鉴于企业开发过程中数据字典难维护,我们团队参考阿里云数据库管理中的数据字典展示,进行了一个克隆。当前 4.0 版本支持 MySQL SQLSERVER ORACLE DB2 PG 数据库的数据字典生成,关联您的数据库后,可以自动生成 PDF和markdown 文件格式的数据字典文档,也可以直接运行项目支持在线 同步数据库数据字典,支持在线选择不同的数据库,得到该库相应的所有表信息列表,支持在线PDF文件下载。 码云下载地址:https://gitee.com/cdtrh_group/database-dictionary 官方QQ群:256612400 -- Gitee From 69ac499922addc285256ab66bf4efde35118e06a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8A=E5=B1=B1=E6=89=93=E8=80=81=E8=99=8E?= <251878350@qq.com> Date: Mon, 9 Sep 2019 17:00:12 +0800 Subject: [PATCH 03/46] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=95=B0=E6=8D=AE=E5=BA=93=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=AD=97=E5=85=B8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E4=B8=8D=E5=90=8C=E7=9A=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=EF=BC=8C=E5=BE=97=E5=88=B0=E8=AF=A5=E5=BA=93=E7=9B=B8?= =?UTF-8?q?=E5=BA=94=E7=9A=84=E6=89=80=E6=9C=89=E8=A1=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=88=97=E8=A1=A8=EF=BC=8C=E6=94=AF=E6=8C=81=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?PDF=E6=96=87=E4=BB=B6=E4=B8=8B=E8=BD=BD=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c7c3c76..eb2c7e0 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ #### 使用说明 在项目的单元测试用例中,有相关数据库的DEMO。 PDF格式数据字典效果展示如下: -![输入图片说明](https://images.gitee.com/uploads/images/2019/0905/144050_91051c40_1447662.png "PDF2.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165825_17d123d2_1447662.png "PDF2.png") 直接运行 DataBaseApplication 开启springboot web 启动成功后,访问:http://127.0.0.1:9998/ 就可以进入首页了 在线markdown展示效果如下: -![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112014_0b8fa0f0_1447662.png "WEB.png") -![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112029_5a4ac06f_1447662.png "web2.png") -![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/162454_a496b28b_1447662.png "v4.png") -![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112039_0ac187ce_1447662.png "web3.png") -![输入图片说明](https://images.gitee.com/uploads/images/2019/0906/112048_4bc293df_1447662.png "web4.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165854_e0c42eb6_1447662.png "WEB.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165904_b0614670_1447662.png "web2.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165915_f047f1b8_1447662.png "v4.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165926_da6ce172_1447662.png "web3.png") +![输入图片说明](https://images.gitee.com/uploads/images/2019/0909/165938_a32c886e_1447662.png "web4.png") -- Gitee From 0287ef735985e1869140bb94c624d9c95247a12f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 00:37:12 +0800 Subject: [PATCH 04/46] =?UTF-8?q?SpringBoot=20=E5=8D=87=E7=BA=A7=E5=88=B0?= =?UTF-8?q?=202.1.8.RELEASE=20=E7=89=88=E6=9C=AC=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E4=B8=94=E6=B7=BB=E5=8A=A0=E4=B8=80=E4=BA=9B=E5=90=8E=E7=BB=AD?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E7=9A=84=E4=BE=9D=E8=B5=96=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 19 ++++++++++++++++++- src/main/resources/application.properties | 8 +++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fc34542..44bb99a 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.4.RELEASE + 2.1.8.RELEASE @@ -62,6 +62,11 @@ + + com.h2database + h2 + runtime + com.microsoft.sqlserver mssql-jdbc @@ -109,6 +114,18 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-freemarker + + + org.springframework.boot + spring-boot-starter-jdbc + com.trh.dictionary db2jcc-db2jcc4 diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e57df52..ca71cc1 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,2 +1,8 @@ server.port=9998 -thymeleaf.prefix.classpath = /templates/ \ No newline at end of file +thymeleaf.prefix.classpath=/templates/ + +spring.datasource.type=com.zaxxer.hikari.HikariDataSource +spring.datasource.url=jdbc:h2:mem: +spring.datasource.username=root +spring.datasource.password=123456 +spring.jpa.database=h2 \ No newline at end of file -- Gitee From b151d5532f98415a6c76757c09bd87c8251596ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 00:39:12 +0800 Subject: [PATCH 05/46] =?UTF-8?q?MySQL=20JDBC=E9=A9=B1=E5=8A=A8=E5=8D=87?= =?UTF-8?q?=E7=BA=A7=E5=88=B08.0,=E5=B9=B6=E4=B8=94=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=9C=A8=E8=BF=9E=E6=8E=A5MySQL=208=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E7=9A=84=E6=97=B6=E5=80=99=E5=87=BA=E7=8E=B0=E7=9A=84=E6=8A=A5?= =?UTF-8?q?=E9=94=99=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../conterller/DatabaseController.java | 42 ++++++++++--------- .../trh/dictionary/dao/ConnectionFactory.java | 2 +- .../dictionary/service/db2/Db2Executor.java | 10 ++--- .../service/mysql/BuildMysqlPdf.java | 2 +- 5 files changed, 30 insertions(+), 28 deletions(-) diff --git a/pom.xml b/pom.xml index 44bb99a..2836e87 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ mysql mysql-connector-java - 5.1.6 + runtime diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index abcc06d..4b01a4e 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -16,9 +16,8 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import sun.security.util.AuthResources_zh_CN; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -43,7 +42,7 @@ public class DatabaseController { switch (selector) { case "mysql": //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC"; + String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; Connection connection = ConnectionFactory.getConnection(url, username, password, "mySql"); tableInfo = BuildPDF.getBuildPdfTableData(BuildPDF.getTables(connection, database)); break; @@ -62,7 +61,7 @@ public class DatabaseController { tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; } - if (tableInfo!=null){ + if (tableInfo != null) { if (tableInfo.size() == 0) { model.addAttribute("markdown", "## 数据库无数据"); return "markdown"; @@ -72,20 +71,20 @@ public class DatabaseController { model.addAttribute("markdown", markdown); return "markdown"; } catch (Exception e) { - logger.error("error==>"+e); - model.addAttribute("markdown", "### "+e.getMessage()); + logger.error("error==>" + e); + model.addAttribute("markdown", "### " + e.getMessage()); return "markdown"; } } @RequestMapping("/getDataBaseNameList") @ResponseBody - public List getDataBaseNmaeList(String selector,String ip, String port, String password, String username, String database){ + public List getDataBaseNmaeList(String selector, String ip, String port, String password, String username, String database) { List list = new ArrayList<>(); try { switch (selector) { case "mysql": - return BuildMysqlPdf.getDataBaseName(ip,database,port,username,password); + return BuildMysqlPdf.getDataBaseName(ip, database, port, username, password); case "oracle": list.add(database); return list; @@ -94,13 +93,13 @@ public class DatabaseController { return WriteSqlserverMarkDown.getDatabasesList(ip, database, port, username, password); case "PostgreSQL": - return BuildPgSqlPdf.getDataBaseName(ip,database,port,username,password); + return BuildPgSqlPdf.getDataBaseName(ip, database, port, username, password); case "DB2": - return Db2Executor.databases(SqlExecutor.newDB2Connection(ip,Integer.valueOf(port),database,username,password)); + return Db2Executor.databases(SqlExecutor.newDB2Connection(ip, Integer.valueOf(port), database, username, password)); } } catch (Exception e) { - logger.error("error==>"+e); + logger.error("error==>" + e); } return list; } @@ -113,7 +112,7 @@ public class DatabaseController { switch (selector) { case "mysql": //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC"; + String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; Connection connection = ConnectionFactory.getConnection(url, username, password, "mySql"); tableInfo = BuildPDF.getBuildPdfTableData(BuildPDF.getTables(connection, database)); break; @@ -123,12 +122,12 @@ public class DatabaseController { case "SQL server": return WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password); case "PostgreSQL": - return BuildPgSqlPdf.getPgMarkdown(ip, database, port, username, password); + return BuildPgSqlPdf.getPgMarkdown(ip, database, port, username, password); case "DB2": tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; } - if (tableInfo!=null){ + if (tableInfo != null) { if (tableInfo.size() == 0) { return "## 数据库无数据"; } @@ -138,21 +137,24 @@ public class DatabaseController { return markdown; } catch (Exception e) { - logger.error("error==>"+e); - return "### "+e.getMessage(); + logger.error("error==>" + e); + return "### " + e.getMessage(); } } @RequestMapping(value = "/download", method = RequestMethod.GET) public void testDownload(HttpServletResponse res, String selector, String ip, String port, String password, String username, String database) { //1.先生成pdf文件 - String filePath = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", "").replaceAll("target/test-classes/", ""); + String filePath = BuildPDF.class.getResource("/") + .getPath() + .replaceAll("target/classes/", "") + .replaceAll("target/test-classes/", ""); filePath += "src/main/resources/"; try { switch (selector) { case "mysql": //得到生成数据 - BuildPDF.MakePdf(ip, database, port, username, password,filePath,"DataBase"); + BuildPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); break; case "oracle": List tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); @@ -164,10 +166,10 @@ public class DatabaseController { BuildPDF.build(filePath, tableInfo, "DataBase"); break; case "SQL server": - BuildSqlserverPDF.MakePdf(ip, database, port, username, password,filePath,"DataBase"); + BuildSqlserverPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); break; case "PostgreSQL": - BuildPgSqlPdf.buildPdf(ip, database, port, username, password,filePath,"DataBase"); + BuildPgSqlPdf.buildPdf(ip, database, port, username, password, filePath, "DataBase"); break; case "DB2": List Db2tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database, username, password); diff --git a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java index 2fb4fc2..a802d6a 100644 --- a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java @@ -31,7 +31,7 @@ public class ConnectionFactory { Connection connection = null; //创建驱动 if (mySql.equals(driverName)) { - Class.forName("org.gjt.mm.mysql.Driver"); + Class.forName("com.mysql.cj.jdbc.Driver"); } else if (pgSql.equals(driverName)) { Class.forName("org.postgresql.Driver"); } diff --git a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java index 1138737..48e7d4a 100644 --- a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java +++ b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java @@ -1,13 +1,12 @@ package com.trh.dictionary.service.db2; -import com.mysql.jdbc.StringUtils; import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.dao.ConnectionFactory; import com.trh.dictionary.util.SqlExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; import java.sql.*; import java.util.ArrayList; @@ -66,7 +65,8 @@ public class Db2Executor { columnInfo.setName(rs.getString("COLNAME").trim()); columnInfo.setDescription(rs.getString("REMARKS").trim()); columnInfo.setIsNull(rs.getString("NULLS").trim()); - columnInfo.setDefaultValue(StringUtils.isNullOrEmpty(rs.getString("DEFAULT")) ? "" : rs.getString("DEFAULT").trim()); + columnInfo.setDefaultValue(StringUtils.isEmpty(rs.getString("DEFAULT")) ? "" : rs.getString("DEFAULT") + .trim()); columnInfo.setType(rs.getString("TYPENAME").trim() + "(" + rs.getString("LENGTH").trim() + ")"); columnInfo.setIsIndex(getTablePrimaryKey(connection, table, rs.getString("COLNAME").trim())); columns.add(columnInfo); @@ -196,7 +196,7 @@ public class Db2Executor { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); String remarks = rs.getString("REMARKS"); - if (StringUtils.isNullOrEmpty(tableName)) { + if (StringUtils.isEmpty(tableName)) { continue; } TableInfo tableInfo = new TableInfo(); @@ -226,7 +226,7 @@ public class Db2Executor { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String schema = rs.getString("SCHEMANAME"); - if (!StringUtils.isNullOrEmpty(schema)) { + if (!StringUtils.isEmpty(schema)) { schemas.add(schema); } } diff --git a/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java b/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java index baf54a1..e543f95 100644 --- a/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java +++ b/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java @@ -31,7 +31,7 @@ public class BuildMysqlPdf { */ public static List getDataBaseName(String ip, String dbName, String port, String userName, String passWord) { //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC"; + String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; try { Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "mySql"); Statement statement = connection.createStatement(); -- Gitee From ec8859a88ed16d0f000e3194abe2ede97d44cbc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 00:46:36 +0800 Subject: [PATCH 06/46] =?UTF-8?q?=E7=BB=99SpringBoot=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=9A=E6=95=B0=E6=8D=AE=E6=BA=90=E7=9A=84?= =?UTF-8?q?=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trh/dictionary/bean/ConnectionDTO.java | 84 ++++++++++++ .../config/DefaultDataSourceConfig.java | 46 +++++++ .../dictionary/config/DynamicDataSource.java | 108 +++++++++++++++ .../dictionary/config/FreemarkerConfig.java | 61 +++++++++ .../dictionary/config/SessionListener.java | 40 ++++++ .../dictionary/conterller/HomeController.java | 124 ++++++++++++++++++ .../trh/dictionary/enums/DatabaseType.java | 58 ++++++++ .../dictionary/service/DataSourceService.java | 61 +++++++++ .../service/DataSourceServiceImpl.java | 119 +++++++++++++++++ .../dictionary/util/ExceptionBiFunction.java | 19 +++ .../util/ExceptionNoneParamsFunction.java | 15 +++ .../com/trh/dictionary/util/JdbcUtils.java | 36 +++++ .../java/com/trh/dictionary/util/Keys.java | 10 ++ 13 files changed, 781 insertions(+) create mode 100644 src/main/java/com/trh/dictionary/bean/ConnectionDTO.java create mode 100644 src/main/java/com/trh/dictionary/config/DefaultDataSourceConfig.java create mode 100644 src/main/java/com/trh/dictionary/config/DynamicDataSource.java create mode 100644 src/main/java/com/trh/dictionary/config/FreemarkerConfig.java create mode 100644 src/main/java/com/trh/dictionary/config/SessionListener.java create mode 100644 src/main/java/com/trh/dictionary/conterller/HomeController.java create mode 100644 src/main/java/com/trh/dictionary/enums/DatabaseType.java create mode 100644 src/main/java/com/trh/dictionary/service/DataSourceService.java create mode 100644 src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java create mode 100644 src/main/java/com/trh/dictionary/util/ExceptionBiFunction.java create mode 100644 src/main/java/com/trh/dictionary/util/ExceptionNoneParamsFunction.java create mode 100644 src/main/java/com/trh/dictionary/util/JdbcUtils.java create mode 100644 src/main/java/com/trh/dictionary/util/Keys.java diff --git a/src/main/java/com/trh/dictionary/bean/ConnectionDTO.java b/src/main/java/com/trh/dictionary/bean/ConnectionDTO.java new file mode 100644 index 0000000..bc69972 --- /dev/null +++ b/src/main/java/com/trh/dictionary/bean/ConnectionDTO.java @@ -0,0 +1,84 @@ +package com.trh.dictionary.bean; + +import com.trh.dictionary.enums.DatabaseType; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @author HouKunLin + * @date 19-9-9 下午11:07 + */ +public class ConnectionDTO implements Serializable { + @NotBlank(message = "主机不能为空") + private String host; + @NotBlank(message = "端口不能为空") + private String port; + @NotBlank(message = "数据库名称不能为空") + private String database; + @NotBlank(message = "用户名不能为空") + private String username; + @NotBlank(message = "密码不能为空") + private String password; + private DatabaseType type; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getDatabase() { + return database; + } + + public void setDatabase(String database) { + this.database = database; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public DatabaseType getType() { + return type; + } + + public void setType(DatabaseType type) { + this.type = type; + } + + @Override + public String toString() { + return "ConnectionDTO{" + + "host='" + host + '\'' + + ", port='" + port + '\'' + + ", database='" + database + '\'' + + ", username='" + username + '\'' + + ", password='" + password + '\'' + + ", type='" + type + '\'' + + '}'; + } +} diff --git a/src/main/java/com/trh/dictionary/config/DefaultDataSourceConfig.java b/src/main/java/com/trh/dictionary/config/DefaultDataSourceConfig.java new file mode 100644 index 0000000..39c0159 --- /dev/null +++ b/src/main/java/com/trh/dictionary/config/DefaultDataSourceConfig.java @@ -0,0 +1,46 @@ +package com.trh.dictionary.config; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +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 javax.sql.DataSource; + +/** + * 默认数据源配置 + * + * @author HouKunLin + * @date 2019/9/10 0010 15:15 + */ +@Configuration +public class DefaultDataSourceConfig implements InitializingBean { + @Autowired + private DynamicDataSource dynamicDataSource; + + @Autowired + @Qualifier("defaultDataSource") + private DataSource dataSource; + + @Bean(name = "defaultDataSource") + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource defaultDataSource(DataSourceProperties properties) { + return DataSourceBuilder.create(properties.getClassLoader()) + .type(properties.getType()) + .url(properties.determineUrl()) + .username(properties.determineUsername()) + .password(properties.determinePassword()) + .driverClassName(properties.determineDriverClassName()) + .build(); + } + + @Override + public void afterPropertiesSet() throws Exception { + dynamicDataSource.setDefaultTargetDataSource(dataSource); + dynamicDataSource.afterPropertiesSet(); + } +} diff --git a/src/main/java/com/trh/dictionary/config/DynamicDataSource.java b/src/main/java/com/trh/dictionary/config/DynamicDataSource.java new file mode 100644 index 0000000..ec8508f --- /dev/null +++ b/src/main/java/com/trh/dictionary/config/DynamicDataSource.java @@ -0,0 +1,108 @@ +package com.trh.dictionary.config; + +import com.trh.dictionary.util.Keys; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpSession; +import javax.sql.DataSource; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * 动态数据源 + * + * @author HouKunLin + * @date 19-9-9 下午11:25 + */ +@Primary +@Component +public class DynamicDataSource extends AbstractRoutingDataSource { + + private Map targetDataSources = new LinkedHashMap<>(); + + @Autowired + private HttpSession session; + + @Override + protected String determineCurrentLookupKey() { + /* + 这里把当前的数据源信息存在了当前的请求会话里面,因此需要使用SESSION对象,当然也可以根据需要存在ThreadLocal当前线程里面 + 但是使用ThreadLocal当前线程需要自己去设置值 + */ + return String.valueOf(session.getAttribute(Keys.datasourcesKey)); + } + + @Override + protected DataSource determineTargetDataSource() { + Object o = session.getAttribute(Keys.datasources); + if (o instanceof DataSource) { + return (DataSource) o; + } + + return super.determineTargetDataSource(); + } + + /** + * 重写该方法,自己维护一个数据源的列表 + * + * @param targetDataSources 新的数据源列表 + */ + @Override + public void setTargetDataSources(Map targetDataSources) { + this.targetDataSources = targetDataSources; + afterPropertiesSet(); + } + + public Map getTargetDataSources() { + return targetDataSources; + } + + /** + * 这个方法必须重写,主要是为了初始化super.setTargetDataSources这个方法的值 + */ + @Override + public void afterPropertiesSet() { + super.setTargetDataSources(this.targetDataSources); + super.afterPropertiesSet(); + } + + public void put(Object key, DataSource value) { + if (key == null) { + return; + } + targetDataSources.put(key, value); + afterPropertiesSet(); + } + + public void putAll(Map map) { + if (map == null) { + return; + } + targetDataSources.putAll(map); + afterPropertiesSet(); + } + + public void remove(Object key) { + if (key == null) { + return; + } + targetDataSources.remove(key); + afterPropertiesSet(); + } + + public void remove(DataSource dataSource) { + Object removeKey = null; + Set> entries = targetDataSources.entrySet(); + for (Map.Entry entry : entries) { + if (entry.getValue() == dataSource) { + removeKey = entry.getKey(); + break; + } + } + remove(removeKey); + } +} diff --git a/src/main/java/com/trh/dictionary/config/FreemarkerConfig.java b/src/main/java/com/trh/dictionary/config/FreemarkerConfig.java new file mode 100644 index 0000000..1b5be25 --- /dev/null +++ b/src/main/java/com/trh/dictionary/config/FreemarkerConfig.java @@ -0,0 +1,61 @@ +package com.trh.dictionary.config; + +import com.trh.dictionary.enums.DatabaseType; +import freemarker.cache.MultiTemplateLoader; +import freemarker.cache.StringTemplateLoader; +import freemarker.cache.TemplateLoader; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextRefreshedEvent; + +/** + * 一些配置信息 + * + * @author HouKunLin + * @date 2019/9/10 0010 10:34 + */ +@Configuration +public class FreemarkerConfig implements ApplicationListener, InitializingBean { + + @Autowired + private freemarker.template.Configuration configuration; + + @Override + public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { + } + + /** + * 初始化FreeMarker框架的字符串渲染加载器(新增一个字符串模板加载器) + */ + public void initFreemarkerTemplateLoader() { + MultiTemplateLoader templateLoader = (MultiTemplateLoader) configuration.getTemplateLoader(); + int len = templateLoader.getTemplateLoaderCount(); + TemplateLoader[] arr = new TemplateLoader[len + 1]; + for (int i = 0; i < len; i++) { + arr[i] = templateLoader.getTemplateLoader(i); + } + arr[len] = stringTemplateLoader(); + + configuration.setTemplateLoader(new MultiTemplateLoader(arr)); + } + + /** + * 创建字符串模板加载器 + * + * @return 字符串模板加载器 + */ + public StringTemplateLoader stringTemplateLoader() { + StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); + for (DatabaseType value : DatabaseType.values()) { + stringTemplateLoader.putTemplate(value.getKey(), value.getJdbcUrl()); + } + return stringTemplateLoader; + } + + @Override + public void afterPropertiesSet() throws Exception { + initFreemarkerTemplateLoader(); + } +} diff --git a/src/main/java/com/trh/dictionary/config/SessionListener.java b/src/main/java/com/trh/dictionary/config/SessionListener.java new file mode 100644 index 0000000..45d79c6 --- /dev/null +++ b/src/main/java/com/trh/dictionary/config/SessionListener.java @@ -0,0 +1,40 @@ +package com.trh.dictionary.config; + +import com.trh.dictionary.service.DataSourceService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.PostConstruct; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +/** + * @author HouKunLin + * @date 19-9-10 上午12:17 + */ +@WebListener +public class SessionListener implements HttpSessionListener { + private static Logger logger = LoggerFactory.getLogger(SessionListener.class); + @Autowired + private DataSourceService dataSourceService; + + @Override + public void sessionCreated(HttpSessionEvent se) { + logger.debug("创建会话:{}", se.getSession().getId()); + } + + @Override + public void sessionDestroyed(HttpSessionEvent se) { + HttpSession session = se.getSession(); + logger.debug("会话注销:{}", session.getId()); + dataSourceService.removeDataSource(session); + } + + @PostConstruct + public void post() { + System.out.println("监听器已注入"); + } +} diff --git a/src/main/java/com/trh/dictionary/conterller/HomeController.java b/src/main/java/com/trh/dictionary/conterller/HomeController.java new file mode 100644 index 0000000..0632797 --- /dev/null +++ b/src/main/java/com/trh/dictionary/conterller/HomeController.java @@ -0,0 +1,124 @@ +package com.trh.dictionary.conterller; + +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.service.DataSourceService; +import com.trh.dictionary.util.ExceptionNoneParamsFunction; +import com.trh.dictionary.util.JdbcUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.sql.DataSource; +import javax.validation.Valid; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author HouKunLin + * @date 19-9-9 下午11:06 + */ +@RestController +@RequestMapping("/") +public class HomeController { + + @Autowired + private DataSource dataSource; + + @Autowired + private HttpServletRequest request; + + @Autowired + private DataSourceService dataSourceService; + + /** + * 注册一个数据源 + * + * @param dto + * @param errors + * @return + */ + @RequestMapping("/register") + public Object register(@Valid ConnectionDTO dto, Errors errors) { + if (errors.hasErrors()) { + return errors.getAllErrors(); + } + System.out.println(request.getRequestURI()); + System.out.println("当前会话ID:" + request.getSession().getId()); + try { + DataSource dataSource = dataSourceService.registerDateSource(dto); + + return "OK:" + dataSource; + } catch (Exception e) { + e.printStackTrace(); + return "error:" + e.getMessage(); + } + } + + @RequestMapping("/test") + public Object test() throws SQLException { + Map map = new LinkedHashMap<>(); + Map databaseMap = new LinkedHashMap<>(); + Map driverMap = new LinkedHashMap<>(); + Map termMap = new LinkedHashMap<>(); + Map functionsMap = new LinkedHashMap<>(); + Connection connection = dataSource.getConnection(); + DatabaseMetaData metaData = connection.getMetaData(); + map.put("getUserName", metaData.getUserName()); + map.put("getExtraNameCharacters", metaData.getExtraNameCharacters()); + map.put("getCatalogSeparator", metaData.getCatalogSeparator()); + + termMap.put("getCatalogTerm", metaData.getCatalogTerm()); + termMap.put("getProcedureTerm", metaData.getProcedureTerm()); + termMap.put("getSchemaTerm", metaData.getSchemaTerm()); + + functionsMap.put("getNumericFunctions", metaData.getNumericFunctions()); + functionsMap.put("getStringFunctions", metaData.getStringFunctions()); + functionsMap.put("getSystemFunctions", metaData.getSystemFunctions()); + functionsMap.put("getTimeDateFunctions", metaData.getTimeDateFunctions()); + + driverMap.put("getDriverName", metaData.getDriverName()); + driverMap.put("getDriverVersion", metaData.getDriverVersion()); + driverMap.put("getDriverMajorVersion", metaData.getDriverMajorVersion()); + driverMap.put("getDriverMinorVersion", metaData.getDriverMinorVersion()); + + databaseMap.put("getDatabaseProductName", metaData.getDatabaseProductName()); + databaseMap.put("getDatabaseProductVersion", metaData.getDatabaseProductVersion()); + databaseMap.put("getDatabaseMajorVersion", metaData.getDatabaseMajorVersion()); + databaseMap.put("getDatabaseMinorVersion", metaData.getDatabaseMinorVersion()); + + map.put("driverInfo", driverMap); + map.put("databaseInfo", databaseMap); + map.put("termInfo", termMap); + map.put("functionsInfo", functionsMap); + + tryMethod(() -> { + map.put("Tables", JdbcUtils.resultSetToMaps(metaData.getTables(null, null, null, null))); + }); + tryMethod(() -> { + map.put("Catalogs", JdbcUtils.resultSetToMaps(metaData.getCatalogs())); + }); + tryMethod(() -> { + map.put("Schemas", JdbcUtils.resultSetToMaps(metaData.getSchemas())); + }); + tryMethod(() -> { + map.put("TableTypes", JdbcUtils.resultSetToMaps(metaData.getTableTypes())); + }); + tryMethod(() -> { + map.put("PrimaryKeys", JdbcUtils.resultSetToMaps(metaData.getPrimaryKeys(null, null, null))); + }); + return map; + } + + public void tryMethod(ExceptionNoneParamsFunction function) { + try { + function.apply(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/trh/dictionary/enums/DatabaseType.java b/src/main/java/com/trh/dictionary/enums/DatabaseType.java new file mode 100644 index 0000000..a24148c --- /dev/null +++ b/src/main/java/com/trh/dictionary/enums/DatabaseType.java @@ -0,0 +1,58 @@ +package com.trh.dictionary.enums; + +/** + * 数据库类型 + * + * @author HouKunLin + * @date 2019/9/10 0010 16:37 + */ +public enum DatabaseType { + /** + * MySQL数据库 + */ + MYSQL("MySQL", "jdbc:mysql://${host}:${port}/${database}?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"), + /** + * Oracle数据库 + */ + ORACLE("Oracle", "jdbc:oracle:thin:@//${host}:${port}/${database}"), + /** + * SQL Server数据库 + */ + SQLSERVER("SQL Server", "jdbc:sqlserver://${host}:${port};DatabaseName=${database}"), + /** + * PostgreSQL数据库 + */ + POSTGRESQL("PostgreSQL", "jdbc:postgresql://${host}:${port}/${database}"), + /** + * DB2数据库 + */ + DB2("DB2", "jdbc:db2://${host}:${port}/${database}"), + ; + + private String name; + private String jdbcUrl; + + private static final String PREFIX = "DatabaseTypeKeyPrefix_"; + + DatabaseType(String name, String jdbcUrl) { + this.name = name; + this.jdbcUrl = jdbcUrl; + } + + /** + * 获得一个KEY + * + * @return + */ + public String getKey() { + return PREFIX + toString(); + } + + public String getName() { + return name; + } + + public String getJdbcUrl() { + return jdbcUrl; + } +} diff --git a/src/main/java/com/trh/dictionary/service/DataSourceService.java b/src/main/java/com/trh/dictionary/service/DataSourceService.java new file mode 100644 index 0000000..80efce9 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/DataSourceService.java @@ -0,0 +1,61 @@ +package com.trh.dictionary.service; + +import com.trh.dictionary.bean.ConnectionDTO; + +import javax.servlet.http.HttpSession; +import javax.sql.DataSource; + +/** + * 数据源的一些操作 + * + * @author HouKunLin + * @date 2019/9/10 0010 11:48 + */ +public interface DataSourceService { + /** + * 注册一个数据源 + * + * @param dto 数据库连接信息 + * @return 一个能够正常使用的数据源 + * @throws Exception + */ + DataSource registerDateSource(ConnectionDTO dto) throws Exception; + + /** + * 注册一个数据源 + * + * @param dataSource 数据源 + * @return + */ + DataSource registerDateSource(DataSource dataSource); + + /** + * 移除一个数据源 + * + * @param dataSource 需要移除的数据源 + */ + void removeDataSource(DataSource dataSource); + + /** + * 移除一个数据源 + * + * @param key 数据源对应的KEY + */ + void removeDataSource(String key); + + /** + * 移除一个会话绑定的数据源信息 + * + * @param session 会话 + */ + void removeDataSource(HttpSession session); + + /** + * 根据数据库连接信息创建数据库连接URL + * + * @param dto 数据库连接信息 + * @return Jdbc Url + * @throws Exception + */ + String getJdbcUrl(ConnectionDTO dto) throws Exception; +} diff --git a/src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java b/src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java new file mode 100644 index 0000000..e64e0cf --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java @@ -0,0 +1,119 @@ +package com.trh.dictionary.service; + +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.config.DynamicDataSource; +import com.trh.dictionary.util.Keys; +import freemarker.template.Configuration; +import freemarker.template.Template; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import javax.servlet.http.HttpSession; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.UUID; + +/** + * 数据源管理 + * + * @author HouKunLin + * @date 2019/9/10 0010 11:50 + */ +@Service +public class DataSourceServiceImpl implements DataSourceService { + + @Autowired + private DynamicDataSource dynamicDataSource; + + @Autowired + private Configuration configuration; + + @Autowired + private HttpSession session; + + @Override + public DataSource registerDateSource(ConnectionDTO dto) throws Exception { + try { + // 构建新数据源 + DataSource dataSource = DataSourceBuilder.create() + .url(getJdbcUrl(dto)) + .username(dto.getUsername()) + .password(dto.getPassword()) + .type(com.zaxxer.hikari.HikariDataSource.class) + .build(); + checkDataSource(dataSource); + // 重设并通知,维护的TargetDataSource + registerDateSource(dataSource); + return dataSource; + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Override + public DataSource registerDateSource(DataSource dataSource) { + removeDataSource(session); + + String key = UUID.randomUUID().toString(); + + session.setAttribute(Keys.datasourcesKey, key); + session.setAttribute(Keys.datasources, dataSource); + + dynamicDataSource.put(key, dataSource); + return dataSource; + } + + @Override + public void removeDataSource(DataSource dataSource) { + dynamicDataSource.remove(dataSource); + } + + @Override + public void removeDataSource(String key) { + dynamicDataSource.remove(key); + } + + @Override + public void removeDataSource(HttpSession session) { + String key = String.valueOf(session.getAttribute(Keys.datasourcesKey)); + + session.removeAttribute(Keys.datasourcesKey); + session.removeAttribute(Keys.datasources); + + removeDataSource(key); + } + + /** + * 检查一个数据源是否能够正常连接数据库 + * + * @param dataSource + * @throws Exception + */ + private void checkDataSource(DataSource dataSource) throws Exception { + Connection connection = null; + try { + connection = dataSource.getConnection(); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + } + + @Override + public String getJdbcUrl(ConnectionDTO dto) throws Exception { + Template template = configuration.getTemplate(dto.getType().getKey(), "UTF-8"); + return FreeMarkerTemplateUtils.processTemplateIntoString(template, dto); + } +} diff --git a/src/main/java/com/trh/dictionary/util/ExceptionBiFunction.java b/src/main/java/com/trh/dictionary/util/ExceptionBiFunction.java new file mode 100644 index 0000000..45cc5bd --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/ExceptionBiFunction.java @@ -0,0 +1,19 @@ +package com.trh.dictionary.util; + +/** + * @author houkunlin + * @date 2019/9/10 下午9:18 + */ +@FunctionalInterface +public interface ExceptionBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws Exception + */ + R apply(T t, U u) throws Exception; +} diff --git a/src/main/java/com/trh/dictionary/util/ExceptionNoneParamsFunction.java b/src/main/java/com/trh/dictionary/util/ExceptionNoneParamsFunction.java new file mode 100644 index 0000000..056416f --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/ExceptionNoneParamsFunction.java @@ -0,0 +1,15 @@ +package com.trh.dictionary.util; + +/** + * @author houkunlin + * @date 2019/9/10 下午9:27 + */ +@FunctionalInterface +public interface ExceptionNoneParamsFunction { + /** + * 执行方法 + * + * @throws Exception + */ + void apply() throws Exception; +} diff --git a/src/main/java/com/trh/dictionary/util/JdbcUtils.java b/src/main/java/com/trh/dictionary/util/JdbcUtils.java new file mode 100644 index 0000000..26ad506 --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/JdbcUtils.java @@ -0,0 +1,36 @@ +package com.trh.dictionary.util; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * JDBC工具 + * + * @author houkunlin + * @date 2019/9/10 下午9:05 + */ +public class JdbcUtils { + public static List> resultSetToMaps(ResultSet resultSet) throws Exception { + return resultSetToMaps(resultSet, ResultSetMetaData::getColumnName); + } + + public static List> resultSetToMaps(ResultSet resultSet, ExceptionBiFunction function) throws Exception { + List> list = new ArrayList<>(); + Map map; + ResultSetMetaData metaData = resultSet.getMetaData(); + int len = metaData.getColumnCount(); + + while (resultSet.next()) { + map = new LinkedHashMap<>(); + for (int i = 1; i <= len; i++) { + map.put(function.apply(metaData, i), resultSet.getObject(i)); + } + list.add(map); + } + return list; + } +} diff --git a/src/main/java/com/trh/dictionary/util/Keys.java b/src/main/java/com/trh/dictionary/util/Keys.java new file mode 100644 index 0000000..bc3a41d --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/Keys.java @@ -0,0 +1,10 @@ +package com.trh.dictionary.util; + +/** + * @author HouKunLin + * @date 19-9-9 下午11:38 + */ +public class Keys { + public static final String datasourcesKey = "datasources_Key"; + public static final String datasources = "datasources"; +} -- Gitee From 26504b46b301ae6b939a64f91181efae72ec2191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 00:55:13 +0800 Subject: [PATCH 07/46] =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=97=A0=E6=B3=95?= =?UTF-8?q?=E6=AD=A3=E5=B8=B8=E8=BF=90=E8=A1=8C=E7=9A=84=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=EF=BC=88=E5=BC=80=E5=A7=8B=E6=89=A7=E8=A1=8C=E7=A8=8B=E5=BA=8F?= =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=AD=A5=E9=AA=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 34 ++++++++++++++----- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 4b01a4e..2526359 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -1,8 +1,10 @@ package com.trh.dictionary.conterller; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.dao.ConnectionFactory; import com.trh.dictionary.service.BuildPDF; +import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.db2.Db2Executor; import com.trh.dictionary.service.mysql.BuildMysqlPdf; import com.trh.dictionary.service.oracleservice.OracleDatabase; @@ -13,13 +15,17 @@ import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; +import javax.sql.DataSource; +import javax.validation.Valid; import java.io.*; import java.sql.Connection; import java.util.ArrayList; @@ -34,30 +40,40 @@ import java.util.List; @Controller public class DatabaseController { static Logger logger = LoggerFactory.getLogger(DatabaseController.class); + @Autowired + private DataSource dataSource; + @Autowired + private DataSourceService dataSourceService; @RequestMapping("/login.action") - public String login(Model model, String selector, String ip, String port, String password, String username, String database) { + public String login(Model model, @Valid ConnectionDTO dto, Errors errors) throws Exception { + DataSource dataSource = dataSourceService.registerDateSource(dto); + + String database = dto.getDatabase(); + String ip = dto.getHost(); + String port = dto.getPort(); + String username = dto.getUsername(); + String password = dto.getPassword(); List tableInfo = null; try { - switch (selector) { - case "mysql": + switch (dto.getType()) { + case MYSQL: //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; - Connection connection = ConnectionFactory.getConnection(url, username, password, "mySql"); + Connection connection = dataSource.getConnection(); tableInfo = BuildPDF.getBuildPdfTableData(BuildPDF.getTables(connection, database)); break; - case "oracle": + case ORACLE: tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); break; - case "SQL server": + case SQLSERVER: model.addAttribute("markdown", WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password)); return "markdown"; - case "PostgreSQL": + case POSTGRESQL: model.addAttribute("markdown", BuildPgSqlPdf.getPgMarkdown(ip, database, port, username, password)); return "markdown"; - case "DB2": + case DB2: tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; } -- Gitee From 01e4b390e881238b94a57d7d64c44986a8b5ce57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:21:06 +0800 Subject: [PATCH 08/46] =?UTF-8?q?'=E4=BF=AE=E6=94=B9Service=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=AE=9E=E7=8E=B0=E7=B1=BB=E6=89=80=E5=9C=A8=E5=8C=85?= =?UTF-8?q?=E5=90=8D'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dictionary/service/{ => impl}/DataSourceServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename src/main/java/com/trh/dictionary/service/{ => impl}/DataSourceServiceImpl.java (97%) diff --git a/src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java similarity index 97% rename from src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java rename to src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java index e64e0cf..d661f05 100644 --- a/src/main/java/com/trh/dictionary/service/DataSourceServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java @@ -1,7 +1,8 @@ -package com.trh.dictionary.service; +package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.config.DynamicDataSource; +import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.util.Keys; import freemarker.template.Configuration; import freemarker.template.Template; -- Gitee From 3554965772e0e93c7b2dd851d0b7b112b96d4dce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:21:45 +0800 Subject: [PATCH 09/46] =?UTF-8?q?'=E4=BF=AE=E6=94=B9git=E5=BF=BD=E7=95=A5?= =?UTF-8?q?=E8=A7=84=E5=88=99=EF=BC=8C=E6=B7=BB=E5=8A=A0=E5=BF=BD=E7=95=A5?= =?UTF-8?q?IDEA=E8=87=AA=E5=8A=A8=E7=94=9F=E6=88=90=E7=9A=84*.iml=E6=96=87?= =?UTF-8?q?=E4=BB=B6'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0c7502d..8048b8f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ # Created by .ignore support plugin (hsz.mobi) /.idea /target +*.iml \ No newline at end of file -- Gitee From 70bd8401caa0fc04f9ddfa6225ead79e049e6e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:27:35 +0800 Subject: [PATCH 10/46] =?UTF-8?q?=E6=B7=BB=E5=8A=A0joda-time=E6=97=A5?= =?UTF-8?q?=E6=9C=9F=E6=97=B6=E9=97=B4=E5=A4=84=E7=90=86=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index 2836e87..e1d48b1 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,12 @@ + + + joda-time + joda-time + 2.10.3 + com.itextpdf -- Gitee From ef6d9cda4070ea0b25930dbe724574473040168a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:31:57 +0800 Subject: [PATCH 11/46] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BB=8E=E6=9C=AA=E4=BD=BF=E7=94=A8=E8=BF=87=E7=9A=84=E6=97=A5?= =?UTF-8?q?=E6=9C=9F=E5=B7=A5=E5=85=B7=E7=B1=BB=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/util/DateUtil.java | 84 ------------------- 1 file changed, 84 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/util/DateUtil.java diff --git a/src/main/java/com/trh/dictionary/util/DateUtil.java b/src/main/java/com/trh/dictionary/util/DateUtil.java deleted file mode 100644 index c00948a..0000000 --- a/src/main/java/com/trh/dictionary/util/DateUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.trh.dictionary.util; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 时间工具类 - * - * @author - * @create 2019-07-26 9:27 - */ -public class DateUtil { - /** - * long类型转换为String类型 - * - * @param - * @param formatType 要转换的string类型的时间格式 - * @return - * @throws ParseException - */ - public static String longToString(long currentTime, String formatType) throws ParseException { - // long类型转成Date类型 - Date date = longToDate(currentTime, formatType); - // date类型转成String - String strTime = dateToString(date, formatType); - return strTime; - } - - /** - * long转换为Date类型 - * - * @param currentTime 要转换的long类型的时间 - * @param formatType 要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒 - * @return - * @throws ParseException - */ - public static Date longToDate(long currentTime, String formatType) throws ParseException { - if (formatType == null) { - formatType = "yyyy-MM-dd HH:mm:ss"; - } - Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间 - String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string - Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型 - return date; - } - - /** - * date类型转换为long类型 - * - * @param date 要转换的date类型的时间 - * @return - */ - public static long dateToLong(Date date) { - return date.getTime(); - } - - /** - * string类型转换为date类型 - * - * @param strTime 要转换的string类型的时间 - * @param formatType 要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒 - * strTime的时间格式必须要与formatType的时间格式相同 - * @return - * @throws ParseException - */ - public static Date stringToDate(String strTime, String formatType) throws ParseException { - SimpleDateFormat formatter = new SimpleDateFormat(formatType); - Date date = null; - date = formatter.parse(strTime); - return date; - } - - /** - * date类型转换为String类型 formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒 - * - * @param data Date类型的时间 - * @param formatType - * @return - */ - public static String dateToString(Date data, String formatType) { - return new SimpleDateFormat(formatType).format(data); - } -} -- Gitee From baf456290e30aca03743b78e062a5e97d6415551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:32:53 +0800 Subject: [PATCH 12/46] =?UTF-8?q?=E4=BB=8EService=E5=8C=85=E9=87=8C?= =?UTF-8?q?=E9=9D=A2=E6=8F=90=E5=8F=96=E4=BA=8B=E4=BB=B6Event=E5=A4=84?= =?UTF-8?q?=E7=90=86=E6=96=87=E4=BB=B6=E5=88=B0=E5=8D=95=E7=8B=AC=E7=9A=84?= =?UTF-8?q?=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/{service => event}/ContentEvent.java | 2 +- .../com/trh/dictionary/{service => event}/IndexEvent.java | 2 +- .../com/trh/dictionary/{service => event}/pdfPageEvent.java | 2 +- src/main/java/com/trh/dictionary/service/BuildPDF.java | 3 +++ .../trh/dictionary/service/sqlserver/BuildSqlserverPDF.java | 5 ++--- 5 files changed, 8 insertions(+), 6 deletions(-) rename src/main/java/com/trh/dictionary/{service => event}/ContentEvent.java (96%) rename src/main/java/com/trh/dictionary/{service => event}/IndexEvent.java (96%) rename src/main/java/com/trh/dictionary/{service => event}/pdfPageEvent.java (99%) diff --git a/src/main/java/com/trh/dictionary/service/ContentEvent.java b/src/main/java/com/trh/dictionary/event/ContentEvent.java similarity index 96% rename from src/main/java/com/trh/dictionary/service/ContentEvent.java rename to src/main/java/com/trh/dictionary/event/ContentEvent.java index bc48ef0..682c233 100644 --- a/src/main/java/com/trh/dictionary/service/ContentEvent.java +++ b/src/main/java/com/trh/dictionary/event/ContentEvent.java @@ -1,4 +1,4 @@ -package com.trh.dictionary.service; +package com.trh.dictionary.event; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; diff --git a/src/main/java/com/trh/dictionary/service/IndexEvent.java b/src/main/java/com/trh/dictionary/event/IndexEvent.java similarity index 96% rename from src/main/java/com/trh/dictionary/service/IndexEvent.java rename to src/main/java/com/trh/dictionary/event/IndexEvent.java index f9344a0..213cc7e 100644 --- a/src/main/java/com/trh/dictionary/service/IndexEvent.java +++ b/src/main/java/com/trh/dictionary/event/IndexEvent.java @@ -1,4 +1,4 @@ -package com.trh.dictionary.service; +package com.trh.dictionary.event; import com.itextpdf.text.*; import com.itextpdf.text.pdf.ColumnText; diff --git a/src/main/java/com/trh/dictionary/service/pdfPageEvent.java b/src/main/java/com/trh/dictionary/event/pdfPageEvent.java similarity index 99% rename from src/main/java/com/trh/dictionary/service/pdfPageEvent.java rename to src/main/java/com/trh/dictionary/event/pdfPageEvent.java index 555f13d..8553808 100644 --- a/src/main/java/com/trh/dictionary/service/pdfPageEvent.java +++ b/src/main/java/com/trh/dictionary/event/pdfPageEvent.java @@ -1,4 +1,4 @@ -package com.trh.dictionary.service; +package com.trh.dictionary.event; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 18f9266..29d2ee3 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -11,6 +11,9 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.dao.ConnectionFactory; +import com.trh.dictionary.event.ContentEvent; +import com.trh.dictionary.event.IndexEvent; +import com.trh.dictionary.event.pdfPageEvent; import com.trh.dictionary.util.ColumnBasicEnum; import com.trh.dictionary.util.SignEnum; import com.trh.dictionary.util.TableBasicEnum; diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java index 76bc830..2bd7a36 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java @@ -12,14 +12,13 @@ import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.service.BuildPDF; -import com.trh.dictionary.service.ContentEvent; -import com.trh.dictionary.service.IndexEvent; +import com.trh.dictionary.event.ContentEvent; +import com.trh.dictionary.event.IndexEvent; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; -import java.lang.reflect.Field; import java.sql.Connection; import java.util.ArrayList; import java.util.List; -- Gitee From 2b28db28cd94fa573fdd9b9fab4bbc839a34b9ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:34:51 +0800 Subject: [PATCH 13/46] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E8=AF=AD=E6=B3=95=E6=80=A7=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/conterller/DatabaseController.java | 4 +--- src/main/java/com/trh/dictionary/service/BuildPDF.java | 5 +---- .../java/com/trh/dictionary/service/db2/Db2Executor.java | 3 +-- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 2526359..9ab6955 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -149,9 +149,7 @@ public class DatabaseController { } } - String markdown = BuildPDF.writeMarkdown(tableInfo); - - return markdown; + return BuildPDF.writeMarkdown(tableInfo); } catch (Exception e) { logger.error("error==>" + e); return "### " + e.getMessage(); diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 29d2ee3..d4604b1 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -982,9 +982,6 @@ public class BuildPDF { String regex = "[\u4e00-\u9fa5]"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); - if (matcher.find()) { - return true; - } - return false; + return matcher.find(); } } diff --git a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java index 48e7d4a..8ee4334 100644 --- a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java +++ b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java @@ -177,8 +177,7 @@ public class Db2Executor { public static List getDB2Tables(String host, int port, String schema, String user, String password) throws SQLException, ClassNotFoundException { Connection connection = SqlExecutor.newDB2Connection(host, port, schema, user, password); - List db2Tables = getDB2Tables(connection, schema); - return db2Tables; + return getDB2Tables(connection, schema); } /** -- Gitee From 378a138228a186e815dcae3e925c36dd15284212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:37:36 +0800 Subject: [PATCH 14/46] =?UTF-8?q?=E4=BD=BF=E7=94=A8IDEA=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8C=96=E4=B8=80=E4=B8=8B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复导入的问题(删除没有使用过的import),以及一些语法的格式化 --- .../com/trh/dictionary/bean/ColumnInfo.java | 22 +++-- .../com/trh/dictionary/bean/IndexInfo.java | 8 +- .../com/trh/dictionary/bean/TableInfo.java | 16 ++-- .../bean/sqlserver/SqlserverColumnInfo.java | 26 +++--- .../bean/sqlserver/SqlserverIndexInfo.java | 8 +- .../bean/sqlserver/SqlserverTabelInfo.java | 11 +-- .../trh/dictionary/dao/ConnectionFactory.java | 2 - .../dao/oracleservice/OracleJdbc.java | 10 ++- .../sqlserver/SqlserverConnectionFactory.java | 18 ++-- .../dao/sqlserver/TestConnection.java | 34 +++---- .../trh/dictionary/event/ContentEvent.java | 7 +- .../com/trh/dictionary/event/IndexEvent.java | 15 ++-- .../trh/dictionary/event/pdfPageEvent.java | 42 ++++----- .../com/trh/dictionary/service/BuildPDF.java | 7 +- .../service/oracleservice/OracleDatabase.java | 1 - .../service/postgreSQL/BuildPgSqlPdf.java | 3 +- .../service/sqlserver/BuildSqlserverPDF.java | 86 +++++++++--------- .../sqlserver/GenerateDataBaseInfo.java | 9 +- .../sqlserver/WriteSqlserverMarkDown.java | 90 +++++++++---------- .../trh/dictionary/util/ColumnBasicEnum.java | 12 +-- 20 files changed, 208 insertions(+), 219 deletions(-) diff --git a/src/main/java/com/trh/dictionary/bean/ColumnInfo.java b/src/main/java/com/trh/dictionary/bean/ColumnInfo.java index 7699c1a..910a4e3 100644 --- a/src/main/java/com/trh/dictionary/bean/ColumnInfo.java +++ b/src/main/java/com/trh/dictionary/bean/ColumnInfo.java @@ -1,7 +1,5 @@ package com.trh.dictionary.bean; -import javafx.beans.binding.ObjectExpression; - /** * 列信息 * @@ -20,23 +18,23 @@ public class ColumnInfo { /** * 类型 */ - private String name= ""; + private String name = ""; /** * 类型 */ - private String type= ""; + private String type = ""; /** * 是否允许为空 */ - private String isNull= ""; + private String isNull = ""; /** * 默认值 */ - private String defaultValue= ""; + private String defaultValue = ""; /** * 描述 */ - private String description= ""; + private String description = ""; public void setIsIndex(int isIndex) { this.isIndex = isIndex; @@ -59,7 +57,7 @@ public class ColumnInfo { } public void setName(String name) { - if (name==null){ + if (name == null) { name = ""; } this.name = name; @@ -70,7 +68,7 @@ public class ColumnInfo { } public void setType(String type) { - if (type==null){ + if (type == null) { type = ""; } this.type = type; @@ -81,7 +79,7 @@ public class ColumnInfo { } public void setIsNull(String isNull) { - if (isNull==null){ + if (isNull == null) { isNull = ""; } this.isNull = isNull; @@ -92,7 +90,7 @@ public class ColumnInfo { } public void setDefaultValue(String defaultValue) { - if (defaultValue==null){ + if (defaultValue == null) { defaultValue = ""; } this.defaultValue = defaultValue; @@ -103,7 +101,7 @@ public class ColumnInfo { } public void setDescription(String description) { - if (description==null){ + if (description == null) { description = ""; } this.description = description; diff --git a/src/main/java/com/trh/dictionary/bean/IndexInfo.java b/src/main/java/com/trh/dictionary/bean/IndexInfo.java index 7a349da..cd9b5fa 100644 --- a/src/main/java/com/trh/dictionary/bean/IndexInfo.java +++ b/src/main/java/com/trh/dictionary/bean/IndexInfo.java @@ -11,11 +11,11 @@ public class IndexInfo { /** * 是否为主键 */ - private int isIndex=0; + private int isIndex = 0; private int order; - private String name= ""; - private String type= ""; - private String containKey= ""; + private String name = ""; + private String type = ""; + private String containKey = ""; public IndexInfo() { } diff --git a/src/main/java/com/trh/dictionary/bean/TableInfo.java b/src/main/java/com/trh/dictionary/bean/TableInfo.java index e4962f2..b94a4b5 100644 --- a/src/main/java/com/trh/dictionary/bean/TableInfo.java +++ b/src/main/java/com/trh/dictionary/bean/TableInfo.java @@ -12,19 +12,19 @@ public class TableInfo { /** * 表名 */ - private String tableName= ""; + private String tableName = ""; /** * 字符集 */ - private String orderType= ""; + private String orderType = ""; /** * 存储引擎 */ - private String storageEngine= ""; + private String storageEngine = ""; /** * 描述 */ - private String description= ""; + private String description = ""; /** * 所有列名 */ @@ -45,7 +45,7 @@ public class TableInfo { } public void setTableName(String tableName) { - if(tableName==null){ + if (tableName == null) { tableName = ""; } this.tableName = tableName; @@ -56,7 +56,7 @@ public class TableInfo { } public void setOrderType(String orderType) { - if(orderType==null){ + if (orderType == null) { orderType = ""; } this.orderType = orderType; @@ -67,7 +67,7 @@ public class TableInfo { } public void setStorageEngine(String storageEngine) { - if(storageEngine==null){ + if (storageEngine == null) { storageEngine = ""; } this.storageEngine = storageEngine; @@ -78,7 +78,7 @@ public class TableInfo { } public void setDescription(String description) { - if(description==null){ + if (description == null) { description = ""; } this.description = description; diff --git a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverColumnInfo.java b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverColumnInfo.java index 4155d0f..cf58e13 100644 --- a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverColumnInfo.java +++ b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverColumnInfo.java @@ -7,31 +7,31 @@ package com.trh.dictionary.bean.sqlserver; */ public class SqlserverColumnInfo { - private String table_name= "";//表名 + private String table_name = "";//表名 - private String column_num= "";//字段序号 + private String column_num = "";//字段序号 - private String column_name= "";//字段名 + private String column_name = "";//字段名 - private String is_identity= "";//标识 + private String is_identity = "";//标识 - private String p_k= "";//主键 + private String p_k = "";//主键 - private String type= "";//类型 + private String type = "";//类型 - private String occupied_num= "";//占用字节数 + private String occupied_num = "";//占用字节数 - private String length= "";//长度 + private String length = "";//长度 - private String scale= "";//小数位数 + private String scale = "";//小数位数 - private String is_null= "";//允许空 + private String is_null = "";//允许空 - private String default_value= "";//默认值 + private String default_value = "";//默认值 - private String decs= " ";//说明 + private String decs = " ";//说明 - private String class_desc= " "; + private String class_desc = " "; public String getTable_name() { return table_name; diff --git a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverIndexInfo.java b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverIndexInfo.java index b34bb4b..44a7ef9 100644 --- a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverIndexInfo.java +++ b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverIndexInfo.java @@ -7,14 +7,14 @@ package com.trh.dictionary.bean.sqlserver; */ public class SqlserverIndexInfo { - private String index_name= ""; + private String index_name = ""; - private String index_desc= ""; + private String index_desc = ""; - private String index_keys= ""; + private String index_keys = ""; public String getIndex_name() { - index_name=index_name.replaceAll("__","_"); + index_name = index_name.replaceAll("__", "_"); return index_name; } diff --git a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java index 64ccfba..325e5e8 100644 --- a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java +++ b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java @@ -1,8 +1,5 @@ package com.trh.dictionary.bean.sqlserver; -import com.trh.dictionary.bean.ColumnInfo; -import com.trh.dictionary.bean.IndexInfo; - import java.util.List; /** @@ -15,9 +12,9 @@ public class SqlserverTabelInfo { /** * 表名 */ - private String tableName= ""; + private String tableName = ""; - private String value= ""; + private String value = ""; /** * 所有列名 @@ -55,8 +52,8 @@ public class SqlserverTabelInfo { } public void setValue(String value) { - if(null==value){ - value=""; + if (null == value) { + value = ""; } this.value = value; } diff --git a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java index a802d6a..be06069 100644 --- a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java @@ -3,8 +3,6 @@ package com.trh.dictionary.dao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.DriverManager; -import java.sql.SQLException; import java.sql.*; /** diff --git a/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java b/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java index abe2b8e..81e1081 100644 --- a/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java +++ b/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java @@ -1,6 +1,8 @@ package com.trh.dictionary.dao.oracleservice; -import java.sql.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; /** * @author: Chen.Chun @@ -22,14 +24,14 @@ public class OracleJdbc { private static String password = "123456"; // 获得连接对象 - public static synchronized Connection getConn(){ - if(conn == null){ + public static synchronized Connection getConn() { + if (conn == null) { try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); - }catch (SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java index cc09286..b356ca2 100644 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java @@ -1,6 +1,5 @@ package com.trh.dictionary.dao.sqlserver; -import com.trh.dictionary.service.BuildPDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,7 +14,7 @@ public class SqlserverConnectionFactory { static Logger logger = LoggerFactory.getLogger(SqlserverConnectionFactory.class); - public static Connection getConnection(String url, String userName, String passWord){ + public static Connection getConnection(String url, String userName, String passWord) { Connection connection = null; //创建驱动 try { @@ -39,33 +38,34 @@ public class SqlserverConnectionFactory { /** * 释放资源 - * @param connection 连接 + * + * @param connection 连接 * @param preparedStatement - * @param resultSet 结果集 + * @param resultSet 结果集 */ - public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement){ - if(null != resultSet){ + public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { + if (null != resultSet) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } - if (null != statement){ + if (null != statement) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } - if(null != preparedStatement){ + if (null != preparedStatement) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } - if(null != connection){ + if (null != connection) { try { connection.close(); } catch (SQLException e) { diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java b/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java index 155ccfa..9cd3dd0 100644 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java +++ b/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java @@ -20,43 +20,43 @@ public class TestConnection { static Logger logger = LoggerFactory.getLogger(SqlserverConnectionFactory.class); @org.junit.Test - public void testConnection(){ + public void testConnection() { - String dbURL="jdbc:sqlserver://192.168.161.3:1433;DatabaseName=zhou"; - String userName="SA"; - String userPwd="zhoufan123AAA"; - Connection connection = SqlserverConnectionFactory.getConnection(dbURL,userName,userPwd); - String sqltabel="SELECT Name as name FROM SysObjects Where XType='U' ORDER BY Name;"; - List list_table=null; + String dbURL = "jdbc:sqlserver://192.168.161.3:1433;DatabaseName=zhou"; + String userName = "SA"; + String userPwd = "zhoufan123AAA"; + Connection connection = SqlserverConnectionFactory.getConnection(dbURL, userName, userPwd); + String sqltabel = "SELECT Name as name FROM SysObjects Where XType='U' ORDER BY Name;"; + List list_table = null; try { - list_table = GenerateDataBaseInfo.getTableInfo(connection,sqltabel); + list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); } catch (Exception e) { e.printStackTrace(); } - for(SqlserverTabelInfo Ta:list_table){ + for (SqlserverTabelInfo Ta : list_table) { logger.info(Ta.getTableName()); - String sqlcolumn="SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='"+Ta.getTableName()+"'"; + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - List list_column=GenerateDataBaseInfo.getColumnInfo(connection,sqlcolumn); - for(SqlserverColumnInfo s:list_column){ + List list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } } catch (Exception e) { e.printStackTrace(); } - String sqlindex="SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + "SELECT i.name AS index_name,(\n" + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('"+Ta.getTableName()+"')) Ind ORDER BY index_name"; + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { - List list_index=GenerateDataBaseInfo.getIndexInfo(connection,sqlindex); - for(SqlserverIndexInfo s:list_index){ + List list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } diff --git a/src/main/java/com/trh/dictionary/event/ContentEvent.java b/src/main/java/com/trh/dictionary/event/ContentEvent.java index 682c233..b8361e9 100644 --- a/src/main/java/com/trh/dictionary/event/ContentEvent.java +++ b/src/main/java/com/trh/dictionary/event/ContentEvent.java @@ -18,18 +18,19 @@ public class ContentEvent extends PdfPageEventHelper { private int page; public Map index = new LinkedHashMap(); + @Override - public void onStartPage (PdfWriter writer, Document document) { + public void onStartPage(PdfWriter writer, Document document) { page++; } @Override - public void onChapter (PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { + public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { index.put(title.getContent(), page); } @Override - public void onSection (PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { + public void onSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { onChapter(writer, document, paragraphPosition, title); } } diff --git a/src/main/java/com/trh/dictionary/event/IndexEvent.java b/src/main/java/com/trh/dictionary/event/IndexEvent.java index 213cc7e..f316b1d 100644 --- a/src/main/java/com/trh/dictionary/event/IndexEvent.java +++ b/src/main/java/com/trh/dictionary/event/IndexEvent.java @@ -1,25 +1,30 @@ package com.trh.dictionary.event; -import com.itextpdf.text.*; +import com.itextpdf.text.Anchor; +import com.itextpdf.text.Document; +import com.itextpdf.text.Element; +import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.ColumnText; -import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfPageEventHelper; import com.itextpdf.text.pdf.PdfWriter; -/** 页码监听 +/** + * 页码监听 + * * @author wangyu * @create 2019-08-21 16:45 */ public class IndexEvent extends PdfPageEventHelper { private int page; private boolean body; + @Override - public void onEndPage (PdfWriter writer, Document document) { + public void onEndPage(PdfWriter writer, Document document) { if (body) { page++; //设置页脚页码 float x = (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F; - Anchor anchor = new Anchor(""+page); + Anchor anchor = new Anchor("" + page); anchor.setName("user"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(anchor), x, document.bottom() - 20, 0); diff --git a/src/main/java/com/trh/dictionary/event/pdfPageEvent.java b/src/main/java/com/trh/dictionary/event/pdfPageEvent.java index 8553808..10bf63f 100644 --- a/src/main/java/com/trh/dictionary/event/pdfPageEvent.java +++ b/src/main/java/com/trh/dictionary/event/pdfPageEvent.java @@ -3,7 +3,9 @@ package com.trh.dictionary.event; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; -/**pdf页面事件监听 +/** + * pdf页面事件监听 + * * @author wangyu * @create 2019-8-2 */ @@ -24,7 +26,7 @@ public class pdfPageEvent extends PdfPageEventHelper { public Rectangle pageSize = PageSize.A4; /** - * 模板 + * 模板 */ public PdfTemplate total; @@ -34,27 +36,21 @@ public class pdfPageEvent extends PdfPageEventHelper { public BaseFont bf = null; /** - * 利用基础字体生成的字体对象,一般用于生成中文文字 + * 利用基础字体生成的字体对象,一般用于生成中文文字 */ public Font fontDetail = null; /** - * * 无参构造方法. - * */ public pdfPageEvent() { } /** - * - * @param bf - * 基础字体大小 - * @param presentFontSize - * 数据字体大小 - * @param pageSize - * 文档格式 + * @param bf 基础字体大小 + * @param presentFontSize 数据字体大小 + * @param pageSize 文档格式 */ public pdfPageEvent(BaseFont bf, int presentFontSize, Rectangle pageSize) { this.bf = bf; @@ -63,15 +59,11 @@ public class pdfPageEvent extends PdfPageEventHelper { } /** + * 构造方法. * - * 构造方法. - * - * @param yeMei - * 页眉字符串 - * @param presentFontSize - * 数据体字体大小 - * @param pageSize - * 页面文档大小,A4,A5,A6横转翻转等Rectangle对象 + * @param yeMei 页眉字符串 + * @param presentFontSize 数据体字体大小 + * @param pageSize 页面文档大小,A4,A5,A6横转翻转等Rectangle对象 */ public pdfPageEvent(String yeMei, int presentFontSize, Rectangle pageSize) { this.header = yeMei; @@ -88,9 +80,7 @@ public class pdfPageEvent extends PdfPageEventHelper { } /** - * * TODO 文档打开时创建模板 - * */ @Override public void onOpenDocument(PdfWriter writer, Document document) { @@ -113,7 +103,7 @@ public class pdfPageEvent extends PdfPageEventHelper { } // 1.写入页眉 - ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(header, fontDetail),document.left(), document.top() + 20, 0); + ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(header, fontDetail), document.left(), document.top() + 20, 0); // 2.写入前半部分的 第 X页/共 int pageS = writer.getPageNumber(); @@ -127,18 +117,16 @@ public class pdfPageEvent extends PdfPageEventHelper { PdfContentByte cb = writer.getDirectContent(); // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F // ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。 - ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer,(document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F,document.bottom() - 20, 0); + ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0); // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F + // len , y 轴和之前的保持一致,底边界-20 - cb.addTemplate(total,(document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F,document.bottom() - 20); + cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20); // 调节模版显示的位置 } /** - * * TODO 关闭文档时,替换模板,完成整个页眉页脚组件 - * */ @Override public void onCloseDocument(PdfWriter writer, Document document) { diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index d4604b1..421ab69 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -23,7 +23,10 @@ import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Field; -import java.sql.*; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -579,7 +582,7 @@ public class BuildPDF { int i = 1; for (TableInfo info : list) { StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName()+ " "+info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); + oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); oneTble.append(res1); List columnInfos = info.getColumnList(); //拼接列 diff --git a/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java b/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java index 7fa2bca..d09dd77 100644 --- a/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java +++ b/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java @@ -3,7 +3,6 @@ package com.trh.dictionary.service.oracleservice; import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.dao.oracleservice.OracleJdbc; import java.sql.*; import java.util.ArrayList; diff --git a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java index f1fe85c..cc67806 100644 --- a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java +++ b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java @@ -172,6 +172,7 @@ public class BuildPgSqlPdf { /** * mysql得到数据库所有库名 + * * @param ip * @param dbName * @param port @@ -189,7 +190,7 @@ public class BuildPgSqlPdf { ResultSet resultSet = null; String sql = " SELECT datname FROM pg_database "; resultSet = statement.executeQuery(sql); - while (resultSet.next()){ + while (resultSet.next()) { String dbNames = resultSet.getString(1); dbList.add(dbNames); } diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java index 2bd7a36..a986163 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java @@ -11,14 +11,16 @@ import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; -import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; +import com.trh.dictionary.service.BuildPDF; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; import java.sql.Connection; import java.util.ArrayList; import java.util.List; @@ -49,41 +51,41 @@ public class BuildSqlserverPDF { public static void MakePdf(String ip, String dbName, String port, String userName, String passWord, String filePath, String pdfName) { try { - String dbURL="jdbc:sqlserver://"+ip+":"+port+";DatabaseName="+dbName+";"; + String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; //得到生成数据 - Connection connection = SqlserverConnectionFactory.getConnection(dbURL, userName,passWord); + Connection connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - String sqltabel="SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - List list_table = GenerateDataBaseInfo.getTableInfo(connection,sqltabel); + List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); if (list_table.size() == 0) { return; } - for(SqlserverTabelInfo Ta:list_table){ + for (SqlserverTabelInfo Ta : list_table) { logger.info(Ta.getTableName()); - List list_column=new ArrayList(); - List list_index=new ArrayList(); - String sqlcolumn="SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + List list_column = new ArrayList(); + List list_index = new ArrayList(); + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='"+Ta.getTableName()+"'"; + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - list_column=GenerateDataBaseInfo.getColumnInfo(connection,sqlcolumn); - for(SqlserverColumnInfo s:list_column){ + list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } } catch (Exception e) { e.printStackTrace(); } - String sqlindex="SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + "SELECT i.name AS index_name,(\n" + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('"+Ta.getTableName()+"')) Ind ORDER BY index_name"; + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { - list_index=GenerateDataBaseInfo.getIndexInfo(connection,sqlindex); - for(SqlserverIndexInfo s:list_index){ + list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } } catch (Exception e) { @@ -101,7 +103,7 @@ public class BuildSqlserverPDF { } } - public static void build(String FILE_DIR, List tableInfos, String pdfName) throws Exception { + public static void build(String FILE_DIR, List tableInfos, String pdfName) throws Exception { String fontDir = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); fontDir += "src/main/resources/"; BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); @@ -127,7 +129,7 @@ public class BuildSqlserverPDF { //根据chapter章节分页 //表格 //设置表格模板 - String[] tableHeader = {"序列", "列名","主键" ,"类型", "可空", "默认值", "注释"}; + String[] tableHeader = {"序列", "列名", "主键", "类型", "可空", "默认值", "注释"}; String[] indexHeader = {"序列", "索引名", "描述", "包含字段"}; for (SqlserverTabelInfo tableInfo : tableInfos) { @@ -137,7 +139,7 @@ public class BuildSqlserverPDF { Anchor tome = new Anchor(point); tome.setName(tableInfo.getTableName()); Phrase engine = new Phrase(" ", font); - Phrase type = new Phrase(" " , font); + Phrase type = new Phrase(" ", font); Phrase description = new Phrase(tableInfo.getValue(), getChineseFontAsStyle(BaseColor.BLACK, 16)); //组装基本数据 Paragraph contentInfo = new Paragraph(); @@ -153,15 +155,15 @@ public class BuildSqlserverPDF { //设置表格 PdfPTable table = BuildPDF.setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); //设置列信息 - BuildColumnCell(table, font,tableInfo); + BuildColumnCell(table, font, tableInfo); tableParagraph.add(table); chapter.add(tableParagraph); //设置索引表 Paragraph blankTwo = new Paragraph("\n\n"); chapter.add(blankTwo); - PdfPTable indexTable = BuildPDF.setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable indexTable = BuildPDF.setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); table.setWidthPercentage(100); - indexTable = BuildIndexCell(indexTable, BuildPDF.getFontAsStyle(BaseColor.RED, 10),tableInfo); + indexTable = BuildIndexCell(indexTable, BuildPDF.getFontAsStyle(BaseColor.RED, 10), tableInfo); Paragraph indexTableParagraph = new Paragraph(); indexTableParagraph.add(indexTable); chapter.add(indexTableParagraph); @@ -183,7 +185,7 @@ public class BuildSqlserverPDF { writer.setPageEvent(indexEvent); document.open(); //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", BuildPDF.getFontAsStyle(BaseColor.BLACK, 18)), 0); + Chapter indexChapter = new Chapter(new Paragraph("", BuildPDF.getFontAsStyle(BaseColor.BLACK, 18)), 0); indexChapter.setNumberDepth(-1); // 设置数字深度 int i = 1; @@ -196,10 +198,10 @@ public class BuildSqlserverPDF { Chunk pageNoChunk = new Chunk(pageNo + ""); String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i-1).getValue())){ - tempDescription += "("+tableInfos.get(i-1).getValue()+")"; + if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { + tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; } - Paragraph jumpParagraph = new Paragraph(tempDescription,getChineseFontAsStyle(BaseColor.BLACK,12 )); + Paragraph jumpParagraph = new Paragraph(tempDescription, getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); jumpParagraph.add(pageNoChunk); Anchor anchor = new Anchor(jumpParagraph); @@ -231,28 +233,28 @@ public class BuildSqlserverPDF { **/ public static PdfPTable BuildColumnCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { - List columnList=tableInfo.getColumnList(); + List columnList = tableInfo.getColumnList(); - for(SqlserverColumnInfo columnInfo:columnList){ + for (SqlserverColumnInfo columnInfo : columnList) { Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - if("YES".equals(columnInfo.getP_k())){ + if ("YES".equals(columnInfo.getP_k())) { cnFont.setColor(BaseColor.RED); - }else{ + } else { cnFont.setColor(BaseColor.BLACK); } - PdfPCell cell1= new PdfPCell(new Paragraph(columnInfo.getColumn_num(),cnFont)); + PdfPCell cell1 = new PdfPCell(new Paragraph(columnInfo.getColumn_num(), cnFont)); table.addCell(cell1); - PdfPCell cell2 = new PdfPCell(new Paragraph(columnInfo.getColumn_name(),cnFont)); + PdfPCell cell2 = new PdfPCell(new Paragraph(columnInfo.getColumn_name(), cnFont)); table.addCell(cell2); - PdfPCell cell3 = new PdfPCell(new Paragraph(columnInfo.getP_k(),cnFont)); + PdfPCell cell3 = new PdfPCell(new Paragraph(columnInfo.getP_k(), cnFont)); table.addCell(cell3); - PdfPCell cell4 = new PdfPCell(new Paragraph(columnInfo.getType()+"("+columnInfo.getLength()+")",cnFont)); + PdfPCell cell4 = new PdfPCell(new Paragraph(columnInfo.getType() + "(" + columnInfo.getLength() + ")", cnFont)); table.addCell(cell4); - PdfPCell cell5 = new PdfPCell(new Paragraph(columnInfo.getIs_null(),cnFont)); + PdfPCell cell5 = new PdfPCell(new Paragraph(columnInfo.getIs_null(), cnFont)); table.addCell(cell5); - PdfPCell cell6 = new PdfPCell(new Paragraph(columnInfo.getDefault_value(),cnFont)); + PdfPCell cell6 = new PdfPCell(new Paragraph(columnInfo.getDefault_value(), cnFont)); table.addCell(cell6); - PdfPCell cell7 = new PdfPCell(new Paragraph(columnInfo.getDecs(),cnFont)); + PdfPCell cell7 = new PdfPCell(new Paragraph(columnInfo.getDecs(), cnFont)); table.addCell(cell7); } return table; @@ -267,12 +269,12 @@ public class BuildSqlserverPDF { **/ public static PdfPTable BuildIndexCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { - List indexInfos=tableInfo.getIndexInfoList(); + List indexInfos = tableInfo.getIndexInfoList(); Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - int i=1; - for(SqlserverIndexInfo indexInfo:indexInfos){ - PdfPCell cell1= new PdfPCell(new Paragraph(i+"")); + int i = 1; + for (SqlserverIndexInfo indexInfo : indexInfos) { + PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); table.addCell(cell1); PdfPCell cell2 = new PdfPCell(new Paragraph(indexInfo.getIndex_name())); table.addCell(cell2); diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java b/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java index 27c8043..e8c0a63 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java @@ -1,10 +1,8 @@ package com.trh.dictionary.service.sqlserver; -import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.util.ColumnBasicEnum; import java.sql.Connection; import java.sql.ResultSet; @@ -87,10 +85,10 @@ public class GenerateDataBaseInfo { sqlserverColumnInfo.setIs_null(resultSet.getString("is_null")); sqlserverColumnInfo.setDefault_value(resultSet.getString("default_value")); sqlserverColumnInfo.setDecs(resultSet.getString("decs")); - String class_desc=resultSet.getString("class_desc"); - if("INDEX".equals(class_desc)){ + String class_desc = resultSet.getString("class_desc"); + if ("INDEX".equals(class_desc)) { continue; - }else{ + } else { sqlserverColumnInfo.setClass_desc(resultSet.getString("class_desc")); } @@ -125,5 +123,4 @@ public class GenerateDataBaseInfo { } - } \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java b/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java index ffbeb5a..38f8607 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java @@ -4,8 +4,6 @@ import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; -import com.trh.dictionary.service.BuildPDF; -import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,6 +23,7 @@ import java.util.List; public class WriteSqlserverMarkDown { static Logger logger = LoggerFactory.getLogger(WriteSqlserverMarkDown.class); + /** * 生成Markdown * @@ -36,45 +35,45 @@ public class WriteSqlserverMarkDown { * @param filePath 例如: D:\ideaspace\export_dbInfo\src\main\resources\ */ public static void MakeMarkdown(String ip, String dbName, String port, String userName, String passWord, String filePath) { - Connection connection=null; + Connection connection = null; try { - String dbURL="jdbc:sqlserver://"+ip+":"+port+";DatabaseName="+dbName+";"; + String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; //得到生成数据 - connection = SqlserverConnectionFactory.getConnection(dbURL, userName,passWord); + connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - String sqltabel="SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - List list_table = GenerateDataBaseInfo.getTableInfo(connection,sqltabel); + List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); if (list_table.size() == 0) { return; } - for(SqlserverTabelInfo Ta:list_table){ + for (SqlserverTabelInfo Ta : list_table) { logger.info(Ta.getTableName()); - List list_column=new ArrayList(); - List list_index=new ArrayList(); - String sqlcolumn="SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + List list_column = new ArrayList(); + List list_index = new ArrayList(); + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='"+Ta.getTableName()+"'"; + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - list_column=GenerateDataBaseInfo.getColumnInfo(connection,sqlcolumn); - for(SqlserverColumnInfo s:list_column){ + list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } } catch (Exception e) { e.printStackTrace(); } - String sqlindex="SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + "SELECT i.name AS index_name,(\n" + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('"+Ta.getTableName()+"')) Ind ORDER BY index_name"; + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { logger.info(sqlindex); - list_index=GenerateDataBaseInfo.getIndexInfo(connection,sqlindex); - for(SqlserverIndexInfo s:list_index){ + list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } } catch (Exception e) { @@ -84,12 +83,12 @@ public class WriteSqlserverMarkDown { Ta.setIndexInfoList(list_index); } - writeMarkdown(list_table,filePath); + writeMarkdown(list_table, filePath); } catch (Exception e) { e.printStackTrace(); logger.info("生成Markdown失败"); - }finally { + } finally { try { connection.close(); } catch (SQLException e) { @@ -154,7 +153,7 @@ public class WriteSqlserverMarkDown { int i = 1; for (SqlserverTabelInfo info : list) { StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() +" "+ info.getValue()+"\n" + "基本信息:" + info.getValue() + " " + oneTble.append("##" + i + "." + info.getTableName() + " " + info.getValue() + "\n" + "基本信息:" + info.getValue() + " " + "\n\n" + "|序列|列名|主键|类型|可空|默认值|注释|" + "\n"); oneTble.append(res1); List columnInfos = info.getColumnList(); @@ -190,7 +189,7 @@ public class WriteSqlserverMarkDown { //目录 markdown.insert(0, "[TOC]\n"); logger.info("表信息\n" + markdown.toString()); - return markdown.toString(); + return markdown.toString(); } @@ -226,45 +225,45 @@ public class WriteSqlserverMarkDown { * @return void **/ public static String MakeMarkdownString(String ip, String dbName, String port, String userName, String passWord) { - Connection connection=null; + Connection connection = null; try { - String dbURL="jdbc:sqlserver://"+ip+":"+port+";DatabaseName="+dbName+";"; + String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; //得到生成数据 - connection = SqlserverConnectionFactory.getConnection(dbURL, userName,passWord); + connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - String sqltabel="SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - List list_table = GenerateDataBaseInfo.getTableInfo(connection,sqltabel); + List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); if (list_table.size() == 0) { return "## 数据库无数据"; } - for(SqlserverTabelInfo Ta:list_table){ + for (SqlserverTabelInfo Ta : list_table) { logger.info(Ta.getTableName()); - List list_column=new ArrayList(); - List list_index=new ArrayList(); - String sqlcolumn="SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + List list_column = new ArrayList(); + List list_index = new ArrayList(); + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='"+Ta.getTableName()+"'"; + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - list_column=GenerateDataBaseInfo.getColumnInfo(connection,sqlcolumn); - for(SqlserverColumnInfo s:list_column){ + list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } } catch (Exception e) { e.printStackTrace(); } - String sqlindex="SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + "SELECT i.name AS index_name,(\n" + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('"+Ta.getTableName()+"')) Ind ORDER BY index_name"; + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { logger.info(sqlindex); - list_index=GenerateDataBaseInfo.getIndexInfo(connection,sqlindex); - for(SqlserverIndexInfo s:list_index){ + list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } } catch (Exception e) { @@ -279,7 +278,7 @@ public class WriteSqlserverMarkDown { } catch (Exception e) { e.printStackTrace(); logger.info("生成Markdown失败"); - }finally { + } finally { try { connection.close(); } catch (SQLException e) { @@ -297,17 +296,17 @@ public class WriteSqlserverMarkDown { * @return java.util.List **/ public static List getDatabasesList(String ip, String dbName, String port, String userName, String passWord) { - Connection connection=null; + Connection connection = null; List list = new ArrayList<>(); try { - String dbURL="jdbc:sqlserver://"+ip+":"+port+";DatabaseName="+dbName+";"; - connection = SqlserverConnectionFactory.getConnection(dbURL, userName,passWord); - String sqltabel="select name from sysdatabases where name not in('master','model','msdb','tempdb');"; - list = GenerateDataBaseInfo.getDataBaseList(connection,sqltabel); + String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; + connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); + String sqltabel = "select name from sysdatabases where name not in('master','model','msdb','tempdb');"; + list = GenerateDataBaseInfo.getDataBaseList(connection, sqltabel); } catch (Exception e) { e.printStackTrace(); - }finally { + } finally { try { connection.close(); } catch (SQLException e) { @@ -318,5 +317,4 @@ public class WriteSqlserverMarkDown { } - } \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/util/ColumnBasicEnum.java b/src/main/java/com/trh/dictionary/util/ColumnBasicEnum.java index 3d70b3e..ec4b2b9 100644 --- a/src/main/java/com/trh/dictionary/util/ColumnBasicEnum.java +++ b/src/main/java/com/trh/dictionary/util/ColumnBasicEnum.java @@ -8,27 +8,27 @@ package com.trh.dictionary.util; */ public enum ColumnBasicEnum { /** - *列名-字段 + * 列名-字段 */ Field("Field"), /** - *列名-字段 + * 列名-字段 */ Extra("Extra"), /** - *类型字段 + * 类型字段 */ Type("Type"), /** - *注释字段 + * 注释字段 */ Comment("Comment"), /** - *是否为空字段 + * 是否为空字段 */ Null("Null"), /** - *默认值字段 + * 默认值字段 */ Default("Default"); private String desc; -- Gitee From d729b26c69c51d70fe765d12fb01261f212e1733 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 09:44:11 +0800 Subject: [PATCH 15/46] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=80=E4=BA=9Bfor?= =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E8=AF=AD=E5=8F=A5=E9=97=AE=E9=A2=98=EF=BC=8C?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=88=90foreach=E8=AF=AD=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/service/BuildPDF.java | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 421ab69..43c4bd3 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -314,11 +314,10 @@ public class BuildPDF { } tableInfo.setIndexInfoList(indexInfoList); //得到表字符集和ENGINE、表注释 - for (int i = 0; i < table.length; i++) { - String oneTemp = table[i]; + for (String oneTemp : table) { //引擎 if (oneTemp.contains(TableBasicEnum.ENGINE.getDesc())) { - tableInfo.setStorageEngine(dropSign(table[i])); + tableInfo.setStorageEngine(dropSign(oneTemp)); continue; } else { if (tableInfo.getStorageEngine() == null) { @@ -327,7 +326,7 @@ public class BuildPDF { } //字符集 if (oneTemp.contains(TableBasicEnum.CHARSET.getDesc())) { - tableInfo.setOrderType(dropSign(table[i])); + tableInfo.setOrderType(dropSign(oneTemp)); continue; } else { if (tableInfo.getOrderType() == null) { @@ -337,7 +336,7 @@ public class BuildPDF { //描述 if (oneTemp.contains(TableBasicEnum.COMMENT.getDesc())) { - tableInfo.setDescription(dropSign(table[i])); + tableInfo.setDescription(dropSign(oneTemp)); continue; } else { if (tableInfo.getDescription() == null) { @@ -529,8 +528,8 @@ public class BuildPDF { int columnSize = header.length; PdfPTable table = new PdfPTable(columnSize); table.setWidthPercentage(100); - for (int i = 0; i < columnSize; i++) { - PdfPCell cell1 = new PdfPCell(new Paragraph(header[i], font)); + for (String value : header) { + PdfPCell cell1 = new PdfPCell(new Paragraph(value, font)); cell1.setVerticalAlignment(Element.ALIGN_CENTER); // cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); @@ -766,17 +765,17 @@ public class BuildPDF { } Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); Field[] fields = obj.getClass().getDeclaredFields(); - for (int j = 0; j < fields.length; j++) { + for (Field field : fields) { PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(Element.ALIGN_CENTER); Paragraph paragraph = new Paragraph(); //将设置私有构造器设为可取值 - fields[j].setAccessible(true); - String name = fields[j].getName(); + field.setAccessible(true); + String name = field.getName(); if ("isIndex".equals(name)) { try { - if ((Integer) fields[j].get(obj) == 1) { + if ((Integer) field.get(obj) == 1) { font = getFontAsStyle(BaseColor.RED, 12); cnFont = getChineseFontAsStyle(BaseColor.RED, 12); } else { @@ -794,13 +793,13 @@ public class BuildPDF { } // 得到类型和名字取值 - if (fields[j].getType().getName().equals(java.lang.String.class.getName())) { + if (field.getType().getName().equals(String.class.getName())) { // String type try { - if (isChineseContent(fields[j].get(obj) + "")) { + if (isChineseContent(field.get(obj) + "")) { font = cnFont; } - paragraph = new Paragraph(fields[j].get(obj) + "", font); + paragraph = new Paragraph(field.get(obj) + "", font); } catch (IllegalArgumentException e) { e.printStackTrace(); @@ -808,11 +807,11 @@ public class BuildPDF { // TODO Auto-generated catch block e.printStackTrace(); } - } else if (fields[j].getType().getName().equals(java.lang.Integer.class.getName()) - || fields[j].getType().getName().equals("int")) { + } else if (field.getType().getName().equals(Integer.class.getName()) + || field.getType().getName().equals("int")) { // Integer type try { - paragraph = new Paragraph(fields[j].get(obj) + "", font); + paragraph = new Paragraph(field.get(obj) + "", font); } catch (IllegalArgumentException e) { e.printStackTrace(); -- Gitee From 8409a2f113ea59b1b6d7487995e9a83ef2cd2bb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 10:04:22 +0800 Subject: [PATCH 16/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E9=87=8A=E6=94=BE=E8=B5=84=E6=BA=90=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E4=BB=A5=E5=8F=8A=E5=88=A0=E9=99=A4=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E4=BB=8E=E6=9C=AA=E4=BD=BF=E7=94=A8=E7=9A=84OracleJdb?= =?UTF-8?q?c.java=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把数据库释放资源的方法提取到JdbcUtils工具类里面 --- .../trh/dictionary/dao/ConnectionFactory.java | 41 +------------------ .../dao/oracleservice/OracleJdbc.java | 40 ------------------ .../sqlserver/SqlserverConnectionFactory.java | 39 ------------------ .../com/trh/dictionary/service/BuildPDF.java | 3 +- .../com/trh/dictionary/util/JdbcUtils.java | 41 ++++++++++++++++++- .../com/trh/dictionary}/TestConnection.java | 3 +- 6 files changed, 45 insertions(+), 122 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java rename src/{main/java/com/trh/dictionary/dao/sqlserver => test/java/com/trh/dictionary}/TestConnection.java (98%) diff --git a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java index be06069..453e32f 100644 --- a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java @@ -3,7 +3,8 @@ package com.trh.dictionary.dao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.*; +import java.sql.Connection; +import java.sql.DriverManager; /** * 数据库连接工厂类 @@ -42,42 +43,4 @@ public class ConnectionFactory { } return connection; } - - /** - * 释放资源 - * - * @param connection 连接 - * @param preparedStatement - * @param resultSet 结果集 - */ - public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { - if (null != resultSet) { - try { - resultSet.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != statement) { - try { - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != preparedStatement) { - try { - preparedStatement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != connection) { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } } diff --git a/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java b/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java deleted file mode 100644 index 81e1081..0000000 --- a/src/main/java/com/trh/dictionary/dao/oracleservice/OracleJdbc.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.trh.dictionary.dao.oracleservice; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * @author: Chen.Chun - * @program: cdtrh_group-database-dictionary-master - * @description: oracle链接 - * @create: 2019-08-30 11:05 - **/ -public class OracleJdbc { - - //数据库连接对象 - private static Connection conn = null; - //驱动 - private static String driver = "oracle.jdbc.driver.OracleDriver"; - //连接字符串 - private static String url = "jdbc:oracle:thin:@//127.0.0.1:1521/orcl"; - //用户名 - private static String username = "root"; - //密码 - private static String password = "123456"; - - // 获得连接对象 - public static synchronized Connection getConn() { - if (conn == null) { - try { - Class.forName(driver); - conn = DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return conn; - } -} \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java index b356ca2..0938387 100644 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java @@ -35,43 +35,4 @@ public class SqlserverConnectionFactory { return connection; } - - /** - * 释放资源 - * - * @param connection 连接 - * @param preparedStatement - * @param resultSet 结果集 - */ - public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { - if (null != resultSet) { - try { - resultSet.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != statement) { - try { - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != preparedStatement) { - try { - preparedStatement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != connection) { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - } \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 43c4bd3..309a0c5 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -15,6 +15,7 @@ import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.event.pdfPageEvent; import com.trh.dictionary.util.ColumnBasicEnum; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.SignEnum; import com.trh.dictionary.util.TableBasicEnum; import org.apache.commons.io.FileUtils; @@ -164,7 +165,7 @@ public class BuildPDF { return tables; } finally { try { - ConnectionFactory.releaseResource(connection, null + JdbcUtils.releaseResource(connection, null , resultSet, statement); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/trh/dictionary/util/JdbcUtils.java b/src/main/java/com/trh/dictionary/util/JdbcUtils.java index 26ad506..f76cb00 100644 --- a/src/main/java/com/trh/dictionary/util/JdbcUtils.java +++ b/src/main/java/com/trh/dictionary/util/JdbcUtils.java @@ -1,7 +1,6 @@ package com.trh.dictionary.util; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; +import java.sql.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -33,4 +32,42 @@ public class JdbcUtils { } return list; } + + /** + * 释放资源 + * + * @param connection 连接 + * @param preparedStatement + * @param resultSet 结果集 + */ + public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { + if (null != resultSet) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (null != statement) { + try { + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (null != preparedStatement) { + try { + preparedStatement.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (null != connection) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java b/src/test/java/com/trh/dictionary/TestConnection.java similarity index 98% rename from src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java rename to src/test/java/com/trh/dictionary/TestConnection.java index 9cd3dd0..f11066e 100644 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/TestConnection.java +++ b/src/test/java/com/trh/dictionary/TestConnection.java @@ -1,8 +1,9 @@ -package com.trh.dictionary.dao.sqlserver; +package com.trh.dictionary; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; +import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -- Gitee From bb18ce47ca4095ec873a50d3fd838ee8994c40e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 10:35:01 +0800 Subject: [PATCH 17/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E5=90=8D=E7=A7=B0=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 未完成,这是一个不可正常运行的提交 --- .../conterller/DatabaseController.java | 30 +++++------- .../dictionary/service/DatabaseService.java | 23 +++++++++ .../service/GeneratePdfService.java | 14 ++++++ .../dictionary/service/db2/Db2Executor.java | 24 ---------- .../service/impl/Db2DatabaseServiceImpl.java | 47 ++++++++++++++++++ .../MySqlDatabaseServiceImpl.java} | 39 +++++++-------- .../impl/MySqlGeneratePdfServiceImpl.java | 28 +++++++++++ .../impl/OracleDatabaseServiceImpl.java | 35 ++++++++++++++ .../impl/PostgreSQLDatabaseServiceImpl.java | 48 +++++++++++++++++++ .../impl/SqlServerDatabaseServiceImpl.java | 48 +++++++++++++++++++ .../service/postgreSQL/BuildPgSqlPdf.java | 31 ------------ .../sqlserver/WriteSqlserverMarkDown.java | 30 ------------ .../java/com/trh/dictionary/util/Keys.java | 1 + 13 files changed, 273 insertions(+), 125 deletions(-) create mode 100644 src/main/java/com/trh/dictionary/service/DatabaseService.java create mode 100644 src/main/java/com/trh/dictionary/service/GeneratePdfService.java create mode 100644 src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java rename src/main/java/com/trh/dictionary/service/{mysql/BuildMysqlPdf.java => impl/MySqlDatabaseServiceImpl.java} (48%) create mode 100644 src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java create mode 100644 src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java create mode 100644 src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java create mode 100644 src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 9ab6955..7816a73 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -5,13 +5,13 @@ import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.dao.ConnectionFactory; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; +import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.db2.Db2Executor; -import com.trh.dictionary.service.mysql.BuildMysqlPdf; import com.trh.dictionary.service.oracleservice.OracleDatabase; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; -import com.trh.dictionary.util.SqlExecutor; +import com.trh.dictionary.util.Keys; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,6 +24,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import javax.validation.Valid; import java.io.*; @@ -44,10 +45,16 @@ public class DatabaseController { private DataSource dataSource; @Autowired private DataSourceService dataSourceService; + @Autowired + private DatabaseService databaseService; + + @Autowired + private HttpSession session; @RequestMapping("/login.action") public String login(Model model, @Valid ConnectionDTO dto, Errors errors) throws Exception { DataSource dataSource = dataSourceService.registerDateSource(dto); + session.setAttribute(Keys.connectionDtoKey, dto); String database = dto.getDatabase(); String ip = dto.getHost(); @@ -95,25 +102,10 @@ public class DatabaseController { @RequestMapping("/getDataBaseNameList") @ResponseBody - public List getDataBaseNmaeList(String selector, String ip, String port, String password, String username, String database) { + public List getDataBaseNmaeList() { List list = new ArrayList<>(); try { - switch (selector) { - case "mysql": - return BuildMysqlPdf.getDataBaseName(ip, database, port, username, password); - case "oracle": - list.add(database); - return list; - case "SQL server": - - return WriteSqlserverMarkDown.getDatabasesList(ip, database, port, username, password); - - case "PostgreSQL": - return BuildPgSqlPdf.getDataBaseName(ip, database, port, username, password); - case "DB2": - return Db2Executor.databases(SqlExecutor.newDB2Connection(ip, Integer.valueOf(port), database, username, password)); - } - + list.addAll(databaseService.getDatabaseName()); } catch (Exception e) { logger.error("error==>" + e); } diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java new file mode 100644 index 0000000..a273119 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -0,0 +1,23 @@ +package com.trh.dictionary.service; + +import org.springframework.stereotype.Service; + +import java.sql.SQLException; +import java.util.List; + +/** + * 数据库操作接口 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:57 + */ +@Service +public interface DatabaseService { + /** + * 获得数据库名称列表 + * + * @return 数据库名称列表 + * @throws SQLException + */ + List getDatabaseName() throws SQLException; +} diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java new file mode 100644 index 0000000..e2b13ae --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -0,0 +1,14 @@ +package com.trh.dictionary.service; + +import java.io.File; +import java.sql.Connection; + +/** + * 创建生成PDF文件的接口 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:49 + */ +public interface GeneratePdfService { + void generatePdfFile(Connection connection, File file); +} diff --git a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java index 8ee4334..57c3109 100644 --- a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java +++ b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java @@ -208,28 +208,4 @@ public class Db2Executor { SqlExecutor.releaseResource(null, null, rs, null); return tables; } - - /** - * 获取数据库实例集合 - * - * @param conn - * @return - */ - public static List databases(Connection conn) throws SQLException { - if (null == conn) { - throw new SQLException("connection can not be null"); - } - String sql = " select SCHEMANAME,owner,CREATE_TIME from syscat.schemata WHERE OWNERTYPE = 'U' "; - List schemas = new ArrayList<>(); - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery(sql); - while (rs.next()) { - String schema = rs.getString("SCHEMANAME"); - if (!StringUtils.isEmpty(schema)) { - schemas.add(schema); - } - } - SqlExecutor.releaseResource(null, null, rs, statement); - return schemas; - } } \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java new file mode 100644 index 0000000..125e1aa --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -0,0 +1,47 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.SqlExecutor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * DB2数据库操作 + * + * @author HouKunLin + * @date 2019/9/11 0011 10:18 + */ +@Service +public class Db2DatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(Db2DatabaseServiceImpl.class); + @Autowired + private DataSource dataSource; + + @Override + public List getDatabaseName() throws SQLException { + Connection conn = dataSource.getConnection(); + String sql = " select SCHEMANAME,owner,CREATE_TIME from syscat.schemata WHERE OWNERTYPE = 'U' "; + List schemas = new ArrayList<>(); + Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery(sql); + while (rs.next()) { + String schema = rs.getString("SCHEMANAME"); + if (!StringUtils.isEmpty(schema)) { + schemas.add(schema); + } + } + SqlExecutor.releaseResource(null, null, rs, statement); + return schemas; + } +} diff --git a/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java similarity index 48% rename from src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java rename to src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index e543f95..682fd6c 100644 --- a/src/main/java/com/trh/dictionary/service/mysql/BuildMysqlPdf.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -1,39 +1,36 @@ -package com.trh.dictionary.service.mysql; +package com.trh.dictionary.service.impl; -import com.trh.dictionary.dao.ConnectionFactory; +import com.trh.dictionary.service.DatabaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** - * mysqlpdf生成 + * MySQL的数据库操作 * - * @author - * @create 2019-09-09 11:10 + * @author HouKunLin + * @date 2019/9/11 0011 10:15 */ -public class BuildMysqlPdf { - static Logger logger = LoggerFactory.getLogger(BuildMysqlPdf.class); +@Service +public class MySqlDatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(MySqlDatabaseServiceImpl.class); + @Autowired + private DataSource dataSource; - /** - * pg得到数据库所有库名 - * - * @param ip - * @param dbName - * @param port - * @param userName - * @param passWord - * @return - */ - public static List getDataBaseName(String ip, String dbName, String port, String userName, String passWord) { + @Override + public List getDatabaseName() { //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; try { - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "mySql"); + Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); List dbList = new ArrayList<>(8); ResultSet resultSet = null; @@ -46,7 +43,7 @@ public class BuildMysqlPdf { return dbList; } catch (Exception e) { logger.error("查询数据库名字集合异常", e); - return new ArrayList<>(1); + return Collections.emptyList(); } } } diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java new file mode 100644 index 0000000..ee26cc3 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java @@ -0,0 +1,28 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.service.GeneratePdfService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; +import java.io.File; +import java.sql.Connection; + +/** + * MySQL数据库创建PDF文件 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:52 + */ +public class MySqlGeneratePdfServiceImpl implements GeneratePdfService { + private static Logger logger = LoggerFactory.getLogger(MySqlGeneratePdfServiceImpl.class); + + @Autowired + private DataSource dataSource; + + @Override + public void generatePdfFile(Connection connection, File file) { + + } +} diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java new file mode 100644 index 0000000..aa6f412 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -0,0 +1,35 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.Keys; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpSession; +import javax.sql.DataSource; +import java.util.Collections; +import java.util.List; + +/** + * Oracle数据库操作 + * + * @author HouKunLin + * @date 2019/9/11 0011 10:15 + */ +@Service +public class OracleDatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(OracleDatabaseServiceImpl.class); + @Autowired + private DataSource dataSource; + @Autowired + private HttpSession session; + + @Override + public List getDatabaseName() { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return Collections.singletonList(dto.getDatabase()); + } +} diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java new file mode 100644 index 0000000..7c0dd16 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java @@ -0,0 +1,48 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.service.DatabaseService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * PostgreSQL数据库操作 + * + * @author HouKunLin + * @date 2019/9/11 0011 10:17 + */ +@Service +public class PostgreSQLDatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(PostgreSQLDatabaseServiceImpl.class); + @Autowired + private DataSource dataSource; + + @Override + public List getDatabaseName() { + //得到生成数据 + try { + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + List dbList = new ArrayList<>(8); + ResultSet resultSet = null; + String sql = " SELECT datname FROM pg_database "; + resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + String dbNames = resultSet.getString(1); + dbList.add(dbNames); + } + return dbList; + } catch (Exception e) { + logger.error("查询数据库名字集合异常", e); + return new ArrayList<>(1); + } + } +} diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java new file mode 100644 index 0000000..f2ecb94 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -0,0 +1,48 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * SQL Server数据库操作 + * + * @author HouKunLin + * @date 2019/9/11 0011 10:16 + */ +@Service +public class SqlServerDatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(SqlServerDatabaseServiceImpl.class); + @Autowired + private DataSource dataSource; + + @Override + public List getDatabaseName() { + Connection connection = null; + List list = new ArrayList<>(); + try { + connection = dataSource.getConnection(); + String sqltabel = "select name from sysdatabases where name not in('master','model','msdb','tempdb');"; + list = GenerateDataBaseInfo.getDataBaseList(connection, sqltabel); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + return list; + } +} diff --git a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java index cc67806..2ba0bb1 100644 --- a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java +++ b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java @@ -169,35 +169,4 @@ public class BuildPgSqlPdf { } return BuildPDF.writeMarkdown(list); } - - /** - * mysql得到数据库所有库名 - * - * @param ip - * @param dbName - * @param port - * @param userName - * @param passWord - * @return - */ - public static List getDataBaseName(String ip, String dbName, String port, String userName, String passWord) { - //得到生成数据 - String url = "jdbc:postgresql://" + ip + ":" + port + "/" + dbName; - try { - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "pgSql"); - Statement statement = connection.createStatement(); - List dbList = new ArrayList<>(8); - ResultSet resultSet = null; - String sql = " SELECT datname FROM pg_database "; - resultSet = statement.executeQuery(sql); - while (resultSet.next()) { - String dbNames = resultSet.getString(1); - dbList.add(dbNames); - } - return dbList; - } catch (Exception e) { - logger.error("查询数据库名字集合异常", e); - return new ArrayList<>(1); - } - } } diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java b/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java index 38f8607..4ea466a 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java @@ -287,34 +287,4 @@ public class WriteSqlserverMarkDown { } return ""; } - - /* - * @Author zhou - * @Description 数据库名称 - * @Date 11:00 2019/9/9 - * @Param [ip, dbName, port, userName, passWord] - * @return java.util.List - **/ - public static List getDatabasesList(String ip, String dbName, String port, String userName, String passWord) { - Connection connection = null; - List list = new ArrayList<>(); - try { - String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; - connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - String sqltabel = "select name from sysdatabases where name not in('master','model','msdb','tempdb');"; - list = GenerateDataBaseInfo.getDataBaseList(connection, sqltabel); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return list; - } - - } \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/util/Keys.java b/src/main/java/com/trh/dictionary/util/Keys.java index bc3a41d..88ef956 100644 --- a/src/main/java/com/trh/dictionary/util/Keys.java +++ b/src/main/java/com/trh/dictionary/util/Keys.java @@ -7,4 +7,5 @@ package com.trh.dictionary.util; public class Keys { public static final String datasourcesKey = "datasources_Key"; public static final String datasources = "datasources"; + public static final String connectionDtoKey = "ConnectionDTO"; } -- Gitee From 3fd80d9675a2b243e3c5d6701e44b70793283a25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 10:46:46 +0800 Subject: [PATCH 18/46] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E9=98=BF=E9=87=8C?= =?UTF-8?q?=E5=B7=B4=E5=B7=B4=E8=A7=84=E8=8C=83=E6=89=8B=E5=86=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9PostgreSqlDatabaseServiceImpl.java=E7=9A=84=E5=90=8D?= =?UTF-8?q?=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...aseServiceImpl.java => PostgreSqlDatabaseServiceImpl.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename src/main/java/com/trh/dictionary/service/impl/{PostgreSQLDatabaseServiceImpl.java => PostgreSqlDatabaseServiceImpl.java} (93%) diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java similarity index 93% rename from src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java rename to src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index 7c0dd16..28da131 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSQLDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -20,8 +20,8 @@ import java.util.List; * @date 2019/9/11 0011 10:17 */ @Service -public class PostgreSQLDatabaseServiceImpl implements DatabaseService { - private static Logger logger = LoggerFactory.getLogger(PostgreSQLDatabaseServiceImpl.class); +public class PostgreSqlDatabaseServiceImpl implements DatabaseService { + private static Logger logger = LoggerFactory.getLogger(PostgreSqlDatabaseServiceImpl.class); @Autowired private DataSource dataSource; -- Gitee From 2efbe012234f5d1dd9c686288fb0efc0e9147c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 10:47:54 +0800 Subject: [PATCH 19/46] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E6=93=8D=E4=BD=9C=E7=9A=84=E4=B8=BB=E8=A6=81=E5=85=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之后所有的数据库操作相关的信息都调用该对象的方法,由该对象判断当前的数据库类型,然后再调用其他相关的具体数据库操作对象方法 --- .../service/impl/DatabaseServiceImpl.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java new file mode 100644 index 0000000..bcd30a6 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -0,0 +1,71 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.enums.DatabaseType; +import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.Keys; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpSession; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 数据库操作 + * + * @author HouKunLin + * @date 2019/9/11 0011 10:35 + */ +@Primary +@Service +public class DatabaseServiceImpl implements DatabaseService { + @Autowired + private Db2DatabaseServiceImpl db2DatabaseService; + @Autowired + private MySqlDatabaseServiceImpl mySqlDatabaseService; + @Autowired + private OracleDatabaseServiceImpl oracleDatabaseService; + @Autowired + private PostgreSqlDatabaseServiceImpl postgreSqlDatabaseService; + @Autowired + private SqlServerDatabaseServiceImpl sqlServerDatabaseService; + + @Autowired + private HttpSession session; + + private Map map = new HashMap<>(); + + @Override + public List getDatabaseName() throws SQLException { + return getDatabaseService().getDatabaseName(); + } + + /** + * 获取与当前会话绑定的数据库操作对象 + * + * @return 数据库操作对象 + */ + private DatabaseService getDatabaseService() { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + DatabaseType type = dto.getType(); + DatabaseService databaseService = map.get(type); + if (databaseService == null) { + throw new RuntimeException("找不到数据库操作对象"); + } + return databaseService; + } + + @PostConstruct + public void post() { + map.put(DatabaseType.DB2, db2DatabaseService); + map.put(DatabaseType.MYSQL, mySqlDatabaseService); + map.put(DatabaseType.ORACLE, oracleDatabaseService); + map.put(DatabaseType.POSTGRESQL, postgreSqlDatabaseService); + map.put(DatabaseType.SQLSERVER, sqlServerDatabaseService); + } +} -- Gitee From 8c034d672b85418bcce908afaf819604bdd57043 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:07:20 +0800 Subject: [PATCH 20/46] =?UTF-8?q?=E9=87=8D=E6=9E=84MySQL=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E8=A1=A8=E5=88=97=E8=A1=A8=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 11 +- .../dictionary/service/DatabaseService.java | 9 + .../service/impl/DatabaseServiceImpl.java | 6 + .../service/impl/Db2DatabaseServiceImpl.java | 6 + .../impl/MySqlDatabaseServiceImpl.java | 272 ++++++++++++++++++ .../impl/OracleDatabaseServiceImpl.java | 7 + .../impl/PostgreSqlDatabaseServiceImpl.java | 7 + .../impl/SqlServerDatabaseServiceImpl.java | 6 + 8 files changed, 317 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 7816a73..7143774 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -2,7 +2,6 @@ package com.trh.dictionary.conterller; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.dao.ConnectionFactory; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; @@ -28,7 +27,6 @@ import javax.servlet.http.HttpSession; import javax.sql.DataSource; import javax.validation.Valid; import java.io.*; -import java.sql.Connection; import java.util.ArrayList; import java.util.List; @@ -66,8 +64,7 @@ public class DatabaseController { switch (dto.getType()) { case MYSQL: //得到生成数据 - Connection connection = dataSource.getConnection(); - tableInfo = BuildPDF.getBuildPdfTableData(BuildPDF.getTables(connection, database)); + tableInfo = databaseService.getTables(); break; case ORACLE: tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); @@ -83,6 +80,7 @@ public class DatabaseController { case DB2: tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; + default: } if (tableInfo != null) { if (tableInfo.size() == 0) { @@ -120,9 +118,7 @@ public class DatabaseController { switch (selector) { case "mysql": //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"; - Connection connection = ConnectionFactory.getConnection(url, username, password, "mySql"); - tableInfo = BuildPDF.getBuildPdfTableData(BuildPDF.getTables(connection, database)); + tableInfo = databaseService.getTables(); break; case "oracle": tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); @@ -134,6 +130,7 @@ public class DatabaseController { case "DB2": tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; + default: } if (tableInfo != null) { if (tableInfo.size() == 0) { diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java index a273119..8d0caf2 100644 --- a/src/main/java/com/trh/dictionary/service/DatabaseService.java +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -1,5 +1,6 @@ package com.trh.dictionary.service; +import com.trh.dictionary.bean.TableInfo; import org.springframework.stereotype.Service; import java.sql.SQLException; @@ -20,4 +21,12 @@ public interface DatabaseService { * @throws SQLException */ List getDatabaseName() throws SQLException; + + /** + * 获取数据库表列表 + * + * @return 数据库表信息 + * @throws SQLException + */ + List getTables() throws SQLException; } diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index bcd30a6..ecf27db 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -1,6 +1,7 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; @@ -60,6 +61,11 @@ public class DatabaseServiceImpl implements DatabaseService { return databaseService; } + @Override + public List getTables() throws SQLException { + return null; + } + @PostConstruct public void post() { map.put(DatabaseType.DB2, db2DatabaseService); diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java index 125e1aa..d8febb8 100644 --- a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -1,5 +1,6 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.SqlExecutor; import org.slf4j.Logger; @@ -44,4 +45,9 @@ public class Db2DatabaseServiceImpl implements DatabaseService { SqlExecutor.releaseResource(null, null, rs, statement); return schemas; } + + @Override + public List getTables() throws SQLException { + return null; + } } diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index 682fd6c..780dc21 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -1,18 +1,27 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.bean.IndexInfo; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * MySQL的数据库操作 @@ -25,6 +34,8 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { private static Logger logger = LoggerFactory.getLogger(MySqlDatabaseServiceImpl.class); @Autowired private DataSource dataSource; + @Autowired + private HttpSession session; @Override public List getDatabaseName() { @@ -46,4 +57,265 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { return Collections.emptyList(); } } + + @Override + public List getTables() throws SQLException { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + + //循环处理表 + List resultList = new ArrayList(); + + Statement statement = null; + ResultSet resultSet = null; + Connection connection = null; + try { + connection = dataSource.getConnection(); + //获取表名 + statement = connection.createStatement(); + String sql = "SHOW TABLES FROM `" + dto.getDatabase() + "`"; + resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + TableInfo tableInfo = new TableInfo(); + //表名 + String tableName = resultSet.getString(1); + tableInfo.setTableName(tableName); + //获取表信息 + String sqlTableInfo = "SHOW CREATE TABLE `" + tableName + "`"; + String createTable = getTableInfo(connection, sqlTableInfo); + String sql1 = "show full columns from `" + tableName + "`"; + List columnInfos = getTableBaseInfo(connection, sql1); + tableInfo.setColumnList(columnInfos); + + //处理表信息字符 + takeTableInfo(tableInfo, createTable); + resultList.add(tableInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + JdbcUtils.releaseResource(connection, null, resultSet, statement); + } catch (Exception e) { + e.printStackTrace(); + } + } + return resultList; + } + + + /** + * 获取单个表全部信息 + * + * @param connection 数据库连接 + * @param sqlTableInfo 表信息sql + * @return + * @throws SQLException + */ + public static String getTableInfo(Connection connection, String sqlTableInfo) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sqlTableInfo); + String table = ""; + while (resultSet.next()) { + table = resultSet.getString("Create Table"); + } + return table; + } + + /** + * 设置表的基本信息 + * + * @param connection 数据库连接 + * @param sql + * @return + * @throws Exception + */ + public static List getTableBaseInfo(Connection connection, String sql) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + List columnInfos = new ArrayList(); + int order = 1; + while (resultSet.next()) { + ColumnInfo columnInfo = new ColumnInfo(); + columnInfo.setName(resultSet.getString(ColumnBasicEnum.Field.getDesc()) + " " + resultSet.getString(ColumnBasicEnum.Extra.getDesc())); + columnInfo.setType(resultSet.getString(ColumnBasicEnum.Type.getDesc())); + columnInfo.setDescription(resultSet.getString(ColumnBasicEnum.Comment.getDesc())); + columnInfo.setIsNull(resultSet.getString(ColumnBasicEnum.Null.getDesc())); + columnInfo.setOrder(order++); + columnInfo.setDefaultValue(resultSet.getString(ColumnBasicEnum.Default.getDesc())); + columnInfos.add(columnInfo); + if (null == columnInfo.getDefaultValue()) { + columnInfo.setDescription(""); + } + } + statement.close(); + resultSet.close(); + return columnInfos; + } + + /** + * 得到表的基本数据 + * + * @param tableInfo 设置单张表构建pdf的数据 + * @param tableInfos 表信息字符串 + * @return TableInfo 表信息对象 + */ + public static TableInfo takeTableInfo(TableInfo tableInfo, String tableInfos) { + //去掉回车 + tableInfos = dest(tableInfos, SignEnum.back_quote.getDesc()); + tableInfos = dest(tableInfos, SignEnum.single_quotation_marks.getDesc()); + String[] test = tableInfos.split("\n"); + //处理字符串 + String str = test[test.length - 1]; + str = dest(str, SignEnum.right_brackets.getDesc()).trim(); + String[] table = str.split(" "); + List indexInfoList = new ArrayList(); + int indexInfoSize = test.length; + for (int i = 0; i < indexInfoSize - 1; i++) { + String temp = test[i]; + //主键索引 + if (temp.contains(TableBasicEnum.PRIMARY_KEY.getDesc())) { + temp = dest(temp, SignEnum.left_brackets.getDesc()); + temp = dest(temp, SignEnum.right_brackets.getDesc()); + String[] tempForIndex = temp.trim().split(" "); + String containKey = tempForIndex[tempForIndex.length - 1]; + IndexInfo indexInfo1 = new IndexInfo(TableBasicEnum.WORD_PRIMARY.getDesc(), TableBasicEnum.WORD_PRIMARY.getDesc(), drop(containKey)); + indexInfo1.setIsIndex(1); + indexInfoList.add(indexInfo1); + } + //唯一索引 + if (temp.contains(TableBasicEnum.UNIQUE_KEY.getDesc())) { + String[] tempForIndex = temp.trim().split(" "); + String containKey = tempForIndex[tempForIndex.length - 1]; + String type = tempForIndex[0] + tempForIndex[1]; + String name = tempForIndex[2]; + containKey = dest(containKey, SignEnum.left_brackets.getDesc()); + containKey = dest(containKey, SignEnum.right_brackets.getDesc()); + containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); + IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); + indexInfoList.add(indexInfo1); + } + //普通索引 + if (temp.contains(TableBasicEnum.KEY.getDesc())) { + String[] tempForIndex = temp.trim().split(" "); + if (!tempForIndex[0].equalsIgnoreCase(TableBasicEnum.WORD_key.getDesc())) { + continue; + } + String containKey = tempForIndex[tempForIndex.length - 1]; + String type = tempForIndex[0]; + String name = tempForIndex[1]; + containKey = dest(containKey, SignEnum.left_brackets.getDesc()); + containKey = dest(containKey, SignEnum.right_brackets.getDesc()); + containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); + IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); + indexInfoList.add(indexInfo1); + } + //全文索引 + if (temp.contains("FULLTEXT KEY")) { + String[] tempForIndex = temp.trim().split(" "); + String containKey = tempForIndex[tempForIndex.length - 1]; + String type = tempForIndex[0]; + String name = tempForIndex[2]; + containKey = dest(containKey, SignEnum.left_brackets.getDesc()); + containKey = dest(containKey, SignEnum.right_brackets.getDesc()); + containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); + IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); + indexInfoList.add(indexInfo1); + } + } + tableInfo.setIndexInfoList(indexInfoList); + //得到表字符集和ENGINE、表注释 + for (String oneTemp : table) { + //引擎 + if (oneTemp.contains(TableBasicEnum.ENGINE.getDesc())) { + tableInfo.setStorageEngine(dropSign(oneTemp)); + continue; + } else { + if (tableInfo.getStorageEngine() == null) { + tableInfo.setStorageEngine(""); + } + } + //字符集 + if (oneTemp.contains(TableBasicEnum.CHARSET.getDesc())) { + tableInfo.setOrderType(dropSign(oneTemp)); + continue; + } else { + if (tableInfo.getOrderType() == null) { + tableInfo.setOrderType(""); + } + } + + //描述 + if (oneTemp.contains(TableBasicEnum.COMMENT.getDesc())) { + tableInfo.setDescription(dropSign(oneTemp)); + continue; + } else { + if (tableInfo.getDescription() == null) { + tableInfo.setDescription(""); + } + } + } + + return tableInfo; + } + + /** + * 去掉字符串中的符号 + * + * @param param 需要处理的变量 + * @return String + */ + public static String dest(String param, String reg) { + String temp = ""; + if (param != null) { + Pattern pattern = Pattern.compile(reg); + Matcher m = pattern.matcher(param); + temp = m.replaceAll(""); + } + return temp; + } + + /** + * 得到一个包含一个等号的字符串,获取等号后的值 + * + * @param param 需处理的变量 + * @return String + */ + public static String dropSign(String param) { + param = param.trim(); + int index = param.indexOf(SignEnum.equal_sign.getDesc()); + String res = param.substring(index + 1); + if (res.contains(SignEnum.single_quotation_marks.getDesc())) { + try { + res = dest(res, SignEnum.single_quotation_marks.getDesc()); + } catch (Exception e) { + e.printStackTrace(); + logger.error("获取等号后的值异常"); + return param; + } + } + return res; + } + + /** + * 去掉索引逗号 + * + * @param param 需处理的变量 + * @return String + */ + public static String drop(String param) { + try { + param = param.trim(); + char[] tempArry = param.toCharArray(); + char res = tempArry[param.length() - 1]; + if (param.contains(SignEnum.comma.getDesc()) && res == ',') { + return param.substring(0, param.length() - 1); + } else { + return param; + } + } catch (Exception e) { + e.getStackTrace(); + return param; + } + } + } diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java index aa6f412..aa8f78f 100644 --- a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -1,6 +1,7 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; @@ -10,6 +11,7 @@ import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; import javax.sql.DataSource; +import java.sql.SQLException; import java.util.Collections; import java.util.List; @@ -32,4 +34,9 @@ public class OracleDatabaseServiceImpl implements DatabaseService { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return Collections.singletonList(dto.getDatabase()); } + + @Override + public List getTables() throws SQLException { + return null; + } } diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index 28da131..f4649ff 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -1,5 +1,6 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,6 +10,7 @@ import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; @@ -45,4 +47,9 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { return new ArrayList<>(1); } } + + @Override + public List getTables() throws SQLException { + return null; + } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index f2ecb94..53eb129 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -1,5 +1,6 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; @@ -45,4 +46,9 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { } return list; } + + @Override + public List getTables() throws SQLException { + return null; + } } -- Gitee From b047dc40a6951cff7119f83f6526348303dbaa4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:08:05 +0800 Subject: [PATCH 21/46] =?UTF-8?q?=E9=87=8D=E6=9E=84MySQL=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E8=A1=A8=E5=88=97=E8=A1=A8=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/service/impl/DatabaseServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index ecf27db..becfaa3 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -63,7 +63,7 @@ public class DatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { - return null; + return getDatabaseService().getTables(); } @PostConstruct -- Gitee From 9699e2568ab11b9c85a078885654124aea8830b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:12:42 +0800 Subject: [PATCH 22/46] =?UTF-8?q?=E9=87=8D=E6=9E=84Oracle=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=95=B0=E6=8D=AE=E5=BA=93=E8=A1=A8=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 13 +- .../impl/OracleDatabaseServiceImpl.java | 112 ++++++++++++++- .../service/oracleservice/OracleDatabase.java | 131 ------------------ src/test/java/com/trh/dictionary/Test.java | 4 +- 4 files changed, 116 insertions(+), 144 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 7143774..bf991ee 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -6,7 +6,6 @@ import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.db2.Db2Executor; -import com.trh.dictionary.service.oracleservice.OracleDatabase; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; @@ -63,11 +62,8 @@ public class DatabaseController { try { switch (dto.getType()) { case MYSQL: - //得到生成数据 - tableInfo = databaseService.getTables(); - break; case ORACLE: - tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); + tableInfo = databaseService.getTables(); break; case SQLSERVER: model.addAttribute("markdown", WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password)); @@ -117,11 +113,8 @@ public class DatabaseController { try { switch (selector) { case "mysql": - //得到生成数据 - tableInfo = databaseService.getTables(); - break; case "oracle": - tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); + tableInfo = databaseService.getTables(); break; case "SQL server": return WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password); @@ -160,7 +153,7 @@ public class DatabaseController { BuildPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); break; case "oracle": - List tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//" + ip + ":" + port + "/" + database + "", username, password); + List tableInfo = databaseService.getTables(); if (tableInfo.size() == 0) { return; } diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java index aa8f78f..d597948 100644 --- a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -1,6 +1,8 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; @@ -11,7 +13,11 @@ import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -37,6 +43,110 @@ public class OracleDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { - return null; + List list = new ArrayList(); + PreparedStatement pstmt; + Connection conn = null; + try { + //1.注册驱动 + //2.建立连接 + conn = dataSource.getConnection(); + //查询数据库下所有的表名 + pstmt = conn.prepareStatement("select t.table_name,u.COMMENTS from user_tables t LEFT JOIN user_tab_comments u ON t.Table_Name=u.Table_Name"); + //建立一个结果集,用来保存查询出来的结果 + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + TableInfo tableInfo = new TableInfo(); + //得到表名 + String tableName = rs.getString("TABLE_NAME"); + //得到表的注释 + String COMMENTS = rs.getString("COMMENTS"); + //通过表名查询主键索引名和列名 + PreparedStatement constraintNamePstmt = conn.prepareStatement("select cu.constraint_name,cu.column_name from user_cons_columns cu LEFT JOIN user_constraints au ON cu.constraint_name = au.constraint_name WHERE au.constraint_type = 'P' and au.table_name = '" + tableName + "'"); + ResultSet index_name = constraintNamePstmt.executeQuery(); + String stringName = ""; + String column_name = ""; + while (index_name.next()) { + stringName = index_name.getString(1); + column_name = index_name.getString(2); + } + constraintNamePstmt.close(); + //通过表名查询所有的列数据 + PreparedStatement columnIdPstmt = conn.prepareStatement("SELECT T.column_id,T.column_name,T.data_type,T.data_default,T.nullable,b.comments\n" + + "FROM USER_TAB_COLUMNS T LEFT JOIN user_col_comments b ON T.TABLE_NAME =b.table_name AND T.COLUMN_NAME =b.column_name WHERE T.TABLE_NAME ='" + tableName + "'"); + ResultSet columnRs = columnIdPstmt.executeQuery(); + List listColumn = new ArrayList(); + while (columnRs.next()) { + ColumnInfo columnInfo = new ColumnInfo(); + //得到列名 + String columnName = columnRs.getString(2); + columnInfo.setName(columnName); + columnInfo.setIsIndex(0); + //得到主键的列名 + if (column_name.equals(columnName)) { + columnInfo.setIsIndex(1); + } + //得到序号 + int order = columnRs.getInt(1); + columnInfo.setOrder(order); + //得到类型 + String type = columnRs.getString(3); + columnInfo.setType(type); + //得到默认值 + String defaultValue = columnRs.getString(4); + columnInfo.setDefaultValue(defaultValue); + //是否为空 + String isNull = columnRs.getString(5); + if (isNull.equalsIgnoreCase("N")) { + isNull = "NO"; + } else { + isNull = "YES"; + } + columnInfo.setIsNull(isNull); + //得到列的描述 + String description = columnRs.getString(6); + columnInfo.setDescription(description); + listColumn.add(columnInfo); + } + //查询表的索引说明 + PreparedStatement rownumPstmt = conn.prepareStatement("SELECT rownum,rs.* FROM ( select t.index_name, i.index_type,listagg(t.column_name,',') within group (order by t.index_name) col_name from user_ind_columns t,user_indexes i where t.index_name = i.index_name " + + "and t.table_name = i.table_name and t.table_name = '" + tableName + "' GROUP BY t.index_name, i.index_type) rs "); + ResultSet IndexRs = rownumPstmt.executeQuery(); + List listIndex = new ArrayList(); + while (IndexRs.next()) { + IndexInfo indexInfo = new IndexInfo(); + String indexRsString = IndexRs.getString(2); + if (stringName.equalsIgnoreCase(indexRsString)) { + indexInfo.setIsIndex(1); + } + indexInfo.setOrder(IndexRs.getInt(1)); + indexInfo.setName(indexRsString); + indexInfo.setType(IndexRs.getString(3)); + indexInfo.setContainKey(IndexRs.getString(4)); + listIndex.add(indexInfo); + } + IndexRs.close(); + columnIdPstmt.close(); + columnRs.close(); + rownumPstmt.close(); + index_name.close(); + tableInfo.setTableName(tableName); + tableInfo.setDescription(COMMENTS); + tableInfo.setColumnList(listColumn); + tableInfo.setIndexInfoList(listIndex); + list.add(tableInfo); + } + rs.close(); + pstmt.close(); + } finally { + if (conn != null) { + try { + //关闭链接 + conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + return list; } } diff --git a/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java b/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java deleted file mode 100644 index d09dd77..0000000 --- a/src/main/java/com/trh/dictionary/service/oracleservice/OracleDatabase.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.trh.dictionary.service.oracleservice; - -import com.trh.dictionary.bean.ColumnInfo; -import com.trh.dictionary.bean.IndexInfo; -import com.trh.dictionary.bean.TableInfo; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; - -/** - * @author: Chen.Chun - * @program: cdtrh_group-database-dictionary-master - * @description: 创建oracle链接 - * @create: 2019-08-30 11:00 - **/ -public class OracleDatabase { - - //驱动 - private static String driver = "oracle.jdbc.driver.OracleDriver"; - - //得到表信息 - public static List getTableInfo(String url, String username, String password) throws Exception { - List list = new ArrayList(); - PreparedStatement pstmt; - Connection conn = null; - try { - //1.注册驱动 - Class.forName(driver); - //2.建立连接 - conn = DriverManager.getConnection(url, username, password); - //查询数据库下所有的表名 - pstmt = conn.prepareStatement("select t.table_name,u.COMMENTS from user_tables t LEFT JOIN user_tab_comments u ON t.Table_Name=u.Table_Name"); - //建立一个结果集,用来保存查询出来的结果 - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - TableInfo tableInfo = new TableInfo(); - //得到表名 - String tableName = rs.getString("TABLE_NAME"); - //得到表的注释 - String COMMENTS = rs.getString("COMMENTS"); - //通过表名查询主键索引名和列名 - PreparedStatement constraintNamePstmt = conn.prepareStatement("select cu.constraint_name,cu.column_name from user_cons_columns cu LEFT JOIN user_constraints au ON cu.constraint_name = au.constraint_name WHERE au.constraint_type = 'P' and au.table_name = '" + tableName + "'"); - ResultSet index_name = constraintNamePstmt.executeQuery(); - String stringName = ""; - String column_name = ""; - while (index_name.next()) { - stringName = index_name.getString(1); - column_name = index_name.getString(2); - } - constraintNamePstmt.close(); - //通过表名查询所有的列数据 - PreparedStatement columnIdPstmt = conn.prepareStatement("SELECT T.column_id,T.column_name,T.data_type,T.data_default,T.nullable,b.comments\n" + - "FROM USER_TAB_COLUMNS T LEFT JOIN user_col_comments b ON T.TABLE_NAME =b.table_name AND T.COLUMN_NAME =b.column_name WHERE T.TABLE_NAME ='" + tableName + "'"); - ResultSet columnRs = columnIdPstmt.executeQuery(); - List listColumn = new ArrayList(); - while (columnRs.next()) { - ColumnInfo columnInfo = new ColumnInfo(); - //得到列名 - String columnName = columnRs.getString(2); - columnInfo.setName(columnName); - columnInfo.setIsIndex(0); - //得到主键的列名 - if (column_name.equals(columnName)) { - columnInfo.setIsIndex(1); - } - //得到序号 - int order = columnRs.getInt(1); - columnInfo.setOrder(order); - //得到类型 - String type = columnRs.getString(3); - columnInfo.setType(type); - //得到默认值 - String defaultValue = columnRs.getString(4); - columnInfo.setDefaultValue(defaultValue); - //是否为空 - String isNull = columnRs.getString(5); - if (isNull.equalsIgnoreCase("N")) { - isNull = "NO"; - } else { - isNull = "YES"; - } - columnInfo.setIsNull(isNull); - //得到列的描述 - String description = columnRs.getString(6); - columnInfo.setDescription(description); - listColumn.add(columnInfo); - } - //查询表的索引说明 - PreparedStatement rownumPstmt = conn.prepareStatement("SELECT rownum,rs.* FROM ( select t.index_name, i.index_type,listagg(t.column_name,',') within group (order by t.index_name) col_name from user_ind_columns t,user_indexes i where t.index_name = i.index_name " + - "and t.table_name = i.table_name and t.table_name = '" + tableName + "' GROUP BY t.index_name, i.index_type) rs "); - ResultSet IndexRs = rownumPstmt.executeQuery(); - List listIndex = new ArrayList(); - while (IndexRs.next()) { - IndexInfo indexInfo = new IndexInfo(); - String indexRsString = IndexRs.getString(2); - if (stringName.equalsIgnoreCase(indexRsString)) { - indexInfo.setIsIndex(1); - } - indexInfo.setOrder(IndexRs.getInt(1)); - indexInfo.setName(indexRsString); - indexInfo.setType(IndexRs.getString(3)); - indexInfo.setContainKey(IndexRs.getString(4)); - listIndex.add(indexInfo); - } - IndexRs.close(); - columnIdPstmt.close(); - columnRs.close(); - rownumPstmt.close(); - index_name.close(); - tableInfo.setTableName(tableName); - tableInfo.setDescription(COMMENTS); - tableInfo.setColumnList(listColumn); - tableInfo.setIndexInfoList(listIndex); - list.add(tableInfo); - } - rs.close(); - pstmt.close(); - } finally { - if (conn != null) { - try { - //关闭链接 - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - return list; - } -} \ No newline at end of file diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index 78e739b..efd7c3b 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -3,7 +3,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.db2.Db2Executor; -import com.trh.dictionary.service.oracleservice.OracleDatabase; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; @@ -14,6 +13,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.sql.Connection; +import java.util.Collections; import java.util.List; /** @@ -56,7 +56,7 @@ public class Test { @org.junit.Test public void testMakeOraclePdf() { try { - List tableInfo = OracleDatabase.getTableInfo("jdbc:oracle:thin:@//127.0.0.1:1521/orcl", "root", "123456"); + List tableInfo = Collections.emptyList();// OracleDatabase.getTableInfo("jdbc:oracle:thin:@//127.0.0.1:1521/orcl", "root", "123456"); if (tableInfo.size() == 0) { return; } -- Gitee From 5e0d63ab6435b8df7db28d0d0df5a45fcdbb88fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:25:10 +0800 Subject: [PATCH 23/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=B8=B2=E6=9F=93Markd?= =?UTF-8?q?own=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 13 +- .../com/trh/dictionary/service/BuildPDF.java | 57 --------- .../dictionary/service/DatabaseService.java | 2 - ...tePdfService.java => GenerateService.java} | 19 ++- .../service/impl/GenerateServiceImpl.java | 81 ++++++++++++ ...mpl.java => MySqlGenerateServiceImpl.java} | 15 ++- .../impl/PostgreSqlDatabaseServiceImpl.java | 119 +++++++++++++++++- .../service/postgreSQL/BuildPgSqlPdf.java | 11 -- src/test/java/com/trh/dictionary/Test.java | 4 +- 9 files changed, 239 insertions(+), 82 deletions(-) rename src/main/java/com/trh/dictionary/service/{GeneratePdfService.java => GenerateService.java} (41%) create mode 100644 src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java rename src/main/java/com/trh/dictionary/service/impl/{MySqlGeneratePdfServiceImpl.java => MySqlGenerateServiceImpl.java} (59%) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index bf991ee..29ce8c8 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -5,6 +5,7 @@ import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.service.GenerateService; import com.trh.dictionary.service.db2.Db2Executor; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; @@ -44,6 +45,8 @@ public class DatabaseController { private DataSourceService dataSourceService; @Autowired private DatabaseService databaseService; + @Autowired + private GenerateService generateService; @Autowired private HttpSession session; @@ -71,8 +74,7 @@ public class DatabaseController { return "markdown"; case POSTGRESQL: - model.addAttribute("markdown", BuildPgSqlPdf.getPgMarkdown(ip, database, port, username, password)); - return "markdown"; + tableInfo = databaseService.getTables(); case DB2: tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; @@ -84,7 +86,7 @@ public class DatabaseController { return "markdown"; } } - String markdown = BuildPDF.writeMarkdown(tableInfo); + String markdown = generateService.generateMarkdown(tableInfo); model.addAttribute("markdown", markdown); return "markdown"; } catch (Exception e) { @@ -119,7 +121,8 @@ public class DatabaseController { case "SQL server": return WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password); case "PostgreSQL": - return BuildPgSqlPdf.getPgMarkdown(ip, database, port, username, password); + tableInfo = databaseService.getTables(); + break; case "DB2": tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); break; @@ -131,7 +134,7 @@ public class DatabaseController { } } - return BuildPDF.writeMarkdown(tableInfo); + return generateService.generateMarkdown(tableInfo); } catch (Exception e) { logger.error("error==>" + e); return "### " + e.getMessage(); diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 309a0c5..440186b 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -573,63 +573,6 @@ public class BuildPDF { return table; } - /** - * 转成markdown语法 - */ - public static String writeMarkdown(List list) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (TableInfo info : list) { - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - if (columnInfos.size() > 0) { - - } - for (int k = 0; k < columnInfos.size(); k++) { - ColumnInfo Column = columnInfos.get(k); - oneTble.append("|").append(Column.getOrder()).append("|"). - append(Column.getName()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIsNull()).append("|"). - append(Column.getDefaultValue()).append("|"); - if ((k + 1) == columnInfos.size()) { - oneTble.append(Column.getDescription()).append("||"). - append("\n"); - } else { - oneTble.append(Column.getDescription()).append("|"). - append("\n"); - - } - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (IndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getName()).append("|"). - append(indexInfo.getType()).append("|"). - append(indexInfo.getContainKey()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - //createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); - } - //目录 - markdown.insert(0, "[TOC]\n"); - return markdown.toString(); - } - - /** * 写markdown文件 */ diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java index 8d0caf2..a269b18 100644 --- a/src/main/java/com/trh/dictionary/service/DatabaseService.java +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -1,7 +1,6 @@ package com.trh.dictionary.service; import com.trh.dictionary.bean.TableInfo; -import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.List; @@ -12,7 +11,6 @@ import java.util.List; * @author HouKunLin * @date 2019/9/11 0011 9:57 */ -@Service public interface DatabaseService { /** * 获得数据库名称列表 diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GenerateService.java similarity index 41% rename from src/main/java/com/trh/dictionary/service/GeneratePdfService.java rename to src/main/java/com/trh/dictionary/service/GenerateService.java index e2b13ae..1d9021e 100644 --- a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateService.java @@ -1,7 +1,10 @@ package com.trh.dictionary.service; +import com.trh.dictionary.bean.TableInfo; + import java.io.File; import java.sql.Connection; +import java.util.List; /** * 创建生成PDF文件的接口 @@ -9,6 +12,20 @@ import java.sql.Connection; * @author HouKunLin * @date 2019/9/11 0011 9:49 */ -public interface GeneratePdfService { +public interface GenerateService { + /** + * 构建PDF文件 + * + * @param connection + * @param file + */ void generatePdfFile(Connection connection, File file); + + /** + * 构建Markdown内容 + * + * @param tableInfos + * @return + */ + String generateMarkdown(List tableInfos); } diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java new file mode 100644 index 0000000..de3378c --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java @@ -0,0 +1,81 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.IndexInfo; +import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.service.GenerateService; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.sql.Connection; +import java.util.List; + +/** + * 创建PDF + * + * @author HouKunLin + * @date 2019/9/11 0011 11:16 + */ +@Primary +@Service +public class GenerateServiceImpl implements GenerateService { + @Override + public void generatePdfFile(Connection connection, File file) { + + } + + @Override + public String generateMarkdown(List tableInfos) { + StringBuffer markdown = new StringBuffer(); + String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; + int i = 1; + for (TableInfo info : tableInfos) { + StringBuffer oneTble = new StringBuffer(); + oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); + oneTble.append(res1); + List columnInfos = info.getColumnList(); + //拼接列 + if (columnInfos.size() > 0) { + + } + for (int k = 0; k < columnInfos.size(); k++) { + ColumnInfo Column = columnInfos.get(k); + oneTble.append("|").append(Column.getOrder()).append("|"). + append(Column.getName()).append("|"). + append(Column.getType()).append("|"). + append(Column.getIsNull()).append("|"). + append(Column.getDefaultValue()).append("|"); + if ((k + 1) == columnInfos.size()) { + oneTble.append(Column.getDescription()).append("||"). + append("\n"); + } else { + oneTble.append(Column.getDescription()).append("|"). + append("\n"); + + } + } + //拼接索引 + oneTble.append("\n"); + oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); + oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); + List indexInfolist = info.getIndexInfoList(); + int j = 1; + for (IndexInfo indexInfo : indexInfolist) { + oneTble.append("|").append(j).append("|"). + append(indexInfo.getName()).append("|"). + append(indexInfo.getType()).append("|"). + append(indexInfo.getContainKey()).append("|"). + append("\n"); + j++; + } + i++; + oneTble.append("\n"); + markdown.append(oneTble); + //createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); + } + //目录 + markdown.insert(0, "[TOC]\n"); + return markdown.toString(); + } +} diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java similarity index 59% rename from src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java rename to src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java index ee26cc3..5da7f1f 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java @@ -1,13 +1,16 @@ package com.trh.dictionary.service.impl; -import com.trh.dictionary.service.GeneratePdfService; +import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.service.GenerateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.io.File; import java.sql.Connection; +import java.util.List; /** * MySQL数据库创建PDF文件 @@ -15,8 +18,9 @@ import java.sql.Connection; * @author HouKunLin * @date 2019/9/11 0011 9:52 */ -public class MySqlGeneratePdfServiceImpl implements GeneratePdfService { - private static Logger logger = LoggerFactory.getLogger(MySqlGeneratePdfServiceImpl.class); +@Service +public class MySqlGenerateServiceImpl implements GenerateService { + private static Logger logger = LoggerFactory.getLogger(MySqlGenerateServiceImpl.class); @Autowired private DataSource dataSource; @@ -25,4 +29,9 @@ public class MySqlGeneratePdfServiceImpl implements GeneratePdfService { public void generatePdfFile(Connection connection, File file) { } + + @Override + public String generateMarkdown(List tableInfos) { + return null; + } } diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index f4649ff..a20d85b 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -1,7 +1,11 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.TableBasicEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -50,6 +54,119 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { - return null; + String sql = "SELECT pg_tables.schemaname,pg_tables.tablename,cast(obj_description(relfilenode,'pg_class') as varchar) as comment FROM pg_tables LEFT JOIN pg_class on relname=tablename WHERE tablename NOT LIKE 'pg%' AND tablename NOT LIKE 'sql_%'"; + + ResultSet resultSet; + List tableInfos = new ArrayList(64); + try { + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + TableInfo tableInfo = new TableInfo(); + String schemaName = resultSet.getString(1); + String tableName = resultSet.getString(2); + String desc = resultSet.getString(3); + tableInfo.setDescription(desc); + tableInfo.setStorageEngine(schemaName); + tableInfo.setTableName(tableName); + String sqlColumn = "SELECT A.attname AS 列名,concat_ws('',t.typname,SUBSTRING(format_type(A.atttypid,A.atttypmod) from '\\(.*\\)')),(CASE WHEN A.attlen> 0 THEN A.attlen ELSE A.atttypmod-4 END) AS 长度,A.attnotnull AS 是否可为空,d.adsrc AS 默认值,col_description (A.attrelid,A.attnum) AS 备注 FROM pg_class C,pg_attribute A LEFT JOIN (SELECT A.attname,ad.adsrc FROM pg_class C,pg_attribute A,pg_attrdef ad WHERE relname='" + tableName + "' AND ad.adrelid=C.oid AND adnum=A.attnum AND attrelid=C.oid) AS d ON A.attname=d.attname LEFT JOIN pg_type t on A.atttypid = t.oid WHERE C.relname='" + tableName + "' AND A.attrelid=C.oid AND A.attnum> 0;"; + String sqlIndex = "SELECT A.SCHEMANAME,A.TABLENAME,A.INDEXNAME,A.INDEXDEF,B.AMNAME,C.INDISUNIQUE,C.INDISPRIMARY,C.INDISCLUSTERED,D.DESCRIPTION FROM PG_AM B LEFT JOIN PG_CLASS F ON B.OID=F.RELAM LEFT JOIN PG_STAT_ALL_INDEXES E ON F.OID=E.INDEXRELID LEFT JOIN PG_INDEX C ON E.INDEXRELID=C.INDEXRELID LEFT OUTER JOIN PG_DESCRIPTION D ON C.INDEXRELID=D.OBJOID,PG_INDEXES A WHERE A.SCHEMANAME=E.SCHEMANAME AND A.TABLENAME=E.RELNAME AND A.INDEXNAME=E.INDEXRELNAME AND E.RELNAME='" + tableName + "'"; + //设置列信息 + tableInfo = getTableBaseInfo(connection, tableInfo, sqlColumn, sqlIndex); + tableInfos.add(tableInfo); + } + } catch (Exception e) { + logger.error("执行sql异常", e); + } + return tableInfos; + } + + /** + * 得到列名和索引 + * + * @param connection + * @param sqlColumn + * @param sqlIndex + * @return + */ + public static TableInfo getTableBaseInfo(Connection connection, TableInfo tableInfo, String sqlColumn, String sqlIndex) { + List indexInfos = new ArrayList<>(8); + List columnInfos = new ArrayList<>(16); + ResultSet resultSet; + ResultSet resultSet1; + //列 + try { + Statement statement = connection.createStatement(); + Statement statement1 = connection.createStatement(); + resultSet = statement.executeQuery(sqlIndex); + while (resultSet.next()) { + IndexInfo indexInfo = new IndexInfo(); + //索引名 + indexInfo.setName(resultSet.getString(3)); + //索引包含字段 + indexInfo.setContainKey(getIndexKey(resultSet.getString(4))); + //索引类型 + boolean isPk = resultSet.getString(7).trim().equals("t"); + if (isPk) { + indexInfo.setType(TableBasicEnum.WORD_PRIMARY.getDesc()); + indexInfo.setIsIndex(1); + } + if (resultSet.getString(6).equals("t") && !isPk) { + indexInfo.setType("UNIQUE"); + indexInfo.setIsIndex(0); + } else if (resultSet.getString(6).equals("f") && !isPk) { + indexInfo.setType(" "); + indexInfo.setIsIndex(0); + } + indexInfos.add(indexInfo); + } + resultSet1 = statement1.executeQuery(sqlColumn); + int order = 1; + while (resultSet1.next()) { + ColumnInfo columnInfo = new ColumnInfo(); + String name = resultSet1.getString(1); + for (IndexInfo info : indexInfos) { + if (info.getContainKey().equals(name)) { + columnInfo.setIsIndex(1); + } + } + columnInfo.setOrder(order); + columnInfo.setName(name); + columnInfo.setType(resultSet1.getString(2)); + boolean isNull = resultSet1.getString(4).equals("t"); + if (isNull) { + columnInfo.setIsNull("NO"); + } else { + columnInfo.setIsNull("YES"); + } + + columnInfo.setDefaultValue(resultSet1.getString(5)); + columnInfo.setDescription(resultSet1.getString(6)); + if (columnInfo.getDefaultValue() == null) { + columnInfo.setDefaultValue(""); + } + columnInfos.add(columnInfo); + order++; + } + } catch (Exception e) { + logger.error("获取列信息和索引信息异常", e); + } + tableInfo.setColumnList(columnInfos); + tableInfo.setIndexInfoList(indexInfos); + return tableInfo; + } + + /** + * 得到括号内的内容 + * + * @param desc + * @return + */ + public static String getIndexKey(String desc) { + int start = desc.indexOf("("); + int end = desc.indexOf(")"); + String key = desc.substring(start + 1, end); + return BuildPDF.dest(key, "\""); } } diff --git a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java index 2ba0bb1..c78595f 100644 --- a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java +++ b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java @@ -158,15 +158,4 @@ public class BuildPgSqlPdf { String key = desc.substring(start + 1, end); return BuildPDF.dest(key, "\""); } - - public static String getPgMarkdown(String ip, String dbName, String port, String userName, String passWord) throws Exception { - //得到生成数据 - String url = "jdbc:postgresql://" + ip + ":" + port + "/" + dbName; - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "pgSql"); - List list = getBuildPdfTableData(connection); - if (list.size() == 0) { - return "## 数据库无数据"; - } - return BuildPDF.writeMarkdown(list); - } } diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index efd7c3b..5d7f58c 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -64,7 +64,7 @@ public class Test { FileUtils.forceMkdir(new File(filePath)); //带目录 BuildPDF.build(filePath, tableInfo, "Oraclecd_core12"); - String markdown = BuildPDF.writeMarkdown(tableInfo); + String markdown = "";//BuildPDF.writeMarkdown(tableInfo); System.out.println(markdown); System.out.println("生成数据字典完毕,一共生成了" + tableInfo.size() + "条数据"); } catch (Exception e) { @@ -83,7 +83,7 @@ public class Test { FileUtils.forceMkdir(new File(filePath)); //带目录 BuildPDF.build(filePath, tableInfo, "Db2"); - BuildPDF.writeMarkdown(tableInfo); + // BuildPDF.writeMarkdown(tableInfo); } -- Gitee From feb973fd310b17ce29b136911c9c4487ae05e2e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:34:27 +0800 Subject: [PATCH 24/46] =?UTF-8?q?=E9=87=8D=E6=9E=84DB2=E7=9A=84getTables?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 20 +- .../sqlserver/SqlserverConnectionFactory.java | 4 +- .../dictionary/service/db2/Db2Executor.java | 211 ------------------ .../service/impl/Db2DatabaseServiceImpl.java | 133 ++++++++++- src/test/java/com/trh/dictionary/Test.java | 3 +- 5 files changed, 137 insertions(+), 234 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/db2/Db2Executor.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 29ce8c8..a9df218 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -6,7 +6,6 @@ import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; -import com.trh.dictionary.service.db2.Db2Executor; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; @@ -66,18 +65,13 @@ public class DatabaseController { switch (dto.getType()) { case MYSQL: case ORACLE: + case POSTGRESQL: + case DB2: tableInfo = databaseService.getTables(); break; case SQLSERVER: model.addAttribute("markdown", WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password)); - return "markdown"; - - case POSTGRESQL: - tableInfo = databaseService.getTables(); - case DB2: - tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); - break; default: } if (tableInfo != null) { @@ -116,16 +110,12 @@ public class DatabaseController { switch (selector) { case "mysql": case "oracle": + case "PostgreSQL": + case "DB2": tableInfo = databaseService.getTables(); break; case "SQL server": return WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password); - case "PostgreSQL": - tableInfo = databaseService.getTables(); - break; - case "DB2": - tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database.toUpperCase(), username, password); - break; default: } if (tableInfo != null) { @@ -171,7 +161,7 @@ public class DatabaseController { BuildPgSqlPdf.buildPdf(ip, database, port, username, password, filePath, "DataBase"); break; case "DB2": - List Db2tableInfo = Db2Executor.getDB2Tables(ip, Integer.valueOf(port), database, username, password); + List Db2tableInfo = databaseService.getTables(); if (Db2tableInfo.size() == 0) { return; } diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java index 0938387..29da903 100644 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java +++ b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java @@ -3,7 +3,9 @@ package com.trh.dictionary.dao.sqlserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; /** * @author zhou diff --git a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java b/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java deleted file mode 100644 index 57c3109..0000000 --- a/src/main/java/com/trh/dictionary/service/db2/Db2Executor.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.trh.dictionary.service.db2; - -import com.trh.dictionary.bean.ColumnInfo; -import com.trh.dictionary.bean.IndexInfo; -import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.util.SqlExecutor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.StringUtils; - -import java.sql.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author TangXu - * @create 2019-09-02 17:32 - * @description: - */ -public class Db2Executor { - - private static Logger logger = LoggerFactory.getLogger(Db2Executor.class); - -// public static void main(String[] args) throws SQLException, ClassNotFoundException { -// Connection connection = SqlExecutor.newDB2Connection("192.168.171.230", "TEST", "db2", "system"); -// List db2Tables = getDB2Tables(connection, "TEST"); -// for (TableInfo table : db2Tables) { -// getDb2Columns(connection, table.getTableName(), "TEST"); -// getTableIndexMap(connection, table.getTableName()); -// } -// } - - /** - * 查询表结构 - * - * @param connection - * @param table - * @param schema - * @throws SQLException - */ - public static List getDb2Columns(Connection connection, String table, String schema) throws SQLException { - String sql = "SELECT " + - " T.COLNO, " + - " T.COLNAME, " + - " T.REMARKS, " + - " T.TYPENAME, " + - " T.LENGTH, " + - " T.SCALE, " + - " T.DEFAULT, " + - " T.NULLS " + - "FROM " + - " SYSCAT.COLUMNS T " + - "WHERE " + - " T.TABSCHEMA = '" + schema + "'" + - " AND T.TABNAME = '" + table + "'" + - " ORDER BY T.COLNO"; - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(sql); - List columns = new ArrayList(); - while (rs.next()) { - ColumnInfo columnInfo = new ColumnInfo(); - columnInfo.setOrder(rs.getInt("COLNO") + 1); - columnInfo.setName(rs.getString("COLNAME").trim()); - columnInfo.setDescription(rs.getString("REMARKS").trim()); - columnInfo.setIsNull(rs.getString("NULLS").trim()); - columnInfo.setDefaultValue(StringUtils.isEmpty(rs.getString("DEFAULT")) ? "" : rs.getString("DEFAULT") - .trim()); - columnInfo.setType(rs.getString("TYPENAME").trim() + "(" + rs.getString("LENGTH").trim() + ")"); - columnInfo.setIsIndex(getTablePrimaryKey(connection, table, rs.getString("COLNAME").trim())); - columns.add(columnInfo); - } - SqlExecutor.releaseResource(null, null, rs, statement); - return columns; - } - - /** - * 判断是否是索引 - * - * @param connection - * @param table - * @param columnName - * @return - * @throws SQLException - */ - public static int isIndex(Connection connection, String table, String columnName) throws SQLException { - List> tableIndexes = getTableIndexMap(connection, table); - for (Map map : tableIndexes) { - if (map.containsKey(columnName)) { - return 1; - } - } - return 0; - } - - /** - * 获取表信息 - * - * @param connection - * @param table - * @return - * @throws SQLException - */ - public static List> getTableIndexMap(Connection connection, String table) throws SQLException { - List> indexList = new ArrayList>(); - String sql = "SELECT INDNAME, COLNAMES, UNIQUERULE FROM SYSCAT.INDEXES WHERE TABNAME = '" + table + "'"; - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(sql); - while (rs.next()) { - Map indexMap = new HashMap(); - String indexName = rs.getString("INDNAME"); - String columnName = rs.getString("COLNAMES"); - columnName = columnName.substring(1); -// String uniqueRule = rs.getString("UNIQUERULE"); - indexMap.put(columnName, indexName); - indexList.add(indexMap); - } - SqlExecutor.releaseResource(null, null, rs, statement); - return indexList; - } - - /** - * 获取表信息 - * - * @param connection - * @param table - * @return - * @throws SQLException - */ - public static List getTableIndexList(Connection connection, String table) throws SQLException { - List indexList = new ArrayList(); - String sql = "SELECT IID, INDNAME, COLNAMES, UNIQUERULE FROM SYSCAT.INDEXES WHERE TABNAME = '" + table + "'"; - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(sql); - while (rs.next()) { - IndexInfo indexInfo = new IndexInfo(); - String indexName = rs.getString("INDNAME"); - String columnName = rs.getString("COLNAMES"); - columnName = columnName.substring(1); - String uniqueRule = rs.getString("UNIQUERULE"); - indexInfo.setType(uniqueRule); - indexInfo.setName(indexName); - indexInfo.setContainKey(columnName); - int tablePrimaryKey = getTablePrimaryKey(connection, table, columnName); - indexInfo.setIsIndex(tablePrimaryKey); - indexInfo.setOrder(rs.getInt("IID")); - indexList.add(indexInfo); - } - SqlExecutor.releaseResource(null, null, rs, statement); - return indexList; - } - - /** - * 判断是否是主鍵 - * - * @param connection - * @param table - * @param columnName - * @return - * @throws SQLException - */ - public static int getTablePrimaryKey(Connection connection, String table, String columnName) throws SQLException { - String sql = "SELECT CONSTNAME, COLNAME FROM SYSCAT.KEYCOLUSE WHERE TABNAME = '" + table + "'"; - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(sql); - while (rs.next()) { - String primaryKey = rs.getString("CONSTNAME"); - String column_name = rs.getString("COLNAME"); - if (column_name.equalsIgnoreCase(columnName)) { - return 1; - } - } - SqlExecutor.releaseResource(null, null, rs, statement); - return 0; - } - - public static List getDB2Tables(String host, int port, String schema, String user, String password) throws SQLException, ClassNotFoundException { - Connection connection = SqlExecutor.newDB2Connection(host, port, schema, user, password); - return getDB2Tables(connection, schema); - } - - /** - * 获取表 - * - * @param connection - * @param schema - * @return - * @throws SQLException - */ - public static List getDB2Tables(Connection connection, String schema) throws SQLException { - List tables = new ArrayList(); - DatabaseMetaData metaData = connection.getMetaData(); - ResultSet rs = metaData.getTables(null, schema, "%", new String[]{"TABLE"}); - while (rs.next()) { - String tableName = rs.getString("TABLE_NAME"); - String remarks = rs.getString("REMARKS"); - if (StringUtils.isEmpty(tableName)) { - continue; - } - TableInfo tableInfo = new TableInfo(); - tableInfo.setTableName(tableName); - tableInfo.setDescription(remarks); - tableInfo.setColumnList(getDb2Columns(connection, tableName, schema)); - tableInfo.setIndexInfoList(getTableIndexList(connection, tableName)); - tables.add(tableInfo); - } - SqlExecutor.releaseResource(null, null, rs, null); - return tables; - } -} \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java index d8febb8..f18bc45 100644 --- a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -1,7 +1,11 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.ConnectionDTO; +import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.SqlExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,11 +13,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.ArrayList; import java.util.List; @@ -28,6 +30,8 @@ public class Db2DatabaseServiceImpl implements DatabaseService { private static Logger logger = LoggerFactory.getLogger(Db2DatabaseServiceImpl.class); @Autowired private DataSource dataSource; + @Autowired + private HttpSession session; @Override public List getDatabaseName() throws SQLException { @@ -48,6 +52,125 @@ public class Db2DatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { - return null; + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + String schema = dto.getDatabase().toUpperCase(); + List tables = new ArrayList(); + Connection connection = dataSource.getConnection(); + DatabaseMetaData metaData = connection.getMetaData(); + ResultSet rs = metaData.getTables(null, schema, "%", new String[]{"TABLE"}); + while (rs.next()) { + String tableName = rs.getString("TABLE_NAME"); + String remarks = rs.getString("REMARKS"); + if (StringUtils.isEmpty(tableName)) { + continue; + } + TableInfo tableInfo = new TableInfo(); + tableInfo.setTableName(tableName); + tableInfo.setDescription(remarks); + tableInfo.setColumnList(getDb2Columns(connection, tableName, schema)); + tableInfo.setIndexInfoList(getTableIndexList(connection, tableName)); + tables.add(tableInfo); + } + SqlExecutor.releaseResource(null, null, rs, null); + return tables; + } + + /** + * 查询表结构 + * + * @param connection + * @param table + * @param schema + * @throws SQLException + */ + public static List getDb2Columns(Connection connection, String table, String schema) throws SQLException { + String sql = "SELECT " + + " T.COLNO, " + + " T.COLNAME, " + + " T.REMARKS, " + + " T.TYPENAME, " + + " T.LENGTH, " + + " T.SCALE, " + + " T.DEFAULT, " + + " T.NULLS " + + "FROM " + + " SYSCAT.COLUMNS T " + + "WHERE " + + " T.TABSCHEMA = '" + schema + "'" + + " AND T.TABNAME = '" + table + "'" + + " ORDER BY T.COLNO"; + Statement statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(sql); + List columns = new ArrayList(); + while (rs.next()) { + ColumnInfo columnInfo = new ColumnInfo(); + columnInfo.setOrder(rs.getInt("COLNO") + 1); + columnInfo.setName(rs.getString("COLNAME").trim()); + columnInfo.setDescription(rs.getString("REMARKS").trim()); + columnInfo.setIsNull(rs.getString("NULLS").trim()); + columnInfo.setDefaultValue(StringUtils.isEmpty(rs.getString("DEFAULT")) ? "" : rs.getString("DEFAULT") + .trim()); + columnInfo.setType(rs.getString("TYPENAME").trim() + "(" + rs.getString("LENGTH").trim() + ")"); + columnInfo.setIsIndex(getTablePrimaryKey(connection, table, rs.getString("COLNAME").trim())); + columns.add(columnInfo); + } + SqlExecutor.releaseResource(null, null, rs, statement); + return columns; + } + + + /** + * 获取表信息 + * + * @param connection + * @param table + * @return + * @throws SQLException + */ + public static List getTableIndexList(Connection connection, String table) throws SQLException { + List indexList = new ArrayList(); + String sql = "SELECT IID, INDNAME, COLNAMES, UNIQUERULE FROM SYSCAT.INDEXES WHERE TABNAME = '" + table + "'"; + Statement statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(sql); + while (rs.next()) { + IndexInfo indexInfo = new IndexInfo(); + String indexName = rs.getString("INDNAME"); + String columnName = rs.getString("COLNAMES"); + columnName = columnName.substring(1); + String uniqueRule = rs.getString("UNIQUERULE"); + indexInfo.setType(uniqueRule); + indexInfo.setName(indexName); + indexInfo.setContainKey(columnName); + int tablePrimaryKey = getTablePrimaryKey(connection, table, columnName); + indexInfo.setIsIndex(tablePrimaryKey); + indexInfo.setOrder(rs.getInt("IID")); + indexList.add(indexInfo); + } + SqlExecutor.releaseResource(null, null, rs, statement); + return indexList; + } + + /** + * 判断是否是主鍵 + * + * @param connection + * @param table + * @param columnName + * @return + * @throws SQLException + */ + public static int getTablePrimaryKey(Connection connection, String table, String columnName) throws SQLException { + String sql = "SELECT CONSTNAME, COLNAME FROM SYSCAT.KEYCOLUSE WHERE TABNAME = '" + table + "'"; + Statement statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(sql); + while (rs.next()) { + String primaryKey = rs.getString("CONSTNAME"); + String column_name = rs.getString("COLNAME"); + if (column_name.equalsIgnoreCase(columnName)) { + return 1; + } + } + SqlExecutor.releaseResource(null, null, rs, statement); + return 0; } } diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index 5d7f58c..c036685 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -2,7 +2,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; -import com.trh.dictionary.service.db2.Db2Executor; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; @@ -75,7 +74,7 @@ public class Test { @org.junit.Test public void testMakeDb2ServerPdf() throws Exception { Connection connection = SqlExecutor.newDB2Connection("192.168.171.230", 50000, "TEST", "db2", "system"); - List tableInfo = Db2Executor.getDB2Tables(connection, "TEST"); + List tableInfo = Collections.emptyList(); //Db2Executor.getDB2Tables(connection, "TEST"); if (tableInfo.size() == 0) { return; } -- Gitee From 2d3da73bcb5e76d6ad29afdf3f72cb35c2e261ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 11:48:47 +0800 Subject: [PATCH 25/46] =?UTF-8?q?=E9=87=8D=E6=9E=84SQL=20Server=E6=B8=B2?= =?UTF-8?q?=E6=9F=93Markdown=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 51 +---- .../dictionary/service/GenerateService.java | 7 + .../service/impl/GenerateServiceImpl.java | 29 +++ .../impl/MySqlGenerateServiceImpl.java | 37 ---- .../SqlServerGenerateServiceImpl.java} | 200 +++--------------- src/test/java/com/trh/dictionary/Test.java | 5 +- 6 files changed, 73 insertions(+), 256 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java rename src/main/java/com/trh/dictionary/service/{sqlserver/WriteSqlserverMarkDown.java => impl/SqlServerGenerateServiceImpl.java} (44%) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index a9df218..1a61889 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -8,7 +8,6 @@ import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; -import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; import com.trh.dictionary.util.Keys; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; @@ -52,35 +51,11 @@ public class DatabaseController { @RequestMapping("/login.action") public String login(Model model, @Valid ConnectionDTO dto, Errors errors) throws Exception { - DataSource dataSource = dataSourceService.registerDateSource(dto); + dataSourceService.registerDateSource(dto); session.setAttribute(Keys.connectionDtoKey, dto); - String database = dto.getDatabase(); - String ip = dto.getHost(); - String port = dto.getPort(); - String username = dto.getUsername(); - String password = dto.getPassword(); - List tableInfo = null; try { - switch (dto.getType()) { - case MYSQL: - case ORACLE: - case POSTGRESQL: - case DB2: - tableInfo = databaseService.getTables(); - break; - case SQLSERVER: - model.addAttribute("markdown", WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password)); - return "markdown"; - default: - } - if (tableInfo != null) { - if (tableInfo.size() == 0) { - model.addAttribute("markdown", "## 数据库无数据"); - return "markdown"; - } - } - String markdown = generateService.generateMarkdown(tableInfo); + String markdown = generateService.generateMarkdown(); model.addAttribute("markdown", markdown); return "markdown"; } catch (Exception e) { @@ -104,27 +79,9 @@ public class DatabaseController { @RequestMapping("/getMarkdownString") @ResponseBody - public String getMarkdownString(Model model, String selector, String ip, String port, String password, String username, String database) { - List tableInfo = null; + public String getMarkdownString(Model model) { try { - switch (selector) { - case "mysql": - case "oracle": - case "PostgreSQL": - case "DB2": - tableInfo = databaseService.getTables(); - break; - case "SQL server": - return WriteSqlserverMarkDown.MakeMarkdownString(ip, database, port, username, password); - default: - } - if (tableInfo != null) { - if (tableInfo.size() == 0) { - return "## 数据库无数据"; - } - } - - return generateService.generateMarkdown(tableInfo); + return generateService.generateMarkdown(); } catch (Exception e) { logger.error("error==>" + e); return "### " + e.getMessage(); diff --git a/src/main/java/com/trh/dictionary/service/GenerateService.java b/src/main/java/com/trh/dictionary/service/GenerateService.java index 1d9021e..4180073 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateService.java @@ -28,4 +28,11 @@ public interface GenerateService { * @return */ String generateMarkdown(List tableInfos); + + /** + * 构建Markdown内容 + * + * @return + */ + String generateMarkdown(); } diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java index de3378c..e13a8cd 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java @@ -1,14 +1,21 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.enums.DatabaseType; +import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; +import com.trh.dictionary.util.Keys; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import java.io.File; import java.sql.Connection; +import java.sql.SQLException; import java.util.List; /** @@ -20,11 +27,33 @@ import java.util.List; @Primary @Service public class GenerateServiceImpl implements GenerateService { + @Autowired + private SqlServerGenerateServiceImpl sqlServerGenerateService; + @Autowired + private DatabaseService databaseService; + @Autowired + private HttpSession session; + @Override public void generatePdfFile(Connection connection, File file) { } + @Override + public String generateMarkdown() { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + DatabaseType type = dto.getType(); + if (type.equals(DatabaseType.SQLSERVER)) { + return sqlServerGenerateService.generateMarkdown(); + } + try { + return generateMarkdown(databaseService.getTables()); + } catch (SQLException e) { + e.printStackTrace(); + } + return "### 暂无数据"; + } + @Override public String generateMarkdown(List tableInfos) { StringBuffer markdown = new StringBuffer(); diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java deleted file mode 100644 index 5da7f1f..0000000 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlGenerateServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.trh.dictionary.service.impl; - -import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.service.GenerateService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.sql.DataSource; -import java.io.File; -import java.sql.Connection; -import java.util.List; - -/** - * MySQL数据库创建PDF文件 - * - * @author HouKunLin - * @date 2019/9/11 0011 9:52 - */ -@Service -public class MySqlGenerateServiceImpl implements GenerateService { - private static Logger logger = LoggerFactory.getLogger(MySqlGenerateServiceImpl.class); - - @Autowired - private DataSource dataSource; - - @Override - public void generatePdfFile(Connection connection, File file) { - - } - - @Override - public String generateMarkdown(List tableInfos) { - return null; - } -} diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java similarity index 44% rename from src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java rename to src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java index 4ea466a..f76ffeb 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/WriteSqlserverMarkDown.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java @@ -1,52 +1,53 @@ -package com.trh.dictionary.service.sqlserver; +package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; +import com.trh.dictionary.service.GenerateService; +import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import javax.sql.DataSource; import java.io.File; -import java.io.FileWriter; -import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** - * @author zhou - * @create 2019-09-04 11:43 - * @description: + * MySQL数据库创建PDF文件 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:52 */ -public class WriteSqlserverMarkDown { +@Service +public class SqlServerGenerateServiceImpl implements GenerateService { + private static Logger logger = LoggerFactory.getLogger(SqlServerGenerateServiceImpl.class); - static Logger logger = LoggerFactory.getLogger(WriteSqlserverMarkDown.class); + @Autowired + private DataSource dataSource; - /** - * 生成Markdown - * - * @param ip :数据库连接的IP 例如:127.0.0.1 或者 localhost - * @param dbName 例如: test - * @param port 例如: 3306 - * @param userName 例如: root - * @param passWord 例如: root - * @param filePath 例如: D:\ideaspace\export_dbInfo\src\main\resources\ - */ - public static void MakeMarkdown(String ip, String dbName, String port, String userName, String passWord, String filePath) { + @Override + public void generatePdfFile(Connection connection, File file) { + + } + + @Override + public String generateMarkdown() { Connection connection = null; try { - - String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; //得到生成数据 - connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); + connection = dataSource.getConnection(); String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); if (list_table.size() == 0) { - return; + return "## 数据库无数据"; } for (SqlserverTabelInfo Ta : list_table) { logger.info(Ta.getTableName()); @@ -83,7 +84,7 @@ public class WriteSqlserverMarkDown { Ta.setIndexInfoList(list_index); } - writeMarkdown(list_table, filePath); + return writeMarkdownString(list_table); } catch (Exception e) { e.printStackTrace(); @@ -95,56 +96,12 @@ public class WriteSqlserverMarkDown { e.printStackTrace(); } } + return "### 暂无数据"; } - - /** - * 写markdown文件 - */ - public static void writeMarkdown(List list, String filePath) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (SqlserverTabelInfo info : list) { - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + "\n" + "基本信息:" + info.getValue() + " " - + "\n\n" + "|序列|列名|主键|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - for (SqlserverColumnInfo Column : columnInfos) { - oneTble.append("|").append(Column.getColumn_num()).append("|"). - append(Column.getColumn_name()).append("|"). - append(Column.getP_k()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIs_null()).append("|"). - append(Column.getDefault_value()).append("|"). - append(Column.getDecs()).append("|"). - append("\n"); - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|描述|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (SqlserverIndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getIndex_name()).append("|"). - append(indexInfo.getIndex_desc()).append("|"). - append(indexInfo.getIndex_keys()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); - } - //目录 - markdown.insert(0, "[TOC]\n"); - logger.info("表信息\n" + markdown.toString()); - createDir(filePath + "\\allTable.txt", markdown.toString()); + @Override + public String generateMarkdown(List tableInfos) { + return ""; } public static String writeMarkdownString(List list) { @@ -192,99 +149,4 @@ public class WriteSqlserverMarkDown { return markdown.toString(); } - - /** - * 创建文件夹 - * - * @param fileName - * @param content - */ - public static void createDir(String fileName, String content) { - File file = new File(fileName); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdir(); - } - if (!file.exists()) { - try { - file.createNewFile(); - //写文件 - FileWriter writer = new FileWriter(fileName); - writer.write(content); - writer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /* - * @Author zhou - * @Description //TODO - * @Date 16:47 2019/9/5 - * @Param [ip, dbName, port, userName, passWord] - * @return void - **/ - public static String MakeMarkdownString(String ip, String dbName, String port, String userName, String passWord) { - Connection connection = null; - try { - - String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; - //得到生成数据 - connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - - String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - - List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); - if (list_table.size() == 0) { - return "## 数据库无数据"; - } - for (SqlserverTabelInfo Ta : list_table) { - logger.info(Ta.getTableName()); - List list_column = new ArrayList(); - List list_index = new ArrayList(); - String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + - "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + - "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + - "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; - try { - list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); - for (SqlserverColumnInfo s : list_column) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + - "SELECT i.name AS index_name,(\n" + - "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + - "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; - try { - logger.info(sqlindex); - list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); - for (SqlserverIndexInfo s : list_index) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - Ta.setColumnList(list_column); - Ta.setIndexInfoList(list_index); - } - - return writeMarkdownString(list_table); - - } catch (Exception e) { - e.printStackTrace(); - logger.info("生成Markdown失败"); - } finally { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return ""; - } -} \ No newline at end of file +} diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index c036685..99e435f 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -4,7 +4,6 @@ import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; -import com.trh.dictionary.service.sqlserver.WriteSqlserverMarkDown; import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; @@ -89,12 +88,12 @@ public class Test { @org.junit.Test public void testMakeSqlServerMarkdown() { String FILE_DIR = "F:/pdf/"; - WriteSqlserverMarkDown.MakeMarkdown("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA", FILE_DIR); + // WriteSqlserverMarkDown.MakeMarkdown("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA", FILE_DIR); } @org.junit.Test public void testMakeSqlServerMarkdownStrig() { - logger.info(WriteSqlserverMarkDown.MakeMarkdownString("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA")); + // logger.info(WriteSqlserverMarkDown.MakeMarkdownString("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA")); } -- Gitee From aacc5e09f7e15953581fd4d4dbb675c04d436aff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 12:07:35 +0800 Subject: [PATCH 26/46] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E6=B8=B2=E6=9F=93PDF=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 36 +- .../com/trh/dictionary/service/BuildPDF.java | 30 -- .../dictionary/service/GenerateService.java | 26 ++ .../service/impl/GenerateServiceImpl.java | 374 ++++++++++++++++++ .../impl/SqlServerGenerateServiceImpl.java | 16 + 5 files changed, 423 insertions(+), 59 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 1a61889..33bfb6a 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -1,15 +1,12 @@ package com.trh.dictionary.conterller; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; -import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.Keys; -import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -96,51 +93,32 @@ public class DatabaseController { .replaceAll("target/classes/", "") .replaceAll("target/test-classes/", ""); filePath += "src/main/resources/"; + File outfile = new File(filePath, "DataBase.pdf"); try { switch (selector) { case "mysql": - //得到生成数据 - BuildPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); - break; case "oracle": - List tableInfo = databaseService.getTables(); - if (tableInfo.size() == 0) { - return; - } - FileUtils.forceMkdir(new File(filePath)); - //带目录 - BuildPDF.build(filePath, tableInfo, "DataBase"); + case "PostgreSQL": + case "DB2": + generateService.generatePdfFile(outfile); break; case "SQL server": BuildSqlserverPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); break; - case "PostgreSQL": - BuildPgSqlPdf.buildPdf(ip, database, port, username, password, filePath, "DataBase"); - break; - case "DB2": - List Db2tableInfo = databaseService.getTables(); - if (Db2tableInfo.size() == 0) { - return; - } - FileUtils.forceMkdir(new File(filePath)); - //带目录 - BuildPDF.build(filePath, Db2tableInfo, "DataBase"); - break; + default: } } catch (Exception e) { logger.error("error==>" + e); } - String fileName = "DataBase.pdf"; res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); - res.setHeader("Content-Disposition", "attachment; filename=" + fileName); + res.setHeader("Content-Disposition", "attachment; filename=" + outfile.getName()); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); - bis = new BufferedInputStream(new FileInputStream( - new File(filePath + fileName))); + bis = new BufferedInputStream(new FileInputStream(outfile)); int i = bis.read(buff); while (i != -1) { diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java index 440186b..23918c6 100644 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ b/src/main/java/com/trh/dictionary/service/BuildPDF.java @@ -96,36 +96,6 @@ public class BuildPDF { } } - public static void main(String[] args) { - try { -/* //得到生成数据 -// List list = getBuildPdfTableData(getTables("localhost", "trh_bill", "3306", "root", "root")); -// logger.info("--------" + list.size()); -// String name = "D:\\ideaspace\\export_dbInfo\\src\\main\\resources\\txt\\" + System.currentTimeMillis(); -//// String FILE_DIR = "D:\\ideaspace\\database-dictionary\\src\\main\\resources\\pdf\\"; -// String FILE_DIR = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); -// logger.info("FILE_DIR===" + FILE_DIR); -// FILE_DIR += "src/main/resources/pdf/"; -// //生成markdown语法 -//// writeMarkdown(list,name); -// FileUtils.forceMkdir(new File(FILE_DIR)); -// -// //生成pdf -// createPdf(FILE_DIR, list, "trh_bill2"); -// -// //带目录 -// build(FILE_DIR, list, "trh_bill3"); -//// demo();*/ -// String FILE_DIR = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); -// logger.info("FILE_DIR===" + FILE_DIR); - String FILE_DIR = "F:/pdf/"; - MakePdf("localhost", "cd_core", "3306", "root", "root", FILE_DIR, "cd_core"); - } catch (Exception e) { - e.getStackTrace(); - - } - } - /** * 获取数据库所有表信息 diff --git a/src/main/java/com/trh/dictionary/service/GenerateService.java b/src/main/java/com/trh/dictionary/service/GenerateService.java index 4180073..1742ef1 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateService.java @@ -1,8 +1,10 @@ package com.trh.dictionary.service; +import com.itextpdf.text.DocumentException; import com.trh.dictionary.bean.TableInfo; import java.io.File; +import java.io.IOException; import java.sql.Connection; import java.util.List; @@ -21,6 +23,30 @@ public interface GenerateService { */ void generatePdfFile(Connection connection, File file); + /** + * 构建PDF文件 + * + * @param tableInfos + */ + void generatePdfFile(List tableInfos); + + /** + * 构建PDF文件 + * + * @param tableInfos + * @param file + * @throws DocumentException + * @throws IOException + */ + void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException; + + /** + * 构建PDF文件 + * + * @param file + */ + void generatePdfFile(File file); + /** * 构建Markdown内容 * diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java index e13a8cd..172fc59 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java @@ -1,22 +1,45 @@ package com.trh.dictionary.service.impl; +import com.github.houbb.markdown.toc.util.StringUtil; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.BaseFont; +import com.itextpdf.text.pdf.PdfPCell; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.text.pdf.draw.DottedLineSeparator; import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.enums.DatabaseType; +import com.trh.dictionary.event.ContentEvent; +import com.trh.dictionary.event.IndexEvent; +import com.trh.dictionary.event.pdfPageEvent; +import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; import com.trh.dictionary.util.Keys; +import com.trh.dictionary.util.SignEnum; +import com.trh.dictionary.util.TableBasicEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; +import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; import java.sql.Connection; import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * 创建PDF @@ -27,6 +50,7 @@ import java.util.List; @Primary @Service public class GenerateServiceImpl implements GenerateService { + private static Logger logger = LoggerFactory.getLogger(GenerateServiceImpl.class); @Autowired private SqlServerGenerateServiceImpl sqlServerGenerateService; @Autowired @@ -39,6 +63,356 @@ public class GenerateServiceImpl implements GenerateService { } + @Override + public void generatePdfFile(List tableInfos) { + + } + + @Override + public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { + String fontDir = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", "").replaceAll("target/test-classes/", ""); + fontDir += "src/main/resources/"; + BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); + Font font = new Font(bfChinese, 12, Font.BOLDITALIC); + // 设置类型,加粗 + font.setStyle(Font.NORMAL); + Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 16); + //页面大小 + Rectangle rect = new Rectangle(PageSize.A4).rotate(); + //页面背景色 + rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); + //设置边框颜色 + rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); + Document doc = new Document(rect); + PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); + //设置事件 + ContentEvent event = new ContentEvent(); + contentWriter.setPageEvent(event); + //存目录监听 开始 + doc.open(); + int order = 1; + List chapterList = new ArrayList(); + //根据chapter章节分页 + //表格 + //设置表格模板 + String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; + String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; + for (TableInfo tableInfo : tableInfos) { + tableInfo = setIsIndex(tableInfo); + Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); + //设置跳转地址 + Phrase point = new Paragraph("基本信息:", cnFont); + Anchor tome = new Anchor(point); + tome.setName(tableInfo.getTableName()); + Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); + Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); + Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", getChineseFontAsStyle(BaseColor.BLACK, 16)); + //组装基本数据 + Paragraph contentInfo = new Paragraph(); + contentInfo.add(tome); + contentInfo.add(engine); + contentInfo.add(type); + contentInfo.add(description); + chapter.add(contentInfo); + chapter.add(new Paragraph("")); + //组装表格 + Paragraph tableParagraph = new Paragraph(); + //设置表格 + PdfPTable table = setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); + //设置列信息 + setTableColumn(table, tableInfo, font); + tableParagraph.add(table); + chapter.add(tableParagraph); + //设置索引表 + Paragraph blankTwo = new Paragraph("\n\n"); + chapter.add(blankTwo); + PdfPTable indexTable = setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); + table.setWidthPercentage(100); + indexTable = setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), getFontAsStyle(BaseColor.RED, 10)); + Paragraph indexTableParagraph = new Paragraph(); + indexTableParagraph.add(indexTable); + chapter.add(indexTableParagraph); + + //加入文档中 + doc.add(chapter); + //保存章节内容 + chapterList.add(chapter); + order++; + } + doc.close(); + //存目录监听 结束 + + + Document document = new Document(rect); + FileOutputStream os = new FileOutputStream(file); + PdfWriter writer = PdfWriter.getInstance(document, os); + IndexEvent indexEvent = new IndexEvent(); + writer.setPageEvent(indexEvent); + document.open(); + //添加章节目录 + Chapter indexChapter = new Chapter(new Paragraph("", getFontAsStyle(BaseColor.BLACK, 18)), 0); + indexChapter.setNumberDepth(-1); + // 设置数字深度 + int i = 1; + for (Map.Entry index : event.index.entrySet()) { + String key = index.getKey(); + String[] keyValue = key.split(" "); + //设置跳转显示名称 + int pageNo = index.getValue(); + Chunk pointChunk = new Chunk(new DottedLineSeparator()); + Chunk pageNoChunk = new Chunk(pageNo + ""); + String tempDescription = key; + if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { + tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; + } + Paragraph jumpParagraph = new Paragraph(tempDescription, getChineseFontAsStyle(BaseColor.BLACK, 12)); + jumpParagraph.add(pointChunk); + jumpParagraph.add(pageNoChunk); + Anchor anchor = new Anchor(jumpParagraph); + String jump = keyValue[keyValue.length - 1].trim(); + //设置跳转链接 + anchor.setReference("#" + jump); + indexChapter.add(anchor); + indexChapter.add(new Paragraph()); + i++; + } + document.add(indexChapter); + document.newPage(); + //添加内容 + for (Chapter c : chapterList) { + indexEvent.setBody(true); + document.add(c); + } + + document.close(); + os.close(); + } + + @Override + public void generatePdfFile(File file) { + + } + + public static TableInfo setIsIndex(TableInfo tableInfo) { + List columnInfos = tableInfo.getColumnList(); + List indexInfos = tableInfo.getIndexInfoList(); + for (ColumnInfo columnInfo : columnInfos) { + for (IndexInfo indexInfo : indexInfos) { + String temp = indexInfo.getContainKey(); +// if (temp.contains(SignEnum.comma.getDesc())) { +// String[] keys = temp.split(SignEnum.comma.getDesc()); +// for (int i = 0; i < keys.length; i++) { +// String key = keys[i]; +// if (key.trim().equals(columnInfo.getName().trim())) { +// columnInfo.setIsIndex(1); +// } +// if (key.trim().contains(columnInfo.getName()) && columnInfo.getOrder() == 1) { +// columnInfo.setIsIndex(1); +// } +// } +// } else { +// if (temp.trim().equals(columnInfo.getName().trim())) { +// columnInfo.setIsIndex(1); +// } + String[] res = columnInfo.getName().split(" "); + if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc().equals(indexInfo.getType().trim())) { + columnInfo.setIsIndex(1); + } +// } + } + } + return tableInfo; + } + + /** + * 设置表格头部 + * + * @param header + * @param font + * @return + */ + public static PdfPTable setTableHeader(String[] header, Font font) { + int columnSize = header.length; + PdfPTable table = new PdfPTable(columnSize); + table.setWidthPercentage(100); + for (String value : header) { + PdfPCell cell1 = new PdfPCell(new Paragraph(value, font)); + cell1.setVerticalAlignment(Element.ALIGN_CENTER); +// cell1.setHorizontalAlignment(Element.ALIGN_CENTER); + cell1.setHorizontalAlignment(Element.ALIGN_LEFT); + cell1.setBackgroundColor(BaseColor.LIGHT_GRAY); + table.addCell(cell1); + } + return table; + } + + /** + * 设置基本表格的列 + * + * @param table + * @param tableInfo + * @param font + * @return + */ + public static PdfPTable setTableColumn(PdfPTable table, TableInfo tableInfo, Font font) { + List Columns = tableInfo.getColumnList(); + for (ColumnInfo column : Columns) { + table = reflectBuildCell(column, table, font, tableInfo); + } + return table; + } + + /** + * 设置基本表格的列 + * + * @param table + * @param Columns + * @return + */ + public static PdfPTable setIndexTableColumn(PdfPTable table, List Columns, Font font) { + int order = 1; + for (IndexInfo column : Columns) { + column.setOrder(order); + table = reflectBuildCell(column, table, font, null); + order++; + } + return table; + } + + + /** + * 通过反射填写表格内容 + * + * @param obj + * @author wangyu + * @date 2019-8-6 + */ + public static PdfPTable reflectBuildCell(Object obj, PdfPTable table, Font font, TableInfo tableInfo) { + if (obj == null) { + logger.error("填写表格内容对象为空"); + return table; + } + Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + Field[] fields = obj.getClass().getDeclaredFields(); + for (Field field : fields) { + PdfPCell cell = new PdfPCell(); + cell.setVerticalAlignment(Element.ALIGN_CENTER); + Paragraph paragraph = new Paragraph(); + //将设置私有构造器设为可取值 + field.setAccessible(true); + String name = field.getName(); + + if ("isIndex".equals(name)) { + try { + if ((Integer) field.get(obj) == 1) { + font = getFontAsStyle(BaseColor.RED, 12); + cnFont = getChineseFontAsStyle(BaseColor.RED, 12); + } else { + font = getFontAsStyle(BaseColor.BLACK, 12); + cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + continue; + } + + if (null != tableInfo) { + + } + + // 得到类型和名字取值 + if (field.getType().getName().equals(String.class.getName())) { + // String type + try { + if (isChineseContent(field.get(obj) + "")) { + font = cnFont; + } + paragraph = new Paragraph(field.get(obj) + "", font); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else if (field.getType().getName().equals(Integer.class.getName()) + || field.getType().getName().equals("int")) { + // Integer type + try { + paragraph = new Paragraph(field.get(obj) + "", font); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch b lock + e.printStackTrace(); + } + } + //添加到表格 + cell.addElement(paragraph); + table.addCell(cell); + } + return table; + } + + //设置页码 + public static void setFooter(PdfWriter writer, BaseFont bf) { + pdfPageEvent headerFooter = new pdfPageEvent(bf, 13, PageSize.A0); + writer.setPageEvent(headerFooter); + } + + public static String getPoint(String name, int size) { + int length = name.length(); + int res = size - length; + StringBuffer str = new StringBuffer(); + for (int i = 0; i < res; i++) { + str.append(SignEnum.point.getDesc()); + } + return str.toString(); + } + + /** + * 得到默认字体 + * + * @param color + * @param size + * @return + */ + public static Font getFontAsStyle(BaseColor color, float size) { + Font font = new Font(); + font.setColor(color); + font.setSize(size); + return font; + } + + /** + * 得到汉字字体 + * + * @param color + * @param size + * @return + */ + public static Font getChineseFontAsStyle(BaseColor color, float size) { + try { + //中文字体 + BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); + Font font = new Font(bfChinese, size, Font.NORMAL); + font.setColor(color); + return font; + } catch (Exception e) { + logger.error("生成中文字体异常", e); + return new Font(); + } + } + + public static boolean isChineseContent(String content) { + String regex = "[\u4e00-\u9fa5]"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(content); + return matcher.find(); + } + @Override public String generateMarkdown() { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java index f76ffeb..9a69da1 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java @@ -36,6 +36,22 @@ public class SqlServerGenerateServiceImpl implements GenerateService { } + @Override + public void generatePdfFile(List tableInfos) { + + } + + + @Override + public void generatePdfFile(List tableInfos, File file) { + + } + + @Override + public void generatePdfFile(File file) { + + } + @Override public String generateMarkdown() { Connection connection = null; -- Gitee From d1c1961b290136d6c516931e7528a2376cb81ef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 13:36:38 +0800 Subject: [PATCH 27/46] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E5=8F=AF=E8=8E=B7=E5=8F=96=E6=8C=87=E5=AE=9A?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E5=90=8D=EF=BC=88schema/database?= =?UTF-8?q?=EF=BC=89=E7=9A=84=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 4 ++-- .../dictionary/service/DatabaseService.java | 9 ++++++++ .../dictionary/service/GenerateService.java | 8 +++++++ .../service/impl/DatabaseServiceImpl.java | 6 ++++++ .../service/impl/Db2DatabaseServiceImpl.java | 5 +++++ .../service/impl/GenerateServiceImpl.java | 21 ++++++++++++++----- .../impl/MySqlDatabaseServiceImpl.java | 11 +++++++--- .../impl/OracleDatabaseServiceImpl.java | 6 ++++++ .../impl/PostgreSqlDatabaseServiceImpl.java | 11 ++++++++++ .../impl/SqlServerDatabaseServiceImpl.java | 11 ++++++++++ .../impl/SqlServerGenerateServiceImpl.java | 11 ++++++++-- 11 files changed, 91 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 33bfb6a..0e831ac 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -76,9 +76,9 @@ public class DatabaseController { @RequestMapping("/getMarkdownString") @ResponseBody - public String getMarkdownString(Model model) { + public String getMarkdownString(Model model, String database) { try { - return generateService.generateMarkdown(); + return generateService.generateMarkdown(database); } catch (Exception e) { logger.error("error==>" + e); return "### " + e.getMessage(); diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java index a269b18..7a0c3bc 100644 --- a/src/main/java/com/trh/dictionary/service/DatabaseService.java +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -27,4 +27,13 @@ public interface DatabaseService { * @throws SQLException */ List getTables() throws SQLException; + + /** + * 获取数据库表列表 + * + * @param schema 数据库名称(模式名称) + * @return 数据库表信息 + * @throws SQLException + */ + List getTables(String schema) throws SQLException; } diff --git a/src/main/java/com/trh/dictionary/service/GenerateService.java b/src/main/java/com/trh/dictionary/service/GenerateService.java index 1742ef1..5d7ba13 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateService.java @@ -55,6 +55,14 @@ public interface GenerateService { */ String generateMarkdown(List tableInfos); + /** + * 构建Markdown内容 + * + * @param schema + * @return + */ + String generateMarkdown(String schema); + /** * 构建Markdown内容 * diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index becfaa3..cb95833 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -66,6 +66,12 @@ public class DatabaseServiceImpl implements DatabaseService { return getDatabaseService().getTables(); } + + @Override + public List getTables(String schema) throws SQLException { + return getDatabaseService().getTables(schema); + } + @PostConstruct public void post() { map.put(DatabaseType.DB2, db2DatabaseService); diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java index f18bc45..6437a4b 100644 --- a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -54,6 +54,11 @@ public class Db2DatabaseServiceImpl implements DatabaseService { public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); String schema = dto.getDatabase().toUpperCase(); + return getTables(schema); + } + + @Override + public List getTables(String schema) throws SQLException { List tables = new ArrayList(); Connection connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java index 172fc59..0408f57 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java @@ -70,7 +70,10 @@ public class GenerateServiceImpl implements GenerateService { @Override public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { - String fontDir = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", "").replaceAll("target/test-classes/", ""); + String fontDir = BuildPDF.class.getResource("/") + .getPath() + .replaceAll("target/classes/", "") + .replaceAll("target/test-classes/", ""); fontDir += "src/main/resources/"; BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); Font font = new Font(bfChinese, 12, Font.BOLDITALIC); @@ -215,7 +218,8 @@ public class GenerateServiceImpl implements GenerateService { // columnInfo.setIsIndex(1); // } String[] res = columnInfo.getName().split(" "); - if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc().equals(indexInfo.getType().trim())) { + if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc() + .equals(indexInfo.getType().trim())) { columnInfo.setIsIndex(1); } // } @@ -415,13 +419,19 @@ public class GenerateServiceImpl implements GenerateService { @Override public String generateMarkdown() { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return generateMarkdown(dto.getDatabase()); + } + + @Override + public String generateMarkdown(String schema) { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); DatabaseType type = dto.getType(); if (type.equals(DatabaseType.SQLSERVER)) { - return sqlServerGenerateService.generateMarkdown(); + return sqlServerGenerateService.generateMarkdown(schema); } try { - return generateMarkdown(databaseService.getTables()); + return generateMarkdown(databaseService.getTables(schema)); } catch (SQLException e) { e.printStackTrace(); } @@ -435,7 +445,8 @@ public class GenerateServiceImpl implements GenerateService { int i = 1; for (TableInfo info : tableInfos) { StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); + oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info + .getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); oneTble.append(res1); List columnInfos = info.getColumnList(); //拼接列 diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index 780dc21..180312c 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -61,6 +61,11 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return getTables(dto.getDatabase()); + } + + @Override + public List getTables(String schema) throws SQLException { //循环处理表 List resultList = new ArrayList(); @@ -72,7 +77,7 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { connection = dataSource.getConnection(); //获取表名 statement = connection.createStatement(); - String sql = "SHOW TABLES FROM `" + dto.getDatabase() + "`"; + String sql = "SHOW TABLES FROM `" + schema + "`"; resultSet = statement.executeQuery(sql); while (resultSet.next()) { TableInfo tableInfo = new TableInfo(); @@ -102,7 +107,6 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { return resultList; } - /** * 获取单个表全部信息 * @@ -136,7 +140,8 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { int order = 1; while (resultSet.next()) { ColumnInfo columnInfo = new ColumnInfo(); - columnInfo.setName(resultSet.getString(ColumnBasicEnum.Field.getDesc()) + " " + resultSet.getString(ColumnBasicEnum.Extra.getDesc())); + columnInfo.setName(resultSet.getString(ColumnBasicEnum.Field.getDesc()) + " " + resultSet.getString(ColumnBasicEnum.Extra + .getDesc())); columnInfo.setType(resultSet.getString(ColumnBasicEnum.Type.getDesc())); columnInfo.setDescription(resultSet.getString(ColumnBasicEnum.Comment.getDesc())); columnInfo.setIsNull(resultSet.getString(ColumnBasicEnum.Null.getDesc())); diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java index d597948..da8d407 100644 --- a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -43,6 +43,12 @@ public class OracleDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return getTables(dto.getDatabase()); + } + + @Override + public List getTables(String schema) throws SQLException { List list = new ArrayList(); PreparedStatement pstmt; Connection conn = null; diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index a20d85b..7e3d978 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -1,16 +1,19 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.TableBasicEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; @@ -30,6 +33,8 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { private static Logger logger = LoggerFactory.getLogger(PostgreSqlDatabaseServiceImpl.class); @Autowired private DataSource dataSource; + @Autowired + private HttpSession session; @Override public List getDatabaseName() { @@ -54,6 +59,12 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return getTables(dto.getDatabase()); + } + + @Override + public List getTables(String schema) throws SQLException { String sql = "SELECT pg_tables.schemaname,pg_tables.tablename,cast(obj_description(relfilenode,'pg_class') as varchar) as comment FROM pg_tables LEFT JOIN pg_class on relname=tablename WHERE tablename NOT LIKE 'pg%' AND tablename NOT LIKE 'sql_%'"; ResultSet resultSet; diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index 53eb129..0177a36 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -1,13 +1,16 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; +import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @@ -25,6 +28,8 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { private static Logger logger = LoggerFactory.getLogger(SqlServerDatabaseServiceImpl.class); @Autowired private DataSource dataSource; + @Autowired + private HttpSession session; @Override public List getDatabaseName() { @@ -49,6 +54,12 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { @Override public List getTables() throws SQLException { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return getTables(dto.getDatabase()); + } + + @Override + public List getTables(String schema) throws SQLException { return null; } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java index 9a69da1..0fda429 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java @@ -54,6 +54,11 @@ public class SqlServerGenerateServiceImpl implements GenerateService { @Override public String generateMarkdown() { + return generateMarkdown((String) null); + } + + @Override + public String generateMarkdown(String schema) { Connection connection = null; try { //得到生成数据 @@ -73,7 +78,8 @@ public class SqlServerGenerateServiceImpl implements GenerateService { "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta + .getTableName() + "'"; try { list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); for (SqlserverColumnInfo s : list_column) { @@ -86,7 +92,8 @@ public class SqlServerGenerateServiceImpl implements GenerateService { "SELECT i.name AS index_name,(\n" + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta + .getTableName() + "')) Ind ORDER BY index_name"; try { logger.info(sqlindex); list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); -- Gitee From 4da5426a14d9b5d94b70c2c50068e8ed56e80049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 13:37:55 +0800 Subject: [PATCH 28/46] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=89=8D=E7=AB=AF?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=E7=9A=84=E4=B8=80=E4=BA=9B=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/templates/index.html | 17 ++-- src/main/resources/templates/markdown.html | 100 ++++++++++----------- 2 files changed, 55 insertions(+), 62 deletions(-) diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index f997351..474a7d0 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -154,7 +154,7 @@
-

mysql

+

MYSQL

@@ -162,7 +162,7 @@
-

oracle

+

ORACLE

@@ -170,7 +170,7 @@
-

SQL server

+

SQLSERVER

@@ -178,7 +178,7 @@
-

PostgreSQL

+

POSTGRESQL

@@ -251,23 +251,22 @@ return alert("参数不完整!"); } - sessionStorage.setItem("ip", ip); + sessionStorage.setItem("host", ip); sessionStorage.setItem("port", port); sessionStorage.setItem("database", database); sessionStorage.setItem("username", username); sessionStorage.setItem("password", password); - sessionStorage.setItem("selector",selector) + sessionStorage.setItem("type", selector); var body = $("body"); //创建表单 var form = $("
"); //设置表单各项属性 form.attr("action", "login.action"); form.attr("method", "post"); - form.attr("method", "post"); - var input = $(""); + var input = $(""); input.attr("value", $("#u12_input").val()); form.append(input); - var ipInput = $(""); + var ipInput = $(""); ipInput.attr("value",ip); form.append(ipInput); var portInput = $(""); diff --git a/src/main/resources/templates/markdown.html b/src/main/resources/templates/markdown.html index 24ffa13..58873d4 100644 --- a/src/main/resources/templates/markdown.html +++ b/src/main/resources/templates/markdown.html @@ -1,21 +1,21 @@ - - 数据字典展示 - - - - - - - - + + 数据字典展示 + + + + + + + +

在线Markdown

- 数据库: 下载PDF
@@ -25,66 +25,60 @@ -- Gitee From 6b88669e883296c9e0489f3a004b348c90265a6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 13:44:55 +0800 Subject: [PATCH 29/46] =?UTF-8?q?=E4=BF=AE=E5=A4=8DMySQL=E6=97=A0=E6=B3=95?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=8C=87=E5=AE=9A=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E8=A1=A8=E4=BF=A1=E6=81=AF=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index 180312c..c1a41c3 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -85,9 +85,9 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { String tableName = resultSet.getString(1); tableInfo.setTableName(tableName); //获取表信息 - String sqlTableInfo = "SHOW CREATE TABLE `" + tableName + "`"; + String sqlTableInfo = "SHOW CREATE TABLE `" + schema + "`.`" + tableName + "`"; String createTable = getTableInfo(connection, sqlTableInfo); - String sql1 = "show full columns from `" + tableName + "`"; + String sql1 = "show full columns from `" + schema + "`.`" + tableName + "`"; List columnInfos = getTableBaseInfo(connection, sql1); tableInfo.setColumnList(columnInfos); -- Gitee From f9263192809f89ae7fbe27c8af2e5d8a3a3ccf04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 13:48:34 +0800 Subject: [PATCH 30/46] =?UTF-8?q?MySQL=E6=95=B0=E6=8D=AE=E5=BA=93=E7=9A=84?= =?UTF-8?q?JDBC=20URL=E6=B7=BB=E5=8A=A0=E5=AD=97=E7=AC=A6=E7=BC=96?= =?UTF-8?q?=E7=A0=81=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/trh/dictionary/enums/DatabaseType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/trh/dictionary/enums/DatabaseType.java b/src/main/java/com/trh/dictionary/enums/DatabaseType.java index a24148c..edeac91 100644 --- a/src/main/java/com/trh/dictionary/enums/DatabaseType.java +++ b/src/main/java/com/trh/dictionary/enums/DatabaseType.java @@ -10,7 +10,7 @@ public enum DatabaseType { /** * MySQL数据库 */ - MYSQL("MySQL", "jdbc:mysql://${host}:${port}/${database}?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true"), + MYSQL("MySQL", "jdbc:mysql://${host}:${port}/${database}?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useInformationSchema=true&useUnicode=true&characterEncoding=UTF-8"), /** * Oracle数据库 */ -- Gitee From 5379f98cf1e9f539150f5f8e1cb824fcfc66ed1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 15:47:02 +0800 Subject: [PATCH 31/46] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=9B=B4=E5=8A=A0=E8=AF=A6=E7=BB=86=E7=9A=84?= =?UTF-8?q?=E5=86=85=E5=AE=B9=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dictionary/conterller/HomeController.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/HomeController.java b/src/main/java/com/trh/dictionary/conterller/HomeController.java index 0632797..c2e7854 100644 --- a/src/main/java/com/trh/dictionary/conterller/HomeController.java +++ b/src/main/java/com/trh/dictionary/conterller/HomeController.java @@ -60,7 +60,7 @@ public class HomeController { } @RequestMapping("/test") - public Object test() throws SQLException { + public Object test(String catalog, String schema, String tableName) throws SQLException { Map map = new LinkedHashMap<>(); Map databaseMap = new LinkedHashMap<>(); Map driverMap = new LinkedHashMap<>(); @@ -97,7 +97,7 @@ public class HomeController { map.put("functionsInfo", functionsMap); tryMethod(() -> { - map.put("Tables", JdbcUtils.resultSetToMaps(metaData.getTables(null, null, null, null))); + map.put("Tables", JdbcUtils.resultSetToMaps(metaData.getTables(catalog, schema, tableName, null))); }); tryMethod(() -> { map.put("Catalogs", JdbcUtils.resultSetToMaps(metaData.getCatalogs())); @@ -109,12 +109,24 @@ public class HomeController { map.put("TableTypes", JdbcUtils.resultSetToMaps(metaData.getTableTypes())); }); tryMethod(() -> { - map.put("PrimaryKeys", JdbcUtils.resultSetToMaps(metaData.getPrimaryKeys(null, null, null))); + map.put("Columns", JdbcUtils.resultSetToMaps(metaData.getColumns(catalog, schema, tableName, null))); + }); + tryMethod(() -> { + map.put("PrimaryKeys", JdbcUtils.resultSetToMaps(metaData.getPrimaryKeys(catalog, schema, tableName))); + }); + tryMethod(() -> { + map.put("IndexInfo", JdbcUtils.resultSetToMaps(metaData.getIndexInfo(catalog, schema, tableName, false, true))); + }); + tryMethod(() -> { + map.put("ImportedKeys", JdbcUtils.resultSetToMaps(metaData.getImportedKeys(catalog, schema, tableName))); + }); + tryMethod(() -> { + map.put("ImportedKeys", JdbcUtils.resultSetToMaps(metaData.getAttributes(catalog, schema, null, null))); }); return map; } - public void tryMethod(ExceptionNoneParamsFunction function) { + private void tryMethod(ExceptionNoneParamsFunction function) { try { function.apply(); } catch (Exception e) { -- Gitee From a88cc5d473cd66302e3c9540678c19334f5aa24c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 15:52:07 +0800 Subject: [PATCH 32/46] =?UTF-8?q?=E5=88=A0=E9=99=A4BuildPgSqlPdf.java?= =?UTF-8?q?=EF=BC=8C=E8=AF=A5=E6=96=87=E4=BB=B6=E5=AE=9E=E7=8E=B0=E7=9A=84?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=B7=B2=E7=BB=8F=E8=B0=83=E6=95=B4=E5=88=B0?= =?UTF-8?q?PostgreSqlDatabaseServiceImpl.java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/postgreSQL/BuildPgSqlPdf.java | 161 ------------------ src/test/java/com/trh/dictionary/Test.java | 3 +- 2 files changed, 1 insertion(+), 163 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java diff --git a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java b/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java deleted file mode 100644 index c78595f..0000000 --- a/src/main/java/com/trh/dictionary/service/postgreSQL/BuildPgSqlPdf.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.trh.dictionary.service.postgreSQL; - -import com.trh.dictionary.bean.ColumnInfo; -import com.trh.dictionary.bean.IndexInfo; -import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.dao.ConnectionFactory; -import com.trh.dictionary.service.BuildPDF; -import com.trh.dictionary.util.TableBasicEnum; -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -/** - * 构建pg数据库pdf - * - * @author wangyu - * @create 2019-09-04 10:29 - */ -public class BuildPgSqlPdf { - static Logger logger = LoggerFactory.getLogger(BuildPgSqlPdf.class); - - public static void buildPdf(String ip, String dbName, String port, String userName, String passWord, String filePath, String pdfName) throws Exception { - //得到生成数据 - String url = "jdbc:postgresql://" + ip + ":" + port + "/" + dbName; - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "pgSql"); - List list = getBuildPdfTableData(connection); - if (list.size() == 0) { - return; - } - - try { - FileUtils.forceMkdir(new File(filePath)); - BuildPDF.build(filePath, list, pdfName); - } catch (Exception e) { - logger.error("生成pdf异常", e); - } - } - - public static List getBuildPdfTableData(Connection connection) { - String sql = "SELECT pg_tables.schemaname,pg_tables.tablename,cast(obj_description(relfilenode,'pg_class') as varchar) as comment FROM pg_tables LEFT JOIN pg_class on relname=tablename WHERE tablename NOT LIKE 'pg%' AND tablename NOT LIKE 'sql_%'"; - - ResultSet resultSet; - List tableInfos = new ArrayList(64); - try { - Statement statement = connection.createStatement(); - resultSet = statement.executeQuery(sql); - while (resultSet.next()) { - TableInfo tableInfo = new TableInfo(); - String schemaName = resultSet.getString(1); - String tableName = resultSet.getString(2); - String desc = resultSet.getString(3); - tableInfo.setDescription(desc); - tableInfo.setStorageEngine(schemaName); - tableInfo.setTableName(tableName); - String sqlColumn = "SELECT A.attname AS 列名,concat_ws('',t.typname,SUBSTRING(format_type(A.atttypid,A.atttypmod) from '\\(.*\\)')),(CASE WHEN A.attlen> 0 THEN A.attlen ELSE A.atttypmod-4 END) AS 长度,A.attnotnull AS 是否可为空,d.adsrc AS 默认值,col_description (A.attrelid,A.attnum) AS 备注 FROM pg_class C,pg_attribute A LEFT JOIN (SELECT A.attname,ad.adsrc FROM pg_class C,pg_attribute A,pg_attrdef ad WHERE relname='" + tableName + "' AND ad.adrelid=C.oid AND adnum=A.attnum AND attrelid=C.oid) AS d ON A.attname=d.attname LEFT JOIN pg_type t on A.atttypid = t.oid WHERE C.relname='" + tableName + "' AND A.attrelid=C.oid AND A.attnum> 0;"; - String sqlIndex = "SELECT A.SCHEMANAME,A.TABLENAME,A.INDEXNAME,A.INDEXDEF,B.AMNAME,C.INDISUNIQUE,C.INDISPRIMARY,C.INDISCLUSTERED,D.DESCRIPTION FROM PG_AM B LEFT JOIN PG_CLASS F ON B.OID=F.RELAM LEFT JOIN PG_STAT_ALL_INDEXES E ON F.OID=E.INDEXRELID LEFT JOIN PG_INDEX C ON E.INDEXRELID=C.INDEXRELID LEFT OUTER JOIN PG_DESCRIPTION D ON C.INDEXRELID=D.OBJOID,PG_INDEXES A WHERE A.SCHEMANAME=E.SCHEMANAME AND A.TABLENAME=E.RELNAME AND A.INDEXNAME=E.INDEXRELNAME AND E.RELNAME='" + tableName + "'"; - //设置列信息 - tableInfo = getTableBaseInfo(connection, tableInfo, sqlColumn, sqlIndex); - tableInfos.add(tableInfo); - } - } catch (Exception e) { - logger.error("执行sql异常", e); - } - return tableInfos; - } - - /** - * 得到列名和索引 - * - * @param connection - * @param sqlColumn - * @param sqlIndex - * @return - */ - public static TableInfo getTableBaseInfo(Connection connection, TableInfo tableInfo, String sqlColumn, String sqlIndex) { - List indexInfos = new ArrayList<>(8); - List columnInfos = new ArrayList<>(16); - ResultSet resultSet; - ResultSet resultSet1; - //列 - try { - Statement statement = connection.createStatement(); - Statement statement1 = connection.createStatement(); - resultSet = statement.executeQuery(sqlIndex); - while (resultSet.next()) { - IndexInfo indexInfo = new IndexInfo(); - //索引名 - indexInfo.setName(resultSet.getString(3)); - //索引包含字段 - indexInfo.setContainKey(getIndexKey(resultSet.getString(4))); - //索引类型 - boolean isPk = resultSet.getString(7).trim().equals("t"); - if (isPk) { - indexInfo.setType(TableBasicEnum.WORD_PRIMARY.getDesc()); - indexInfo.setIsIndex(1); - } - if (resultSet.getString(6).equals("t") && !isPk) { - indexInfo.setType("UNIQUE"); - indexInfo.setIsIndex(0); - } else if (resultSet.getString(6).equals("f") && !isPk) { - indexInfo.setType(" "); - indexInfo.setIsIndex(0); - } - indexInfos.add(indexInfo); - } - resultSet1 = statement1.executeQuery(sqlColumn); - int order = 1; - while (resultSet1.next()) { - ColumnInfo columnInfo = new ColumnInfo(); - String name = resultSet1.getString(1); - for (IndexInfo info : indexInfos) { - if (info.getContainKey().equals(name)) { - columnInfo.setIsIndex(1); - } - } - columnInfo.setOrder(order); - columnInfo.setName(name); - columnInfo.setType(resultSet1.getString(2)); - boolean isNull = resultSet1.getString(4).equals("t"); - if (isNull) { - columnInfo.setIsNull("NO"); - } else { - columnInfo.setIsNull("YES"); - } - - columnInfo.setDefaultValue(resultSet1.getString(5)); - columnInfo.setDescription(resultSet1.getString(6)); - if (columnInfo.getDefaultValue() == null) { - columnInfo.setDefaultValue(""); - } - columnInfos.add(columnInfo); - order++; - } - } catch (Exception e) { - logger.error("获取列信息和索引信息异常", e); - } - tableInfo.setColumnList(columnInfos); - tableInfo.setIndexInfoList(indexInfos); - return tableInfo; - } - - /** - * 得到括号内的内容 - * - * @param desc - * @return - */ - public static String getIndexKey(String desc) { - int start = desc.indexOf("("); - int end = desc.indexOf(")"); - String key = desc.substring(start + 1, end); - return BuildPDF.dest(key, "\""); - } -} diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index 99e435f..cebe7f6 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -2,7 +2,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.BuildPDF; -import com.trh.dictionary.service.postgreSQL.BuildPgSqlPdf; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; @@ -36,7 +35,7 @@ public class Test { String FILE_DIR = "F:/pdf/"; //生成PDF文件 try { - BuildPgSqlPdf.buildPdf("192.168.161.3", "mydata", "54321", "postgres", "root", FILE_DIR, "mydata"); + // BuildPgSqlPdf.buildPdf("192.168.161.3", "mydata", "54321", "postgres", "root", FILE_DIR, "mydata"); } catch (Exception e) { e.printStackTrace(); } -- Gitee From b7251a23facdb90c14a3e3d823c945d94a233c80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 15:55:05 +0800 Subject: [PATCH 33/46] =?UTF-8?q?=E8=B0=83=E6=95=B4SQL=20Server=E7=9A=84ge?= =?UTF-8?q?tDatabaseName=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/SqlServerDatabaseServiceImpl.java | 14 ++++++++++--- .../sqlserver/GenerateDataBaseInfo.java | 20 ------------------- 2 files changed, 11 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index 0177a36..0b3abac 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -3,7 +3,6 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.service.DatabaseService; -import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,7 +12,9 @@ import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.List; @@ -37,8 +38,15 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { List list = new ArrayList<>(); try { connection = dataSource.getConnection(); - String sqltabel = "select name from sysdatabases where name not in('master','model','msdb','tempdb');"; - list = GenerateDataBaseInfo.getDataBaseList(connection, sqltabel); + String sqlTableInfo = "select name from sysdatabases where name not in('master','model','msdb','tempdb');"; + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sqlTableInfo); + while (resultSet.next()) { + list.add(resultSet.getString("name")); + } + resultSet.close(); + statement.close(); + return list; } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java b/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java index e8c0a63..7effded 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java @@ -17,26 +17,6 @@ import java.util.List; */ public class GenerateDataBaseInfo { - - /* - * @Author zhou - * @Description 所有用户库 - * @Date 10:58 2019/9/9 - * @Param [connection, sqlTableInfo] - * @return java.util.List - **/ - public static List getDataBaseList(Connection connection, String sqlTableInfo) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sqlTableInfo); - List list = new ArrayList<>(); - while (resultSet.next()) { - list.add(resultSet.getString("name")); - } - resultSet.close(); - statement.close(); - return list; - } - /* * @Author zhou * @Description 生成数据库表名 -- Gitee From dbec5a4ef17cba66c26f5ac08918edf327710281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 16:16:33 +0800 Subject: [PATCH 34/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=9E=84=E5=BB=BAPDF?= =?UTF-8?q?=E7=9A=84=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81=EF=BC=8C=E5=B0=86?= =?UTF-8?q?=E5=85=B6=E6=94=BE=E5=88=B0=E5=85=B6=E4=BB=96=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 39 +- .../com/trh/dictionary/service/BuildPDF.java | 903 ------------------ .../service/impl/GenerateServiceImpl.java | 3 +- .../impl/PostgreSqlDatabaseServiceImpl.java | 3 +- .../impl/SqlServerGenerateServiceImpl.java | 93 +- .../service/sqlserver/BuildSqlserverPDF.java | 24 +- src/test/java/com/trh/dictionary/Test.java | 9 +- 7 files changed, 126 insertions(+), 948 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/BuildPDF.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 0e831ac..bb4fc3a 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -1,7 +1,7 @@ package com.trh.dictionary.conterller; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.service.BuildPDF; +import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; @@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; +import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -47,11 +48,17 @@ public class DatabaseController { private HttpSession session; @RequestMapping("/login.action") - public String login(Model model, @Valid ConnectionDTO dto, Errors errors) throws Exception { - dataSourceService.registerDateSource(dto); - session.setAttribute(Keys.connectionDtoKey, dto); - + public String login(Model model, @Valid ConnectionDTO dto, Errors errors) { try { + if (errors.hasErrors()) { + List list = new ArrayList<>(); + for (ObjectError allError : errors.getAllErrors()) { + list.add(allError.getDefaultMessage()); + } + throw new RuntimeException(list.toString()); + } + dataSourceService.registerDateSource(dto); + session.setAttribute(Keys.connectionDtoKey, dto); String markdown = generateService.generateMarkdown(); model.addAttribute("markdown", markdown); return "markdown"; @@ -76,7 +83,7 @@ public class DatabaseController { @RequestMapping("/getMarkdownString") @ResponseBody - public String getMarkdownString(Model model, String database) { + public String getMarkdownString(String database) { try { return generateService.generateMarkdown(database); } catch (Exception e) { @@ -86,26 +93,20 @@ public class DatabaseController { } @RequestMapping(value = "/download", method = RequestMethod.GET) - public void testDownload(HttpServletResponse res, String selector, String ip, String port, String password, String username, String database) { + public void testDownload(HttpServletResponse res, String database) { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); //1.先生成pdf文件 - String filePath = BuildPDF.class.getResource("/") + String filePath = this.getClass().getResource("/") .getPath() .replaceAll("target/classes/", "") .replaceAll("target/test-classes/", ""); filePath += "src/main/resources/"; File outfile = new File(filePath, "DataBase.pdf"); try { - switch (selector) { - case "mysql": - case "oracle": - case "PostgreSQL": - case "DB2": - generateService.generatePdfFile(outfile); - break; - case "SQL server": - BuildSqlserverPDF.MakePdf(ip, database, port, username, password, filePath, "DataBase"); - break; - default: + if (dto.getType() == DatabaseType.SQLSERVER) { + BuildSqlserverPDF.MakePdf(dto.getHost(), database, dto.getPort(), dto.getUsername(), dto.getPassword(), filePath, "DataBase"); + } else { + generateService.generatePdfFile(outfile); } } catch (Exception e) { logger.error("error==>" + e); diff --git a/src/main/java/com/trh/dictionary/service/BuildPDF.java b/src/main/java/com/trh/dictionary/service/BuildPDF.java deleted file mode 100644 index 23918c6..0000000 --- a/src/main/java/com/trh/dictionary/service/BuildPDF.java +++ /dev/null @@ -1,903 +0,0 @@ -package com.trh.dictionary.service; - -import com.github.houbb.markdown.toc.util.StringUtil; -import com.itextpdf.text.*; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; -import com.itextpdf.text.pdf.draw.DottedLineSeparator; -import com.trh.dictionary.bean.ColumnInfo; -import com.trh.dictionary.bean.IndexInfo; -import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.dao.ConnectionFactory; -import com.trh.dictionary.event.ContentEvent; -import com.trh.dictionary.event.IndexEvent; -import com.trh.dictionary.event.pdfPageEvent; -import com.trh.dictionary.util.ColumnBasicEnum; -import com.trh.dictionary.util.JdbcUtils; -import com.trh.dictionary.util.SignEnum; -import com.trh.dictionary.util.TableBasicEnum; -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.*; -import java.lang.reflect.Field; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author wangyu - * @create 2019-07-25 11:24 - */ -public class BuildPDF { - static Logger logger = LoggerFactory.getLogger(BuildPDF.class); - - /** - * 生成PDF - * - * @param ip :数据库连接的IP 例如:127.0.0.1 或者 localhost - * @param dbName 例如: test - * @param port 例如: 3306 - * @param userName 例如: root - * @param passWord 例如: root - * @param filePath 例如: D:\ideaspace\export_dbInfo\src\main\resources\ - * @param pdfName 例如: testPDF - */ - public static void MakePdf(String ip, String dbName, String port, String userName, String passWord, String filePath, String pdfName) { - try { - //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC"; - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "mySql"); - List list = getBuildPdfTableData(getTables(connection, dbName)); - if (list.size() == 0) { - return; - } - FileUtils.forceMkdir(new File(filePath)); - //带目录 - build(filePath, list, pdfName); - } catch (Exception e) { - logger.error("生成PDF失败.......", e); - } - } - - - /** - * 生成PDF - * - * @param ip :数据库连接的IP 例如:127.0.0.1 或者 localhost - * @param dbName 例如: test - * @param port 例如: 3306 - * @param userName 例如: root - * @param passWord 例如: root - * @param filePath 例如: D:\ideaspace\export_dbInfo\src\main\resources\ - */ - public static void MakeMarkDown(String ip, String dbName, String port, String userName, String passWord, String filePath) { - try { - //得到生成数据 - String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC"; - Connection connection = ConnectionFactory.getConnection(url, userName, passWord, "mySql"); - List list = getBuildPdfTableData(getTables(connection, dbName)); - if (list.size() == 0) { - return; - } - writeMarkdown(list, filePath); - } catch (Exception e) { - logger.error("生成markdown失败.......", e); - } - } - - - /** - * 获取数据库所有表信息 - * - * @param connection - * @param dbName - * @return - */ - public static List> getTables(Connection connection, String dbName) { - Statement statement = null; - ResultSet resultSet = null; - List> tables = new ArrayList>(); - try { - //获取表名 - statement = connection.createStatement(); - String sql = "SHOW TABLES FROM `" + dbName + "`"; - resultSet = statement.executeQuery(sql); - while (resultSet.next()) { - Map resMap = new HashMap(2); - TableInfo tableInfo = new TableInfo(); - //表名 - String tableName = resultSet.getString(1); - //获取表信息 - String sqlTableInfo = "SHOW CREATE TABLE `" + tableName + "`"; - String createTable = getTableInfo(connection, sqlTableInfo); - tableInfo.setTableName(tableName); - resMap.put("createTable", createTable); - String sql1 = "show full columns from `" + tableName + "`"; - List columnInfos = getTableBaseInfo(connection, sql1); - tableInfo.setColumnList(columnInfos); - resMap.put("tableInfo", tableInfo); - tables.add(resMap); - } - return tables; - } catch (Exception e) { - e.printStackTrace(); - return tables; - } finally { - try { - JdbcUtils.releaseResource(connection, null - , resultSet, statement); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * 获取单个表全部信息 - * - * @param connection 数据库连接 - * @param sqlTableInfo 表信息sql - * @return - * @throws SQLException - */ - public static String getTableInfo(Connection connection, String sqlTableInfo) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sqlTableInfo); - String table = ""; - while (resultSet.next()) { - table = resultSet.getString("Create Table"); - } - return table; - } - - /** - * 设置表的基本信息 - * - * @param connection 数据库连接 - * @param sql - * @return - * @throws Exception - */ - public static List getTableBaseInfo(Connection connection, String sql) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sql); - List columnInfos = new ArrayList(); - int order = 1; - while (resultSet.next()) { - ColumnInfo columnInfo = new ColumnInfo(); - columnInfo.setName(resultSet.getString(ColumnBasicEnum.Field.getDesc()) + " " + resultSet.getString(ColumnBasicEnum.Extra.getDesc())); - columnInfo.setType(resultSet.getString(ColumnBasicEnum.Type.getDesc())); - columnInfo.setDescription(resultSet.getString(ColumnBasicEnum.Comment.getDesc())); - columnInfo.setIsNull(resultSet.getString(ColumnBasicEnum.Null.getDesc())); - columnInfo.setOrder(order++); - columnInfo.setDefaultValue(resultSet.getString(ColumnBasicEnum.Default.getDesc())); - columnInfos.add(columnInfo); - if (null == columnInfo.getDefaultValue()) { - columnInfo.setDescription(""); - } - } - statement.close(); - resultSet.close(); - return columnInfos; - } - - /** - * 得到构建pdf文件的数据 - * - * @param tables 获取构建pdf需要的表信息的集合 - * @return List - */ - public static List getBuildPdfTableData(List> tables) { - //循环处理表 - List resultList = new ArrayList(); - for (Map table : tables) { - TableInfo tableInfo = (TableInfo) table.get("tableInfo"); - String tableName = tableInfo.getTableName(); - String createTable = (String) table.get("createTable"); - tableInfo.setTableName(tableName); - //处理表信息字符 - tableInfo = takeTableInfo(tableInfo, createTable); - resultList.add(tableInfo); - } - return resultList; - } - - /** - * 得到表的基本数据 - * - * @param tableInfo 设置单张表构建pdf的数据 - * @param tableInfos 表信息字符串 - * @return TableInfo 表信息对象 - */ - public static TableInfo takeTableInfo(TableInfo tableInfo, String tableInfos) { - //去掉回车 - tableInfos = dest(tableInfos, SignEnum.back_quote.getDesc()); - tableInfos = dest(tableInfos, SignEnum.single_quotation_marks.getDesc()); - String[] test = tableInfos.split("\n"); - //处理字符串 - String str = test[test.length - 1]; - str = dest(str, SignEnum.right_brackets.getDesc()).trim(); - String[] table = str.split(" "); - List indexInfoList = new ArrayList(); - int indexInfoSize = test.length; - for (int i = 0; i < indexInfoSize - 1; i++) { - String temp = test[i]; - //主键索引 - if (temp.contains(TableBasicEnum.PRIMARY_KEY.getDesc())) { - temp = dest(temp, SignEnum.left_brackets.getDesc()); - temp = dest(temp, SignEnum.right_brackets.getDesc()); - String[] tempForIndex = temp.trim().split(" "); - String containKey = tempForIndex[tempForIndex.length - 1]; - IndexInfo indexInfo1 = new IndexInfo(TableBasicEnum.WORD_PRIMARY.getDesc(), TableBasicEnum.WORD_PRIMARY.getDesc(), drop(containKey)); - indexInfo1.setIsIndex(1); - indexInfoList.add(indexInfo1); - } - //唯一索引 - if (temp.contains(TableBasicEnum.UNIQUE_KEY.getDesc())) { - String[] tempForIndex = temp.trim().split(" "); - String containKey = tempForIndex[tempForIndex.length - 1]; - String type = tempForIndex[0] + tempForIndex[1]; - String name = tempForIndex[2]; - containKey = dest(containKey, SignEnum.left_brackets.getDesc()); - containKey = dest(containKey, SignEnum.right_brackets.getDesc()); - containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); - IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); - indexInfoList.add(indexInfo1); - } - //普通索引 - if (temp.contains(TableBasicEnum.KEY.getDesc())) { - String[] tempForIndex = temp.trim().split(" "); - if (!tempForIndex[0].equalsIgnoreCase(TableBasicEnum.WORD_key.getDesc())) { - continue; - } - String containKey = tempForIndex[tempForIndex.length - 1]; - String type = tempForIndex[0]; - String name = tempForIndex[1]; - containKey = dest(containKey, SignEnum.left_brackets.getDesc()); - containKey = dest(containKey, SignEnum.right_brackets.getDesc()); - containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); - IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); - indexInfoList.add(indexInfo1); - } - //全文索引 - if (temp.contains("FULLTEXT KEY")) { - String[] tempForIndex = temp.trim().split(" "); - String containKey = tempForIndex[tempForIndex.length - 1]; - String type = tempForIndex[0]; - String name = tempForIndex[2]; - containKey = dest(containKey, SignEnum.left_brackets.getDesc()); - containKey = dest(containKey, SignEnum.right_brackets.getDesc()); - containKey = dest(containKey, SignEnum.single_quotation_marks.getDesc()); - IndexInfo indexInfo1 = new IndexInfo(name, type, drop(containKey)); - indexInfoList.add(indexInfo1); - } - } - tableInfo.setIndexInfoList(indexInfoList); - //得到表字符集和ENGINE、表注释 - for (String oneTemp : table) { - //引擎 - if (oneTemp.contains(TableBasicEnum.ENGINE.getDesc())) { - tableInfo.setStorageEngine(dropSign(oneTemp)); - continue; - } else { - if (tableInfo.getStorageEngine() == null) { - tableInfo.setStorageEngine(""); - } - } - //字符集 - if (oneTemp.contains(TableBasicEnum.CHARSET.getDesc())) { - tableInfo.setOrderType(dropSign(oneTemp)); - continue; - } else { - if (tableInfo.getOrderType() == null) { - tableInfo.setOrderType(""); - } - } - - //描述 - if (oneTemp.contains(TableBasicEnum.COMMENT.getDesc())) { - tableInfo.setDescription(dropSign(oneTemp)); - continue; - } else { - if (tableInfo.getDescription() == null) { - tableInfo.setDescription(""); - } - } - } - - return tableInfo; - } - - - /** - * 去掉字符串中的符号 - * - * @param param 需要处理的变量 - * @return String - */ - public static String dest(String param, String reg) { - String temp = ""; - if (param != null) { - Pattern pattern = Pattern.compile(reg); - Matcher m = pattern.matcher(param); - temp = m.replaceAll(""); - } - return temp; - } - - /** - * 得到一个包含一个等号的字符串,获取等号后的值 - * - * @param param 需处理的变量 - * @return String - */ - public static String dropSign(String param) { - param = param.trim(); - int index = param.indexOf(SignEnum.equal_sign.getDesc()); - String res = param.substring(index + 1); - if (res.contains(SignEnum.single_quotation_marks.getDesc())) { - try { - res = dest(res, SignEnum.single_quotation_marks.getDesc()); - } catch (Exception e) { - e.printStackTrace(); - logger.error("获取等号后的值异常"); - return param; - } - } - return res; - } - - /** - * 去掉索引逗号 - * - * @param param 需处理的变量 - * @return String - */ - public static String drop(String param) { - try { - param = param.trim(); - char[] tempArry = param.toCharArray(); - char res = tempArry[param.length() - 1]; - if (param.contains(SignEnum.comma.getDesc()) && res == ',') { - return param.substring(0, param.length() - 1); - } else { - return param; - } - } catch (Exception e) { - e.getStackTrace(); - return param; - } - } - - - public static void createPdf(String FILE_DIR, List tableInfos, String pdfName) { - try { - //中文字体 -// BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); -// BaseFont bfChinese = BaseFont.createFont(AsianFontMapper.ChineseTraditionalFont_MHei, AsianFontMapper.ChineseTraditionalEncoding_H, BaseFont.EMBEDDED); - BaseFont bfChinese = BaseFont.createFont(FILE_DIR.replaceAll("pdf", "font") + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, 12, Font.BOLDITALIC); - // 设置类型,加粗 - font.setStyle(Font.NORMAL); - - //页面大小 - Rectangle rect = new Rectangle(PageSize.A4).rotate(); - //页面背景色 -// rect.setBackgroundColor(BaseColor.WHITE); - rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); - //设置边框颜色 - rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); - - Document doc = new Document(rect); - PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + pdfName + ".pdf")); - //PDF版本(默认1.4) - writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2); - //设置行间距 - writer.setInitialLeading(30); - - //页边空白 - doc.setMargins(10, 20, 30, 40); - //设置页码 - setFooter(writer, bfChinese); - // 标题 - doc.addTitle("trh-bill"); - doc.open(); - //目录 - doc.newPage(); - Paragraph indexInfo = new Paragraph("目录", font); - indexInfo.setIndentationLeft(280); - doc.add(indexInfo); - int index = 1; - // 取到锚点 - for (TableInfo tableInfo : tableInfos) { - Paragraph p1 = new Paragraph(); - p1.setAlignment(Element.ALIGN_JUSTIFIED_ALL); - String name = tableInfo.getTableName(); - // 生成 - String t = name + getPoint(name, 120) + index; - logger.info(t); - Anchor toUS = new Anchor(t); - // 取到锚点 - String point = "#" + name; - toUS.setReference(point); - p1.add(toUS); - doc.add(p1); - index++; - } - - //居中 - doc.newPage(); - //表格 - //设置表格模板 - String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; - String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; - String baseInfo; - int order = 1; - for (TableInfo tableInfo : tableInfos) { - tableInfo = setIsIndex(tableInfo); - // 生成锚点 - Paragraph paragraph1 = new Paragraph("\n\n"); - Anchor dest = new Anchor(order + "." + tableInfo.getTableName(), font); - // 设置锚点的名字 - dest.setName(tableInfo.getTableName()); - // 连接 - paragraph1.add(dest); - doc.add(paragraph1); - // 生成 - Phrase base = new Phrase("\n基本信息:", getChineseFontAsStyle(BaseColor.BLACK, 16)); - Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); - Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); - Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", getChineseFontAsStyle(BaseColor.BLACK, 16)); - Paragraph paragraph = new Paragraph(); - paragraph.add(base); - paragraph.add(engine); - paragraph.add(type); - paragraph.add(description); - paragraph.setLeading(20f); - doc.add(paragraph); - //设置表格 - PdfPTable table = setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - //设置列信息 - setTableColumn(table, tableInfo, font); - doc.add(table); - //设置索引表 - Paragraph blankTwo = new Paragraph("\n\n"); - - doc.add(blankTwo); - PdfPTable indexTable = setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - table.setWidthPercentage(100); - indexTable = setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), font); - doc.add(indexTable); - //序号 - order++; - } - doc.close(); - } catch (Exception e) { - e.getStackTrace(); - } - } - - /** - * 设置表格头部 - * - * @param header - * @param font - * @return - */ - public static PdfPTable setTableHeader(String[] header, Font font) { - int columnSize = header.length; - PdfPTable table = new PdfPTable(columnSize); - table.setWidthPercentage(100); - for (String value : header) { - PdfPCell cell1 = new PdfPCell(new Paragraph(value, font)); - cell1.setVerticalAlignment(Element.ALIGN_CENTER); -// cell1.setHorizontalAlignment(Element.ALIGN_CENTER); - cell1.setHorizontalAlignment(Element.ALIGN_LEFT); - cell1.setBackgroundColor(BaseColor.LIGHT_GRAY); - table.addCell(cell1); - } - return table; - } - - /** - * 设置基本表格的列 - * - * @param table - * @param tableInfo - * @param font - * @return - */ - public static PdfPTable setTableColumn(PdfPTable table, TableInfo tableInfo, Font font) { - List Columns = tableInfo.getColumnList(); - for (ColumnInfo column : Columns) { - table = reflectBuildCell(column, table, font, tableInfo); - } - return table; - } - - /** - * 设置基本表格的列 - * - * @param table - * @param Columns - * @return - */ - public static PdfPTable setIndexTableColumn(PdfPTable table, List Columns, Font font) { - int order = 1; - for (IndexInfo column : Columns) { - column.setOrder(order); - table = reflectBuildCell(column, table, font, null); - order++; - } - return table; - } - - /** - * 写markdown文件 - */ - public static String writeMarkdown(List list, String filePath) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (TableInfo info : list) { - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + "\n" + "基本信息:" + info.getDescription() + " " + info.getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - for (ColumnInfo Column : columnInfos) { - oneTble.append("|").append(Column.getOrder()).append("|"). - append(Column.getName()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIsNull()).append("|"). - append(Column.getDefaultValue()).append("|"). - append(Column.getDescription()).append("|"). - append("\n"); - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (IndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getName()).append("|"). - append(indexInfo.getType()).append("|"). - append(indexInfo.getContainKey()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); - } - //目录 - markdown.insert(0, "[TOC]\n"); - return markdown.toString(); - } - - /** - * 创建文件夹 - * - * @param fileName - * @param content - */ - public static void createDir(String fileName, String content) { - File file = new File(fileName); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdir(); - } - if (!file.exists()) { - try { - file.createNewFile(); - //写文件 - FileWriter writer = new FileWriter(fileName); - writer.write(content); - writer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - //设置页码 - public static void setFooter(PdfWriter writer, BaseFont bf) { - pdfPageEvent headerFooter = new pdfPageEvent(bf, 13, PageSize.A0); - writer.setPageEvent(headerFooter); - } - - public static String getPoint(String name, int size) { - int length = name.length(); - int res = size - length; - StringBuffer str = new StringBuffer(); - for (int i = 0; i < res; i++) { - str.append(SignEnum.point.getDesc()); - } - return str.toString(); - } - - /** - * 得到默认字体 - * - * @param color - * @param size - * @return - */ - public static Font getFontAsStyle(BaseColor color, float size) { - Font font = new Font(); - font.setColor(color); - font.setSize(size); - return font; - } - - /** - * 得到汉字字体 - * - * @param color - * @param size - * @return - */ - public static Font getChineseFontAsStyle(BaseColor color, float size) { - try { - //中文字体 - BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, size, Font.NORMAL); - font.setColor(color); - return font; - } catch (Exception e) { - logger.error("生成中文字体异常", e); - return new Font(); - } - } - - - /** - * 通过反射填写表格内容 - * - * @param obj - * @author wangyu - * @date 2019-8-6 - */ - public static PdfPTable reflectBuildCell(Object obj, PdfPTable table, Font font, TableInfo tableInfo) { - if (obj == null) { - logger.error("填写表格内容对象为空"); - return table; - } - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - Field[] fields = obj.getClass().getDeclaredFields(); - for (Field field : fields) { - PdfPCell cell = new PdfPCell(); - cell.setVerticalAlignment(Element.ALIGN_CENTER); - Paragraph paragraph = new Paragraph(); - //将设置私有构造器设为可取值 - field.setAccessible(true); - String name = field.getName(); - - if ("isIndex".equals(name)) { - try { - if ((Integer) field.get(obj) == 1) { - font = getFontAsStyle(BaseColor.RED, 12); - cnFont = getChineseFontAsStyle(BaseColor.RED, 12); - } else { - font = getFontAsStyle(BaseColor.BLACK, 12); - cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - continue; - } - - if (null != tableInfo) { - - } - - // 得到类型和名字取值 - if (field.getType().getName().equals(String.class.getName())) { - // String type - try { - if (isChineseContent(field.get(obj) + "")) { - font = cnFont; - } - paragraph = new Paragraph(field.get(obj) + "", font); - - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else if (field.getType().getName().equals(Integer.class.getName()) - || field.getType().getName().equals("int")) { - // Integer type - try { - paragraph = new Paragraph(field.get(obj) + "", font); - - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch b lock - e.printStackTrace(); - } - } - //添加到表格 - cell.addElement(paragraph); - table.addCell(cell); - } - return table; - } - - - public static TableInfo setIsIndex(TableInfo tableInfo) { - List columnInfos = tableInfo.getColumnList(); - List indexInfos = tableInfo.getIndexInfoList(); - for (ColumnInfo columnInfo : columnInfos) { - for (IndexInfo indexInfo : indexInfos) { - String temp = indexInfo.getContainKey(); -// if (temp.contains(SignEnum.comma.getDesc())) { -// String[] keys = temp.split(SignEnum.comma.getDesc()); -// for (int i = 0; i < keys.length; i++) { -// String key = keys[i]; -// if (key.trim().equals(columnInfo.getName().trim())) { -// columnInfo.setIsIndex(1); -// } -// if (key.trim().contains(columnInfo.getName()) && columnInfo.getOrder() == 1) { -// columnInfo.setIsIndex(1); -// } -// } -// } else { -// if (temp.trim().equals(columnInfo.getName().trim())) { -// columnInfo.setIsIndex(1); -// } - String[] res = columnInfo.getName().split(" "); - if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc().equals(indexInfo.getType().trim())) { - columnInfo.setIsIndex(1); - } -// } - } - } - return tableInfo; - } - - - public static void build(String FILE_DIR, List tableInfos, String pdfName) throws Exception { - String fontDir = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", "").replaceAll("target/test-classes/", ""); - fontDir += "src/main/resources/"; - BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, 12, Font.BOLDITALIC); - // 设置类型,加粗 - font.setStyle(Font.NORMAL); - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 16); - //页面大小 - Rectangle rect = new Rectangle(PageSize.A4).rotate(); - //页面背景色 - rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); - //设置边框颜色 - rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); - Document doc = new Document(rect); - PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); - //设置事件 - ContentEvent event = new ContentEvent(); - contentWriter.setPageEvent(event); - //存目录监听 开始 - doc.open(); - int order = 1; - List chapterList = new ArrayList(); - //根据chapter章节分页 - //表格 - //设置表格模板 - String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; - String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; - for (TableInfo tableInfo : tableInfos) { - tableInfo = setIsIndex(tableInfo); - Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); - //设置跳转地址 - Phrase point = new Paragraph("基本信息:", cnFont); - Anchor tome = new Anchor(point); - tome.setName(tableInfo.getTableName()); - Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); - Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); - Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", getChineseFontAsStyle(BaseColor.BLACK, 16)); - //组装基本数据 - Paragraph contentInfo = new Paragraph(); - contentInfo.add(tome); - contentInfo.add(engine); - contentInfo.add(type); - contentInfo.add(description); - chapter.add(contentInfo); - chapter.add(new Paragraph("")); - //组装表格 - Paragraph tableParagraph = new Paragraph(); - //设置表格 - PdfPTable table = setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - //设置列信息 - setTableColumn(table, tableInfo, font); - tableParagraph.add(table); - chapter.add(tableParagraph); - //设置索引表 - Paragraph blankTwo = new Paragraph("\n\n"); - chapter.add(blankTwo); - PdfPTable indexTable = setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - table.setWidthPercentage(100); - indexTable = setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), getFontAsStyle(BaseColor.RED, 10)); - Paragraph indexTableParagraph = new Paragraph(); - indexTableParagraph.add(indexTable); - chapter.add(indexTableParagraph); - - //加入文档中 - doc.add(chapter); - //保存章节内容 - chapterList.add(chapter); - order++; - } - doc.close(); - //存目录监听 结束 - - - Document document = new Document(rect); - FileOutputStream os = new FileOutputStream(FILE_DIR + pdfName + ".pdf"); - PdfWriter writer = PdfWriter.getInstance(document, os); - IndexEvent indexEvent = new IndexEvent(); - writer.setPageEvent(indexEvent); - document.open(); - //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", getFontAsStyle(BaseColor.BLACK, 18)), 0); - indexChapter.setNumberDepth(-1); - // 设置数字深度 - int i = 1; - for (Map.Entry index : event.index.entrySet()) { - String key = index.getKey(); - String[] keyValue = key.split(" "); - //设置跳转显示名称 - int pageNo = index.getValue(); - Chunk pointChunk = new Chunk(new DottedLineSeparator()); - Chunk pageNoChunk = new Chunk(pageNo + ""); - String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { - tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; - } - Paragraph jumpParagraph = new Paragraph(tempDescription, getChineseFontAsStyle(BaseColor.BLACK, 12)); - jumpParagraph.add(pointChunk); - jumpParagraph.add(pageNoChunk); - Anchor anchor = new Anchor(jumpParagraph); - String jump = keyValue[keyValue.length - 1].trim(); - //设置跳转链接 - anchor.setReference("#" + jump); - indexChapter.add(anchor); - indexChapter.add(new Paragraph()); - i++; - } - document.add(indexChapter); - document.newPage(); - //添加内容 - for (Chapter c : chapterList) { - indexEvent.setBody(true); - document.add(c); - } - - document.close(); - os.close(); - } - - - public static boolean isChineseContent(String content) { - String regex = "[\u4e00-\u9fa5]"; - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(content); - return matcher.find(); - } -} diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java index 0408f57..fdc62b6 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java @@ -15,7 +15,6 @@ import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.event.pdfPageEvent; -import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateService; import com.trh.dictionary.util.Keys; @@ -70,7 +69,7 @@ public class GenerateServiceImpl implements GenerateService { @Override public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { - String fontDir = BuildPDF.class.getResource("/") + String fontDir = this.getClass().getResource("/") .getPath() .replaceAll("target/classes/", "") .replaceAll("target/test-classes/", ""); diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index 7e3d978..4e68825 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -4,7 +4,6 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.TableBasicEnum; @@ -178,6 +177,6 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { int start = desc.indexOf("("); int end = desc.indexOf(")"); String key = desc.substring(start + 1, end); - return BuildPDF.dest(key, "\""); + return MySqlDatabaseServiceImpl.dest(key, "\""); } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java index 0fda429..14d05b4 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java @@ -5,7 +5,6 @@ import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.GenerateService; -import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -14,7 +13,9 @@ import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.io.File; import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.List; @@ -66,7 +67,7 @@ public class SqlServerGenerateServiceImpl implements GenerateService { String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); + List list_table = getTableInfo(connection, sqltabel); if (list_table.size() == 0) { return "## 数据库无数据"; } @@ -81,7 +82,7 @@ public class SqlServerGenerateServiceImpl implements GenerateService { "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta .getTableName() + "'"; try { - list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + list_column = getColumnInfo(connection, sqlcolumn); for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } @@ -96,7 +97,7 @@ public class SqlServerGenerateServiceImpl implements GenerateService { .getTableName() + "')) Ind ORDER BY index_name"; try { logger.info(sqlindex); - list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + list_index = getIndexInfo(connection, sqlindex); for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } @@ -127,6 +128,90 @@ public class SqlServerGenerateServiceImpl implements GenerateService { return ""; } + /* + * @Author zhou + * @Description 生成数据库表名 + * @Date 16:46 2019/8/29 + * @Param [connection, sqlTableInfo] + * @return java.util.List + **/ + public static List getTableInfo(Connection connection, String sqlTableInfo) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sqlTableInfo); + List list = new ArrayList(); + while (resultSet.next()) { + SqlserverTabelInfo sqlserverTabelInfo = new SqlserverTabelInfo(); + sqlserverTabelInfo.setTableName(resultSet.getString("name")); + sqlserverTabelInfo.setValue(resultSet.getString("value")); + list.add(sqlserverTabelInfo); + } + resultSet.close(); + statement.close(); + return list; + } + + + /* + * @Author zhou + * @Description 生成数据库表列名 + * @Date 17:16 2019/8/29 + * @Param [connection, sql] + * @return java.util.List + **/ + public static List getColumnInfo(Connection connection, String sql) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + List list = new ArrayList(); + while (resultSet.next()) { + SqlserverColumnInfo sqlserverColumnInfo = new SqlserverColumnInfo(); + sqlserverColumnInfo.setTable_name(resultSet.getString("table_name")); + sqlserverColumnInfo.setColumn_num(resultSet.getString("column_num")); + sqlserverColumnInfo.setColumn_name(resultSet.getString("column_name")); + sqlserverColumnInfo.setIs_identity(resultSet.getString("is_identity")); + sqlserverColumnInfo.setP_k(resultSet.getString("p_k")); + sqlserverColumnInfo.setType(resultSet.getString("type")); + sqlserverColumnInfo.setOccupied_num(resultSet.getString("occupied_num")); + sqlserverColumnInfo.setLength(resultSet.getString("length")); + sqlserverColumnInfo.setScale(resultSet.getString("scale")); + sqlserverColumnInfo.setIs_null(resultSet.getString("is_null")); + sqlserverColumnInfo.setDefault_value(resultSet.getString("default_value")); + sqlserverColumnInfo.setDecs(resultSet.getString("decs")); + String class_desc = resultSet.getString("class_desc"); + if ("INDEX".equals(class_desc)) { + continue; + } else { + sqlserverColumnInfo.setClass_desc(resultSet.getString("class_desc")); + } + + list.add(sqlserverColumnInfo); + } + resultSet.close(); + statement.close(); + return list; + } + + /* + * @Author zhou + * @Description 生成数据库表索引 + * @Date 17:18 2019/8/29 + * @Param [connection, sql] + * @return java.util.List + **/ + public static List getIndexInfo(Connection connection, String sql) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + List list = new ArrayList(); + while (resultSet.next()) { + SqlserverIndexInfo sqlserverIndexInfo = new SqlserverIndexInfo(); + sqlserverIndexInfo.setIndex_name(resultSet.getString("index_name")); + sqlserverIndexInfo.setIndex_desc(resultSet.getString("index_desc")); + sqlserverIndexInfo.setIndex_keys(resultSet.getString("index_keys")); + list.add(sqlserverIndexInfo); + } + resultSet.close(); + statement.close(); + return list; + } public static String writeMarkdownString(List list) { StringBuffer markdown = new StringBuffer(); String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java index a986163..2a328aa 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java @@ -13,7 +13,7 @@ import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; -import com.trh.dictionary.service.BuildPDF; +import com.trh.dictionary.service.impl.GenerateServiceImpl; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,8 +26,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import static com.trh.dictionary.service.BuildPDF.getChineseFontAsStyle; - /** * @author zhou * @create 2019-08-30 10:22 @@ -104,13 +102,13 @@ public class BuildSqlserverPDF { } public static void build(String FILE_DIR, List tableInfos, String pdfName) throws Exception { - String fontDir = BuildPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); + String fontDir = BuildSqlserverPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); fontDir += "src/main/resources/"; BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); Font font = new Font(bfChinese, 12, Font.BOLDITALIC); // 设置类型,加粗 font.setStyle(Font.NORMAL); - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 16); + Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); //页面大小 Rectangle rect = new Rectangle(PageSize.A4).rotate(); //页面背景色 @@ -140,7 +138,7 @@ public class BuildSqlserverPDF { tome.setName(tableInfo.getTableName()); Phrase engine = new Phrase(" ", font); Phrase type = new Phrase(" ", font); - Phrase description = new Phrase(tableInfo.getValue(), getChineseFontAsStyle(BaseColor.BLACK, 16)); + Phrase description = new Phrase(tableInfo.getValue(), GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); //组装基本数据 Paragraph contentInfo = new Paragraph(); contentInfo.add(tome); @@ -153,7 +151,7 @@ public class BuildSqlserverPDF { //组装表格 Paragraph tableParagraph = new Paragraph(); //设置表格 - PdfPTable table = BuildPDF.setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable table = GenerateServiceImpl.setTableHeader(tableHeader, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); //设置列信息 BuildColumnCell(table, font, tableInfo); tableParagraph.add(table); @@ -161,9 +159,9 @@ public class BuildSqlserverPDF { //设置索引表 Paragraph blankTwo = new Paragraph("\n\n"); chapter.add(blankTwo); - PdfPTable indexTable = BuildPDF.setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable indexTable = GenerateServiceImpl.setTableHeader(indexHeader, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); table.setWidthPercentage(100); - indexTable = BuildIndexCell(indexTable, BuildPDF.getFontAsStyle(BaseColor.RED, 10), tableInfo); + indexTable = BuildIndexCell(indexTable, GenerateServiceImpl.getFontAsStyle(BaseColor.RED, 10), tableInfo); Paragraph indexTableParagraph = new Paragraph(); indexTableParagraph.add(indexTable); chapter.add(indexTableParagraph); @@ -185,7 +183,7 @@ public class BuildSqlserverPDF { writer.setPageEvent(indexEvent); document.open(); //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", BuildPDF.getFontAsStyle(BaseColor.BLACK, 18)), 0); + Chapter indexChapter = new Chapter(new Paragraph("", GenerateServiceImpl.getFontAsStyle(BaseColor.BLACK, 18)), 0); indexChapter.setNumberDepth(-1); // 设置数字深度 int i = 1; @@ -201,7 +199,7 @@ public class BuildSqlserverPDF { if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; } - Paragraph jumpParagraph = new Paragraph(tempDescription, getChineseFontAsStyle(BaseColor.BLACK, 12)); + Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); jumpParagraph.add(pageNoChunk); Anchor anchor = new Anchor(jumpParagraph); @@ -236,7 +234,7 @@ public class BuildSqlserverPDF { List columnList = tableInfo.getColumnList(); for (SqlserverColumnInfo columnInfo : columnList) { - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); if ("YES".equals(columnInfo.getP_k())) { cnFont.setColor(BaseColor.RED); } else { @@ -271,7 +269,7 @@ public class BuildSqlserverPDF { List indexInfos = tableInfo.getIndexInfoList(); - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); int i = 1; for (SqlserverIndexInfo indexInfo : indexInfos) { PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index cebe7f6..20e09e0 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -1,7 +1,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.service.BuildPDF; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; @@ -25,9 +24,9 @@ public class Test { public void testMakeMySqlPdf() { String FILE_DIR = "F:/pdf/"; //生成PDF文件 - BuildPDF.MakePdf("localhost", "cd_core", "3306", "root", "root", FILE_DIR, "cd_core"); + // BuildPDF.MakePdf("localhost", "cd_core", "3306", "root", "root", FILE_DIR, "cd_core"); //生成MARKDOWN文件 - BuildPDF.MakeMarkDown("localhost", "cd_core", "3306", "root", "root", FILE_DIR); + // BuildPDF.MakeMarkDown("localhost", "cd_core", "3306", "root", "root", FILE_DIR); } @org.junit.Test @@ -60,7 +59,7 @@ public class Test { String filePath = "F:/pdf/"; FileUtils.forceMkdir(new File(filePath)); //带目录 - BuildPDF.build(filePath, tableInfo, "Oraclecd_core12"); + // BuildPDF.build(filePath, tableInfo, "Oraclecd_core12"); String markdown = "";//BuildPDF.writeMarkdown(tableInfo); System.out.println(markdown); System.out.println("生成数据字典完毕,一共生成了" + tableInfo.size() + "条数据"); @@ -79,7 +78,7 @@ public class Test { String filePath = "E:/pdf/"; FileUtils.forceMkdir(new File(filePath)); //带目录 - BuildPDF.build(filePath, tableInfo, "Db2"); + // BuildPDF.build(filePath, tableInfo, "Db2"); // BuildPDF.writeMarkdown(tableInfo); } -- Gitee From 64b227254e403a81fafbfe06209968cac5cf9622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 16:34:59 +0800 Subject: [PATCH 35/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=9E=84=E5=BB=BAPDF?= =?UTF-8?q?=E5=92=8CMarkdown=E7=9A=84=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将PDF和Markdown的代码分开存放,根据其作用放到不同的文件内 --- .../conterller/DatabaseController.java | 13 +- .../trh/dictionary/dao/ConnectionFactory.java | 46 --- .../service/GenerateMarkdownService.java | 36 +++ ...teService.java => GeneratePdfService.java} | 34 +-- ....java => GenerateMarkdownServiceImpl.java} | 285 +++++------------- .../service/impl/GeneratePdfServiceImpl.java | 184 +++++++++++ ...SqlServerGenerateMarkdownServiceImpl.java} | 34 +-- .../impl/SqlServerGeneratePdfServiceImpl.java | 42 +++ .../service/sqlserver/BuildSqlserverPDF.java | 20 +- .../com/trh/dictionary/util/PdfUtils.java | 10 + 10 files changed, 366 insertions(+), 338 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/dao/ConnectionFactory.java create mode 100644 src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java rename src/main/java/com/trh/dictionary/service/{GenerateService.java => GeneratePdfService.java} (56%) rename src/main/java/com/trh/dictionary/service/impl/{GenerateServiceImpl.java => GenerateMarkdownServiceImpl.java} (64%) create mode 100644 src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java rename src/main/java/com/trh/dictionary/service/impl/{SqlServerGenerateServiceImpl.java => SqlServerGenerateMarkdownServiceImpl.java} (95%) create mode 100644 src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java create mode 100644 src/main/java/com/trh/dictionary/util/PdfUtils.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index bb4fc3a..20e4e86 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -4,7 +4,8 @@ import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; -import com.trh.dictionary.service.GenerateService; +import com.trh.dictionary.service.GenerateMarkdownService; +import com.trh.dictionary.service.GeneratePdfService; import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; @@ -42,7 +43,9 @@ public class DatabaseController { @Autowired private DatabaseService databaseService; @Autowired - private GenerateService generateService; + private GeneratePdfService pdfService; + @Autowired + private GenerateMarkdownService markdownService; @Autowired private HttpSession session; @@ -59,7 +62,7 @@ public class DatabaseController { } dataSourceService.registerDateSource(dto); session.setAttribute(Keys.connectionDtoKey, dto); - String markdown = generateService.generateMarkdown(); + String markdown = markdownService.generateMarkdown(); model.addAttribute("markdown", markdown); return "markdown"; } catch (Exception e) { @@ -85,7 +88,7 @@ public class DatabaseController { @ResponseBody public String getMarkdownString(String database) { try { - return generateService.generateMarkdown(database); + return markdownService.generateMarkdown(database); } catch (Exception e) { logger.error("error==>" + e); return "### " + e.getMessage(); @@ -106,7 +109,7 @@ public class DatabaseController { if (dto.getType() == DatabaseType.SQLSERVER) { BuildSqlserverPDF.MakePdf(dto.getHost(), database, dto.getPort(), dto.getUsername(), dto.getPassword(), filePath, "DataBase"); } else { - generateService.generatePdfFile(outfile); + pdfService.generatePdfFile(outfile); } } catch (Exception e) { logger.error("error==>" + e); diff --git a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java deleted file mode 100644 index 453e32f..0000000 --- a/src/main/java/com/trh/dictionary/dao/ConnectionFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.trh.dictionary.dao; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DriverManager; - -/** - * 数据库连接工厂类 - * - * @author - * @create 2019-08-28 16:28 - */ -public class ConnectionFactory { - public static String mySql = "mySql"; - public static String pgSql = "pgSql"; - static Logger logger = LoggerFactory.getLogger(ConnectionFactory.class); - - /** - * 得到数据库连接 - * - * @param url 地址 - * @param userName 用户名 - * @param passWord 密码 - * @param driverName 驱动名:mySql、pgSql - * @return - */ - public static Connection getConnection(String url, String userName, String passWord, String driverName) throws Exception { - Connection connection = null; - //创建驱动 - if (mySql.equals(driverName)) { - Class.forName("com.mysql.cj.jdbc.Driver"); - } else if (pgSql.equals(driverName)) { - Class.forName("org.postgresql.Driver"); - } - logger.info("-----------------------连接数据库"); - //创建连接 - connection = DriverManager.getConnection(url, userName, passWord); - if (connection.isClosed()) { - logger.error("------------------- the connect is closed --------------"); - return null; - } - return connection; - } -} diff --git a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java new file mode 100644 index 0000000..7419a7c --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java @@ -0,0 +1,36 @@ +package com.trh.dictionary.service; + +import com.trh.dictionary.bean.TableInfo; + +import java.util.List; + +/** + * 创建生成PDF文件的接口 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:49 + */ +public interface GenerateMarkdownService { + /** + * 构建Markdown内容 + * + * @param tableInfos + * @return + */ + String generateMarkdown(List tableInfos); + + /** + * 构建Markdown内容 + * + * @param schema + * @return + */ + String generateMarkdown(String schema); + + /** + * 构建Markdown内容 + * + * @return + */ + String generateMarkdown(); +} diff --git a/src/main/java/com/trh/dictionary/service/GenerateService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java similarity index 56% rename from src/main/java/com/trh/dictionary/service/GenerateService.java rename to src/main/java/com/trh/dictionary/service/GeneratePdfService.java index 5d7ba13..b7db5c2 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateService.java +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -5,7 +5,6 @@ import com.trh.dictionary.bean.TableInfo; import java.io.File; import java.io.IOException; -import java.sql.Connection; import java.util.List; /** @@ -14,15 +13,7 @@ import java.util.List; * @author HouKunLin * @date 2019/9/11 0011 9:49 */ -public interface GenerateService { - /** - * 构建PDF文件 - * - * @param connection - * @param file - */ - void generatePdfFile(Connection connection, File file); - +public interface GeneratePdfService { /** * 构建PDF文件 * @@ -46,27 +37,4 @@ public interface GenerateService { * @param file */ void generatePdfFile(File file); - - /** - * 构建Markdown内容 - * - * @param tableInfos - * @return - */ - String generateMarkdown(List tableInfos); - - /** - * 构建Markdown内容 - * - * @param schema - * @return - */ - String generateMarkdown(String schema); - - /** - * 构建Markdown内容 - * - * @return - */ - String generateMarkdown(); } diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java similarity index 64% rename from src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java rename to src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java index fdc62b6..9ae23fd 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java @@ -1,22 +1,18 @@ package com.trh.dictionary.service.impl; -import com.github.houbb.markdown.toc.util.StringUtil; import com.itextpdf.text.*; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; -import com.itextpdf.text.pdf.draw.DottedLineSeparator; import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.enums.DatabaseType; -import com.trh.dictionary.event.ContentEvent; -import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.event.pdfPageEvent; import com.trh.dictionary.service.DatabaseService; -import com.trh.dictionary.service.GenerateService; +import com.trh.dictionary.service.GenerateMarkdownService; import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.SignEnum; import com.trh.dictionary.util.TableBasicEnum; @@ -27,172 +23,104 @@ import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; import java.lang.reflect.Field; -import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * 创建PDF + * 构建Markdown内容 * * @author HouKunLin - * @date 2019/9/11 0011 11:16 + * @date 2019/9/11 0011 16:21 */ @Primary @Service -public class GenerateServiceImpl implements GenerateService { - private static Logger logger = LoggerFactory.getLogger(GenerateServiceImpl.class); +public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { + private static Logger logger = LoggerFactory.getLogger(GenerateMarkdownServiceImpl.class); + @Autowired - private SqlServerGenerateServiceImpl sqlServerGenerateService; + private SqlServerGenerateMarkdownServiceImpl sqlServerGenerateMarkdownService; @Autowired private DatabaseService databaseService; @Autowired private HttpSession session; @Override - public void generatePdfFile(Connection connection, File file) { - + public String generateMarkdown() { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return generateMarkdown(dto.getDatabase()); } @Override - public void generatePdfFile(List tableInfos) { - + public String generateMarkdown(String schema) { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + DatabaseType type = dto.getType(); + if (type.equals(DatabaseType.SQLSERVER)) { + return sqlServerGenerateMarkdownService.generateMarkdown(schema); + } + try { + return generateMarkdown(databaseService.getTables(schema)); + } catch (SQLException e) { + e.printStackTrace(); + } + return "### 暂无数据"; } @Override - public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { - String fontDir = this.getClass().getResource("/") - .getPath() - .replaceAll("target/classes/", "") - .replaceAll("target/test-classes/", ""); - fontDir += "src/main/resources/"; - BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, 12, Font.BOLDITALIC); - // 设置类型,加粗 - font.setStyle(Font.NORMAL); - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 16); - //页面大小 - Rectangle rect = new Rectangle(PageSize.A4).rotate(); - //页面背景色 - rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); - //设置边框颜色 - rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); - Document doc = new Document(rect); - PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); - //设置事件 - ContentEvent event = new ContentEvent(); - contentWriter.setPageEvent(event); - //存目录监听 开始 - doc.open(); - int order = 1; - List chapterList = new ArrayList(); - //根据chapter章节分页 - //表格 - //设置表格模板 - String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; - String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; - for (TableInfo tableInfo : tableInfos) { - tableInfo = setIsIndex(tableInfo); - Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); - //设置跳转地址 - Phrase point = new Paragraph("基本信息:", cnFont); - Anchor tome = new Anchor(point); - tome.setName(tableInfo.getTableName()); - Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); - Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); - Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", getChineseFontAsStyle(BaseColor.BLACK, 16)); - //组装基本数据 - Paragraph contentInfo = new Paragraph(); - contentInfo.add(tome); - contentInfo.add(engine); - contentInfo.add(type); - contentInfo.add(description); - chapter.add(contentInfo); - chapter.add(new Paragraph("")); - //组装表格 - Paragraph tableParagraph = new Paragraph(); - //设置表格 - PdfPTable table = setTableHeader(tableHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - //设置列信息 - setTableColumn(table, tableInfo, font); - tableParagraph.add(table); - chapter.add(tableParagraph); - //设置索引表 - Paragraph blankTwo = new Paragraph("\n\n"); - chapter.add(blankTwo); - PdfPTable indexTable = setTableHeader(indexHeader, getChineseFontAsStyle(BaseColor.BLACK, 16)); - table.setWidthPercentage(100); - indexTable = setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), getFontAsStyle(BaseColor.RED, 10)); - Paragraph indexTableParagraph = new Paragraph(); - indexTableParagraph.add(indexTable); - chapter.add(indexTableParagraph); - - //加入文档中 - doc.add(chapter); - //保存章节内容 - chapterList.add(chapter); - order++; - } - doc.close(); - //存目录监听 结束 + public String generateMarkdown(List tableInfos) { + StringBuffer markdown = new StringBuffer(); + String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; + int i = 1; + for (TableInfo info : tableInfos) { + StringBuffer oneTble = new StringBuffer(); + oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info + .getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); + oneTble.append(res1); + List columnInfos = info.getColumnList(); + //拼接列 + if (columnInfos.size() > 0) { + } + for (int k = 0; k < columnInfos.size(); k++) { + ColumnInfo Column = columnInfos.get(k); + oneTble.append("|").append(Column.getOrder()).append("|"). + append(Column.getName()).append("|"). + append(Column.getType()).append("|"). + append(Column.getIsNull()).append("|"). + append(Column.getDefaultValue()).append("|"); + if ((k + 1) == columnInfos.size()) { + oneTble.append(Column.getDescription()).append("||"). + append("\n"); + } else { + oneTble.append(Column.getDescription()).append("|"). + append("\n"); - Document document = new Document(rect); - FileOutputStream os = new FileOutputStream(file); - PdfWriter writer = PdfWriter.getInstance(document, os); - IndexEvent indexEvent = new IndexEvent(); - writer.setPageEvent(indexEvent); - document.open(); - //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", getFontAsStyle(BaseColor.BLACK, 18)), 0); - indexChapter.setNumberDepth(-1); - // 设置数字深度 - int i = 1; - for (Map.Entry index : event.index.entrySet()) { - String key = index.getKey(); - String[] keyValue = key.split(" "); - //设置跳转显示名称 - int pageNo = index.getValue(); - Chunk pointChunk = new Chunk(new DottedLineSeparator()); - Chunk pageNoChunk = new Chunk(pageNo + ""); - String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { - tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; + } + } + //拼接索引 + oneTble.append("\n"); + oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); + oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); + List indexInfolist = info.getIndexInfoList(); + int j = 1; + for (IndexInfo indexInfo : indexInfolist) { + oneTble.append("|").append(j).append("|"). + append(indexInfo.getName()).append("|"). + append(indexInfo.getType()).append("|"). + append(indexInfo.getContainKey()).append("|"). + append("\n"); + j++; } - Paragraph jumpParagraph = new Paragraph(tempDescription, getChineseFontAsStyle(BaseColor.BLACK, 12)); - jumpParagraph.add(pointChunk); - jumpParagraph.add(pageNoChunk); - Anchor anchor = new Anchor(jumpParagraph); - String jump = keyValue[keyValue.length - 1].trim(); - //设置跳转链接 - anchor.setReference("#" + jump); - indexChapter.add(anchor); - indexChapter.add(new Paragraph()); i++; + oneTble.append("\n"); + markdown.append(oneTble); + //createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); } - document.add(indexChapter); - document.newPage(); - //添加内容 - for (Chapter c : chapterList) { - indexEvent.setBody(true); - document.add(c); - } - - document.close(); - os.close(); - } - - @Override - public void generatePdfFile(File file) { - + //目录 + markdown.insert(0, "[TOC]\n"); + return markdown.toString(); } public static TableInfo setIsIndex(TableInfo tableInfo) { @@ -416,79 +344,4 @@ public class GenerateServiceImpl implements GenerateService { return matcher.find(); } - @Override - public String generateMarkdown() { - ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); - return generateMarkdown(dto.getDatabase()); - } - - @Override - public String generateMarkdown(String schema) { - ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); - DatabaseType type = dto.getType(); - if (type.equals(DatabaseType.SQLSERVER)) { - return sqlServerGenerateService.generateMarkdown(schema); - } - try { - return generateMarkdown(databaseService.getTables(schema)); - } catch (SQLException e) { - e.printStackTrace(); - } - return "### 暂无数据"; - } - - @Override - public String generateMarkdown(List tableInfos) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (TableInfo info : tableInfos) { - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info - .getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - if (columnInfos.size() > 0) { - - } - for (int k = 0; k < columnInfos.size(); k++) { - ColumnInfo Column = columnInfos.get(k); - oneTble.append("|").append(Column.getOrder()).append("|"). - append(Column.getName()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIsNull()).append("|"). - append(Column.getDefaultValue()).append("|"); - if ((k + 1) == columnInfos.size()) { - oneTble.append(Column.getDescription()).append("||"). - append("\n"); - } else { - oneTble.append(Column.getDescription()).append("|"). - append("\n"); - - } - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (IndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getName()).append("|"). - append(indexInfo.getType()).append("|"). - append(indexInfo.getContainKey()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - //createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); - } - //目录 - markdown.insert(0, "[TOC]\n"); - return markdown.toString(); - } } diff --git a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java new file mode 100644 index 0000000..48db194 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java @@ -0,0 +1,184 @@ +package com.trh.dictionary.service.impl; + +import com.github.houbb.markdown.toc.util.StringUtil; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.BaseFont; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.text.pdf.draw.DottedLineSeparator; +import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.event.ContentEvent; +import com.trh.dictionary.event.IndexEvent; +import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.service.GeneratePdfService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpSession; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 创建PDF + * + * @author HouKunLin + * @date 2019/9/11 0011 11:16 + */ +@Primary +@Service +public class GeneratePdfServiceImpl implements GeneratePdfService { + private static Logger logger = LoggerFactory.getLogger(GeneratePdfServiceImpl.class); + @Autowired + private SqlServerGeneratePdfServiceImpl sqlServerGenerateService; + @Autowired + private DatabaseService databaseService; + @Autowired + private HttpSession session; + + @Override + public void generatePdfFile(List tableInfos) { + + } + + @Override + public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { + String fontDir = this.getClass().getResource("/") + .getPath() + .replaceAll("target/classes/", "") + .replaceAll("target/test-classes/", ""); + fontDir += "src/main/resources/"; + BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); + Font font = new Font(bfChinese, 12, Font.BOLDITALIC); + // 设置类型,加粗 + font.setStyle(Font.NORMAL); + Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); + //页面大小 + Rectangle rect = new Rectangle(PageSize.A4).rotate(); + //页面背景色 + rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); + //设置边框颜色 + rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); + Document doc = new Document(rect); + PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); + //设置事件 + ContentEvent event = new ContentEvent(); + contentWriter.setPageEvent(event); + //存目录监听 开始 + doc.open(); + int order = 1; + List chapterList = new ArrayList(); + //根据chapter章节分页 + //表格 + //设置表格模板 + String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; + String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; + for (TableInfo tableInfo : tableInfos) { + tableInfo = GenerateMarkdownServiceImpl.setIsIndex(tableInfo); + Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); + //设置跳转地址 + Phrase point = new Paragraph("基本信息:", cnFont); + Anchor tome = new Anchor(point); + tome.setName(tableInfo.getTableName()); + Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); + Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); + Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + //组装基本数据 + Paragraph contentInfo = new Paragraph(); + contentInfo.add(tome); + contentInfo.add(engine); + contentInfo.add(type); + contentInfo.add(description); + chapter.add(contentInfo); + chapter.add(new Paragraph("")); + //组装表格 + Paragraph tableParagraph = new Paragraph(); + //设置表格 + PdfPTable table = GenerateMarkdownServiceImpl.setTableHeader(tableHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + //设置列信息 + GenerateMarkdownServiceImpl.setTableColumn(table, tableInfo, font); + tableParagraph.add(table); + chapter.add(tableParagraph); + //设置索引表 + Paragraph blankTwo = new Paragraph("\n\n"); + chapter.add(blankTwo); + PdfPTable indexTable = GenerateMarkdownServiceImpl.setTableHeader(indexHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + table.setWidthPercentage(100); + indexTable = GenerateMarkdownServiceImpl.setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.RED, 10)); + Paragraph indexTableParagraph = new Paragraph(); + indexTableParagraph.add(indexTable); + chapter.add(indexTableParagraph); + + //加入文档中 + doc.add(chapter); + //保存章节内容 + chapterList.add(chapter); + order++; + } + doc.close(); + //存目录监听 结束 + + + Document document = new Document(rect); + FileOutputStream os = new FileOutputStream(file); + PdfWriter writer = PdfWriter.getInstance(document, os); + IndexEvent indexEvent = new IndexEvent(); + writer.setPageEvent(indexEvent); + document.open(); + //添加章节目录 + Chapter indexChapter = new Chapter(new Paragraph("", GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 18)), 0); + indexChapter.setNumberDepth(-1); + // 设置数字深度 + int i = 1; + for (Map.Entry index : event.index.entrySet()) { + String key = index.getKey(); + String[] keyValue = key.split(" "); + //设置跳转显示名称 + int pageNo = index.getValue(); + Chunk pointChunk = new Chunk(new DottedLineSeparator()); + Chunk pageNoChunk = new Chunk(pageNo + ""); + String tempDescription = key; + if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { + tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; + } + Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); + jumpParagraph.add(pointChunk); + jumpParagraph.add(pageNoChunk); + Anchor anchor = new Anchor(jumpParagraph); + String jump = keyValue[keyValue.length - 1].trim(); + //设置跳转链接 + anchor.setReference("#" + jump); + indexChapter.add(anchor); + indexChapter.add(new Paragraph()); + i++; + } + document.add(indexChapter); + document.newPage(); + //添加内容 + for (Chapter c : chapterList) { + indexEvent.setBody(true); + document.add(c); + } + + document.close(); + os.close(); + } + + @Override + public void generatePdfFile(File file) { + try { + generatePdfFile(databaseService.getTables(), file); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java similarity index 95% rename from src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java rename to src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 14d05b4..446b991 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -4,14 +4,13 @@ import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.service.GenerateService; +import com.trh.dictionary.service.GenerateMarkdownService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; -import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -20,39 +19,18 @@ import java.util.ArrayList; import java.util.List; /** - * MySQL数据库创建PDF文件 + * SQL Server数据渲染Markdown内容 * * @author HouKunLin - * @date 2019/9/11 0011 9:52 + * @date 2019/9/11 0011 16:24 */ @Service -public class SqlServerGenerateServiceImpl implements GenerateService { - private static Logger logger = LoggerFactory.getLogger(SqlServerGenerateServiceImpl.class); +public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownService { + private static Logger logger = LoggerFactory.getLogger(SqlServerGenerateMarkdownServiceImpl.class); @Autowired private DataSource dataSource; - @Override - public void generatePdfFile(Connection connection, File file) { - - } - - @Override - public void generatePdfFile(List tableInfos) { - - } - - - @Override - public void generatePdfFile(List tableInfos, File file) { - - } - - @Override - public void generatePdfFile(File file) { - - } - @Override public String generateMarkdown() { return generateMarkdown((String) null); @@ -212,6 +190,7 @@ public class SqlServerGenerateServiceImpl implements GenerateService { statement.close(); return list; } + public static String writeMarkdownString(List list) { StringBuffer markdown = new StringBuffer(); String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; @@ -255,6 +234,5 @@ public class SqlServerGenerateServiceImpl implements GenerateService { markdown.insert(0, "[TOC]\n"); logger.info("表信息\n" + markdown.toString()); return markdown.toString(); - } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java new file mode 100644 index 0000000..c017350 --- /dev/null +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -0,0 +1,42 @@ +package com.trh.dictionary.service.impl; + +import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.service.GeneratePdfService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.io.File; +import java.util.List; + +/** + * MySQL数据库创建PDF文件 + * + * @author HouKunLin + * @date 2019/9/11 0011 9:52 + */ +@Service +public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { + private static Logger logger = LoggerFactory.getLogger(SqlServerGeneratePdfServiceImpl.class); + + @Autowired + private DataSource dataSource; + + @Override + public void generatePdfFile(List tableInfos) { + + } + + + @Override + public void generatePdfFile(List tableInfos, File file) { + + } + + @Override + public void generatePdfFile(File file) { + + } +} diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java index 2a328aa..af7ebd4 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java @@ -13,7 +13,7 @@ import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; -import com.trh.dictionary.service.impl.GenerateServiceImpl; +import com.trh.dictionary.service.impl.GenerateMarkdownServiceImpl; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,7 +108,7 @@ public class BuildSqlserverPDF { Font font = new Font(bfChinese, 12, Font.BOLDITALIC); // 设置类型,加粗 font.setStyle(Font.NORMAL); - Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); + Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); //页面大小 Rectangle rect = new Rectangle(PageSize.A4).rotate(); //页面背景色 @@ -138,7 +138,7 @@ public class BuildSqlserverPDF { tome.setName(tableInfo.getTableName()); Phrase engine = new Phrase(" ", font); Phrase type = new Phrase(" ", font); - Phrase description = new Phrase(tableInfo.getValue(), GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + Phrase description = new Phrase(tableInfo.getValue(), GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); //组装基本数据 Paragraph contentInfo = new Paragraph(); contentInfo.add(tome); @@ -151,7 +151,7 @@ public class BuildSqlserverPDF { //组装表格 Paragraph tableParagraph = new Paragraph(); //设置表格 - PdfPTable table = GenerateServiceImpl.setTableHeader(tableHeader, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable table = GenerateMarkdownServiceImpl.setTableHeader(tableHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); //设置列信息 BuildColumnCell(table, font, tableInfo); tableParagraph.add(table); @@ -159,9 +159,9 @@ public class BuildSqlserverPDF { //设置索引表 Paragraph blankTwo = new Paragraph("\n\n"); chapter.add(blankTwo); - PdfPTable indexTable = GenerateServiceImpl.setTableHeader(indexHeader, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable indexTable = GenerateMarkdownServiceImpl.setTableHeader(indexHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); table.setWidthPercentage(100); - indexTable = BuildIndexCell(indexTable, GenerateServiceImpl.getFontAsStyle(BaseColor.RED, 10), tableInfo); + indexTable = BuildIndexCell(indexTable, GenerateMarkdownServiceImpl.getFontAsStyle(BaseColor.RED, 10), tableInfo); Paragraph indexTableParagraph = new Paragraph(); indexTableParagraph.add(indexTable); chapter.add(indexTableParagraph); @@ -183,7 +183,7 @@ public class BuildSqlserverPDF { writer.setPageEvent(indexEvent); document.open(); //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", GenerateServiceImpl.getFontAsStyle(BaseColor.BLACK, 18)), 0); + Chapter indexChapter = new Chapter(new Paragraph("", GenerateMarkdownServiceImpl.getFontAsStyle(BaseColor.BLACK, 18)), 0); indexChapter.setNumberDepth(-1); // 设置数字深度 int i = 1; @@ -199,7 +199,7 @@ public class BuildSqlserverPDF { if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; } - Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); + Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); jumpParagraph.add(pageNoChunk); Anchor anchor = new Anchor(jumpParagraph); @@ -234,7 +234,7 @@ public class BuildSqlserverPDF { List columnList = tableInfo.getColumnList(); for (SqlserverColumnInfo columnInfo : columnList) { - Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); if ("YES".equals(columnInfo.getP_k())) { cnFont.setColor(BaseColor.RED); } else { @@ -269,7 +269,7 @@ public class BuildSqlserverPDF { List indexInfos = tableInfo.getIndexInfoList(); - Font cnFont = GenerateServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); int i = 1; for (SqlserverIndexInfo indexInfo : indexInfos) { PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); diff --git a/src/main/java/com/trh/dictionary/util/PdfUtils.java b/src/main/java/com/trh/dictionary/util/PdfUtils.java new file mode 100644 index 0000000..2609d95 --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/PdfUtils.java @@ -0,0 +1,10 @@ +package com.trh.dictionary.util; + +/** + * PDF一些通用的方法 + * + * @author HouKunLin + * @date 2019/9/11 0011 16:32 + */ +public class PdfUtils { +} -- Gitee From c37711ccbb97bb8ce06e55d928bc28f471f041af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 16:40:01 +0800 Subject: [PATCH 36/46] =?UTF-8?q?=E6=94=B9=E5=8F=98PDF=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E7=9A=84=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81=E5=AD=98=E6=94=BE?= =?UTF-8?q?=E7=9A=84=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/GenerateMarkdownServiceImpl.java | 232 ----------------- .../service/impl/GeneratePdfServiceImpl.java | 20 +- .../service/sqlserver/BuildSqlserverPDF.java | 20 +- .../com/trh/dictionary/util/PdfUtils.java | 241 ++++++++++++++++++ 4 files changed, 261 insertions(+), 252 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java index 9ae23fd..07e4c3e 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java @@ -1,21 +1,13 @@ package com.trh.dictionary.service.impl; -import com.itextpdf.text.*; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.enums.DatabaseType; -import com.trh.dictionary.event.pdfPageEvent; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateMarkdownService; import com.trh.dictionary.util.Keys; -import com.trh.dictionary.util.SignEnum; -import com.trh.dictionary.util.TableBasicEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -23,11 +15,8 @@ import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; -import java.lang.reflect.Field; import java.sql.SQLException; import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * 构建Markdown内容 @@ -123,225 +112,4 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { return markdown.toString(); } - public static TableInfo setIsIndex(TableInfo tableInfo) { - List columnInfos = tableInfo.getColumnList(); - List indexInfos = tableInfo.getIndexInfoList(); - for (ColumnInfo columnInfo : columnInfos) { - for (IndexInfo indexInfo : indexInfos) { - String temp = indexInfo.getContainKey(); -// if (temp.contains(SignEnum.comma.getDesc())) { -// String[] keys = temp.split(SignEnum.comma.getDesc()); -// for (int i = 0; i < keys.length; i++) { -// String key = keys[i]; -// if (key.trim().equals(columnInfo.getName().trim())) { -// columnInfo.setIsIndex(1); -// } -// if (key.trim().contains(columnInfo.getName()) && columnInfo.getOrder() == 1) { -// columnInfo.setIsIndex(1); -// } -// } -// } else { -// if (temp.trim().equals(columnInfo.getName().trim())) { -// columnInfo.setIsIndex(1); -// } - String[] res = columnInfo.getName().split(" "); - if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc() - .equals(indexInfo.getType().trim())) { - columnInfo.setIsIndex(1); - } -// } - } - } - return tableInfo; - } - - /** - * 设置表格头部 - * - * @param header - * @param font - * @return - */ - public static PdfPTable setTableHeader(String[] header, Font font) { - int columnSize = header.length; - PdfPTable table = new PdfPTable(columnSize); - table.setWidthPercentage(100); - for (String value : header) { - PdfPCell cell1 = new PdfPCell(new Paragraph(value, font)); - cell1.setVerticalAlignment(Element.ALIGN_CENTER); -// cell1.setHorizontalAlignment(Element.ALIGN_CENTER); - cell1.setHorizontalAlignment(Element.ALIGN_LEFT); - cell1.setBackgroundColor(BaseColor.LIGHT_GRAY); - table.addCell(cell1); - } - return table; - } - - /** - * 设置基本表格的列 - * - * @param table - * @param tableInfo - * @param font - * @return - */ - public static PdfPTable setTableColumn(PdfPTable table, TableInfo tableInfo, Font font) { - List Columns = tableInfo.getColumnList(); - for (ColumnInfo column : Columns) { - table = reflectBuildCell(column, table, font, tableInfo); - } - return table; - } - - /** - * 设置基本表格的列 - * - * @param table - * @param Columns - * @return - */ - public static PdfPTable setIndexTableColumn(PdfPTable table, List Columns, Font font) { - int order = 1; - for (IndexInfo column : Columns) { - column.setOrder(order); - table = reflectBuildCell(column, table, font, null); - order++; - } - return table; - } - - - /** - * 通过反射填写表格内容 - * - * @param obj - * @author wangyu - * @date 2019-8-6 - */ - public static PdfPTable reflectBuildCell(Object obj, PdfPTable table, Font font, TableInfo tableInfo) { - if (obj == null) { - logger.error("填写表格内容对象为空"); - return table; - } - Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - Field[] fields = obj.getClass().getDeclaredFields(); - for (Field field : fields) { - PdfPCell cell = new PdfPCell(); - cell.setVerticalAlignment(Element.ALIGN_CENTER); - Paragraph paragraph = new Paragraph(); - //将设置私有构造器设为可取值 - field.setAccessible(true); - String name = field.getName(); - - if ("isIndex".equals(name)) { - try { - if ((Integer) field.get(obj) == 1) { - font = getFontAsStyle(BaseColor.RED, 12); - cnFont = getChineseFontAsStyle(BaseColor.RED, 12); - } else { - font = getFontAsStyle(BaseColor.BLACK, 12); - cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - continue; - } - - if (null != tableInfo) { - - } - - // 得到类型和名字取值 - if (field.getType().getName().equals(String.class.getName())) { - // String type - try { - if (isChineseContent(field.get(obj) + "")) { - font = cnFont; - } - paragraph = new Paragraph(field.get(obj) + "", font); - - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else if (field.getType().getName().equals(Integer.class.getName()) - || field.getType().getName().equals("int")) { - // Integer type - try { - paragraph = new Paragraph(field.get(obj) + "", font); - - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch b lock - e.printStackTrace(); - } - } - //添加到表格 - cell.addElement(paragraph); - table.addCell(cell); - } - return table; - } - - //设置页码 - public static void setFooter(PdfWriter writer, BaseFont bf) { - pdfPageEvent headerFooter = new pdfPageEvent(bf, 13, PageSize.A0); - writer.setPageEvent(headerFooter); - } - - public static String getPoint(String name, int size) { - int length = name.length(); - int res = size - length; - StringBuffer str = new StringBuffer(); - for (int i = 0; i < res; i++) { - str.append(SignEnum.point.getDesc()); - } - return str.toString(); - } - - /** - * 得到默认字体 - * - * @param color - * @param size - * @return - */ - public static Font getFontAsStyle(BaseColor color, float size) { - Font font = new Font(); - font.setColor(color); - font.setSize(size); - return font; - } - - /** - * 得到汉字字体 - * - * @param color - * @param size - * @return - */ - public static Font getChineseFontAsStyle(BaseColor color, float size) { - try { - //中文字体 - BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, size, Font.NORMAL); - font.setColor(color); - return font; - } catch (Exception e) { - logger.error("生成中文字体异常", e); - return new Font(); - } - } - - public static boolean isChineseContent(String content) { - String regex = "[\u4e00-\u9fa5]"; - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(content); - return matcher.find(); - } - } diff --git a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java index 48db194..81c41c2 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java @@ -11,6 +11,7 @@ import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GeneratePdfService; +import com.trh.dictionary.util.PdfUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -22,7 +23,6 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.sql.Connection; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -60,7 +60,7 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { Font font = new Font(bfChinese, 12, Font.BOLDITALIC); // 设置类型,加粗 font.setStyle(Font.NORMAL); - Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16); //页面大小 Rectangle rect = new Rectangle(PageSize.A4).rotate(); //页面背景色 @@ -82,7 +82,7 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; for (TableInfo tableInfo : tableInfos) { - tableInfo = GenerateMarkdownServiceImpl.setIsIndex(tableInfo); + tableInfo = PdfUtils.setIsIndex(tableInfo); Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); //设置跳转地址 Phrase point = new Paragraph("基本信息:", cnFont); @@ -90,7 +90,7 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { tome.setName(tableInfo.getTableName()); Phrase engine = new Phrase(" " + tableInfo.getStorageEngine(), font); Phrase type = new Phrase(" " + tableInfo.getOrderType(), font); - Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + Phrase description = new Phrase(" " + tableInfo.getDescription() + "\n\n", PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); //组装基本数据 Paragraph contentInfo = new Paragraph(); contentInfo.add(tome); @@ -102,17 +102,17 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { //组装表格 Paragraph tableParagraph = new Paragraph(); //设置表格 - PdfPTable table = GenerateMarkdownServiceImpl.setTableHeader(tableHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable table = PdfUtils.setTableHeader(tableHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); //设置列信息 - GenerateMarkdownServiceImpl.setTableColumn(table, tableInfo, font); + PdfUtils.setTableColumn(table, tableInfo, font); tableParagraph.add(table); chapter.add(tableParagraph); //设置索引表 Paragraph blankTwo = new Paragraph("\n\n"); chapter.add(blankTwo); - PdfPTable indexTable = GenerateMarkdownServiceImpl.setTableHeader(indexHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable indexTable = PdfUtils.setTableHeader(indexHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); table.setWidthPercentage(100); - indexTable = GenerateMarkdownServiceImpl.setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.RED, 10)); + indexTable = PdfUtils.setIndexTableColumn(indexTable, tableInfo.getIndexInfoList(), PdfUtils.getChineseFontAsStyle(BaseColor.RED, 10)); Paragraph indexTableParagraph = new Paragraph(); indexTableParagraph.add(indexTable); chapter.add(indexTableParagraph); @@ -134,7 +134,7 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { writer.setPageEvent(indexEvent); document.open(); //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 18)), 0); + Chapter indexChapter = new Chapter(new Paragraph("", PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 18)), 0); indexChapter.setNumberDepth(-1); // 设置数字深度 int i = 1; @@ -149,7 +149,7 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; } - Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); + Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); jumpParagraph.add(pageNoChunk); Anchor anchor = new Anchor(jumpParagraph); diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java index af7ebd4..f08b78b 100644 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java @@ -13,7 +13,7 @@ import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; -import com.trh.dictionary.service.impl.GenerateMarkdownServiceImpl; +import com.trh.dictionary.util.PdfUtils; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,7 +108,7 @@ public class BuildSqlserverPDF { Font font = new Font(bfChinese, 12, Font.BOLDITALIC); // 设置类型,加粗 font.setStyle(Font.NORMAL); - Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16); + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16); //页面大小 Rectangle rect = new Rectangle(PageSize.A4).rotate(); //页面背景色 @@ -138,7 +138,7 @@ public class BuildSqlserverPDF { tome.setName(tableInfo.getTableName()); Phrase engine = new Phrase(" ", font); Phrase type = new Phrase(" ", font); - Phrase description = new Phrase(tableInfo.getValue(), GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + Phrase description = new Phrase(tableInfo.getValue(), PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); //组装基本数据 Paragraph contentInfo = new Paragraph(); contentInfo.add(tome); @@ -151,7 +151,7 @@ public class BuildSqlserverPDF { //组装表格 Paragraph tableParagraph = new Paragraph(); //设置表格 - PdfPTable table = GenerateMarkdownServiceImpl.setTableHeader(tableHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable table = PdfUtils.setTableHeader(tableHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); //设置列信息 BuildColumnCell(table, font, tableInfo); tableParagraph.add(table); @@ -159,9 +159,9 @@ public class BuildSqlserverPDF { //设置索引表 Paragraph blankTwo = new Paragraph("\n\n"); chapter.add(blankTwo); - PdfPTable indexTable = GenerateMarkdownServiceImpl.setTableHeader(indexHeader, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 16)); + PdfPTable indexTable = PdfUtils.setTableHeader(indexHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); table.setWidthPercentage(100); - indexTable = BuildIndexCell(indexTable, GenerateMarkdownServiceImpl.getFontAsStyle(BaseColor.RED, 10), tableInfo); + indexTable = BuildIndexCell(indexTable, PdfUtils.getFontAsStyle(BaseColor.RED, 10), tableInfo); Paragraph indexTableParagraph = new Paragraph(); indexTableParagraph.add(indexTable); chapter.add(indexTableParagraph); @@ -183,7 +183,7 @@ public class BuildSqlserverPDF { writer.setPageEvent(indexEvent); document.open(); //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", GenerateMarkdownServiceImpl.getFontAsStyle(BaseColor.BLACK, 18)), 0); + Chapter indexChapter = new Chapter(new Paragraph("", PdfUtils.getFontAsStyle(BaseColor.BLACK, 18)), 0); indexChapter.setNumberDepth(-1); // 设置数字深度 int i = 1; @@ -199,7 +199,7 @@ public class BuildSqlserverPDF { if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; } - Paragraph jumpParagraph = new Paragraph(tempDescription, GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12)); + Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); jumpParagraph.add(pageNoChunk); Anchor anchor = new Anchor(jumpParagraph); @@ -234,7 +234,7 @@ public class BuildSqlserverPDF { List columnList = tableInfo.getColumnList(); for (SqlserverColumnInfo columnInfo : columnList) { - Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); if ("YES".equals(columnInfo.getP_k())) { cnFont.setColor(BaseColor.RED); } else { @@ -269,7 +269,7 @@ public class BuildSqlserverPDF { List indexInfos = tableInfo.getIndexInfoList(); - Font cnFont = GenerateMarkdownServiceImpl.getChineseFontAsStyle(BaseColor.BLACK, 12); + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); int i = 1; for (SqlserverIndexInfo indexInfo : indexInfos) { PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); diff --git a/src/main/java/com/trh/dictionary/util/PdfUtils.java b/src/main/java/com/trh/dictionary/util/PdfUtils.java index 2609d95..5f0ab94 100644 --- a/src/main/java/com/trh/dictionary/util/PdfUtils.java +++ b/src/main/java/com/trh/dictionary/util/PdfUtils.java @@ -1,5 +1,22 @@ package com.trh.dictionary.util; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.BaseFont; +import com.itextpdf.text.pdf.PdfPCell; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; +import com.trh.dictionary.bean.ColumnInfo; +import com.trh.dictionary.bean.IndexInfo; +import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.event.pdfPageEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * PDF一些通用的方法 * @@ -7,4 +24,228 @@ package com.trh.dictionary.util; * @date 2019/9/11 0011 16:32 */ public class PdfUtils { + private static Logger logger = LoggerFactory.getLogger(PdfUtils.class); + + public static TableInfo setIsIndex(TableInfo tableInfo) { + List columnInfos = tableInfo.getColumnList(); + List indexInfos = tableInfo.getIndexInfoList(); + for (ColumnInfo columnInfo : columnInfos) { + for (IndexInfo indexInfo : indexInfos) { + String temp = indexInfo.getContainKey(); +// if (temp.contains(SignEnum.comma.getDesc())) { +// String[] keys = temp.split(SignEnum.comma.getDesc()); +// for (int i = 0; i < keys.length; i++) { +// String key = keys[i]; +// if (key.trim().equals(columnInfo.getName().trim())) { +// columnInfo.setIsIndex(1); +// } +// if (key.trim().contains(columnInfo.getName()) && columnInfo.getOrder() == 1) { +// columnInfo.setIsIndex(1); +// } +// } +// } else { +// if (temp.trim().equals(columnInfo.getName().trim())) { +// columnInfo.setIsIndex(1); +// } + String[] res = columnInfo.getName().split(" "); + if (res[0].equals(temp.trim()) && TableBasicEnum.WORD_PRIMARY.getDesc() + .equals(indexInfo.getType().trim())) { + columnInfo.setIsIndex(1); + } +// } + } + } + return tableInfo; + } + + /** + * 设置表格头部 + * + * @param header + * @param font + * @return + */ + public static PdfPTable setTableHeader(String[] header, Font font) { + int columnSize = header.length; + PdfPTable table = new PdfPTable(columnSize); + table.setWidthPercentage(100); + for (String value : header) { + PdfPCell cell1 = new PdfPCell(new Paragraph(value, font)); + cell1.setVerticalAlignment(Element.ALIGN_CENTER); +// cell1.setHorizontalAlignment(Element.ALIGN_CENTER); + cell1.setHorizontalAlignment(Element.ALIGN_LEFT); + cell1.setBackgroundColor(BaseColor.LIGHT_GRAY); + table.addCell(cell1); + } + return table; + } + + /** + * 设置基本表格的列 + * + * @param table + * @param tableInfo + * @param font + * @return + */ + public static PdfPTable setTableColumn(PdfPTable table, TableInfo tableInfo, Font font) { + List Columns = tableInfo.getColumnList(); + for (ColumnInfo column : Columns) { + table = reflectBuildCell(column, table, font, tableInfo); + } + return table; + } + + /** + * 设置基本表格的列 + * + * @param table + * @param Columns + * @return + */ + public static PdfPTable setIndexTableColumn(PdfPTable table, List Columns, Font font) { + int order = 1; + for (IndexInfo column : Columns) { + column.setOrder(order); + table = reflectBuildCell(column, table, font, null); + order++; + } + return table; + } + + + /** + * 通过反射填写表格内容 + * + * @param obj + * @author wangyu + * @date 2019-8-6 + */ + public static PdfPTable reflectBuildCell(Object obj, PdfPTable table, Font font, TableInfo tableInfo) { + if (obj == null) { + logger.error("填写表格内容对象为空"); + return table; + } + Font cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + Field[] fields = obj.getClass().getDeclaredFields(); + for (Field field : fields) { + PdfPCell cell = new PdfPCell(); + cell.setVerticalAlignment(Element.ALIGN_CENTER); + Paragraph paragraph = new Paragraph(); + //将设置私有构造器设为可取值 + field.setAccessible(true); + String name = field.getName(); + + if ("isIndex".equals(name)) { + try { + if ((Integer) field.get(obj) == 1) { + font = getFontAsStyle(BaseColor.RED, 12); + cnFont = getChineseFontAsStyle(BaseColor.RED, 12); + } else { + font = getFontAsStyle(BaseColor.BLACK, 12); + cnFont = getChineseFontAsStyle(BaseColor.BLACK, 12); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + continue; + } + + if (null != tableInfo) { + + } + + // 得到类型和名字取值 + if (field.getType().getName().equals(String.class.getName())) { + // String type + try { + if (isChineseContent(field.get(obj) + "")) { + font = cnFont; + } + paragraph = new Paragraph(field.get(obj) + "", font); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else if (field.getType().getName().equals(Integer.class.getName()) + || field.getType().getName().equals("int")) { + // Integer type + try { + paragraph = new Paragraph(field.get(obj) + "", font); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch b lock + e.printStackTrace(); + } + } + //添加到表格 + cell.addElement(paragraph); + table.addCell(cell); + } + return table; + } + + /** + * 得到汉字字体 + * + * @param color + * @param size + * @return + */ + public static Font getChineseFontAsStyle(BaseColor color, float size) { + try { + //中文字体 + BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); + Font font = new Font(bfChinese, size, Font.NORMAL); + font.setColor(color); + return font; + } catch (Exception e) { + logger.error("生成中文字体异常", e); + return new Font(); + } + } + + public static boolean isChineseContent(String content) { + String regex = "[\u4e00-\u9fa5]"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(content); + return matcher.find(); + } + + + //设置页码 + public static void setFooter(PdfWriter writer, BaseFont bf) { + pdfPageEvent headerFooter = new pdfPageEvent(bf, 13, PageSize.A0); + writer.setPageEvent(headerFooter); + } + + public static String getPoint(String name, int size) { + int length = name.length(); + int res = size - length; + StringBuffer str = new StringBuffer(); + for (int i = 0; i < res; i++) { + str.append(SignEnum.point.getDesc()); + } + return str.toString(); + } + + /** + * 得到默认字体 + * + * @param color + * @param size + * @return + */ + public static Font getFontAsStyle(BaseColor color, float size) { + Font font = new Font(); + font.setColor(color); + font.setSize(size); + return font; + } + } -- Gitee From 75155ca6a0274e47039c9fddfd7e47029d22c675 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 16:46:10 +0800 Subject: [PATCH 37/46] =?UTF-8?q?=E6=94=B9=E5=8F=98SQL=20Server=20PDF?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E7=9A=84=E4=BB=A3=E7=A0=81=E5=AD=98=E6=94=BE?= =?UTF-8?q?=E7=9A=84=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conterller/DatabaseController.java | 3 +- .../sqlserver/SqlserverConnectionFactory.java | 40 --- .../impl/SqlServerGeneratePdfServiceImpl.java | 254 ++++++++++++++- .../service/sqlserver/BuildSqlserverPDF.java | 288 ------------------ src/test/java/com/trh/dictionary/Test.java | 3 +- .../com/trh/dictionary/TestConnection.java | 5 +- 6 files changed, 257 insertions(+), 336 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java delete mode 100644 src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index 20e4e86..c715495 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -6,7 +6,6 @@ import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateMarkdownService; import com.trh.dictionary.service.GeneratePdfService; -import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -107,7 +106,7 @@ public class DatabaseController { File outfile = new File(filePath, "DataBase.pdf"); try { if (dto.getType() == DatabaseType.SQLSERVER) { - BuildSqlserverPDF.MakePdf(dto.getHost(), database, dto.getPort(), dto.getUsername(), dto.getPassword(), filePath, "DataBase"); +// BuildSqlserverPDF.MakePdf(dto.getHost(), database, dto.getPort(), dto.getUsername(), dto.getPassword(), filePath, "DataBase"); } else { pdfService.generatePdfFile(outfile); } diff --git a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java b/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java deleted file mode 100644 index 29da903..0000000 --- a/src/main/java/com/trh/dictionary/dao/sqlserver/SqlserverConnectionFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.trh.dictionary.dao.sqlserver; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * @author zhou - * @create 2019-08-29 16:31 - * @description: - */ -public class SqlserverConnectionFactory { - - static Logger logger = LoggerFactory.getLogger(SqlserverConnectionFactory.class); - - public static Connection getConnection(String url, String userName, String passWord) { - Connection connection = null; - //创建驱动 - try { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - //创建连接 - try { - connection = DriverManager.getConnection(url, userName, passWord); - if (connection.isClosed()) { - logger.info("-------------------the connect is closed--------------"); - return null; - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return connection; - } -} \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java index c017350..23a2d97 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -1,15 +1,34 @@ package com.trh.dictionary.service.impl; +import com.github.houbb.markdown.toc.util.StringUtil; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.BaseFont; +import com.itextpdf.text.pdf.PdfPCell; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.text.pdf.draw.DottedLineSeparator; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; +import com.trh.dictionary.event.ContentEvent; +import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.GeneratePdfService; +import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; +import com.trh.dictionary.util.PdfUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; +import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.util.ArrayList; import java.util.List; +import java.util.Map; /** * MySQL数据库创建PDF文件 @@ -29,7 +48,6 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { } - @Override public void generatePdfFile(List tableInfos, File file) { @@ -37,6 +55,240 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { @Override public void generatePdfFile(File file) { + try { + + //得到生成数据 + Connection connection = dataSource.getConnection(); + + String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + + List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); + if (list_table.size() == 0) { + return; + } + for (SqlserverTabelInfo Ta : list_table) { + logger.info(Ta.getTableName()); + List list_column = new ArrayList(); + List list_index = new ArrayList(); + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; + try { + list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { + logger.info(s.toString()); + } + } catch (Exception e) { + e.printStackTrace(); + } + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + "SELECT i.name AS index_name,(\n" + + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; + try { + list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { + logger.info(s.toString()); + } + } catch (Exception e) { + e.printStackTrace(); + } + Ta.setColumnList(list_column); + Ta.setIndexInfoList(list_index); + } + //带目录 + build(list_table, file); + } catch (Exception e) { + e.printStackTrace(); + logger.info("生成PDF失败"); + } + } + + public static void build(List tableInfos, File file) throws Exception { + String fontDir = SqlServerGeneratePdfServiceImpl.class.getResource("/").getPath().replaceAll("target/classes/", ""); + fontDir += "src/main/resources/"; + BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); + Font font = new Font(bfChinese, 12, Font.BOLDITALIC); + // 设置类型,加粗 + font.setStyle(Font.NORMAL); + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16); + //页面大小 + Rectangle rect = new Rectangle(PageSize.A4).rotate(); + //页面背景色 + rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); + //设置边框颜色 + rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); + Document doc = new Document(rect); + PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); + //设置事件 + ContentEvent event = new ContentEvent(); + contentWriter.setPageEvent(event); + //存目录监听 开始 + doc.open(); + int order = 1; + List chapterList = new ArrayList(); + //根据chapter章节分页 + //表格 + //设置表格模板 + String[] tableHeader = {"序列", "列名", "主键", "类型", "可空", "默认值", "注释"}; + String[] indexHeader = {"序列", "索引名", "描述", "包含字段"}; + for (SqlserverTabelInfo tableInfo : tableInfos) { + + Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); + //设置跳转地址 + Phrase point = new Paragraph("基本信息:", cnFont); + Anchor tome = new Anchor(point); + tome.setName(tableInfo.getTableName()); + Phrase engine = new Phrase(" ", font); + Phrase type = new Phrase(" ", font); + Phrase description = new Phrase(tableInfo.getValue(), PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); + //组装基本数据 + Paragraph contentInfo = new Paragraph(); + contentInfo.add(tome); + contentInfo.add(engine); + contentInfo.add(type); + contentInfo.add(description); + contentInfo.add(new Paragraph(" ")); + chapter.add(contentInfo); + chapter.add(new Paragraph("")); + //组装表格 + Paragraph tableParagraph = new Paragraph(); + //设置表格 + PdfPTable table = PdfUtils.setTableHeader(tableHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); + //设置列信息 + BuildColumnCell(table, font, tableInfo); + tableParagraph.add(table); + chapter.add(tableParagraph); + //设置索引表 + Paragraph blankTwo = new Paragraph("\n\n"); + chapter.add(blankTwo); + PdfPTable indexTable = PdfUtils.setTableHeader(indexHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); + table.setWidthPercentage(100); + indexTable = BuildIndexCell(indexTable, PdfUtils.getFontAsStyle(BaseColor.RED, 10), tableInfo); + Paragraph indexTableParagraph = new Paragraph(); + indexTableParagraph.add(indexTable); + chapter.add(indexTableParagraph); + + //加入文档中 + doc.add(chapter); + //保存章节内容 + chapterList.add(chapter); + order++; + } + doc.close(); + //存目录监听 结束 + + + Document document = new Document(rect); + FileOutputStream os = new FileOutputStream(file); + PdfWriter writer = PdfWriter.getInstance(document, os); + IndexEvent indexEvent = new IndexEvent(); + writer.setPageEvent(indexEvent); + document.open(); + //添加章节目录 + Chapter indexChapter = new Chapter(new Paragraph("", PdfUtils.getFontAsStyle(BaseColor.BLACK, 18)), 0); + indexChapter.setNumberDepth(-1); + // 设置数字深度 + int i = 1; + for (Map.Entry index : event.index.entrySet()) { + String key = index.getKey(); + String[] keyValue = key.split(" "); + //设置跳转显示名称 + int pageNo = index.getValue(); + Chunk pointChunk = new Chunk(new DottedLineSeparator()); + Chunk pageNoChunk = new Chunk(pageNo + ""); + String tempDescription = key; + if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { + tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; + } + Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); + jumpParagraph.add(pointChunk); + jumpParagraph.add(pageNoChunk); + Anchor anchor = new Anchor(jumpParagraph); + String jump = keyValue[keyValue.length - 1].trim(); + //设置跳转链接 + anchor.setReference("#" + jump); + indexChapter.add(anchor); + indexChapter.add(new Paragraph()); + i++; + } + document.add(indexChapter); + document.newPage(); + //添加内容 + for (Chapter c : chapterList) { + indexEvent.setBody(true); + document.add(c); + } + + document.close(); + os.close(); + } + + /* + * @Author zhou + * @Description 循环生成列信息 + * @Date 11:19 2019/8/30 + * @Param [table, font, tableInfo] + * @return com.itextpdf.text.pdf.PdfPTable + **/ + public static PdfPTable BuildColumnCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { + + List columnList = tableInfo.getColumnList(); + + for (SqlserverColumnInfo columnInfo : columnList) { + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); + if ("YES".equals(columnInfo.getP_k())) { + cnFont.setColor(BaseColor.RED); + } else { + cnFont.setColor(BaseColor.BLACK); + } + PdfPCell cell1 = new PdfPCell(new Paragraph(columnInfo.getColumn_num(), cnFont)); + table.addCell(cell1); + PdfPCell cell2 = new PdfPCell(new Paragraph(columnInfo.getColumn_name(), cnFont)); + table.addCell(cell2); + PdfPCell cell3 = new PdfPCell(new Paragraph(columnInfo.getP_k(), cnFont)); + table.addCell(cell3); + PdfPCell cell4 = new PdfPCell(new Paragraph(columnInfo.getType() + "(" + columnInfo.getLength() + ")", cnFont)); + table.addCell(cell4); + PdfPCell cell5 = new PdfPCell(new Paragraph(columnInfo.getIs_null(), cnFont)); + table.addCell(cell5); + PdfPCell cell6 = new PdfPCell(new Paragraph(columnInfo.getDefault_value(), cnFont)); + table.addCell(cell6); + PdfPCell cell7 = new PdfPCell(new Paragraph(columnInfo.getDecs(), cnFont)); + table.addCell(cell7); + } + return table; } + + /* + * @Author zhou + * @Description 循环生成索引信息 + * @Date 11:19 2019/8/30 + * @Param [table, font, tableInfo] + * @return com.itextpdf.text.pdf.PdfPTable + **/ + public static PdfPTable BuildIndexCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { + + List indexInfos = tableInfo.getIndexInfoList(); + + Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); + int i = 1; + for (SqlserverIndexInfo indexInfo : indexInfos) { + PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); + table.addCell(cell1); + PdfPCell cell2 = new PdfPCell(new Paragraph(indexInfo.getIndex_name())); + table.addCell(cell2); + PdfPCell cell3 = new PdfPCell(new Paragraph(indexInfo.getIndex_desc())); + table.addCell(cell3); + PdfPCell cell4 = new PdfPCell(new Paragraph(indexInfo.getIndex_keys())); + table.addCell(cell4); + i++; + } + return table; + } + } diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java b/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java deleted file mode 100644 index f08b78b..0000000 --- a/src/main/java/com/trh/dictionary/service/sqlserver/BuildSqlserverPDF.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.trh.dictionary.service.sqlserver; - -import com.github.houbb.markdown.toc.util.StringUtil; -import com.itextpdf.text.*; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; -import com.itextpdf.text.pdf.draw.DottedLineSeparator; -import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; -import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; -import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; -import com.trh.dictionary.event.ContentEvent; -import com.trh.dictionary.event.IndexEvent; -import com.trh.dictionary.util.PdfUtils; -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * @author zhou - * @create 2019-08-30 10:22 - * @description: - */ -public class BuildSqlserverPDF { - - static Logger logger = LoggerFactory.getLogger(BuildSqlserverPDF.class); - - /** - * 生成PDF - * - * @param ip :数据库连接的IP 例如:127.0.0.1 或者 localhost - * @param dbName 例如: test - * @param port 例如: 3306 - * @param userName 例如: root - * @param passWord 例如: root - * @param filePath 例如: D:\ideaspace\export_dbInfo\src\main\resources\ - * @param pdfName 例如: testPDF - */ - public static void MakePdf(String ip, String dbName, String port, String userName, String passWord, String filePath, String pdfName) { - try { - - String dbURL = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dbName + ";"; - //得到生成数据 - Connection connection = SqlserverConnectionFactory.getConnection(dbURL, userName, passWord); - - String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - - List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); - if (list_table.size() == 0) { - return; - } - for (SqlserverTabelInfo Ta : list_table) { - logger.info(Ta.getTableName()); - List list_column = new ArrayList(); - List list_index = new ArrayList(); - String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + - "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + - "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + - "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; - try { - list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); - for (SqlserverColumnInfo s : list_column) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + - "SELECT i.name AS index_name,(\n" + - "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + - "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; - try { - list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); - for (SqlserverIndexInfo s : list_index) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - Ta.setColumnList(list_column); - Ta.setIndexInfoList(list_index); - } - FileUtils.forceMkdir(new File(filePath)); - //带目录 - build(filePath, list_table, pdfName); - } catch (Exception e) { - e.printStackTrace(); - logger.info("生成PDF失败"); - } - } - - public static void build(String FILE_DIR, List tableInfos, String pdfName) throws Exception { - String fontDir = BuildSqlserverPDF.class.getResource("/").getPath().replaceAll("target/classes/", ""); - fontDir += "src/main/resources/"; - BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); - Font font = new Font(bfChinese, 12, Font.BOLDITALIC); - // 设置类型,加粗 - font.setStyle(Font.NORMAL); - Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16); - //页面大小 - Rectangle rect = new Rectangle(PageSize.A4).rotate(); - //页面背景色 - rect.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE)); - //设置边框颜色 - rect.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE)); - Document doc = new Document(rect); - PdfWriter contentWriter = PdfWriter.getInstance(doc, new ByteArrayOutputStream()); - //设置事件 - ContentEvent event = new ContentEvent(); - contentWriter.setPageEvent(event); - //存目录监听 开始 - doc.open(); - int order = 1; - List chapterList = new ArrayList(); - //根据chapter章节分页 - //表格 - //设置表格模板 - String[] tableHeader = {"序列", "列名", "主键", "类型", "可空", "默认值", "注释"}; - String[] indexHeader = {"序列", "索引名", "描述", "包含字段"}; - for (SqlserverTabelInfo tableInfo : tableInfos) { - - Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); - //设置跳转地址 - Phrase point = new Paragraph("基本信息:", cnFont); - Anchor tome = new Anchor(point); - tome.setName(tableInfo.getTableName()); - Phrase engine = new Phrase(" ", font); - Phrase type = new Phrase(" ", font); - Phrase description = new Phrase(tableInfo.getValue(), PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); - //组装基本数据 - Paragraph contentInfo = new Paragraph(); - contentInfo.add(tome); - contentInfo.add(engine); - contentInfo.add(type); - contentInfo.add(description); - contentInfo.add(new Paragraph(" ")); - chapter.add(contentInfo); - chapter.add(new Paragraph("")); - //组装表格 - Paragraph tableParagraph = new Paragraph(); - //设置表格 - PdfPTable table = PdfUtils.setTableHeader(tableHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); - //设置列信息 - BuildColumnCell(table, font, tableInfo); - tableParagraph.add(table); - chapter.add(tableParagraph); - //设置索引表 - Paragraph blankTwo = new Paragraph("\n\n"); - chapter.add(blankTwo); - PdfPTable indexTable = PdfUtils.setTableHeader(indexHeader, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 16)); - table.setWidthPercentage(100); - indexTable = BuildIndexCell(indexTable, PdfUtils.getFontAsStyle(BaseColor.RED, 10), tableInfo); - Paragraph indexTableParagraph = new Paragraph(); - indexTableParagraph.add(indexTable); - chapter.add(indexTableParagraph); - - //加入文档中 - doc.add(chapter); - //保存章节内容 - chapterList.add(chapter); - order++; - } - doc.close(); - //存目录监听 结束 - - - Document document = new Document(rect); - FileOutputStream os = new FileOutputStream(FILE_DIR + pdfName + ".pdf"); - PdfWriter writer = PdfWriter.getInstance(document, os); - IndexEvent indexEvent = new IndexEvent(); - writer.setPageEvent(indexEvent); - document.open(); - //添加章节目录 - Chapter indexChapter = new Chapter(new Paragraph("", PdfUtils.getFontAsStyle(BaseColor.BLACK, 18)), 0); - indexChapter.setNumberDepth(-1); - // 设置数字深度 - int i = 1; - for (Map.Entry index : event.index.entrySet()) { - String key = index.getKey(); - String[] keyValue = key.split(" "); - //设置跳转显示名称 - int pageNo = index.getValue(); - Chunk pointChunk = new Chunk(new DottedLineSeparator()); - Chunk pageNoChunk = new Chunk(pageNo + ""); - - String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { - tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; - } - Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); - jumpParagraph.add(pointChunk); - jumpParagraph.add(pageNoChunk); - Anchor anchor = new Anchor(jumpParagraph); - String jump = keyValue[keyValue.length - 1].trim(); - //设置跳转链接 - anchor.setReference("#" + jump); - indexChapter.add(anchor); - indexChapter.add(new Paragraph()); - i++; - } - document.add(indexChapter); - document.newPage(); - //添加内容 - for (Chapter c : chapterList) { - indexEvent.setBody(true); - document.add(c); - } - - document.close(); - os.close(); - } - - /* - * @Author zhou - * @Description 循环生成列信息 - * @Date 11:19 2019/8/30 - * @Param [table, font, tableInfo] - * @return com.itextpdf.text.pdf.PdfPTable - **/ - public static PdfPTable BuildColumnCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { - - List columnList = tableInfo.getColumnList(); - - for (SqlserverColumnInfo columnInfo : columnList) { - Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); - if ("YES".equals(columnInfo.getP_k())) { - cnFont.setColor(BaseColor.RED); - } else { - cnFont.setColor(BaseColor.BLACK); - } - PdfPCell cell1 = new PdfPCell(new Paragraph(columnInfo.getColumn_num(), cnFont)); - table.addCell(cell1); - PdfPCell cell2 = new PdfPCell(new Paragraph(columnInfo.getColumn_name(), cnFont)); - table.addCell(cell2); - PdfPCell cell3 = new PdfPCell(new Paragraph(columnInfo.getP_k(), cnFont)); - table.addCell(cell3); - PdfPCell cell4 = new PdfPCell(new Paragraph(columnInfo.getType() + "(" + columnInfo.getLength() + ")", cnFont)); - table.addCell(cell4); - PdfPCell cell5 = new PdfPCell(new Paragraph(columnInfo.getIs_null(), cnFont)); - table.addCell(cell5); - PdfPCell cell6 = new PdfPCell(new Paragraph(columnInfo.getDefault_value(), cnFont)); - table.addCell(cell6); - PdfPCell cell7 = new PdfPCell(new Paragraph(columnInfo.getDecs(), cnFont)); - table.addCell(cell7); - } - return table; - } - - /* - * @Author zhou - * @Description 循环生成索引信息 - * @Date 11:19 2019/8/30 - * @Param [table, font, tableInfo] - * @return com.itextpdf.text.pdf.PdfPTable - **/ - public static PdfPTable BuildIndexCell(PdfPTable table, Font font, SqlserverTabelInfo tableInfo) { - - List indexInfos = tableInfo.getIndexInfoList(); - - Font cnFont = PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12); - int i = 1; - for (SqlserverIndexInfo indexInfo : indexInfos) { - PdfPCell cell1 = new PdfPCell(new Paragraph(i + "")); - table.addCell(cell1); - PdfPCell cell2 = new PdfPCell(new Paragraph(indexInfo.getIndex_name())); - table.addCell(cell2); - PdfPCell cell3 = new PdfPCell(new Paragraph(indexInfo.getIndex_desc())); - table.addCell(cell3); - PdfPCell cell4 = new PdfPCell(new Paragraph(indexInfo.getIndex_keys())); - table.addCell(cell4); - i++; - } - return table; - } - -} \ No newline at end of file diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index 20e09e0..45d6c99 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -1,7 +1,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.service.sqlserver.BuildSqlserverPDF; import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; @@ -46,7 +45,7 @@ public class Test { @org.junit.Test public void testMakeSqlServerPdf() { String FILE_DIR = "F:/pdf/"; - BuildSqlserverPDF.MakePdf("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA", FILE_DIR, "zhou"); + // BuildSqlserverPDF.MakePdf("192.168.161.3", "zhou", "1433", "SA", "zhoufan123AAA", FILE_DIR, "zhou"); } @org.junit.Test diff --git a/src/test/java/com/trh/dictionary/TestConnection.java b/src/test/java/com/trh/dictionary/TestConnection.java index f11066e..c652dcf 100644 --- a/src/test/java/com/trh/dictionary/TestConnection.java +++ b/src/test/java/com/trh/dictionary/TestConnection.java @@ -3,7 +3,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.dao.sqlserver.SqlserverConnectionFactory; import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,7 +17,7 @@ import java.util.List; */ public class TestConnection { - static Logger logger = LoggerFactory.getLogger(SqlserverConnectionFactory.class); + private static Logger logger = LoggerFactory.getLogger(TestConnection.class); @org.junit.Test public void testConnection() { @@ -26,7 +25,7 @@ public class TestConnection { String dbURL = "jdbc:sqlserver://192.168.161.3:1433;DatabaseName=zhou"; String userName = "SA"; String userPwd = "zhoufan123AAA"; - Connection connection = SqlserverConnectionFactory.getConnection(dbURL, userName, userPwd); + Connection connection = null;// SqlserverConnectionFactory.getConnection(dbURL, userName, userPwd); String sqltabel = "SELECT Name as name FROM SysObjects Where XType='U' ORDER BY Name;"; List list_table = null; try { -- Gitee From 4b6eef62df329aea6c51fb6214420e92cac1a73b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 17:03:12 +0800 Subject: [PATCH 38/46] =?UTF-8?q?=E7=BB=99TableInfo=E5=92=8CSqlServerTable?= =?UTF-8?q?Info=E6=8A=BD=E5=8F=96=E5=87=BA=E4=B8=80=E4=B8=AA=E7=88=B6?= =?UTF-8?q?=E7=B1=BBBaseTableInfo.java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/trh/dictionary/bean/TableInfo.java | 41 +--------------- .../dictionary/bean/base/BaseTableInfo.java | 49 +++++++++++++++++++ .../bean/sqlserver/SqlserverTabelInfo.java | 41 +--------------- .../dictionary/service/DatabaseService.java | 6 +-- .../service/GenerateMarkdownService.java | 4 +- .../service/GeneratePdfService.java | 6 +-- .../service/impl/DatabaseServiceImpl.java | 6 +-- .../service/impl/Db2DatabaseServiceImpl.java | 7 +-- .../impl/GenerateMarkdownServiceImpl.java | 6 ++- .../service/impl/GeneratePdfServiceImpl.java | 14 ++++-- .../impl/MySqlDatabaseServiceImpl.java | 7 +-- .../impl/OracleDatabaseServiceImpl.java | 7 +-- .../impl/PostgreSqlDatabaseServiceImpl.java | 7 +-- .../impl/SqlServerDatabaseServiceImpl.java | 6 +-- .../SqlServerGenerateMarkdownServiceImpl.java | 4 +- .../impl/SqlServerGeneratePdfServiceImpl.java | 6 +-- 16 files changed, 101 insertions(+), 116 deletions(-) create mode 100644 src/main/java/com/trh/dictionary/bean/base/BaseTableInfo.java diff --git a/src/main/java/com/trh/dictionary/bean/TableInfo.java b/src/main/java/com/trh/dictionary/bean/TableInfo.java index b94a4b5..89af19d 100644 --- a/src/main/java/com/trh/dictionary/bean/TableInfo.java +++ b/src/main/java/com/trh/dictionary/bean/TableInfo.java @@ -1,6 +1,6 @@ package com.trh.dictionary.bean; -import java.util.List; +import com.trh.dictionary.bean.base.BaseTableInfo; /** * 表信息 @@ -8,11 +8,7 @@ import java.util.List; * @author * @create 2019-07-25 14:17 */ -public class TableInfo { - /** - * 表名 - */ - private String tableName = ""; +public class TableInfo extends BaseTableInfo { /** * 字符集 */ @@ -25,31 +21,6 @@ public class TableInfo { * 描述 */ private String description = ""; - /** - * 所有列名 - */ - private List columnList; - - private List indexInfoList; - - public List getIndexInfoList() { - return indexInfoList; - } - - public void setIndexInfoList(List indexInfoList) { - this.indexInfoList = indexInfoList; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - if (tableName == null) { - tableName = ""; - } - this.tableName = tableName; - } public String getOrderType() { return orderType; @@ -83,12 +54,4 @@ public class TableInfo { } this.description = description; } - - public List getColumnList() { - return columnList; - } - - public void setColumnList(List columnList) { - this.columnList = columnList; - } } diff --git a/src/main/java/com/trh/dictionary/bean/base/BaseTableInfo.java b/src/main/java/com/trh/dictionary/bean/base/BaseTableInfo.java new file mode 100644 index 0000000..8ccc889 --- /dev/null +++ b/src/main/java/com/trh/dictionary/bean/base/BaseTableInfo.java @@ -0,0 +1,49 @@ +package com.trh.dictionary.bean.base; + +import java.util.List; + +/** + * 基础的表信息 + * + * @author HouKunLin + * @date 2019/9/11 0011 16:48 + */ +public class BaseTableInfo { + /** + * 表名 + */ + private String tableName = ""; + /** + * 所有列名 + */ + private List columnList; + + private List indexInfoList; + + public List getIndexInfoList() { + return indexInfoList; + } + + public void setIndexInfoList(List indexInfoList) { + this.indexInfoList = indexInfoList; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + if (tableName == null) { + tableName = ""; + } + this.tableName = tableName; + } + + public List getColumnList() { + return columnList; + } + + public void setColumnList(List columnList) { + this.columnList = columnList; + } +} \ No newline at end of file diff --git a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java index 325e5e8..ec794ad 100644 --- a/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java +++ b/src/main/java/com/trh/dictionary/bean/sqlserver/SqlserverTabelInfo.java @@ -1,52 +1,15 @@ package com.trh.dictionary.bean.sqlserver; -import java.util.List; +import com.trh.dictionary.bean.base.BaseTableInfo; /** * @author zhou * @create 2019-08-29 16:12 * @description: */ -public class SqlserverTabelInfo { - - /** - * 表名 - */ - private String tableName = ""; - +public class SqlserverTabelInfo extends BaseTableInfo { private String value = ""; - /** - * 所有列名 - */ - private List columnList; - - private List indexInfoList; - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public List getColumnList() { - return columnList; - } - - public void setColumnList(List columnList) { - this.columnList = columnList; - } - - public List getIndexInfoList() { - return indexInfoList; - } - - public void setIndexInfoList(List indexInfoList) { - this.indexInfoList = indexInfoList; - } - public String getValue() { return value; } diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java index 7a0c3bc..2f26729 100644 --- a/src/main/java/com/trh/dictionary/service/DatabaseService.java +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -1,6 +1,6 @@ package com.trh.dictionary.service; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import java.sql.SQLException; import java.util.List; @@ -26,7 +26,7 @@ public interface DatabaseService { * @return 数据库表信息 * @throws SQLException */ - List getTables() throws SQLException; + List getTables() throws SQLException; /** * 获取数据库表列表 @@ -35,5 +35,5 @@ public interface DatabaseService { * @return 数据库表信息 * @throws SQLException */ - List getTables(String schema) throws SQLException; + List getTables(String schema) throws SQLException; } diff --git a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java index 7419a7c..59ac571 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java @@ -1,6 +1,6 @@ package com.trh.dictionary.service; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import java.util.List; @@ -17,7 +17,7 @@ public interface GenerateMarkdownService { * @param tableInfos * @return */ - String generateMarkdown(List tableInfos); + String generateMarkdown(List tableInfos); /** * 构建Markdown内容 diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java index b7db5c2..b2decc8 100644 --- a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -1,7 +1,7 @@ package com.trh.dictionary.service; import com.itextpdf.text.DocumentException; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import java.io.File; import java.io.IOException; @@ -19,7 +19,7 @@ public interface GeneratePdfService { * * @param tableInfos */ - void generatePdfFile(List tableInfos); + void generatePdfFile(List tableInfos); /** * 构建PDF文件 @@ -29,7 +29,7 @@ public interface GeneratePdfService { * @throws DocumentException * @throws IOException */ - void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException; + void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException; /** * 构建PDF文件 diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index cb95833..b495deb 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -1,7 +1,7 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; @@ -62,13 +62,13 @@ public class DatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { return getDatabaseService().getTables(); } @Override - public List getTables(String schema) throws SQLException { + public List getTables(String schema) throws SQLException { return getDatabaseService().getTables(schema); } diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java index 6437a4b..19547a8 100644 --- a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -4,6 +4,7 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.SqlExecutor; @@ -51,15 +52,15 @@ public class Db2DatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); String schema = dto.getDatabase().toUpperCase(); return getTables(schema); } @Override - public List getTables(String schema) throws SQLException { - List tables = new ArrayList(); + public List getTables(String schema) throws SQLException { + List tables = new ArrayList<>(); Connection connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); ResultSet rs = metaData.getTables(null, schema, "%", new String[]{"TABLE"}); diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java index 07e4c3e..3ddc2c5 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java @@ -4,6 +4,7 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateMarkdownService; @@ -58,11 +59,12 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { } @Override - public String generateMarkdown(List tableInfos) { + public String generateMarkdown(List tableInfos) { StringBuffer markdown = new StringBuffer(); String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; int i = 1; - for (TableInfo info : tableInfos) { + for (BaseTableInfo baseTableInfo : tableInfos) { + TableInfo info = (TableInfo) baseTableInfo; StringBuffer oneTble = new StringBuffer(); oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info .getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); diff --git a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java index 81c41c2..e87c4a5 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java @@ -7,6 +7,7 @@ import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.draw.DottedLineSeparator; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.DatabaseService; @@ -45,12 +46,12 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { private HttpSession session; @Override - public void generatePdfFile(List tableInfos) { + public void generatePdfFile(List tableInfos) { } @Override - public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { + public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { String fontDir = this.getClass().getResource("/") .getPath() .replaceAll("target/classes/", "") @@ -81,7 +82,8 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { //设置表格模板 String[] tableHeader = {"序列", "列名", "类型", "可空", "默认值", "注释"}; String[] indexHeader = {"序列", "索引名", "类型", "包含字段"}; - for (TableInfo tableInfo : tableInfos) { + for (BaseTableInfo baseTableInfo : tableInfos) { + TableInfo tableInfo = (TableInfo) baseTableInfo; tableInfo = PdfUtils.setIsIndex(tableInfo); Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); //设置跳转地址 @@ -146,8 +148,10 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { Chunk pointChunk = new Chunk(new DottedLineSeparator()); Chunk pageNoChunk = new Chunk(pageNo + ""); String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i - 1).getDescription())) { - tempDescription += "(" + tableInfos.get(i - 1).getDescription() + ")"; + TableInfo item = (TableInfo) tableInfos.get(i - 1); + + if (!StringUtil.isEmpty(item.getDescription())) { + tempDescription += "(" + item.getDescription() + ")"; } Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index c1a41c3..69a0db4 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -4,6 +4,7 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.*; import org.slf4j.Logger; @@ -59,16 +60,16 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return getTables(dto.getDatabase()); } @Override - public List getTables(String schema) throws SQLException { + public List getTables(String schema) throws SQLException { //循环处理表 - List resultList = new ArrayList(); + List resultList = new ArrayList<>(); Statement statement = null; ResultSet resultSet = null; diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java index da8d407..54e0225 100644 --- a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -4,6 +4,7 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; @@ -42,14 +43,14 @@ public class OracleDatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return getTables(dto.getDatabase()); } @Override - public List getTables(String schema) throws SQLException { - List list = new ArrayList(); + public List getTables(String schema) throws SQLException { + List list = new ArrayList<>(); PreparedStatement pstmt; Connection conn = null; try { diff --git a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java index 4e68825..2c5f4f9 100644 --- a/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/PostgreSqlDatabaseServiceImpl.java @@ -4,6 +4,7 @@ import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.TableBasicEnum; @@ -57,17 +58,17 @@ public class PostgreSqlDatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return getTables(dto.getDatabase()); } @Override - public List getTables(String schema) throws SQLException { + public List getTables(String schema) throws SQLException { String sql = "SELECT pg_tables.schemaname,pg_tables.tablename,cast(obj_description(relfilenode,'pg_class') as varchar) as comment FROM pg_tables LEFT JOIN pg_class on relname=tablename WHERE tablename NOT LIKE 'pg%' AND tablename NOT LIKE 'sql_%'"; ResultSet resultSet; - List tableInfos = new ArrayList(64); + List tableInfos = new ArrayList<>(64); try { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index 0b3abac..cd5da6f 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -1,7 +1,7 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; @@ -61,13 +61,13 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return getTables(dto.getDatabase()); } @Override - public List getTables(String schema) throws SQLException { + public List getTables(String schema) throws SQLException { return null; } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 446b991..5cd1351 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -1,6 +1,6 @@ package com.trh.dictionary.service.impl; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; @@ -102,7 +102,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer } @Override - public String generateMarkdown(List tableInfos) { + public String generateMarkdown(List tableInfos) { return ""; } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java index 23a2d97..a44a455 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -7,7 +7,7 @@ import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.draw.DottedLineSeparator; -import com.trh.dictionary.bean.TableInfo; +import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; @@ -44,12 +44,12 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { private DataSource dataSource; @Override - public void generatePdfFile(List tableInfos) { + public void generatePdfFile(List tableInfos) { } @Override - public void generatePdfFile(List tableInfos, File file) { + public void generatePdfFile(List tableInfos, File file) { } -- Gitee From c958cdb70eb8a79e70bb9b357e1ca81ff069c740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 17:11:14 +0800 Subject: [PATCH 39/46] =?UTF-8?q?=E6=94=B9=E5=8F=98SQL=20Server=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E6=95=B0=E6=8D=AE=E5=BA=93=E6=93=8D=E4=BD=9C=E7=9A=84?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/SqlServerDatabaseServiceImpl.java | 84 +++++++++++++- .../impl/SqlServerGeneratePdfServiceImpl.java | 24 ++-- .../sqlserver/GenerateDataBaseInfo.java | 106 ------------------ .../com/trh/dictionary/TestConnection.java | 7 +- 4 files changed, 100 insertions(+), 121 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index cd5da6f..adbd45c 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -2,6 +2,9 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.base.BaseTableInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; +import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; @@ -68,6 +71,85 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { @Override public List getTables(String schema) throws SQLException { - return null; + //得到生成数据 + Connection connection = dataSource.getConnection(); + + String sqlTableInfo = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sqlTableInfo); + List list = new ArrayList<>(); + while (resultSet.next()) { + SqlserverTabelInfo sqlserverTabelInfo = new SqlserverTabelInfo(); + sqlserverTabelInfo.setTableName(resultSet.getString("name")); + sqlserverTabelInfo.setValue(resultSet.getString("value")); + list.add(sqlserverTabelInfo); + } + resultSet.close(); + statement.close(); + return list; + } + + + /* + * @Author zhou + * @Description 生成数据库表列名 + * @Date 17:16 2019/8/29 + * @Param [connection, sql] + * @return java.util.List + **/ + public static List getColumnInfo(Connection connection, String sql) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + List list = new ArrayList(); + while (resultSet.next()) { + SqlserverColumnInfo sqlserverColumnInfo = new SqlserverColumnInfo(); + sqlserverColumnInfo.setTable_name(resultSet.getString("table_name")); + sqlserverColumnInfo.setColumn_num(resultSet.getString("column_num")); + sqlserverColumnInfo.setColumn_name(resultSet.getString("column_name")); + sqlserverColumnInfo.setIs_identity(resultSet.getString("is_identity")); + sqlserverColumnInfo.setP_k(resultSet.getString("p_k")); + sqlserverColumnInfo.setType(resultSet.getString("type")); + sqlserverColumnInfo.setOccupied_num(resultSet.getString("occupied_num")); + sqlserverColumnInfo.setLength(resultSet.getString("length")); + sqlserverColumnInfo.setScale(resultSet.getString("scale")); + sqlserverColumnInfo.setIs_null(resultSet.getString("is_null")); + sqlserverColumnInfo.setDefault_value(resultSet.getString("default_value")); + sqlserverColumnInfo.setDecs(resultSet.getString("decs")); + String class_desc = resultSet.getString("class_desc"); + if ("INDEX".equals(class_desc)) { + continue; + } else { + sqlserverColumnInfo.setClass_desc(resultSet.getString("class_desc")); + } + + list.add(sqlserverColumnInfo); + } + resultSet.close(); + statement.close(); + return list; + } + + /* + * @Author zhou + * @Description 生成数据库表索引 + * @Date 17:18 2019/8/29 + * @Param [connection, sql] + * @return java.util.List + **/ + public static List getIndexInfo(Connection connection, String sql) throws Exception { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + List list = new ArrayList(); + while (resultSet.next()) { + SqlserverIndexInfo sqlserverIndexInfo = new SqlserverIndexInfo(); + sqlserverIndexInfo.setIndex_name(resultSet.getString("index_name")); + sqlserverIndexInfo.setIndex_desc(resultSet.getString("index_desc")); + sqlserverIndexInfo.setIndex_keys(resultSet.getString("index_keys")); + list.add(sqlserverIndexInfo); + } + resultSet.close(); + statement.close(); + return list; } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java index a44a455..970b66d 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -14,7 +14,6 @@ import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.GeneratePdfService; -import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import com.trh.dictionary.util.PdfUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +42,9 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { @Autowired private DataSource dataSource; + @Autowired + private SqlServerDatabaseServiceImpl databaseService; + @Override public void generatePdfFile(List tableInfos) { @@ -62,11 +64,12 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - List list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); + List list_table = databaseService.getTables(); if (list_table.size() == 0) { return; } - for (SqlserverTabelInfo Ta : list_table) { + for (BaseTableInfo baseTableInfo : list_table) { + SqlserverTabelInfo Ta = (SqlserverTabelInfo) baseTableInfo; logger.info(Ta.getTableName()); List list_column = new ArrayList(); List list_index = new ArrayList(); @@ -76,7 +79,7 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + list_column = SqlServerDatabaseServiceImpl.getColumnInfo(connection, sqlcolumn); for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } @@ -89,7 +92,7 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { - list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + list_index = SqlServerDatabaseServiceImpl.getIndexInfo(connection, sqlindex); for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } @@ -107,7 +110,7 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { } } - public static void build(List tableInfos, File file) throws Exception { + public static void build(List tableInfos, File file) throws Exception { String fontDir = SqlServerGeneratePdfServiceImpl.class.getResource("/").getPath().replaceAll("target/classes/", ""); fontDir += "src/main/resources/"; BaseFont bfChinese = BaseFont.createFont(fontDir + "font" + File.separator + "verdana.ttf", BaseFont.MACROMAN, BaseFont.NOT_EMBEDDED); @@ -135,8 +138,8 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { //设置表格模板 String[] tableHeader = {"序列", "列名", "主键", "类型", "可空", "默认值", "注释"}; String[] indexHeader = {"序列", "索引名", "描述", "包含字段"}; - for (SqlserverTabelInfo tableInfo : tableInfos) { - + for (BaseTableInfo baseTableInfo : tableInfos) { + SqlserverTabelInfo tableInfo = (SqlserverTabelInfo) baseTableInfo; Chapter chapter = new Chapter(new Paragraph(tableInfo.getTableName()), order); //设置跳转地址 Phrase point = new Paragraph("基本信息:", cnFont); @@ -202,8 +205,9 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { Chunk pageNoChunk = new Chunk(pageNo + ""); String tempDescription = key; - if (!StringUtil.isEmpty(tableInfos.get(i - 1).getValue())) { - tempDescription += "(" + tableInfos.get(i - 1).getValue() + ")"; + SqlserverTabelInfo item = (SqlserverTabelInfo) tableInfos.get(i - 1); + if (!StringUtil.isEmpty(item.getValue())) { + tempDescription += "(" + item.getValue() + ")"; } Paragraph jumpParagraph = new Paragraph(tempDescription, PdfUtils.getChineseFontAsStyle(BaseColor.BLACK, 12)); jumpParagraph.add(pointChunk); diff --git a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java b/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java deleted file mode 100644 index 7effded..0000000 --- a/src/main/java/com/trh/dictionary/service/sqlserver/GenerateDataBaseInfo.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.trh.dictionary.service.sqlserver; - -import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; -import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; -import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -/** - * @author zhou - * @create 2019-08-29 16:44 - * @description: - */ -public class GenerateDataBaseInfo { - - /* - * @Author zhou - * @Description 生成数据库表名 - * @Date 16:46 2019/8/29 - * @Param [connection, sqlTableInfo] - * @return java.util.List - **/ - public static List getTableInfo(Connection connection, String sqlTableInfo) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sqlTableInfo); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverTabelInfo sqlserverTabelInfo = new SqlserverTabelInfo(); - sqlserverTabelInfo.setTableName(resultSet.getString("name")); - sqlserverTabelInfo.setValue(resultSet.getString("value")); - list.add(sqlserverTabelInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - - /* - * @Author zhou - * @Description 生成数据库表列名 - * @Date 17:16 2019/8/29 - * @Param [connection, sql] - * @return java.util.List - **/ - public static List getColumnInfo(Connection connection, String sql) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sql); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverColumnInfo sqlserverColumnInfo = new SqlserverColumnInfo(); - sqlserverColumnInfo.setTable_name(resultSet.getString("table_name")); - sqlserverColumnInfo.setColumn_num(resultSet.getString("column_num")); - sqlserverColumnInfo.setColumn_name(resultSet.getString("column_name")); - sqlserverColumnInfo.setIs_identity(resultSet.getString("is_identity")); - sqlserverColumnInfo.setP_k(resultSet.getString("p_k")); - sqlserverColumnInfo.setType(resultSet.getString("type")); - sqlserverColumnInfo.setOccupied_num(resultSet.getString("occupied_num")); - sqlserverColumnInfo.setLength(resultSet.getString("length")); - sqlserverColumnInfo.setScale(resultSet.getString("scale")); - sqlserverColumnInfo.setIs_null(resultSet.getString("is_null")); - sqlserverColumnInfo.setDefault_value(resultSet.getString("default_value")); - sqlserverColumnInfo.setDecs(resultSet.getString("decs")); - String class_desc = resultSet.getString("class_desc"); - if ("INDEX".equals(class_desc)) { - continue; - } else { - sqlserverColumnInfo.setClass_desc(resultSet.getString("class_desc")); - } - - list.add(sqlserverColumnInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - /* - * @Author zhou - * @Description 生成数据库表索引 - * @Date 17:18 2019/8/29 - * @Param [connection, sql] - * @return java.util.List - **/ - public static List getIndexInfo(Connection connection, String sql) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sql); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverIndexInfo sqlserverIndexInfo = new SqlserverIndexInfo(); - sqlserverIndexInfo.setIndex_name(resultSet.getString("index_name")); - sqlserverIndexInfo.setIndex_desc(resultSet.getString("index_desc")); - sqlserverIndexInfo.setIndex_keys(resultSet.getString("index_keys")); - list.add(sqlserverIndexInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - -} \ No newline at end of file diff --git a/src/test/java/com/trh/dictionary/TestConnection.java b/src/test/java/com/trh/dictionary/TestConnection.java index c652dcf..e69e842 100644 --- a/src/test/java/com/trh/dictionary/TestConnection.java +++ b/src/test/java/com/trh/dictionary/TestConnection.java @@ -3,7 +3,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; -import com.trh.dictionary.service.sqlserver.GenerateDataBaseInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,7 +28,7 @@ public class TestConnection { String sqltabel = "SELECT Name as name FROM SysObjects Where XType='U' ORDER BY Name;"; List list_table = null; try { - list_table = GenerateDataBaseInfo.getTableInfo(connection, sqltabel); + list_table = null;// GenerateDataBaseInfo.getTableInfo(connection, sqltabel); } catch (Exception e) { e.printStackTrace(); } @@ -41,7 +40,7 @@ public class TestConnection { "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; try { - List list_column = GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); + List list_column = null;// GenerateDataBaseInfo.getColumnInfo(connection, sqlcolumn); for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } @@ -55,7 +54,7 @@ public class TestConnection { "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; try { - List list_index = GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); + List list_index = null;// GenerateDataBaseInfo.getIndexInfo(connection, sqlindex); for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } -- Gitee From 6813991abdcdfe14ced22b9174e51cb22fdb6bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 17:29:23 +0800 Subject: [PATCH 40/46] =?UTF-8?q?=E6=9B=B4=E6=94=B9SQL=20Server=E7=94=9F?= =?UTF-8?q?=E6=88=90PDF=E7=9A=84=E4=B8=80=E4=BA=9B=E8=B7=9F=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E7=9B=B8=E5=85=B3=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/GeneratePdfService.java | 11 +-- .../service/impl/GeneratePdfServiceImpl.java | 16 +-- .../impl/SqlServerGeneratePdfServiceImpl.java | 99 ++++++++----------- 3 files changed, 53 insertions(+), 73 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java index b2decc8..f27a515 100644 --- a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -14,13 +14,6 @@ import java.util.List; * @date 2019/9/11 0011 9:49 */ public interface GeneratePdfService { - /** - * 构建PDF文件 - * - * @param tableInfos - */ - void generatePdfFile(List tableInfos); - /** * 构建PDF文件 * @@ -29,12 +22,12 @@ public interface GeneratePdfService { * @throws DocumentException * @throws IOException */ - void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException; + void generatePdfFile(List tableInfos, File file) throws Exception; /** * 构建PDF文件 * * @param file */ - void generatePdfFile(File file); + void generatePdfFile(File file) throws Exception; } diff --git a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java index e87c4a5..a8f72d8 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java @@ -6,12 +6,15 @@ import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.draw.DottedLineSeparator; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.base.BaseTableInfo; +import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GeneratePdfService; +import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.PdfUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,11 +48,6 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { @Autowired private HttpSession session; - @Override - public void generatePdfFile(List tableInfos) { - - } - @Override public void generatePdfFile(List tableInfos, File file) throws DocumentException, IOException { String fontDir = this.getClass().getResource("/") @@ -178,8 +176,14 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { @Override public void generatePdfFile(File file) { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); try { - generatePdfFile(databaseService.getTables(), file); + List tables = databaseService.getTables(); + if (dto.getType().equals(DatabaseType.SQLSERVER)) { + sqlServerGenerateService.generatePdfFile(tables, file); + } else { + generatePdfFile(tables, file); + } } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java index 970b66d..cb6912c 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -46,68 +46,51 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { private SqlServerDatabaseServiceImpl databaseService; @Override - public void generatePdfFile(List tableInfos) { - - } - - @Override - public void generatePdfFile(List tableInfos, File file) { - - } - - @Override - public void generatePdfFile(File file) { - try { - - //得到生成数据 - Connection connection = dataSource.getConnection(); - - String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; - - List list_table = databaseService.getTables(); - if (list_table.size() == 0) { - return; - } - for (BaseTableInfo baseTableInfo : list_table) { - SqlserverTabelInfo Ta = (SqlserverTabelInfo) baseTableInfo; - logger.info(Ta.getTableName()); - List list_column = new ArrayList(); - List list_index = new ArrayList(); - String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + - "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + - "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + - "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + - "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; - try { - list_column = SqlServerDatabaseServiceImpl.getColumnInfo(connection, sqlcolumn); - for (SqlserverColumnInfo s : list_column) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); + public void generatePdfFile(List tableInfos, File file) throws Exception { + Connection connection = dataSource.getConnection(); + for (BaseTableInfo baseTableInfo : tableInfos) { + SqlserverTabelInfo Ta = (SqlserverTabelInfo) baseTableInfo; + logger.info(Ta.getTableName()); + List list_column = new ArrayList(); + List list_index = new ArrayList(); + String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + + "SELECT name FROM sysindexes WHERE (id=a.id) AND (indid IN (\n" + + "SELECT indid FROM sysindexkeys WHERE (id=a.id) AND (colid IN (\n" + + "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta.getTableName() + "'"; + try { + list_column = SqlServerDatabaseServiceImpl.getColumnInfo(connection, sqlcolumn); + for (SqlserverColumnInfo s : list_column) { + logger.info(s.toString()); } - String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + - "SELECT i.name AS index_name,(\n" + - "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + - "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + - "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; - try { - list_index = SqlServerDatabaseServiceImpl.getIndexInfo(connection, sqlindex); - for (SqlserverIndexInfo s : list_index) { - logger.info(s.toString()); - } - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + String sqlindex = "SELECT index_name,index_desc,(LEFT (ind_col,LEN(ind_col)-1)+CASE WHEN include_col IS NOT NULL THEN ' INCLUDE ('+LEFT (include_col,LEN(include_col)-1)+')' ELSE '' END) AS index_keys FROM (\n" + + "SELECT i.name AS index_name,(\n" + + "SELECT CONVERT (VARCHAR (MAX),CASE WHEN i.index_id =1 THEN 'clustered' ELSE 'nonclustered' END+CASE WHEN i.ignore_dup_key <> 0 THEN ', ignore duplicate keys' ELSE '' END+CASE WHEN i.is_unique <> 0 THEN ', unique' ELSE '' END+CASE WHEN i.is_hypothetical <> 0 THEN ', hypothetical' ELSE '' END+CASE WHEN i.is_primary_key <> 0 THEN ', primary key' ELSE '' END+CASE WHEN i.is_unique_constraint <> 0 THEN ', unique key' ELSE '' END+CASE WHEN s.auto_created <> 0 THEN ', auto create' ELSE '' END+CASE WHEN s.no_recompute <> 0 THEN ', stats no recompute' ELSE '' END+' located on '+ISNULL(name,'')+CASE WHEN i.has_filter =1 THEN ', filter={'+i.filter_definition +'}' ELSE '' END) FROM sys.data_spaces WHERE data_space_id=i.data_space_id) AS 'index_desc',(\n" + + "SELECT INDEX_COL(OBJECT_NAME(i.object_id),i.index_id,key_ordinal),CASE WHEN is_descending_key=1 THEN N'(-)' ELSE N'' END+',' FROM sys.index_columns WHERE object_id=i.object_id AND index_id=i.index_id AND key_ordinal<> 0 ORDER BY key_ordinal FOR XML PATH ('')) AS ind_col,(\n" + + "SELECT col.name +',' FROM sys.index_columns inxc JOIN sys.columns col ON col.object_id=inxc.object_id AND col.column_id =inxc.column_id WHERE inxc.object_id=i.object_id AND inxc.index_id =i.index_id AND inxc.is_included_column =1 FOR XML PATH ('')) AS include_col FROM sys.indexes i JOIN sys.stats s ON i.object_id=s.object_id AND i.index_id =s.stats_id WHERE i.object_id=object_id('" + Ta.getTableName() + "')) Ind ORDER BY index_name"; + try { + list_index = SqlServerDatabaseServiceImpl.getIndexInfo(connection, sqlindex); + for (SqlserverIndexInfo s : list_index) { + logger.info(s.toString()); } - Ta.setColumnList(list_column); - Ta.setIndexInfoList(list_index); + } catch (Exception e) { + e.printStackTrace(); } - //带目录 - build(list_table, file); - } catch (Exception e) { - e.printStackTrace(); - logger.info("生成PDF失败"); + Ta.setColumnList(list_column); + Ta.setIndexInfoList(list_index); } + //带目录 + build(tableInfos, file); + } + + @Override + public void generatePdfFile(File file) throws Exception { + //得到生成数据 + List tables = databaseService.getTables(); + generatePdfFile(tables, file); } public static void build(List tableInfos, File file) throws Exception { -- Gitee From 9f3bbaecdbe0b443f09a6d6c8a8393188c99e0eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 17:39:16 +0800 Subject: [PATCH 41/46] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=BC=E5=87=BAPDF?= =?UTF-8?q?=E6=97=B6=E5=8F=AF=E4=BB=A5=E4=BC=A0=E5=85=A5database=E5=8F=82?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 给后期操作预留功能接口 --- .../conterller/DatabaseController.java | 7 +------ .../service/GenerateMarkdownService.java | 6 +++--- .../dictionary/service/GeneratePdfService.java | 12 ++++++++++-- .../service/impl/GeneratePdfServiceImpl.java | 9 +++++++-- .../impl/SqlServerGeneratePdfServiceImpl.java | 16 ++++++++++++++-- 5 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java index c715495..2ef5b6f 100644 --- a/src/main/java/com/trh/dictionary/conterller/DatabaseController.java +++ b/src/main/java/com/trh/dictionary/conterller/DatabaseController.java @@ -1,7 +1,6 @@ package com.trh.dictionary.conterller; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DataSourceService; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateMarkdownService; @@ -105,11 +104,7 @@ public class DatabaseController { filePath += "src/main/resources/"; File outfile = new File(filePath, "DataBase.pdf"); try { - if (dto.getType() == DatabaseType.SQLSERVER) { -// BuildSqlserverPDF.MakePdf(dto.getHost(), database, dto.getPort(), dto.getUsername(), dto.getPassword(), filePath, "DataBase"); - } else { - pdfService.generatePdfFile(outfile); - } + pdfService.generatePdfFile(database, outfile); } catch (Exception e) { logger.error("error==>" + e); } diff --git a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java index 59ac571..db02c0b 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java @@ -12,7 +12,7 @@ import java.util.List; */ public interface GenerateMarkdownService { /** - * 构建Markdown内容 + * 使用一个已知的表列表构建Markdown内容 * * @param tableInfos * @return @@ -20,7 +20,7 @@ public interface GenerateMarkdownService { String generateMarkdown(List tableInfos); /** - * 构建Markdown内容 + * 指定一个数据库的表列表构建Markdown内容 * * @param schema * @return @@ -28,7 +28,7 @@ public interface GenerateMarkdownService { String generateMarkdown(String schema); /** - * 构建Markdown内容 + * 使用默认当前数据库的表列表构建Markdown内容 * * @return */ diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java index f27a515..6d4c790 100644 --- a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -15,7 +15,7 @@ import java.util.List; */ public interface GeneratePdfService { /** - * 构建PDF文件 + * 指定数据库表列表构建PDF文件 * * @param tableInfos * @param file @@ -25,7 +25,15 @@ public interface GeneratePdfService { void generatePdfFile(List tableInfos, File file) throws Exception; /** - * 构建PDF文件 + * 指定一个数据库的表列表构建PDF文件 + * + * @param schema + * @param file + */ + void generatePdfFile(String schema, File file) throws Exception; + + /** + * 构建PDF文件,使用默认当前数据库的表列表 * * @param file */ diff --git a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java index a8f72d8..64b8e33 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GeneratePdfServiceImpl.java @@ -175,10 +175,10 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { } @Override - public void generatePdfFile(File file) { + public void generatePdfFile(String schema, File file) throws Exception { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); try { - List tables = databaseService.getTables(); + List tables = databaseService.getTables(schema); if (dto.getType().equals(DatabaseType.SQLSERVER)) { sqlServerGenerateService.generatePdfFile(tables, file); } else { @@ -189,4 +189,9 @@ public class GeneratePdfServiceImpl implements GeneratePdfService { } } + @Override + public void generatePdfFile(File file) throws Exception { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + generatePdfFile(dto.getDatabase(), file); + } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java index cb6912c..df46066 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGeneratePdfServiceImpl.java @@ -7,6 +7,7 @@ import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.draw.DottedLineSeparator; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; @@ -14,12 +15,14 @@ import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.event.ContentEvent; import com.trh.dictionary.event.IndexEvent; import com.trh.dictionary.service.GeneratePdfService; +import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.PdfUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.io.ByteArrayOutputStream; import java.io.File; @@ -45,6 +48,9 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { @Autowired private SqlServerDatabaseServiceImpl databaseService; + @Autowired + private HttpSession session; + @Override public void generatePdfFile(List tableInfos, File file) throws Exception { Connection connection = dataSource.getConnection(); @@ -87,12 +93,18 @@ public class SqlServerGeneratePdfServiceImpl implements GeneratePdfService { } @Override - public void generatePdfFile(File file) throws Exception { + public void generatePdfFile(String schema, File file) throws Exception { //得到生成数据 - List tables = databaseService.getTables(); + List tables = databaseService.getTables(schema); generatePdfFile(tables, file); } + @Override + public void generatePdfFile(File file) throws Exception { + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + generatePdfFile(dto.getDatabase(), file); + } + public static void build(List tableInfos, File file) throws Exception { String fontDir = SqlServerGeneratePdfServiceImpl.class.getResource("/").getPath().replaceAll("target/classes/", ""); fontDir += "src/main/resources/"; -- Gitee From cd2083ae9d59f7c099e7afe10f9dd027be92d80d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 19:36:25 +0800 Subject: [PATCH 42/46] =?UTF-8?q?=E9=87=8D=E6=9E=84SQL=20Server=20?= =?UTF-8?q?=E6=9E=84=E5=BB=BAMarkdown=E5=86=85=E5=AE=B9=E7=9A=84=E6=97=B6?= =?UTF-8?q?=E5=80=99=E8=8E=B7=E5=8F=96=E6=95=B0=E6=8D=AE=E5=BA=93=E5=86=85?= =?UTF-8?q?=E5=AE=B9=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SqlServerGenerateMarkdownServiceImpl.java | 143 +++++------------- 1 file changed, 39 insertions(+), 104 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 5cd1351..0070972 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -1,20 +1,21 @@ package com.trh.dictionary.service.impl; +import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.GenerateMarkdownService; +import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.List; @@ -28,12 +29,17 @@ import java.util.List; public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownService { private static Logger logger = LoggerFactory.getLogger(SqlServerGenerateMarkdownServiceImpl.class); + @Autowired + private SqlServerDatabaseServiceImpl sqlServerDatabaseService; @Autowired private DataSource dataSource; + @Autowired + private HttpSession session; @Override public String generateMarkdown() { - return generateMarkdown((String) null); + ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); + return generateMarkdown(dto.getDatabase()); } @Override @@ -43,15 +49,34 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer //得到生成数据 connection = dataSource.getConnection(); - String sqltabel = "SELECT DISTINCT d.name,f.value FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=G.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY d.name;"; + List tables = sqlServerDatabaseService.getTables(schema); + return generateMarkdown(tables); + } catch (Exception e) { + e.printStackTrace(); + logger.info("生成Markdown失败"); + } finally { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + return "### 暂无数据"; + } - List list_table = getTableInfo(connection, sqltabel); - if (list_table.size() == 0) { + @Override + public String generateMarkdown(List tableInfos) { + Connection connection = null; + try { + //得到生成数据 + connection = dataSource.getConnection(); + if (tableInfos.size() == 0) { return "## 数据库无数据"; } - for (SqlserverTabelInfo Ta : list_table) { + for (BaseTableInfo baseTableInfo : tableInfos) { + SqlserverTabelInfo Ta = (SqlserverTabelInfo) baseTableInfo; logger.info(Ta.getTableName()); - List list_column = new ArrayList(); + List list_column = new ArrayList<>(); List list_index = new ArrayList(); String sqlcolumn = "SELECT (CASE WHEN a.colorder=1 THEN d.name ELSE NULL END) table_name,a.colorder column_num,a.name column_name,(CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'YES' ELSE '' END) is_identity,(CASE WHEN (\n" + "SELECT COUNT (*) FROM sysobjects WHERE (name IN (\n" + @@ -60,7 +85,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer "SELECT colid FROM syscolumns WHERE (id=a.id) AND (name=a.name))))))) AND (xtype='PK'))> 0 THEN 'YES' ELSE '' END) p_k,b.name type,a.length occupied_num,COLUMNPROPERTY(a.id,a.name,'PRECISION') AS length,isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS scale,(CASE WHEN a.isnullable=1 THEN 'YES' ELSE '' END) is_null,isnull(e.text,'') default_value,isnull(g.[value],' ') AS decs,isnull(g.[class_desc],' ') AS class_desc FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.class AND f.minor_id=0 WHERE d.name ='" + Ta .getTableName() + "'"; try { - list_column = getColumnInfo(connection, sqlcolumn); + list_column = SqlServerDatabaseServiceImpl.getColumnInfo(connection, sqlcolumn); for (SqlserverColumnInfo s : list_column) { logger.info(s.toString()); } @@ -75,7 +100,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer .getTableName() + "')) Ind ORDER BY index_name"; try { logger.info(sqlindex); - list_index = getIndexInfo(connection, sqlindex); + list_index = SqlServerDatabaseServiceImpl.getIndexInfo(connection, sqlindex); for (SqlserverIndexInfo s : list_index) { logger.info(s.toString()); } @@ -86,8 +111,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer Ta.setIndexInfoList(list_index); } - return writeMarkdownString(list_table); - + return writeMarkdownString(tableInfos); } catch (Exception e) { e.printStackTrace(); logger.info("生成Markdown失败"); @@ -101,101 +125,12 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer return "### 暂无数据"; } - @Override - public String generateMarkdown(List tableInfos) { - return ""; - } - - /* - * @Author zhou - * @Description 生成数据库表名 - * @Date 16:46 2019/8/29 - * @Param [connection, sqlTableInfo] - * @return java.util.List - **/ - public static List getTableInfo(Connection connection, String sqlTableInfo) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sqlTableInfo); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverTabelInfo sqlserverTabelInfo = new SqlserverTabelInfo(); - sqlserverTabelInfo.setTableName(resultSet.getString("name")); - sqlserverTabelInfo.setValue(resultSet.getString("value")); - list.add(sqlserverTabelInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - - /* - * @Author zhou - * @Description 生成数据库表列名 - * @Date 17:16 2019/8/29 - * @Param [connection, sql] - * @return java.util.List - **/ - public static List getColumnInfo(Connection connection, String sql) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sql); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverColumnInfo sqlserverColumnInfo = new SqlserverColumnInfo(); - sqlserverColumnInfo.setTable_name(resultSet.getString("table_name")); - sqlserverColumnInfo.setColumn_num(resultSet.getString("column_num")); - sqlserverColumnInfo.setColumn_name(resultSet.getString("column_name")); - sqlserverColumnInfo.setIs_identity(resultSet.getString("is_identity")); - sqlserverColumnInfo.setP_k(resultSet.getString("p_k")); - sqlserverColumnInfo.setType(resultSet.getString("type")); - sqlserverColumnInfo.setOccupied_num(resultSet.getString("occupied_num")); - sqlserverColumnInfo.setLength(resultSet.getString("length")); - sqlserverColumnInfo.setScale(resultSet.getString("scale")); - sqlserverColumnInfo.setIs_null(resultSet.getString("is_null")); - sqlserverColumnInfo.setDefault_value(resultSet.getString("default_value")); - sqlserverColumnInfo.setDecs(resultSet.getString("decs")); - String class_desc = resultSet.getString("class_desc"); - if ("INDEX".equals(class_desc)) { - continue; - } else { - sqlserverColumnInfo.setClass_desc(resultSet.getString("class_desc")); - } - - list.add(sqlserverColumnInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - /* - * @Author zhou - * @Description 生成数据库表索引 - * @Date 17:18 2019/8/29 - * @Param [connection, sql] - * @return java.util.List - **/ - public static List getIndexInfo(Connection connection, String sql) throws Exception { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(sql); - List list = new ArrayList(); - while (resultSet.next()) { - SqlserverIndexInfo sqlserverIndexInfo = new SqlserverIndexInfo(); - sqlserverIndexInfo.setIndex_name(resultSet.getString("index_name")); - sqlserverIndexInfo.setIndex_desc(resultSet.getString("index_desc")); - sqlserverIndexInfo.setIndex_keys(resultSet.getString("index_keys")); - list.add(sqlserverIndexInfo); - } - resultSet.close(); - statement.close(); - return list; - } - - public static String writeMarkdownString(List list) { + public static String writeMarkdownString(List list) { StringBuffer markdown = new StringBuffer(); String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; int i = 1; - for (SqlserverTabelInfo info : list) { + for (BaseTableInfo baseTableInfo : list) { + SqlserverTabelInfo info = (SqlserverTabelInfo) baseTableInfo; StringBuffer oneTble = new StringBuffer(); oneTble.append("##" + i + "." + info.getTableName() + " " + info.getValue() + "\n" + "基本信息:" + info.getValue() + " " + "\n\n" + "|序列|列名|主键|类型|可空|默认值|注释|" + "\n"); -- Gitee From 98d211c8cdb1e6f835ad46cdec42c293cc12f3a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 22:47:37 +0800 Subject: [PATCH 43/46] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E7=9A=84Markdown=E5=86=85=E5=AE=B9=E7=94=9F=E6=88=90=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 感觉代码有点多余,增加了复杂度和维护难度,就只是为了提供一个更方便的自定义渲染方法,而增加这么多复杂的内容,也不知道是否值得 --- .../impl/GenerateMarkdownServiceImpl.java | 84 ++---- .../trh/dictionary/util/MarkdownUtils.java | 244 ++++++++++++++++++ 2 files changed, 272 insertions(+), 56 deletions(-) create mode 100644 src/main/java/com/trh/dictionary/util/MarkdownUtils.java diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java index 3ddc2c5..2501edb 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java @@ -1,23 +1,24 @@ package com.trh.dictionary.service.impl; -import com.trh.dictionary.bean.ColumnInfo; import com.trh.dictionary.bean.ConnectionDTO; -import com.trh.dictionary.bean.IndexInfo; -import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.enums.DatabaseType; import com.trh.dictionary.service.DatabaseService; import com.trh.dictionary.service.GenerateMarkdownService; import com.trh.dictionary.util.Keys; +import com.trh.dictionary.util.MarkdownUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; +import javax.annotation.PostConstruct; import javax.servlet.http.HttpSession; import java.sql.SQLException; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * 构建Markdown内容 @@ -36,6 +37,9 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { private DatabaseService databaseService; @Autowired private HttpSession session; + private Map header = new LinkedHashMap<>(); + private Map table = new LinkedHashMap<>(); + private Map indexs = new LinkedHashMap<>(); @Override public String generateMarkdown() { @@ -51,7 +55,8 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { return sqlServerGenerateMarkdownService.generateMarkdown(schema); } try { - return generateMarkdown(databaseService.getTables(schema)); + List tables = databaseService.getTables(schema); + return generateMarkdown(tables); } catch (SQLException e) { e.printStackTrace(); } @@ -59,59 +64,26 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { } @Override - public String generateMarkdown(List tableInfos) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (BaseTableInfo baseTableInfo : tableInfos) { - TableInfo info = (TableInfo) baseTableInfo; - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + " " + info.getDescription() + "\n" + "基本信息:" + info.getDescription() + " " + info - .getStorageEngine() + " " + info.getOrderType() + "\n\n" + "|序列|列名|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - if (columnInfos.size() > 0) { + public String generateMarkdown(List tables) { + return MarkdownUtils.toMarkdown(tables, table, indexs, header); + } - } - for (int k = 0; k < columnInfos.size(); k++) { - ColumnInfo Column = columnInfos.get(k); - oneTble.append("|").append(Column.getOrder()).append("|"). - append(Column.getName()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIsNull()).append("|"). - append(Column.getDefaultValue()).append("|"); - if ((k + 1) == columnInfos.size()) { - oneTble.append(Column.getDescription()).append("||"). - append("\n"); - } else { - oneTble.append(Column.getDescription()).append("|"). - append("\n"); + @PostConstruct + public void post() { + header.put("tableName", "tableName"); + header.put("marker", "description"); + header.put("info", "description,storageEngine,orderType"); - } - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|类型|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (IndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getName()).append("|"). - append(indexInfo.getType()).append("|"). - append(indexInfo.getContainKey()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - //createDir(filePath + "\\" + info.getTableName() + ".txt", oneTble.toString()); - } - //目录 - markdown.insert(0, "[TOC]\n"); - return markdown.toString(); - } + table.put("_index", "序列"); + table.put("name", "列名"); + table.put("type", "类型"); + table.put("isNull", "可空"); + table.put("defaultValue", "默认值"); + table.put("description", "注释"); + indexs.put("_index", "序列"); + indexs.put("name", "索引名"); + indexs.put("type", "类型"); + indexs.put("containKey", "包含字段"); + } } diff --git a/src/main/java/com/trh/dictionary/util/MarkdownUtils.java b/src/main/java/com/trh/dictionary/util/MarkdownUtils.java new file mode 100644 index 0000000..17d4bf7 --- /dev/null +++ b/src/main/java/com/trh/dictionary/util/MarkdownUtils.java @@ -0,0 +1,244 @@ +package com.trh.dictionary.util; + +import com.trh.dictionary.bean.base.BaseTableInfo; +import freemarker.cache.MultiTemplateLoader; +import freemarker.cache.StringTemplateLoader; +import freemarker.cache.TemplateLoader; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; +import org.springframework.util.DigestUtils; +import org.springframework.util.ReflectionUtils; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Markdown工具类 + * + * @author houkunlin + * @date 2019/9/11 下午8:17 + */ +@Component +public class MarkdownUtils { + private static Map, Map> classFieldMap = new ConcurrentHashMap(); + + private static Configuration configuration; + + @Autowired + public void setConfiguration(Configuration configuration) { + System.out.println(configuration); + MarkdownUtils.configuration = configuration; + } + + /** + * 渲染成Markdown内容 + * + * @param list 表格列表 + * @param table 表格渲染参数 + * @param indexs 索引渲染参数 + * @param header 表格顶部信息渲染参数 + * @return + */ + public static String toMarkdown(List list, Map table, Map indexs, Map header) { + List lineString = new ArrayList<>(); + lineString.add("[TOC]\n"); + int index = 0; + for (BaseTableInfo baseTableInfo : list) { + // object is table info + ++index; + lineString.add(getHeaderString(header, index, baseTableInfo)); + lineString.add("\n"); + + List columnInfos = baseTableInfo.getColumnList(); + try { + lineString.addAll(getTableStrings(table, columnInfos)); + } catch (Exception e) { + e.printStackTrace(); + } + lineString.add("\n"); + + List indexInfoList = baseTableInfo.getIndexInfoList(); + try { + lineString.addAll(getTableStrings(indexs, indexInfoList)); + } catch (Exception e) { + e.printStackTrace(); + } + lineString.add("\n"); + } + return String.join("\n", lineString); + } + + /** + * 渲染每个表格的所有信息 + * + * @param table 渲染参数 + * @param columns 表格字段列表 + * @return + * @throws IOException + * @throws TemplateException + */ + private static List getTableStrings(Map table, List columns) throws IOException, TemplateException { + List lineString = new ArrayList<>(); + lineString.addAll(getTableHeader(table)); + + if (columns.isEmpty()) { + return lineString; + } + + String columnTpl = getTableRowTpl(table); + String columnTplKey = DigestUtils.md5DigestAsHex(columnTpl.getBytes()); + Template template = getTemplate(columnTplKey, columnTpl); + + for (int i = 0; i < columns.size(); i++) { + Map columnValue = new HashMap<>(); + for (Map.Entry entry : table.entrySet()) { + String key = entry.getKey(); + columnValue.put(key, getValue(columns.get(i), key)); + } + columnValue.put("_index", i + 1); + String templateIntoString = FreeMarkerTemplateUtils.processTemplateIntoString(template, columnValue); + if (i + 1 == columns.size()) { + lineString.add(templateIntoString + "|"); + } else { + lineString.add(templateIntoString); + } + } + + return lineString; + } + + /** + * 获得表格表头的Markdown内容 + * + * @param table 渲染参数 + * @return + */ + private static List getTableHeader(Map table) { + List lineHeader = new ArrayList<>(); + List lineHr = new ArrayList<>(); + lineHeader.add(""); + lineHr.add(""); + for (Map.Entry entry : table.entrySet()) { + lineHeader.add(entry.getValue()); + lineHr.add(":------:"); + } + lineHeader.add(""); + lineHr.add(""); + return Arrays.asList(String.join("|", lineHeader), String.join("|", lineHr)); + } + + /** + * 获取表格每一行内容的渲染模板内容 + * + * @param table 渲染参数 + * @return + */ + private static String getTableRowTpl(Map table) { + List strings = new ArrayList<>(); + strings.add(""); + for (Map.Entry entry : table.entrySet()) { + strings.add(String.format("${%s}", entry.getKey())); + } + strings.add(""); + return String.join("|", strings); + } + + /** + * 渲染每个表格顶部的标题介绍信息 + * + * @param header 表格顶部的内容 + * @param index 当前索引 + * @param object 表格信息 + * @return 渲染结果 + */ + private static String getHeaderString(Map header, int index, Object object) { + Map headerValue = new HashMap<>(); + headerValue.put("index", index); + for (Map.Entry entry : header.entrySet()) { + String value = entry.getValue(); + String[] split = value.split(","); + List strings = new ArrayList<>(); + for (String s : split) { + strings.add(String.valueOf(getValue(object, s))); + } + headerValue.put(entry.getKey(), String.join(" ", strings)); + } + try { + String key = "Markdown_Header_Value_Key"; + String tpl = "## ${index}. ${tableName} ${marker} \n基本信息: ${info}"; + Template template = getTemplate(key, tpl); + return FreeMarkerTemplateUtils.processTemplateIntoString(template, headerValue); + } catch (Exception e) { + e.printStackTrace(); + return String.format("<渲染头部失败:%s>", e.getMessage()); + } + } + + /** + * 获取渲染模板 + * + * @return 模板 + * @throws IOException 异常 + */ + private synchronized static Template getTemplate(String key, String tpl) throws IOException { + Template template = getTemplate(key); + if (template == null) { + configuration.setTemplateUpdateDelayMilliseconds(0); + MultiTemplateLoader templateLoaders = (MultiTemplateLoader) configuration.getTemplateLoader(); + int len = templateLoaders.getTemplateLoaderCount(); + for (int i = 0; i < len; i++) { + TemplateLoader templateLoader1 = templateLoaders.getTemplateLoader(i); + if (templateLoader1 instanceof StringTemplateLoader) { + StringTemplateLoader stringTemplateLoader = (StringTemplateLoader) templateLoader1; + stringTemplateLoader.putTemplate(key, tpl); + break; + } + } + template = getTemplate(key); + configuration.setTemplateUpdateDelayMilliseconds(5000); + } + return template; + } + + private static Template getTemplate(String key) { + try { + return configuration.getTemplate(key, "UTF-8"); + } catch (Exception e) { + } + return null; + } + + /** + * 通过反射获取一个对象的某个字段值 + * + * @param object 某个对象 + * @param fieldName 字段名 + * @return 字段值 + */ + private static Object getValue(Object object, String fieldName) { + Class clazz = object.getClass(); + + Map fieldMap = classFieldMap.get(clazz); + if (fieldMap == null) { + fieldMap = new ConcurrentHashMap<>(); + classFieldMap.put(clazz, fieldMap); + } + + Field field = fieldMap.get(fieldName); + if (field == null) { + field = ReflectionUtils.findField(clazz, fieldName); + if (field == null) { + return "<空字段>"; + } + field.setAccessible(true); + fieldMap.put(fieldName, field); + } + return ReflectionUtils.getField(field, object); + } +} -- Gitee From 54b256ce1547fb414ecacf0651b1c3ad09f95e87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Wed, 11 Sep 2019 22:52:48 +0800 Subject: [PATCH 44/46] =?UTF-8?q?=E9=87=8D=E6=9E=84SQL=20Server=E7=9A=84Ma?= =?UTF-8?q?rkdown=E5=86=85=E5=AE=B9=E7=94=9F=E6=88=90=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SqlServerGenerateMarkdownServiceImpl.java | 72 +++++++------------ 1 file changed, 27 insertions(+), 45 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 0070972..92bca26 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -7,17 +7,21 @@ import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.GenerateMarkdownService; import com.trh.dictionary.util.Keys; +import com.trh.dictionary.util.MarkdownUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.annotation.PostConstruct; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * SQL Server数据渲染Markdown内容 @@ -36,6 +40,10 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer @Autowired private HttpSession session; + private Map header = new LinkedHashMap<>(); + private Map table = new LinkedHashMap<>(); + private Map indexs = new LinkedHashMap<>(); + @Override public String generateMarkdown() { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); @@ -111,7 +119,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer Ta.setIndexInfoList(list_index); } - return writeMarkdownString(tableInfos); + return MarkdownUtils.toMarkdown(tableInfos, table, indexs, header); } catch (Exception e) { e.printStackTrace(); logger.info("生成Markdown失败"); @@ -125,49 +133,23 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer return "### 暂无数据"; } - public static String writeMarkdownString(List list) { - StringBuffer markdown = new StringBuffer(); - String res1 = "|:------:|:------:|:------:|:------:|:------:|:------:|:------:|" + "\n"; - int i = 1; - for (BaseTableInfo baseTableInfo : list) { - SqlserverTabelInfo info = (SqlserverTabelInfo) baseTableInfo; - StringBuffer oneTble = new StringBuffer(); - oneTble.append("##" + i + "." + info.getTableName() + " " + info.getValue() + "\n" + "基本信息:" + info.getValue() + " " - + "\n\n" + "|序列|列名|主键|类型|可空|默认值|注释|" + "\n"); - oneTble.append(res1); - List columnInfos = info.getColumnList(); - //拼接列 - for (SqlserverColumnInfo Column : columnInfos) { - oneTble.append("|").append(Column.getColumn_num()).append("|"). - append(Column.getColumn_name()).append("|"). - append(Column.getP_k()).append("|"). - append(Column.getType()).append("|"). - append(Column.getIs_null()).append("|"). - append(Column.getDefault_value()).append("|"). - append(Column.getDecs()).append("|"). - append("\n"); - } - //拼接索引 - oneTble.append("\n"); - oneTble.append("|序列|索引名|描述|包含字段|" + "\n"); - oneTble.append("|:------:|:------:|:------:|:------:|" + "\n"); - List indexInfolist = info.getIndexInfoList(); - int j = 1; - for (SqlserverIndexInfo indexInfo : indexInfolist) { - oneTble.append("|").append(j).append("|"). - append(indexInfo.getIndex_name()).append("|"). - append(indexInfo.getIndex_desc()).append("|"). - append(indexInfo.getIndex_keys()).append("|"). - append("\n"); - j++; - } - i++; - oneTble.append("\n"); - markdown.append(oneTble); - } - //目录 - markdown.insert(0, "[TOC]\n"); - logger.info("表信息\n" + markdown.toString()); - return markdown.toString(); + @PostConstruct + public void post() { + header.put("tableName", "tableName"); + header.put("marker", "value"); + header.put("info", "value"); + + table.put("_index", "序列"); + table.put("column_name", "列名"); + table.put("p_k", "主键"); + table.put("type", "类型"); + table.put("is_null", "可空"); + table.put("default_value", "默认值"); + table.put("decs", "注释"); + + indexs.put("_index", "序列"); + indexs.put("index_name", "索引名"); + indexs.put("index_desc", "描述"); + indexs.put("index_keys", "包含字段"); } } -- Gitee From 5e96d5a9d3859945cfb8033287d8026fbe789e8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Thu, 12 Sep 2019 09:48:51 +0800 Subject: [PATCH 45/46] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=B1=BB=E7=9A=84=E5=BC=82=E5=B8=B8=E6=8A=9B?= =?UTF-8?q?=E5=87=BA=EF=BC=8C=E7=BB=9F=E4=B8=80=E5=85=A8=E9=83=A8=E6=8A=9B?= =?UTF-8?q?=E5=87=BA=E5=88=B0=E5=A4=96=E5=B1=82=E7=BB=99=E5=A4=96=E5=B1=82?= =?UTF-8?q?=E6=8D=95=E8=8E=B7=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dictionary/service/DatabaseService.java | 13 +++++----- .../service/GenerateMarkdownService.java | 16 +++++++------ .../service/GeneratePdfService.java | 17 +++++++------ .../service/impl/DatabaseServiceImpl.java | 6 ++--- .../impl/GenerateMarkdownServiceImpl.java | 4 ++-- .../SqlServerGenerateMarkdownServiceImpl.java | 24 ++++--------------- 6 files changed, 32 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/trh/dictionary/service/DatabaseService.java b/src/main/java/com/trh/dictionary/service/DatabaseService.java index 2f26729..f63c34a 100644 --- a/src/main/java/com/trh/dictionary/service/DatabaseService.java +++ b/src/main/java/com/trh/dictionary/service/DatabaseService.java @@ -2,7 +2,6 @@ package com.trh.dictionary.service; import com.trh.dictionary.bean.base.BaseTableInfo; -import java.sql.SQLException; import java.util.List; /** @@ -16,24 +15,24 @@ public interface DatabaseService { * 获得数据库名称列表 * * @return 数据库名称列表 - * @throws SQLException + * @throws Exception 数据库操作异常 */ - List getDatabaseName() throws SQLException; + List getDatabaseName() throws Exception; /** * 获取数据库表列表 * * @return 数据库表信息 - * @throws SQLException + * @throws Exception 数据库操作异常 */ - List getTables() throws SQLException; + List getTables() throws Exception; /** * 获取数据库表列表 * * @param schema 数据库名称(模式名称) * @return 数据库表信息 - * @throws SQLException + * @throws Exception 数据库操作异常 */ - List getTables(String schema) throws SQLException; + List getTables(String schema) throws Exception; } diff --git a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java index db02c0b..7cd3d8c 100644 --- a/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java +++ b/src/main/java/com/trh/dictionary/service/GenerateMarkdownService.java @@ -14,23 +14,25 @@ public interface GenerateMarkdownService { /** * 使用一个已知的表列表构建Markdown内容 * - * @param tableInfos - * @return + * @param tableInfos 数据库表信息列表 + * @return Markdown内容 */ String generateMarkdown(List tableInfos); /** * 指定一个数据库的表列表构建Markdown内容 * - * @param schema - * @return + * @param schema 数据库名称 + * @return Markdown内容 + * @throws Exception 渲染失败 */ - String generateMarkdown(String schema); + String generateMarkdown(String schema) throws Exception; /** * 使用默认当前数据库的表列表构建Markdown内容 * - * @return + * @return Markdown内容 + * @throws Exception 渲染失败 */ - String generateMarkdown(); + String generateMarkdown() throws Exception; } diff --git a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java index 6d4c790..1ab49f7 100644 --- a/src/main/java/com/trh/dictionary/service/GeneratePdfService.java +++ b/src/main/java/com/trh/dictionary/service/GeneratePdfService.java @@ -1,10 +1,8 @@ package com.trh.dictionary.service; -import com.itextpdf.text.DocumentException; import com.trh.dictionary.bean.base.BaseTableInfo; import java.io.File; -import java.io.IOException; import java.util.List; /** @@ -17,25 +15,26 @@ public interface GeneratePdfService { /** * 指定数据库表列表构建PDF文件 * - * @param tableInfos - * @param file - * @throws DocumentException - * @throws IOException + * @param tableInfos 数据库表格内容 + * @param file 渲染的文件 + * @throws Exception 渲染异常 */ void generatePdfFile(List tableInfos, File file) throws Exception; /** * 指定一个数据库的表列表构建PDF文件 * - * @param schema - * @param file + * @param schema 数据库名称 + * @param file 保存的文件 + * @throws Exception 渲染异常 */ void generatePdfFile(String schema, File file) throws Exception; /** * 构建PDF文件,使用默认当前数据库的表列表 * - * @param file + * @param file 保存的文件 + * @throws Exception 渲染异常 */ void generatePdfFile(File file) throws Exception; } diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index b495deb..fd69e7a 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -42,7 +42,7 @@ public class DatabaseServiceImpl implements DatabaseService { private Map map = new HashMap<>(); @Override - public List getDatabaseName() throws SQLException { + public List getDatabaseName() throws Exception { return getDatabaseService().getDatabaseName(); } @@ -62,13 +62,13 @@ public class DatabaseServiceImpl implements DatabaseService { } @Override - public List getTables() throws SQLException { + public List getTables() throws Exception { return getDatabaseService().getTables(); } @Override - public List getTables(String schema) throws SQLException { + public List getTables(String schema) throws Exception { return getDatabaseService().getTables(schema); } diff --git a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java index 2501edb..478d134 100644 --- a/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/GenerateMarkdownServiceImpl.java @@ -42,13 +42,13 @@ public class GenerateMarkdownServiceImpl implements GenerateMarkdownService { private Map indexs = new LinkedHashMap<>(); @Override - public String generateMarkdown() { + public String generateMarkdown() throws Exception { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return generateMarkdown(dto.getDatabase()); } @Override - public String generateMarkdown(String schema) { + public String generateMarkdown(String schema) throws Exception { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); DatabaseType type = dto.getType(); if (type.equals(DatabaseType.SQLSERVER)) { diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 92bca26..4aec420 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -45,31 +45,15 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer private Map indexs = new LinkedHashMap<>(); @Override - public String generateMarkdown() { + public String generateMarkdown() throws SQLException { ConnectionDTO dto = (ConnectionDTO) session.getAttribute(Keys.connectionDtoKey); return generateMarkdown(dto.getDatabase()); } @Override - public String generateMarkdown(String schema) { - Connection connection = null; - try { - //得到生成数据 - connection = dataSource.getConnection(); - - List tables = sqlServerDatabaseService.getTables(schema); - return generateMarkdown(tables); - } catch (Exception e) { - e.printStackTrace(); - logger.info("生成Markdown失败"); - } finally { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return "### 暂无数据"; + public String generateMarkdown(String schema) throws SQLException { + List tables = sqlServerDatabaseService.getTables(schema); + return generateMarkdown(tables); } @Override -- Gitee From 337a6577dca1de9f69d10162f84198a4c8dabba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=AF=E5=9D=A4=E6=9E=97?= Date: Thu, 12 Sep 2019 10:00:05 +0800 Subject: [PATCH 46/46] =?UTF-8?q?=E6=8F=90=E5=8F=96=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E8=B5=84=E6=BA=90=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E7=BB=9F=E4=B8=80=E5=88=B0JdbcUtils=E9=87=8C?= =?UTF-8?q?=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/DataSourceServiceImpl.java | 10 +- .../service/impl/DatabaseServiceImpl.java | 1 - .../service/impl/Db2DatabaseServiceImpl.java | 12 +-- .../impl/MySqlDatabaseServiceImpl.java | 5 +- .../impl/OracleDatabaseServiceImpl.java | 21 +---- .../impl/SqlServerDatabaseServiceImpl.java | 19 ++-- .../SqlServerGenerateMarkdownServiceImpl.java | 7 +- .../com/trh/dictionary/util/JdbcUtils.java | 44 +++------ .../trh/dictionary/util/MarkdownUtils.java | 2 +- .../com/trh/dictionary/util/SqlExecutor.java | 92 ------------------- src/test/java/com/trh/dictionary/Test.java | 3 +- 11 files changed, 37 insertions(+), 179 deletions(-) delete mode 100644 src/main/java/com/trh/dictionary/util/SqlExecutor.java diff --git a/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java index d661f05..e587d07 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DataSourceServiceImpl.java @@ -3,6 +3,7 @@ package com.trh.dictionary.service.impl; import com.trh.dictionary.bean.ConnectionDTO; import com.trh.dictionary.config.DynamicDataSource; import com.trh.dictionary.service.DataSourceService; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.Keys; import freemarker.template.Configuration; import freemarker.template.Template; @@ -14,7 +15,6 @@ import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.sql.Connection; -import java.sql.SQLException; import java.util.UUID; /** @@ -102,13 +102,7 @@ public class DataSourceServiceImpl implements DataSourceService { e.printStackTrace(); throw e; } finally { - if (connection != null) { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } + JdbcUtils.releaseResource(connection); } } diff --git a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java index fd69e7a..3958e56 100644 --- a/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/DatabaseServiceImpl.java @@ -11,7 +11,6 @@ import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.servlet.http.HttpSession; -import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java index 19547a8..0a653ce 100644 --- a/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/Db2DatabaseServiceImpl.java @@ -6,8 +6,8 @@ import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.Keys; -import com.trh.dictionary.util.SqlExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -47,7 +47,7 @@ public class Db2DatabaseServiceImpl implements DatabaseService { schemas.add(schema); } } - SqlExecutor.releaseResource(null, null, rs, statement); + JdbcUtils.releaseResource(rs, statement); return schemas; } @@ -77,7 +77,7 @@ public class Db2DatabaseServiceImpl implements DatabaseService { tableInfo.setIndexInfoList(getTableIndexList(connection, tableName)); tables.add(tableInfo); } - SqlExecutor.releaseResource(null, null, rs, null); + JdbcUtils.releaseResource(rs, null); return tables; } @@ -120,7 +120,7 @@ public class Db2DatabaseServiceImpl implements DatabaseService { columnInfo.setIsIndex(getTablePrimaryKey(connection, table, rs.getString("COLNAME").trim())); columns.add(columnInfo); } - SqlExecutor.releaseResource(null, null, rs, statement); + JdbcUtils.releaseResource(rs, statement); return columns; } @@ -152,7 +152,7 @@ public class Db2DatabaseServiceImpl implements DatabaseService { indexInfo.setOrder(rs.getInt("IID")); indexList.add(indexInfo); } - SqlExecutor.releaseResource(null, null, rs, statement); + JdbcUtils.releaseResource(rs, statement); return indexList; } @@ -176,7 +176,7 @@ public class Db2DatabaseServiceImpl implements DatabaseService { return 1; } } - SqlExecutor.releaseResource(null, null, rs, statement); + JdbcUtils.releaseResource(rs, statement); return 0; } } diff --git a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java index 69a0db4..cd783f6 100644 --- a/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/MySqlDatabaseServiceImpl.java @@ -100,7 +100,7 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { e.printStackTrace(); } finally { try { - JdbcUtils.releaseResource(connection, null, resultSet, statement); + JdbcUtils.releaseResource(connection, resultSet, statement); } catch (Exception e) { e.printStackTrace(); } @@ -153,8 +153,7 @@ public class MySqlDatabaseServiceImpl implements DatabaseService { columnInfo.setDescription(""); } } - statement.close(); - resultSet.close(); + JdbcUtils.releaseResource(statement, resultSet); return columnInfos; } diff --git a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java index 54e0225..7052f72 100644 --- a/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/OracleDatabaseServiceImpl.java @@ -6,6 +6,7 @@ import com.trh.dictionary.bean.IndexInfo; import com.trh.dictionary.bean.TableInfo; import com.trh.dictionary.bean.base.BaseTableInfo; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,7 +77,7 @@ public class OracleDatabaseServiceImpl implements DatabaseService { stringName = index_name.getString(1); column_name = index_name.getString(2); } - constraintNamePstmt.close(); + JdbcUtils.releaseResource(constraintNamePstmt); //通过表名查询所有的列数据 PreparedStatement columnIdPstmt = conn.prepareStatement("SELECT T.column_id,T.column_name,T.data_type,T.data_default,T.nullable,b.comments\n" + "FROM USER_TAB_COLUMNS T LEFT JOIN user_col_comments b ON T.TABLE_NAME =b.table_name AND T.COLUMN_NAME =b.column_name WHERE T.TABLE_NAME ='" + tableName + "'"); @@ -131,28 +132,16 @@ public class OracleDatabaseServiceImpl implements DatabaseService { indexInfo.setContainKey(IndexRs.getString(4)); listIndex.add(indexInfo); } - IndexRs.close(); - columnIdPstmt.close(); - columnRs.close(); - rownumPstmt.close(); - index_name.close(); + JdbcUtils.releaseResource(IndexRs, columnIdPstmt, columnRs, rownumPstmt, index_name); tableInfo.setTableName(tableName); tableInfo.setDescription(COMMENTS); tableInfo.setColumnList(listColumn); tableInfo.setIndexInfoList(listIndex); list.add(tableInfo); } - rs.close(); - pstmt.close(); + JdbcUtils.releaseResource(rs, pstmt); } finally { - if (conn != null) { - try { - //关闭链接 - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } + JdbcUtils.releaseResource(conn); } return list; } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java index adbd45c..75e642c 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerDatabaseServiceImpl.java @@ -6,6 +6,7 @@ import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.DatabaseService; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,18 +48,13 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { while (resultSet.next()) { list.add(resultSet.getString("name")); } - resultSet.close(); - statement.close(); + JdbcUtils.releaseResource(resultSet, statement); return list; } catch (Exception e) { e.printStackTrace(); } finally { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + JdbcUtils.releaseResource(connection); } return list; } @@ -85,8 +81,7 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { sqlserverTabelInfo.setValue(resultSet.getString("value")); list.add(sqlserverTabelInfo); } - resultSet.close(); - statement.close(); + JdbcUtils.releaseResource(resultSet, statement); return list; } @@ -125,8 +120,7 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { list.add(sqlserverColumnInfo); } - resultSet.close(); - statement.close(); + JdbcUtils.releaseResource(resultSet, statement); return list; } @@ -148,8 +142,7 @@ public class SqlServerDatabaseServiceImpl implements DatabaseService { sqlserverIndexInfo.setIndex_keys(resultSet.getString("index_keys")); list.add(sqlserverIndexInfo); } - resultSet.close(); - statement.close(); + JdbcUtils.releaseResource(resultSet, statement); return list; } } diff --git a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java index 4aec420..bf12dda 100644 --- a/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java +++ b/src/main/java/com/trh/dictionary/service/impl/SqlServerGenerateMarkdownServiceImpl.java @@ -6,6 +6,7 @@ import com.trh.dictionary.bean.sqlserver.SqlserverColumnInfo; import com.trh.dictionary.bean.sqlserver.SqlserverIndexInfo; import com.trh.dictionary.bean.sqlserver.SqlserverTabelInfo; import com.trh.dictionary.service.GenerateMarkdownService; +import com.trh.dictionary.util.JdbcUtils; import com.trh.dictionary.util.Keys; import com.trh.dictionary.util.MarkdownUtils; import org.slf4j.Logger; @@ -108,11 +109,7 @@ public class SqlServerGenerateMarkdownServiceImpl implements GenerateMarkdownSer e.printStackTrace(); logger.info("生成Markdown失败"); } finally { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + JdbcUtils.releaseResource(connection); } return "### 暂无数据"; } diff --git a/src/main/java/com/trh/dictionary/util/JdbcUtils.java b/src/main/java/com/trh/dictionary/util/JdbcUtils.java index f76cb00..59d6ed6 100644 --- a/src/main/java/com/trh/dictionary/util/JdbcUtils.java +++ b/src/main/java/com/trh/dictionary/util/JdbcUtils.java @@ -1,6 +1,7 @@ package com.trh.dictionary.util; -import java.sql.*; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -34,39 +35,18 @@ public class JdbcUtils { } /** - * 释放资源 + * 释放资源(释放数据库连接资源) * - * @param connection 连接 - * @param preparedStatement - * @param resultSet 结果集 + * @param autoCloseable 一个通用的接口 */ - public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { - if (null != resultSet) { - try { - resultSet.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != statement) { - try { - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != preparedStatement) { - try { - preparedStatement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - if (null != connection) { - try { - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); + public static void releaseResource(AutoCloseable... autoCloseable) { + for (AutoCloseable closeable : autoCloseable) { + if (closeable != null) { + try { + closeable.close(); + } catch (Exception e) { + e.printStackTrace(); + } } } } diff --git a/src/main/java/com/trh/dictionary/util/MarkdownUtils.java b/src/main/java/com/trh/dictionary/util/MarkdownUtils.java index 17d4bf7..1c1dbd7 100644 --- a/src/main/java/com/trh/dictionary/util/MarkdownUtils.java +++ b/src/main/java/com/trh/dictionary/util/MarkdownUtils.java @@ -26,7 +26,7 @@ import java.util.concurrent.ConcurrentHashMap; */ @Component public class MarkdownUtils { - private static Map, Map> classFieldMap = new ConcurrentHashMap(); + private static Map, Map> classFieldMap = new ConcurrentHashMap<>(); private static Configuration configuration; diff --git a/src/main/java/com/trh/dictionary/util/SqlExecutor.java b/src/main/java/com/trh/dictionary/util/SqlExecutor.java deleted file mode 100644 index 37b5eb1..0000000 --- a/src/main/java/com/trh/dictionary/util/SqlExecutor.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.trh.dictionary.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.*; -import java.util.Properties; - -/** - * @author TangXu - * @create 2019-08-29 17:23 - * @description: - */ -public class SqlExecutor { - - static final Logger logger = LoggerFactory.getLogger(SqlExecutor.class); - - public static Connection newDB2Connection(String db) throws ClassNotFoundException, SQLException { - String host = "127.0.0.1"; - return newDB2Connection(host, db); - } - - public static Connection newDB2Connection(String host, String db) throws ClassNotFoundException, SQLException { - String user = "db2"; - String password = "system"; - return newDB2Connection(host, db, user, password); - } - - public static Connection newDB2Connection(String host, String db, String user, String password) throws ClassNotFoundException, SQLException { - int port = 50000; - return newDB2Connection(host, port, db, user, password); - } - - public static Connection newDB2Connection(String host, int port, String db, String user, String password) throws ClassNotFoundException, SQLException { - boolean reconnect = true; - String encoding = "utf-8"; - return newDB2Connection(host, port, db, reconnect, encoding, user, password); - } - - public static Connection newDB2Connection(String host, int port, String db, boolean reconnect, String encoding, String username, String password) throws ClassNotFoundException, SQLException, SQLException { - String driver = "com.ibm.db2.jcc.DB2Driver"; - String format = "jdbc:db2://%s:%d/%s"; - String url = String.format(format, host, port, db); - Class.forName(driver); - return DriverManager.getConnection(url, username, password); - } - - public static Connection getConnections(String driver, String url, String username, String password) throws Exception { - try { - Properties props = new Properties(); - props.put("remarksReporting", "true"); - props.put("user", username); - props.put("password", password); - Class.forName(driver); - return DriverManager.getConnection(url, props); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * 释放连接 - * - * @param connection - * @param preparedStatement - * @param resultSet - * @param statement - */ - public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, Statement statement) { - try { - - if (null != statement) { - statement.close(); - } - - if (null != preparedStatement) { - preparedStatement.close(); - } - - if (null != resultSet) { - resultSet.close(); - } - - if (null != connection) { - connection.close(); - } - } catch (SQLException e) { - logger.error(e.getMessage()); - } - } -} \ No newline at end of file diff --git a/src/test/java/com/trh/dictionary/Test.java b/src/test/java/com/trh/dictionary/Test.java index 45d6c99..c05c456 100644 --- a/src/test/java/com/trh/dictionary/Test.java +++ b/src/test/java/com/trh/dictionary/Test.java @@ -1,7 +1,6 @@ package com.trh.dictionary; import com.trh.dictionary.bean.TableInfo; -import com.trh.dictionary.util.SqlExecutor; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -69,7 +68,7 @@ public class Test { @org.junit.Test public void testMakeDb2ServerPdf() throws Exception { - Connection connection = SqlExecutor.newDB2Connection("192.168.171.230", 50000, "TEST", "db2", "system"); + Connection connection = null;// SqlExecutor.newDB2Connection("192.168.171.230", 50000, "TEST", "db2", "system"); List tableInfo = Collections.emptyList(); //Db2Executor.getDB2Tables(connection, "TEST"); if (tableInfo.size() == 0) { return; -- Gitee