Browse Source

init

master
Zhenfei.Li 4 years ago
commit
10358f0089
  1. 0
      README.md
  2. 126
      build.xml
  3. 26
      plugin.xml
  4. 28
      pom.xml
  5. 24
      src/main/java/com/fr/plugin/decision/ExcelMngAliasBridge.java
  6. 40
      src/main/java/com/fr/plugin/decision/ExcelMngConfigAccessBridge.java
  7. 24
      src/main/java/com/fr/plugin/decision/ExcelMngHandleBridge.java
  8. 15
      src/main/java/com/fr/plugin/decision/HWComponent.java
  9. 37
      src/main/java/com/fr/plugin/decision/HWOptionProvider.java
  10. 305
      src/main/java/com/fr/plugin/decision/HWUtils.java
  11. 40
      src/main/java/com/fr/plugin/decision/ReuseConfigAccessBridge.java
  12. 29
      src/main/java/com/fr/plugin/decision/core/ActionEunm.java
  13. 32
      src/main/java/com/fr/plugin/decision/core/ActionFactory.java
  14. 238
      src/main/java/com/fr/plugin/decision/core/DML.java
  15. 45
      src/main/java/com/fr/plugin/decision/core/Drop.java
  16. 91
      src/main/java/com/fr/plugin/decision/core/ExcelDmlBean.java
  17. 56
      src/main/java/com/fr/plugin/decision/core/action/AddAction.java
  18. 60
      src/main/java/com/fr/plugin/decision/core/action/CoverAction.java
  19. 67
      src/main/java/com/fr/plugin/decision/core/action/CreateAction.java
  20. 27
      src/main/java/com/fr/plugin/decision/core/action/ExcelDmlAction.java
  21. 142
      src/main/java/com/fr/plugin/decision/dao/ExcelLinkService.java
  22. 16
      src/main/java/com/fr/plugin/decision/dao/ExcelMngDao.java
  23. 70
      src/main/java/com/fr/plugin/decision/dao/ExcelMngEntity.java
  24. 15
      src/main/java/com/fr/plugin/decision/dao/ReuseDao.java
  25. 36
      src/main/java/com/fr/plugin/decision/dao/ReuseEntity.java
  26. 104
      src/main/java/com/fr/plugin/decision/dao/ReuseService.java
  27. 41
      src/main/java/com/fr/plugin/decision/dialect/DialectCreator.java
  28. 58
      src/main/java/com/fr/plugin/decision/dialect/gauss/GaussDialectColumnType2SQLExecutor.java
  29. 15
      src/main/java/com/fr/plugin/decision/dialect/gauss/GaussDialectConsummate.java
  30. 50
      src/main/java/com/fr/plugin/decision/dialect/hive/HiveDialectColumnType2SQLExecutor.java
  31. 17
      src/main/java/com/fr/plugin/decision/dialect/hive/HiveDialectConsummate.java
  32. 13
      src/main/java/com/fr/plugin/decision/dialect/postgre/PostgreDialectConsummate.java
  33. 12
      src/main/java/com/fr/plugin/decision/dialect/sybase/SybaseDialectConsummate.java
  34. 53
      src/main/java/com/fr/plugin/decision/http/AddLinkHttpHandler.java
  35. 73
      src/main/java/com/fr/plugin/decision/http/DeleteLinkHttpHandle.java
  36. 43
      src/main/java/com/fr/plugin/decision/http/GetAllUserListHandler.java
  37. 53
      src/main/java/com/fr/plugin/decision/http/GetAuthUserByLinkNameHandler.java
  38. 62
      src/main/java/com/fr/plugin/decision/http/GetSchemaHttpHandler.java
  39. 58
      src/main/java/com/fr/plugin/decision/http/IfTableExistHttpHandler.java
  40. 66
      src/main/java/com/fr/plugin/decision/http/QueryLinkHttpHandle.java
  41. 50
      src/main/java/com/fr/plugin/decision/http/QueryTableColAttrHttpHandle.java
  42. 125
      src/main/java/com/fr/plugin/decision/http/QueryTableDataHttpHandle.java
  43. 65
      src/main/java/com/fr/plugin/decision/http/RenameHttpHandle.java
  44. 41
      src/main/java/com/fr/plugin/decision/http/UpdateLinkAuthHandler.java
  45. 23
      src/main/java/com/fr/plugin/decision/request/HWHandlerProvider.java
  46. 26
      src/main/java/com/fr/plugin/decision/request/HWURLAliasProvider.java
  47. 62
      src/main/java/com/fr/plugin/decision/request/handler/ExcelFiledHandler.java
  48. 66
      src/main/java/com/fr/plugin/decision/request/handler/ExcelSheetCountHandler.java
  49. 64
      src/main/java/com/fr/plugin/decision/request/handler/HWAbstractHandler.java
  50. 40
      src/main/java/com/fr/plugin/decision/request/handler/HWFileUploadHander.java
  51. 91
      src/main/java/com/fr/plugin/decision/request/handler/TableDataImport.java
  52. 25
      src/main/java/com/fr/plugin/decision/utils/HttpUtils.java
  53. 566
      src/main/java/com/fr/plugin/decision/utils/JdbcUtils.java
  54. 211
      src/main/resources/com/fr/plugin/hw/decision/js/attr/col.attr.js
  55. 104
      src/main/resources/com/fr/plugin/hw/decision/js/attr/col.attr.model.js
  56. 127
      src/main/resources/com/fr/plugin/hw/decision/js/attr/sheet.masker.js
  57. 193
      src/main/resources/com/fr/plugin/hw/decision/js/attr/table.attr.js
  58. 73
      src/main/resources/com/fr/plugin/hw/decision/js/attr/table.attr.model.js
  59. 46
      src/main/resources/com/fr/plugin/hw/decision/js/attr/td.widget.js
  60. 265
      src/main/resources/com/fr/plugin/hw/decision/js/hw.option.js
  61. 187
      src/main/resources/com/fr/plugin/hw/decision/js/hw.table.add.pop.js
  62. 15
      src/main/resources/com/fr/plugin/hw/decision/js/hw.table.add.pop.model.js
  63. 72
      src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.js
  64. 12
      src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.model.js
  65. 99
      src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.right.js
  66. 123
      src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.right.model.js
  67. 86
      src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.hw.excel.export.pane.js
  68. 11
      src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.hw.excel.export.pane.model.js
  69. 88
      src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.page.table.plugin.js
  70. 107
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.js
  71. 100
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.item.js
  72. 18
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.item.model.js
  73. 60
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.js
  74. 99
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.model.js
  75. 7
      src/main/resources/com/fr/plugin/hw/decision/js/pane/left.model.js
  76. 70
      src/main/resources/com/fr/plugin/hw/decision/js/pane/panes.js
  77. 16
      src/main/resources/com/fr/plugin/hw/decision/js/pane/panes.model.js
  78. 150
      src/main/resources/com/fr/plugin/hw/decision/js/pane/right.js
  79. 7
      src/main/resources/com/fr/plugin/hw/decision/js/pane/right.model.js
  80. 74
      src/main/resources/com/fr/plugin/hw/decision/js/pane/right.table.js
  81. 77
      src/main/resources/com/fr/plugin/hw/decision/js/pane/right.table.model.js
  82. 243
      src/main/resources/com/fr/plugin/hw/decision/js/table.info.js
  83. 158
      src/main/resources/com/fr/plugin/hw/decision/js/table.info.model.js
  84. 26
      src/main/resources/com/fr/plugin/hw/decision/js/utils.js

126
build.xml

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="jar" name="plugin">
<!-- JDK路径,根据自己机器上实际位置修改-->
<property name="jdk.home" value="/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home"/>
<property name="libs" value="${basedir}/lib"/>
<!-- <property name="dependenceLibs" value="${basedir}/dependence"/>-->
<!-- <property name="FRLibs" value="E:\jar-FR\10.0-idea"/>-->
<property name="destLoc" value="."/>
<property name="classes" value="classes"/>
<xmlproperty file="${basedir}/plugin.xml"/>
<property name="current-version" value="${plugin.version}"/>
<property name="current-id" value="${plugin.id}"/>
<property name="plugin-version" value="${current-version}"/>
<property name="plugin-name" value="hwExcelExport"/>
<property name="plugin-jar" value="fr-plugin-${plugin-name}-${plugin-version}.jar"/>
<target name="prepare">
<delete dir="${classes}"/>
</target>
<path id="compile.classpath">
<!-- <fileset dir="${FRLibs}">-->
<!-- <include name="**/*.jar"/>-->
<!-- </fileset>-->
<fileset dir="${libs}">
<include name="**/*.jar"/>
</fileset>
<!-- <fileset dir="${dependenceLibs}">-->
<!-- <include name="**/*.jar"/>-->
<!-- </fileset>-->
</path>
<patternset id="resources4Jar">
<exclude name="**/.settings/**"/>
<exclude name=".classpath"/>
<exclude name=".project"/>
<exclude name="**/*.java"/>
<exclude name="**/*.db"/>
<exclude name="**/*.g"/>
<exclude name="**/package.html"/>
</patternset>
<target name="copy_resources">
<echo message="从${resources_from}拷贝图片,JS,CSS等资源文件"/>
<delete dir="tmp"/>
<copy todir="tmp">
<fileset dir="${resources_from}\src\main\java">
<patternset refid="resources4Jar"/>
</fileset>
</copy>
<copy todir="tmp">
<fileset dir="${resources_from}\src\main\resources">
<patternset refid="resources4Jar"/>
</fileset>
</copy>
<copy todir="${classes}">
<fileset dir="tmp"/>
</copy>
<delete dir="tmp"/>
</target>
<target name="compile_javas">
<echo message="编译${compile_files}下的Java文件"/>
<javac destdir="${classes}" debug="false" optimize="on" source="${source_jdk_version}"
target="${target_jdk_version}"
fork="true" memoryMaximumSize="512m" listfiles="false" srcdir="${basedir}"
executable="${compile_jdk_version}/bin/javac" includeantruntime="on">
<src path="${basedir}/src"/>
<exclude name="**/.svn/**"/>
<compilerarg line="-encoding UTF8 "/>
<classpath refid="compile.classpath"/>
</javac>
</target>
<target name="jar_classes">
<echo message="打Jar包:${jar_name}"/>
<delete file="${basedir}/${jar_name}"/>
<jar jarfile="${basedir}/${jar_name}">
<fileset dir="${classes}">
</fileset>
</jar>
</target>
<target name="super_jar" depends="prepare">
<antcall target="copy_resources">
<param name="resources_from" value="${basedir}"/>
</antcall>
<antcall target="compile_javas">
<param name="source_jdk_version" value="1.7"/>
<param name="target_jdk_version" value="1.7"/>
<param name="compile_jdk_version" value="${jdk.home}"/>
<param name="compile_files" value="${basedir}/src"/>
</antcall>
<echo message="compile plugin success!"/>
<antcall target="jar_classes">
<param name="jar_name" value="${plugin-jar}"/>
</antcall>
<delete dir="${classes}"/>
</target>
<target name="jar" depends="super_jar">
<antcall target="zip"/>
</target>
<target name="zip">
<property name="plugin-folder" value="fr-plugin-${plugin-name}-${plugin-version}"/>
<echo message="----------zip files----------"/>
<mkdir dir="${plugin-folder}"/>
<copy todir="${plugin-folder}">
<fileset dir=".">
<include name="*.jar"/>
<include name="plugin.xml"/>
</fileset>
</copy>
<!-- <copy todir="${plugin-folder}">-->
<!-- <fileset dir="${libs}">-->
<!-- <include name="**/*.jar"/>-->
<!-- </fileset>-->
<!-- </copy>-->
<zip destfile="${basedir}/${plugin-folder}.zip" basedir=".">
<include name="${plugin-folder}/*.jar"/>
<include name="${plugin-folder}/plugin.xml"/>
</zip>
<xmlproperty file="${basedir}/plugin.xml"/>
<delete dir="${plugin-folder}"/>
<delete file="${plugin-jar}" />
</target>
</project>

26
plugin.xml

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.fr.plugin.hw.import.excel</id>
<name><![CDATA[直接导入数据库表]]></name>
<active>yes</active>
<version>1.8.3</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>author</vendor>
<description><![CDATA[直接导入数据库表]]></description>
<change-notes><![CDATA[区分链接权限,管理员可见全部,普通用户仅可见本人创建]]></change-notes>
<extra-decision>
<SystemOptionProvider class="com.fr.plugin.decision.HWOptionProvider"/>
<HttpHandlerProvider class="com.fr.plugin.decision.request.HWHandlerProvider"/>
<URLAliasProvider class="com.fr.plugin.decision.request.HWURLAliasProvider"/>
<HttpHandlerProvider class="com.fr.plugin.decision.ExcelMngHandleBridge"/>
<URLAliasProvider class="com.fr.plugin.decision.ExcelMngAliasBridge"/>
</extra-decision>
<extra-core>
<DBAccessProvider class="com.fr.plugin.decision.ExcelMngConfigAccessBridge"/>
<DBAccessProvider class="com.fr.plugin.decision.ReuseConfigAccessBridge"/>
<DialectCreator class="com.fr.plugin.decision.dialect.DialectCreator"/>
</extra-core>
<function-recorder class="com.fr.plugin.decision.HWOptionProvider"/>
</plugin>

28
pom.xml

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>starter</artifactId>
<groupId>com.fr.plugin</groupId>
<version>10.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>plugin-exceldatamanagement</artifactId>
<build>
<plugins>
<plugin>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<compilerArgument>-Xlint:unchecked</compilerArgument>
</configuration>
</plugin>
</plugins>
<outputDirectory>${project.basedir}/../webroot/WEB-INF/plugins/plugin-com.fr.plugin.exceldatamanagement-1.0/classes</outputDirectory>
</build>
</project>

24
src/main/java/com/fr/plugin/decision/ExcelMngAliasBridge.java

@ -0,0 +1,24 @@
package com.fr.plugin.decision;
import com.fr.decision.fun.impl.AbstractURLAliasProvider;
import com.fr.decision.webservice.url.alias.URLAlias;
import com.fr.decision.webservice.url.alias.URLAliasFactory;
public class ExcelMngAliasBridge extends AbstractURLAliasProvider {
@Override
public URLAlias[] registerAlias() {
return new URLAlias[]{
URLAliasFactory.createPluginAlias("/excelmng/addlink","/excelmng/addlink",false),
URLAliasFactory.createPluginAlias("/excelmng/delete","/excelmng/delete",false),
URLAliasFactory.createPluginAlias("/excelmng/querylink","/excelmng/querylink",false),
URLAliasFactory.createPluginAlias("/excelmng/rename","/excelmng/rename",false),
URLAliasFactory.createPluginAlias("/excelmng/querydata","/excelmng/querydata",false),
URLAliasFactory.createPluginAlias("/excelmng/querycolattr","/excelmng/querycolattr",false),
URLAliasFactory.createPluginAlias("/excelmng/getSchema","/excelmng/getSchema",false),
URLAliasFactory.createPluginAlias("/excelmng/iftableexist","/excelmng/iftableexist",false),
URLAliasFactory.createPluginAlias("/excelmng/getAllUserList","/excelmng/getAllUserList",false),
URLAliasFactory.createPluginAlias("/excelmng/getAuthUserList","/excelmng/getAuthUserList",false),
URLAliasFactory.createPluginAlias("/excelmng/updateLinkAuth","/excelmng/updateLinkAuth",false)
};
}
}

40
src/main/java/com/fr/plugin/decision/ExcelMngConfigAccessBridge.java

@ -0,0 +1,40 @@
package com.fr.plugin.decision;
import com.fr.db.fun.impl.AbstractDBAccessProvider;
import com.fr.plugin.decision.dao.ExcelMngDao;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
public class ExcelMngConfigAccessBridge extends AbstractDBAccessProvider {
private static DBAccessor dbAccessor = null;
public static DBAccessor getDbAccessor() {
return dbAccessor;
}
@Override
public DAOProvider[] registerDAO() {
return new DAOProvider[]{
new DAOProvider(){
@Override
public Class getEntityClass() {
return ExcelMngEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return ExcelMngDao.class;
}
}
};
}
@Override
public void onDBAvailable(DBAccessor dbAccessor) {
ExcelMngConfigAccessBridge.dbAccessor = dbAccessor;
}
}

24
src/main/java/com/fr/plugin/decision/ExcelMngHandleBridge.java

@ -0,0 +1,24 @@
package com.fr.plugin.decision;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
import com.fr.plugin.decision.http.*;
public class ExcelMngHandleBridge extends AbstractHttpHandlerProvider {
@Override
public HttpHandler[] registerHandlers() {
return new HttpHandler[]{
new AddLinkHttpHandler(),
new DeleteLinkHttpHandle(),
new QueryLinkHttpHandle(),
new RenameHttpHandle(),
new QueryTableDataHttpHandle(),
new QueryTableColAttrHttpHandle(),
new GetSchemaHttpHandler(),
new IfTableExistHttpHandler(),
new GetAllUserListHandler(),
new GetAuthUserByLinkNameHandler(),
new UpdateLinkAuthHandler()
};
}
}

15
src/main/java/com/fr/plugin/decision/HWComponent.java

@ -0,0 +1,15 @@
package com.fr.plugin.decision;
import com.fr.web.struct.Component;
import com.fr.web.struct.category.ScriptPath;
/**
* created by ezreal 2020/1/9
*/
public class HWComponent extends Component {
public static HWComponent KEY = new HWComponent();
@Override
public ScriptPath script() {
return ScriptPath.build("/com/fr/plugin/hw/decision/js/hw.option.js");
}
}

37
src/main/java/com/fr/plugin/decision/HWOptionProvider.java

@ -0,0 +1,37 @@
package com.fr.plugin.decision;
import com.fr.decision.fun.impl.AbstractSystemOptionProvider;
import com.fr.decision.web.MainComponent;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.web.struct.Atom;
/**
* created by ezreal 2020/1/9
*/
@FunctionRecorder
public class HWOptionProvider extends AbstractSystemOptionProvider {
@Override
public String id() {
return "fanruan-hw-excecl";
}
@Override
public String displayName() {
return "Excel导入";
}
@Override
public int sortIndex() {
return 3;
}
@Override
public Atom attach() {
return MainComponent.KEY;
}
@Override
public Atom client() {
return HWComponent.KEY;
}
}

305
src/main/java/com/fr/plugin/decision/HWUtils.java

@ -0,0 +1,305 @@
package com.fr.plugin.decision;
import com.fr.cache.Attachment;
import com.fr.cache.AttachmentSource;
import com.fr.general.CommonDateUtils;
import com.fr.general.DateUtils;
import com.fr.general.Inter;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.poi.hssf.usermodel.*;
import com.fr.third.org.apache.poi.hssf.util.Region;
import com.fr.third.org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Cell;
import com.fr.third.v2.org.apache.poi.ss.usermodel.DateUtil;
import com.fr.third.v2.org.apache.poi.ss.util.CellRangeAddress;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFCell;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFRow;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFSheet;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* created by ezreal 2020/1/12
*/
public class HWUtils {
/**
* 根据附件id获取对应附件excel对象
*
* @param attachId
* @return
*/
public static XSSFWorkbook getExcelWork(String attachId) {
XSSFWorkbook sheets = null;
try {
Attachment attachment = AttachmentSource.getAttachment(attachId);
if (attachment != null) {
InputStream inputStream = attachment.getInputStream();
sheets = new XSSFWorkbook(inputStream);
sheets.getNumberOfSheets();
}
} catch (IOException e) {
e.printStackTrace();
}
return sheets;
}
public static JSONArray getSheetFiled(XSSFSheet sheet) {
JSONArray result = JSONArray.create();
int rowCounts = sheet.getPhysicalNumberOfRows();
int titleRow = -1;
for (int row = 0; row < rowCounts; row++) {
XSSFRow xssfRow = sheet.getRow(row);
if (xssfRow == null) {
continue;
}
titleRow = row;
//循环取每个单元格(cell)的数据
Iterator<Cell> cellIterator = xssfRow.cellIterator();
while (cellIterator.hasNext()) {
XSSFCell cell = (XSSFCell) cellIterator.next();
String value = getString(cell);
if (StringUtils.isNotBlank(value)) {
JSONObject o = JSONObject.create().put("titleRow", titleRow).put("value", cell.getColumnIndex()).put("text", value);
result.add(o);
}
}
if (titleRow >= 0) {
break;
}
}
return result;
}
public static Map<String, List> getSheetContent(XSSFSheet sheet, int titleRow, JSONObject tableCol) {
Map<String, List> result = new HashMap<String, List>();
Iterator<Map.Entry<String, Object>> iterator = tableCol.iterator();
List<CellRangeAddress> combineCell = getCombineCell(sheet);
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
result.put(entry.getKey(), new ArrayList());
}
int lastRowNum = sheet.getLastRowNum();
for (int row = titleRow + 1; row <= lastRowNum; row++) {
XSSFRow xssfRow = sheet.getRow(row);
if (xssfRow == null) {
continue;
}
for (Map.Entry<String, List> entry : result.entrySet()) {
String key = entry.getKey();
int col = tableCol.getInt(key);
List value = entry.getValue();
XSSFCell cell = xssfRow.getCell(col);
if (cell != null) {
String cellValue = getCellValue(sheet, combineCell, row, col, cell);
value.add(StringUtils.isBlank(cellValue) ? StringUtils.EMPTY : cellValue);
} else {
value.add(StringUtils.EMPTY);
}
}
}
return result;
}
public static String getCellValue(XSSFSheet sheet, List<CellRangeAddress> combineCell, int row, int col, XSSFCell cell) {
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for (CellRangeAddress ca : combineCell) {
// 获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if (cell.getColumnIndex() <= lastC && cell.getColumnIndex() >= firstC) {
if (cell.getRowIndex() <= lastR && cell.getRowIndex() >= firstR) {
XSSFRow xRow = sheet.getRow(firstR);
XSSFCell xCell = xRow.getCell(firstC);
return getString(xCell);
}
}
}
return getString(cell);
}
public static List<CellRangeAddress> getCombineCell(XSSFSheet sheet) {
// 获得一个 sheet 中合并单元格的数量
List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
int sheetmergerCount = sheet.getNumMergedRegions();
// 遍历合并单元格
for (int i = 0; i < sheetmergerCount; i++) {
// 获得合并单元格加入list中
CellRangeAddress ca = sheet.getMergedRegion(i);
list.add(ca);
}
return list;
}
/**
* 把单元格的内容转为字符串
*
* @param xssfCell 单元格
* @return 字符串
*/
public static String getString(XSSFCell xssfCell) {
if (xssfCell == null) {
return "";
}
int type = xssfCell.getCellType();
if (type == XSSFCell.CELL_TYPE_NUMERIC) {
if (DateUtil.isCellDateFormatted(xssfCell)) {
// 如果是date类型则 ,获取该cell的date值
return new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getJavaDate(xssfCell.getNumericCellValue()));
} else { // 纯数字
return String.valueOf(xssfCell.getNumericCellValue());
}
} else if (type == XSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfCell.getBooleanCellValue());
} else {
return xssfCell.getStringCellValue();
}
}
/********************************excel2003*************************************************/
public static HSSFWorkbook getExcel2003Work(String attachId) {
HSSFWorkbook sheets = null;
try {
Attachment attachment = AttachmentSource.getAttachment(attachId);
if (attachment != null) {
InputStream inputStream = attachment.getInputStream();
POIFSFileSystem poifsFileSystem = null;
try {
poifsFileSystem = new POIFSFileSystem(inputStream);
} catch (IOException var13) {
throw new IOException(Inter.getLocText("Fine-Engine_NS_Exception_ReadExcelError"));
}
sheets = new HSSFWorkbook(poifsFileSystem);
sheets.getNumberOfSheets();
}
} catch (IOException e) {
e.printStackTrace();
}
return sheets;
}
public static JSONArray get2003SheetFiled(HSSFSheet sheet) {
JSONArray result = JSONArray.create();
int rowCounts = sheet.getPhysicalNumberOfRows();
int titleRow = -1;
for (int row = 0; row < rowCounts; row++) {
HSSFRow hssfRow = sheet.getRow(row);
if (hssfRow == null) {
continue;
}
//循环取每个单元格(cell)的数据
for (int cellIndex = 0; cellIndex < hssfRow.getPhysicalNumberOfCells(); cellIndex++) {
HSSFCell hssfCell = hssfRow.getCell(cellIndex);
String value = get2003String(hssfCell);
if (StringUtils.isNotBlank(value)) {
titleRow = row;
JSONObject o = JSONObject.create().put("titleRow", titleRow).put("value", cellIndex).put("text", value);
result.add(o);
}
}
if (titleRow >= 0) {
break;
}
}
return result;
}
/**
* 把单元格的内容转为字符串
*
* @param hssfCell 单元格
* @return 字符串
*/
public static String get2003String(HSSFCell hssfCell) {
if (hssfCell == null) {
return "";
}
int type = hssfCell.getCellType();
if (type == HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {
// 如果是date类型则 ,获取该cell的date值
return new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getJavaDate(hssfCell.getNumericCellValue()));
} else { // 纯数字
return String.valueOf(hssfCell.getNumericCellValue());
}
} else if (type == XSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else {
return hssfCell.getStringCellValue();
}
}
/**
* 获取2003的值
*
* @param sheet
* @param row
* @param col
* @param cell
* @return
*/
public static String get2003CellValue(HSSFSheet sheet, int row, int col, HSSFCell cell) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
Region mergedRegionAt = sheet.getMergedRegionAt(i);
mergedRegionAt.getRowFrom();
// CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = mergedRegionAt.getColumnFrom();
int lastColumn = mergedRegionAt.getColumnTo();
int firstRow = mergedRegionAt.getRowFrom();
int lastRow = mergedRegionAt.getRowTo();
if (row >= firstRow && row <= lastRow) {
if (col >= firstColumn && col <= lastColumn) {
HSSFRow fRow = sheet.getRow(firstRow);
HSSFCell fCell = fRow.getCell(firstColumn);
return get2003String(fCell);
}
}
}
return get2003String(cell);
}
public static Map<String, List> get2003SheetContent(HSSFSheet sheet, int titleRow, JSONObject tableCol) {
Map<String, List> result = new HashMap<String, List>();
Iterator<Map.Entry<String, Object>> iterator = tableCol.iterator();
// List<CellRangeAddress> combineCell = getCombineCell(sheet);
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
result.put(entry.getKey(), new ArrayList());
}
int lastRowNum = sheet.getLastRowNum();
for (int row = titleRow + 1; row <= lastRowNum; row++) {
HSSFRow hssfRow = sheet.getRow(row);
if (hssfRow == null) {
continue;
}
for (Map.Entry<String, List> entry : result.entrySet()) {
String key = entry.getKey();
int col = tableCol.getInt(key);
List value = entry.getValue();
HSSFCell cell = hssfRow.getCell(col);
if (cell != null) {
String cellValue = get2003CellValue(sheet, row, col, cell);
value.add(StringUtils.isBlank(cellValue) ? StringUtils.EMPTY : cellValue);
} else {
value.add(StringUtils.EMPTY);
}
}
}
return result;
}
}

40
src/main/java/com/fr/plugin/decision/ReuseConfigAccessBridge.java

@ -0,0 +1,40 @@
package com.fr.plugin.decision;
import com.fr.db.fun.impl.AbstractDBAccessProvider;
import com.fr.plugin.decision.dao.ReuseDao;
import com.fr.plugin.decision.dao.ReuseEntity;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
public class ReuseConfigAccessBridge extends AbstractDBAccessProvider {
private static DBAccessor dbAccessor = null;
public static DBAccessor getDbAccessor() {
return dbAccessor;
}
@Override
public DAOProvider[] registerDAO() {
return new DAOProvider[]{
new DAOProvider(){
@Override
public Class getEntityClass() {
return ReuseEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return ReuseDao.class;
}
}
};
}
@Override
public void onDBAvailable(DBAccessor dbAccessor) {
ReuseConfigAccessBridge.dbAccessor = dbAccessor;
}
}

29
src/main/java/com/fr/plugin/decision/core/ActionEunm.java

@ -0,0 +1,29 @@
package com.fr.plugin.decision.core;
import com.fr.stable.StringUtils;
public enum ActionEunm {
ADDTO_ACTION("addTo"),
COVER_ACTION("cover"),
CREATE_ACTION("add");
private String value;
private ActionEunm(String value){
this.value = value;
}
public String getValue(){
return value;
}
public static ActionEunm fromTypeName(String value){
for (ActionEunm typeEnum: ActionEunm.values()) {
if(StringUtils.equals(value, typeEnum.getValue())){
return typeEnum;
}
}
return null;
}
}

32
src/main/java/com/fr/plugin/decision/core/ActionFactory.java

@ -0,0 +1,32 @@
package com.fr.plugin.decision.core;
import com.fr.plugin.decision.core.action.AddAction;
import com.fr.plugin.decision.core.action.CoverAction;
import com.fr.plugin.decision.core.action.CreateAction;
import com.fr.plugin.decision.core.action.ExcelDmlAction;
import java.util.HashMap;
import java.util.Map;
public class ActionFactory {
private static Map actionMap = new HashMap();
private static ActionFactory actionFactory = new ActionFactory();
private ActionFactory(){
}
public static ActionFactory getInstance(){
return actionFactory;
}
public ExcelDmlAction create(String type){
return (ExcelDmlAction) actionMap.get(ActionEunm.fromTypeName(type));
}
{
actionMap.put(ActionEunm.ADDTO_ACTION, new AddAction());
actionMap.put(ActionEunm.COVER_ACTION, new CoverAction());
actionMap.put(ActionEunm.CREATE_ACTION,new CreateAction());
}
}

238
src/main/java/com/fr/plugin/decision/core/DML.java

@ -0,0 +1,238 @@
package com.fr.plugin.decision.core;
import com.fr.cache.Attachment;
import com.fr.cache.list.IntList;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.base.DialectKeyConstants;
import com.fr.data.core.db.dialect.base.key.init.table.DialectInitTableParameter;
import com.fr.data.core.db.dml.CreateTable;
import com.fr.data.core.db.dml.Delete;
import com.fr.data.core.db.dml.Table;
import com.fr.data.core.db.tableObject.Column;
import com.fr.data.core.db.tableObject.ColumnSize;
import com.fr.data.dao.*;
import com.fr.file.DatasourceManager;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.stable.StableUtils;
import com.fr.web.AttachmentHelper;
import com.fr.workspace.WorkContext;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
public class DML {
public static void initTable(Dialect dialect, Connection conn, Table table, String connectionName, List<String> tableColName, List<String> tableColLength, List<Integer> tableColType) throws Exception {
FieldColumnMapper[] fieldColumnMappers = new FieldColumnMapper[tableColName.size()];
for (int k=0; k<tableColName.size(); k++){
String[] colLen = tableColLength.get(k).split(",");
ColumnSize columnSize;
if (colLen.length == 1) {
columnSize = new ColumnSize(Integer.parseInt(colLen[0]));
} else {
columnSize = new ColumnSize(Integer.parseInt(colLen[0]), Integer.parseInt(colLen[1]));
}
CommonFieldColumnMapper fieldColumnMapper = new CommonFieldColumnMapper(
tableColName.get(k),
tableColType.get(k),
columnSize);
fieldColumnMappers[k] = fieldColumnMapper;
}
Class clazz = conn.getClass();
ObjectTableMapper objectTableMapper = new ObjectTableMapper(clazz, table, fieldColumnMappers);
// 不校验 table 是否存在
objectTableMapper.applyNoCheckTableObjectCase();
com.fr.data.impl.Connection implconn = DatasourceManager.getInstance().getConnection(connectionName);
ObjectMappingTable objectMappingTable = ObjectMappingTable.createObjectMappingTable(objectTableMapper, new HashMap());
conn.setAutoCommit(false);
dialect.execute(DialectKeyConstants.INIT_TABLE_KEY, new DialectInitTableParameter(
new JDBCDataAccessObjectOperator(implconn, new ObjectTableMapper[]{}),
conn,
new ObjectMappingTable[]{objectMappingTable}));
}
public static void createTable(Dialect dialect, Connection conn, Table table, List<String> tableColName, List<String> tableColLength, List<Integer> tableColType, List<Boolean> tablePrimaryKey) throws SQLException {
CreateTable createTable = new CreateTable(table, dialect);
for (int i=0; i<tableColName.size(); i++) {
Column column = new Column();
column.setName(tableColName.get(i));
column.setValueType(tableColType.get(i));
String[] colLen = tableColLength.get(i).split(",");
if (colLen.length > 1) {
column.setColumnSize(new ColumnSize(Integer.parseInt(colLen[0]), Integer.parseInt(colLen[1])));
} else {
column.setColumnSize(new ColumnSize(Integer.parseInt(tableColLength.get(i))));
}
if (tablePrimaryKey.get(i)) {
column.setPrimaryKey(true);
column.setAllowNull(false);
}
createTable.addColumn(column);
}
PreparedStatement createPs = createTable.createPreparedStatementByValidatedParameters(conn);
createPs.execute();
}
public static int deleteTable(Dialect dialect, Connection conn, Table table) throws SQLException {
Delete delete = new Delete(table, dialect);
PreparedStatement deletePs = delete.createPreparedStatementByValidatedParameters(conn);
return deletePs.executeUpdate();
}
public static void dropTable(Dialect dialect, Connection conn, Table table) throws SQLException {
Drop drop = new Drop(table, dialect);
PreparedStatement dropPs = drop.createPreparedStatementByValidatedParameters(conn);
dropPs.execute();
}
public static PreparedStatement createInsertedPreparedStatement(Dialect dialect, Connection conn, Table table, List<String> tableColName) throws SQLException {
IntList intList = new IntList();
ArrayList list = new ArrayList();
ArrayList list1 = new ArrayList();
int i = 0;
for(int colSize = tableColName.size(); i < colSize; ++i) {
list.add(dialect.column2SQL(tableColName.get(i)));
list1.add("?");
intList.add(i);
}
if (list1.isEmpty()) {
return null;
} else {
String sql = "INSERT INTO " + table.toStatementSQLString(dialect) + " (" + StableUtils.join(list, ",") + ") VALUES (" + StableUtils.join(list1, ",") + ")";
FineLoggerFactory.getLogger().sql("SQL: " + sql);
return conn.prepareStatement(sql);
}
}
public static int execInsertedPreparedStatement(Dialect dialect, Connection conn, Table table,PreparedStatement ps, int rowCount, List<String> tableColName, List<Integer> tableColType, Map<String, List> tableValue) throws SQLException, IOException {
int count = 0;
boolean supportsBatchUpdates = conn.getMetaData().supportsBatchUpdates();
if (JdbcUtils.isHive(conn)) {
return execHiveInsert(dialect, conn, table, ps, rowCount, tableColName, tableColType, tableValue);
}
if (!supportsBatchUpdates) {
return execInsertedPreparedStatementByItem(dialect, conn, table, ps, rowCount, tableColName, tableColType, tableValue);
}
for (int rownum=0; rownum<rowCount; rownum++) {
for (int index=0; index<tableColName.size(); index++) {
int type = tableColType.get(index);
Object value = tableValue.get(tableColName.get(index)).get(rownum);
// excel 中读数 1 会识别为 1.0 , 列格式为[文本]时需要调整下
if(type == 12 && JdbcUtils.isNumeric(value.toString())) {
value = value.toString().split("\\.")[0];
}
DBUtils.applyColumnTypeValue(
dialect,
conn,
table,
null,
null,
ps,
index + 1,
type,
value
);
}
count ++ ;
ps.addBatch();
if(rownum!=0 && rownum%10000==0){
ps.executeBatch();
ps.clearBatch();
}
}
ps.executeBatch();
ps.clearBatch();
return count;
}
public static int execInsertedPreparedStatementByItem(Dialect dialect, Connection conn, Table table,PreparedStatement ps, int rowCount, List<String> tableColName, List<Integer> tableColType, Map<String, List> tableValue) throws SQLException {
int count = 0;
for (int rownum=0; rownum<rowCount; rownum++) {
for (int index=0; index<tableColName.size(); index++) {
int type = tableColType.get(index);
Object value = tableValue.get(tableColName.get(index)).get(rownum);
// excel 中读数 1 会识别为 1.0 , 列格式为[文本]时需要调整下
if(type == 12 && JdbcUtils.isNumeric(value.toString())) {
value = value.toString().split("\\.")[0];
}
DBUtils.applyColumnTypeValue(
dialect,
conn,
table,
null,
null,
ps,
index + 1,
type,
value
);
}
count ++ ;
ps.execute();
}
return count;
}
public static int execHiveInsert(Dialect dialect, Connection conn, Table table,PreparedStatement ps, int rowCount, List<String> tableColName, List<Integer> tableColType, Map<String, List> tableValue){
try {
String txt = hiveInsertCreateTxt(tableValue);
DBUtils.close(ps);
String sql = "LOAD DATA LOCAL INPATH '" + txt +"' OVERWRITE into table " + dialect.table2SQL(table);
FineLoggerFactory.getLogger().info("execHiveInsert insert sql:" + sql);
PreparedStatement hiveInsertPs = conn.prepareStatement(sql);
hiveInsertPs.execute();
FineLoggerFactory.getLogger().info("execHiveInsert:执行正常");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rowCount;
}
public static String hiveInsertCreateTxt(Map<String, List> tableValue) throws IOException {
StringBuffer txtStr = new StringBuffer();
String path = new StringBuilder().append(WorkContext.getCurrent().getPath()).append("/txt/hw_excel_hive").append((int)(Math.random() * 10000)).append(".txt").toString() ;
FineLoggerFactory.getLogger().info("hiveInsert_path: " + path);
File writename = new File(path);
if(!writename.exists()){
writename.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
Set set = tableValue.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
List<String> colItems = (ArrayList<String>) entry.getValue();
for (String item : colItems) {
txtStr.append(item).append("\001");
}
txtStr.deleteCharAt(txtStr.length()-4);
txtStr.append("\n");
}
txtStr.deleteCharAt(txtStr.length()-2);
out.write(txtStr.toString());
out.flush();
out.close();
FineLoggerFactory.getLogger().info("hiveInsert_path: " + path + " 文件创建成功");
return path;
}
}

45
src/main/java/com/fr/plugin/decision/core/Drop.java

@ -0,0 +1,45 @@
package com.fr.plugin.decision.core;
import com.fr.base.TemplateUtils;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dml.AbstractDML;
import com.fr.data.core.db.dml.Table;
import com.fr.log.FineLoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Drop extends AbstractDML {
protected Drop(Table table, Dialect dialect) {
super(table, dialect);
}
@Override
protected PreparedStatement createPreparedStatementByValidatedParameters(Connection connection) throws SQLException {
String dropSQL = TemplateUtils.render("DROP TABLE ${table} ", new String[]{"table"}, new String[]{this.getTable().toStatementSQLString(this.dialect)});
FineLoggerFactory.getLogger().debug(dropSQL.toString());
PreparedStatement preparedStatement = connection.prepareStatement(dropSQL);
return preparedStatement;
}
// todo: executeUpdate 执行 drop 后的返回值
public int execute(Connection connection) throws SQLException {
PreparedStatement preparedStatement = this.createPreparedStatement(connection);
int result;
try {
if (preparedStatement == null) {
return 0;
}
result = preparedStatement.executeUpdate();
} finally {
DBUtils.closeStatement(preparedStatement);
}
return result;
}
}

91
src/main/java/com/fr/plugin/decision/core/ExcelDmlBean.java

@ -0,0 +1,91 @@
package com.fr.plugin.decision.core;
import com.fr.data.core.db.dml.Table;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ExcelDmlBean {
private String connectionName;
private Table table;
private int rowCount;
private Map<String, List> tableValue;
private List<String> tableColName = new ArrayList<>();
private List<String> tableColLength = new ArrayList<>();
private List<Integer> tableColType = new ArrayList<>();
private List<Boolean> tablePrimaryKey = new ArrayList<>();
public ExcelDmlBean(String connectionName, String schema, String tableName, JSONArray tableColItems, Map<String, List> tableValue){
this.connectionName = connectionName;
this.tableValue = tableValue;
for (Object o : tableColItems) {
String colName = ((JSONObject) o).getString("colName");
String colLength = ((JSONObject) o).getString("colLength");
int colType = ((JSONObject) o).getInt("colType");
boolean primaryKey = ((JSONObject) o).getBoolean("primaryKey");
tableColName.add(colName);
tableColType.add(colType);
tableColLength.add(colLength);
tablePrimaryKey.add(primaryKey);
}
table = new Table(schema, tableName);
rowCount = tableValue.get(tableColName.get(0)).size();
}
public List<Boolean> getTablePrimaryKey() {
return tablePrimaryKey;
}
public void setTablePrimaryKey(List<Boolean> tablePrimaryKey) {
this.tablePrimaryKey = tablePrimaryKey;
}
public Table getTable() {
return table;
}
public int getRowCount() {
return rowCount;
}
public List<String> getTableColLength() {
return tableColLength;
}
public String getConnectionName() {
return connectionName;
}
public void setConnectionName(String connectionName) {
this.connectionName = connectionName;
}
public Map<String, List> getTableValue() {
return tableValue;
}
public void setTableValue(Map<String, List> tableValue) {
this.tableValue = tableValue;
}
public List<String> getTableColName() {
return tableColName;
}
public void setTableColName(List<String> tableColName) {
this.tableColName = tableColName;
}
public List<Integer> getTableColType() {
return tableColType;
}
public void setTableColType(List<Integer> tableColType) {
this.tableColType = tableColType;
}
}

56
src/main/java/com/fr/plugin/decision/core/action/AddAction.java

@ -0,0 +1,56 @@
package com.fr.plugin.decision.core.action;
import com.fr.data.core.db.DBUtils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.core.DML;
import java.sql.PreparedStatement;
public class AddAction extends ExcelDmlAction {
public AddAction() {
}
@Override
public JSONObject execute() {
PreparedStatement preparedStatement = null;
JSONObject result = JSONObject.create();
int count = -1;
try {
conn.setAutoCommit(false);
preparedStatement = DML.createInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
excelDmlBean.getTableColName()
);
count = DML.execInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
preparedStatement,
excelDmlBean.getRowCount(),
excelDmlBean.getTableColName(),
excelDmlBean.getTableColType(),
excelDmlBean.getTableValue()
);
conn.commit();
conn.setAutoCommit(true);
result.put("status", "success").put("text", "成功追加数据条数为 "+ count +"条").put("addLink",false);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:AddAction failed !", e.getMessage());
DBUtils.rollback(conn);
e.printStackTrace();
result.put("status", "fail").put("errorText", "追加操作数据插入异常" + e.getLocalizedMessage());
} finally {
DBUtils.close(conn);
DBUtils.close(preparedStatement);
}
return result;
}
}

60
src/main/java/com/fr/plugin/decision/core/action/CoverAction.java

@ -0,0 +1,60 @@
package com.fr.plugin.decision.core.action;
import com.fr.data.core.db.DBUtils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.core.DML;
import java.sql.PreparedStatement;
public class CoverAction extends ExcelDmlAction {
public CoverAction() {
}
@Override
public JSONObject execute() {
PreparedStatement preparedStatement = null;
JSONObject result = JSONObject.create();
int insertCount = 0;
int deleteCount = 0;
try {
conn.setAutoCommit(false);
deleteCount = DML.deleteTable(
dialect,
conn,
excelDmlBean.getTable()
);
preparedStatement = DML.createInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
excelDmlBean.getTableColName()
);
insertCount = DML.execInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
preparedStatement,
excelDmlBean.getRowCount(),
excelDmlBean.getTableColName(),
excelDmlBean.getTableColType(),
excelDmlBean.getTableValue()
);
conn.commit();
conn.setAutoCommit(true);
result.put("status", "success").put("text", "成功删除数据" + deleteCount + "条,插入数据 " + insertCount +"条").put("addLink",false);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:CoverAction failed !", e.getMessage());
DBUtils.rollback(conn);
e.printStackTrace();
result.put("status", "fail").put("errorText", "覆盖操作数据插入异常" + e.getLocalizedMessage());
} finally {
DBUtils.close(conn);
DBUtils.close(preparedStatement);
}
return result;
}
}

67
src/main/java/com/fr/plugin/decision/core/action/CreateAction.java

@ -0,0 +1,67 @@
package com.fr.plugin.decision.core.action;
import com.fr.data.core.db.DBUtils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.core.DML;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CreateAction extends ExcelDmlAction {
public CreateAction() {
}
@Override
public JSONObject execute() {
PreparedStatement preparedStatement = null;
JSONObject result = JSONObject.create();
int count = 0;
try {
conn.setAutoCommit(false);
DML.createTable(
dialect,
conn,
excelDmlBean.getTable(),
excelDmlBean.getTableColName(),
excelDmlBean.getTableColLength(),
excelDmlBean.getTableColType(),
excelDmlBean.getTablePrimaryKey()
);
preparedStatement = DML.createInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
excelDmlBean.getTableColName()
);
count = DML.execInsertedPreparedStatement(
dialect,
conn,
excelDmlBean.getTable(),
preparedStatement,
excelDmlBean.getRowCount(),
excelDmlBean.getTableColName(),
excelDmlBean.getTableColType(),
excelDmlBean.getTableValue()
);
conn.commit();
conn.setAutoCommit(true);
result.put("status", "success").put("text", "表创建正常,成功插入数据" + count + "条").put("addLink",true);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:CreateAction failed !", e.getMessage());
DBUtils.rollback(conn);
try {
DML.dropTable(dialect, conn, excelDmlBean.getTable());
} catch (SQLException e1) {
FineLoggerFactory.getLogger().error("HW_excel导入:dropTable failed !", e.getMessage());
}
e.printStackTrace();
result.put("status", "failed").put("errorText", "新增操作异常" + e.getLocalizedMessage());
} finally {
DBUtils.close(conn);
DBUtils.close(preparedStatement);
}
return result;
}
}

27
src/main/java/com/fr/plugin/decision/core/action/ExcelDmlAction.java

@ -0,0 +1,27 @@
package com.fr.plugin.decision.core.action;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.core.ExcelDmlBean;
import com.fr.plugin.decision.utils.JdbcUtils;
import java.sql.Connection;
public abstract class ExcelDmlAction {
public Connection conn;
public Dialect dialect;
public ExcelDmlBean excelDmlBean;
public ExcelDmlAction(){
}
public void setExcelDmlBean(ExcelDmlBean excelDmlBean) {
this.excelDmlBean = excelDmlBean;
this.conn = JdbcUtils.getConnection(excelDmlBean.getConnectionName());
this.dialect = DialectFactory.generateDialect(conn);
}
public abstract JSONObject execute();
}

142
src/main/java/com/fr/plugin/decision/dao/ExcelLinkService.java

@ -0,0 +1,142 @@
package com.fr.plugin.decision.dao;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.condition.impl.QueryConditionImpl;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.web.utils.WebUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ExcelLinkService {
private static ExcelLinkService instance ;
private ExcelLinkService(){
}
public static synchronized ExcelLinkService getInstance() {
if (instance == null) {
instance = new ExcelLinkService();
}
return instance;
}
public void addLink(final String name, final String datasouces, final String schema, final String tablename, final String createUser){
try {
ExcelMngConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
ExcelMngEntity entity=new ExcelMngEntity();
entity.setId(UUID.randomUUID().toString());
entity.setName(name);
entity.setDatasouces(datasouces);
entity.setSchema(schema);
entity.setTablename(tablename);
entity.setCreateUser(createUser);
daoContext.getDAO(ExcelMngDao.class).add(entity);
return entity;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接添加失败");
e.printStackTrace();
}
}
public void deleteLinkById(final String id){
try {
ExcelMngConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(ExcelMngDao.class).remove(id);
return null;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接删除失败");
e.printStackTrace();
}
}
public void deleteLinkByName(final String name){
try {
ExcelMngConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(ExcelMngDao.class).remove(new QueryConditionImpl().addRestriction(RestrictionFactory.eq("name", name)));
return null;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接删除失败");
e.printStackTrace();
}
}
public ExcelMngEntity getLinkById(final String id){
ExcelMngEntity entity = null;
try {
entity = ExcelMngConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ExcelMngDao.class).findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id",id)));
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接查询失败");
e.printStackTrace();
}
return entity;
}
public ExcelMngEntity getLinkByName(final String name){
ExcelMngEntity entity = null;
try {
entity = ExcelMngConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ExcelMngDao.class).findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name",name)));
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接查询失败");
e.printStackTrace();
}
return entity;
}
public List<ExcelMngEntity> getAllLink(final String key, final String createUser){
List<ExcelMngEntity> entities = new ArrayList<>();
final QueryCondition queryCondition = StringUtils.isBlank(key)? QueryFactory.create().addSort("name"):QueryFactory.create().addSort("name").addRestriction(RestrictionFactory.like("name", key));
try {
if (!UserService.getInstance().isAdmin(createUser)){
queryCondition.addRestriction(RestrictionFactory.eq("createUser", createUser));
}
entities = ExcelMngConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<List<ExcelMngEntity> >() {
@Override
public List<ExcelMngEntity> run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ExcelMngDao.class).find(queryCondition);
}
});
} catch (Exception e){
FineLoggerFactory.getLogger().error("HW_excel导入:查询全部链接异常");
e.printStackTrace();
}
return entities;
}
}

16
src/main/java/com/fr/plugin/decision/dao/ExcelMngDao.java

@ -0,0 +1,16 @@
package com.fr.plugin.decision.dao;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.session.DAOSession;
public class ExcelMngDao extends BaseDAO<ExcelMngEntity> {
public ExcelMngDao(DAOSession daoSession){
super(daoSession);
}
@Override
protected Class<ExcelMngEntity> getEntityClass() {
return ExcelMngEntity.class;
}
}

70
src/main/java/com/fr/plugin/decision/dao/ExcelMngEntity.java

@ -0,0 +1,70 @@
package com.fr.plugin.decision.dao;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
@Entity
@Table(name = "FINE_PLUGIN_HW_EXCEL")
public class ExcelMngEntity extends BaseEntity {
@Column(name="name", unique = true)
private String name;
@Column(name="dataSources")
private String datasouces;
@Column(name="schemaName")
private String schema;
@Column(name="tableName")
private String tablename;
@Column(name="createUser")
private String createUser;
public ExcelMngEntity(){
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setDatasouces(String datasouces){
this.datasouces = datasouces;
}
public String getDatasouces(){
return datasouces;
}
public void setSchema(String schema){
this.schema = schema;
}
public String getSchema(){
return schema;
}
public void setTablename(String tablename){
this.tablename = tablename;
}
public String getTablename(){
return tablename;
}
public void setCreateUser(String createUser){
this.createUser = createUser;
}
public String getCreateUser(){
return createUser;
}
}

15
src/main/java/com/fr/plugin/decision/dao/ReuseDao.java

@ -0,0 +1,15 @@
package com.fr.plugin.decision.dao;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.session.DAOSession;
public class ReuseDao extends BaseDAO<ReuseEntity> {
public ReuseDao(DAOSession daoSession) {
super(daoSession);
}
@Override
protected Class<ReuseEntity> getEntityClass() {
return ReuseEntity.class;
}
}

36
src/main/java/com/fr/plugin/decision/dao/ReuseEntity.java

@ -0,0 +1,36 @@
package com.fr.plugin.decision.dao;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
@Entity
@Table(name = "FINE_PLUGIN_HW_EXCEL_REUSE")
public class ReuseEntity extends BaseEntity {
@Column(name="userName")
private String userName;
@Column(name="linkName")
private String linkName;
public ReuseEntity(){
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLinkName() {
return linkName;
}
public void setLinkName(String linkName) {
this.linkName = linkName;
}
}

104
src/main/java/com/fr/plugin/decision/dao/ReuseService.java

@ -0,0 +1,104 @@
package com.fr.plugin.decision.dao;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.ReuseConfigAccessBridge;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.condition.impl.QueryConditionImpl;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.*;
public class ReuseService {
private static ReuseService instance ;
private ReuseService(){
}
public static synchronized ReuseService getInstance() {
if (instance == null) {
instance = new ReuseService();
}
return instance;
}
public void addUserOnLinkName(final String userNames, final String linkName){
try {
ReuseConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ReuseEntity>() {
@Override
public ReuseEntity run(DAOContext daoContext) throws Exception {
//for (String user:userNames){
ReuseEntity entity = new ReuseEntity();
entity.setId(UUID.randomUUID().toString());
entity.setLinkName(linkName);
entity.setUserName(userNames);
daoContext.getDAO(ReuseDao.class).add(entity);
//}
return null;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:复用添加用户失败");
e.printStackTrace();
}
}
public void deleteUserOnLinkName(final String userNames, final String linkName){
try {
ReuseConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ReuseEntity>() {
@Override
public ReuseEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(ReuseDao.class).remove(new QueryConditionImpl().addRestriction(RestrictionFactory.eq("linkName", linkName)).addRestriction(RestrictionFactory.eq("userName",userNames)));
return null;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:链接删除失败");
e.printStackTrace();
}
}
public List<ReuseEntity> getUserByLinkName(final String linkName){
List<ReuseEntity> entities = new ArrayList<>();
final QueryCondition queryCondition = QueryFactory.create().addSort("userName").addRestriction(RestrictionFactory.eq("linkName", linkName));
try {
entities = ReuseConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<List<ReuseEntity> >() {
@Override
public List<ReuseEntity> run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ReuseDao.class).find(queryCondition);
}
});
} catch (Exception e){
FineLoggerFactory.getLogger().error("HW_excel导入:getUserByLinkName异常");
e.printStackTrace();
}
return entities;
}
public List<ReuseEntity> getLinkByUserName(final String userName){
List<ReuseEntity> entities = new ArrayList<>();
final QueryCondition queryCondition = QueryFactory.create().addSort("linkName").addRestriction(RestrictionFactory.eq("userName", userName));
try {
entities = ReuseConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<List<ReuseEntity> >() {
@Override
public List<ReuseEntity> run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ReuseDao.class).find(queryCondition);
}
});
} catch (Exception e){
FineLoggerFactory.getLogger().error("HW_excel导入:getLinkByUserName异常");
e.printStackTrace();
}
return entities;
}
}

41
src/main/java/com/fr/plugin/decision/dialect/DialectCreator.java

@ -0,0 +1,41 @@
package com.fr.plugin.decision.dialect;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.dialect.gauss.GaussDialectConsummate;
import com.fr.plugin.decision.dialect.hive.HiveDialectConsummate;
import com.fr.plugin.decision.dialect.postgre.PostgreDialectConsummate;
import com.fr.plugin.decision.dialect.sybase.SybaseDialectConsummate;
import com.fr.stable.StringUtils;
import com.fr.stable.UrlDriver;
import com.fr.stable.fun.impl.AbstractDialectCreator;
import java.sql.Connection;
import java.sql.SQLException;
public class DialectCreator extends AbstractDialectCreator {
@Override
public Class<?> generate(UrlDriver urlDriver) {
return null;
}
@Override
public Class<?> generate(Connection connection) {
try {
String DatabaseProductName = connection.getMetaData().getDatabaseProductName().trim().toUpperCase();
FineLoggerFactory.getLogger().debug("DialectCreator:" + DatabaseProductName);
if (StringUtils.contains(DatabaseProductName,"POSTGRE")){
return PostgreDialectConsummate.class;
} else if (StringUtils.contains(DatabaseProductName,"SYBASE")){
return SybaseDialectConsummate.class;
} else if (StringUtils.contains(DatabaseProductName,"ZENITH")){ // gauss
return GaussDialectConsummate.class;
} else if (StringUtils.contains(DatabaseProductName,"HIVE")){
return HiveDialectConsummate.class;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

58
src/main/java/com/fr/plugin/decision/dialect/gauss/GaussDialectColumnType2SQLExecutor.java

@ -0,0 +1,58 @@
package com.fr.plugin.decision.dialect.gauss;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.base.key.column.typetosql.AbstractDialectColumnType2SQLExecutor;
import com.fr.data.core.db.dialect.base.key.column.typetosql.DialectColumnType2SQLParameter;
import com.fr.data.core.db.dialect.util.DialectUtils;
public class GaussDialectColumnType2SQLExecutor extends AbstractDialectColumnType2SQLExecutor {
public GaussDialectColumnType2SQLExecutor(){
}
@Override
public String execute(DialectColumnType2SQLParameter dialectColumnType2SQLParameter, Dialect dialect) {
int columnType = dialectColumnType2SQLParameter.getColumnType();
String columnSize = dialectColumnType2SQLParameter.getParameter();
switch(columnType) {
case -7:
return "bit";
case -5:
return "numeric(" + columnSize + ")";
case -4:
return "image";
case -3:
return "varbinary(" + columnSize + ")";
case -2:
return "binary(" + columnSize + ")";
case -1:
return "text";
case 1:
return "char(" + columnSize + ")";
case 2:
return "numeric(" + columnSize + ")";
case 3:
return "decimal(" + columnSize + ")";
case 4:
return "int";
case 8:
return "float";
case 12:
return "varchar(" + columnSize + ")";
case 16:
return "boolean";
case 91:
return "datetime";
case 92:
return "datetime";
case 93:
return "datetime";
case 2004:
return "image";
case 2005:
return "text";
default:
return DialectUtils.getTypeName(dialectColumnType2SQLParameter.getColumnType());
}
}
}

15
src/main/java/com/fr/plugin/decision/dialect/gauss/GaussDialectConsummate.java

@ -0,0 +1,15 @@
package com.fr.plugin.decision.dialect.gauss;
import com.fr.data.core.db.dialect.GaussDBDialect;
import com.fr.data.core.db.dialect.base.DialectKeyConstants;
import com.fr.data.core.db.dialect.base.key.column.tosql.DialectColumn2SQLWithDoubleQuoteExecutor;
import com.fr.data.core.db.dialect.base.key.topn.KylinDialectCreateTOPNSQLExecutor;
public class GaussDialectConsummate extends GaussDBDialect {
public GaussDialectConsummate(){
super();
this.putExecutor(DialectKeyConstants.COLUMN_2_SQL_KEY, new DialectColumn2SQLWithDoubleQuoteExecutor());
this.putExecutor(DialectKeyConstants.COLUMN_TYPE_2_SQL_KEY, new GaussDialectColumnType2SQLExecutor());
this.putExecutor(DialectKeyConstants.CREATE_TOP_N_SQL_KEY, new KylinDialectCreateTOPNSQLExecutor());
}
}

50
src/main/java/com/fr/plugin/decision/dialect/hive/HiveDialectColumnType2SQLExecutor.java

@ -0,0 +1,50 @@
package com.fr.plugin.decision.dialect.hive;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.base.key.column.typetosql.AbstractDialectColumnType2SQLExecutor;
import com.fr.data.core.db.dialect.base.key.column.typetosql.DialectColumnType2SQLParameter;
import com.fr.data.core.db.dialect.util.DialectUtils;
public class HiveDialectColumnType2SQLExecutor extends AbstractDialectColumnType2SQLExecutor {
public HiveDialectColumnType2SQLExecutor(){
}
@Override
public String execute(DialectColumnType2SQLParameter dialectColumnType2SQLParameter, Dialect dialect) {
int columnType = dialectColumnType2SQLParameter.getColumnType();
String columnSize = dialectColumnType2SQLParameter.getParameter();
switch(columnType) {
case -7:
return "boolean";
case 1:
return "char(" + columnSize + ")";
case 2:
return "bigint";
case 3:
return "decimal(" + columnSize + ")";
case 4:
return "int";
case 7:
return "float";
case 8:
return "float";
case 12:
return "varchar(" + columnSize + ")";
case 16:
return "boolean";
case 91:
return "date";
case 92:
return "date";
case 93:
return "date";
case 2004:
return "image";
case 2005:
return "text";
default:
return DialectUtils.getTypeName(columnType);
}
}
}

17
src/main/java/com/fr/plugin/decision/dialect/hive/HiveDialectConsummate.java

@ -0,0 +1,17 @@
package com.fr.plugin.decision.dialect.hive;
import com.fr.data.core.db.dialect.HiveDialect;
import com.fr.data.core.db.dialect.base.DialectKeyConstants;
import com.fr.data.core.db.dialect.base.key.column.tosql.DialectColumn2SQLWithBackQuoteExecutor;
import com.fr.data.core.db.dialect.base.key.init.column.DialectInitColumnUnSupportNullExecutor;
import com.fr.data.core.db.dialect.base.key.topn.KylinDialectCreateTOPNSQLExecutor;
public class HiveDialectConsummate extends HiveDialect {
public HiveDialectConsummate(){
super();
this.putExecutor(DialectKeyConstants.COLUMN_2_SQL_KEY, new DialectColumn2SQLWithBackQuoteExecutor());
this.putExecutor(DialectKeyConstants.COLUMN_TYPE_2_SQL_KEY, new HiveDialectColumnType2SQLExecutor());
this.putExecutor(DialectKeyConstants.CREATE_TOP_N_SQL_KEY, new KylinDialectCreateTOPNSQLExecutor());
this.putExecutor(DialectKeyConstants.INIT_COLUMN_KEY, new DialectInitColumnUnSupportNullExecutor());
}
}

13
src/main/java/com/fr/plugin/decision/dialect/postgre/PostgreDialectConsummate.java

@ -0,0 +1,13 @@
package com.fr.plugin.decision.dialect.postgre;
import com.fr.data.core.db.dialect.PostgreSQLDialect;
import com.fr.data.core.db.dialect.base.DialectKeyConstants;
import com.fr.data.core.db.dialect.base.key.topn.KylinDialectCreateTOPNSQLExecutor;
public class PostgreDialectConsummate extends PostgreSQLDialect {
public PostgreDialectConsummate(){
super();
this.putExecutor(DialectKeyConstants.CREATE_TOP_N_SQL_KEY, new KylinDialectCreateTOPNSQLExecutor());
}
}

12
src/main/java/com/fr/plugin/decision/dialect/sybase/SybaseDialectConsummate.java

@ -0,0 +1,12 @@
package com.fr.plugin.decision.dialect.sybase;
import com.fr.data.core.db.dialect.SybaseDialect;
import com.fr.data.core.db.dialect.base.DialectKeyConstants;
import com.fr.data.core.db.dialect.base.key.column.tosql.DialectColumn2SQLWithDoubleQuoteExecutor;
public class SybaseDialectConsummate extends SybaseDialect {
public SybaseDialectConsummate(){
super();
this.putExecutor(DialectKeyConstants.COLUMN_2_SQL_KEY, new DialectColumn2SQLWithDoubleQuoteExecutor());
}
}

53
src/main/java/com/fr/plugin/decision/http/AddLinkHttpHandler.java

@ -0,0 +1,53 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.dao.ExcelLinkService;
import com.fr.plugin.decision.dao.ExcelMngDao;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
public class AddLinkHttpHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/addlink";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
final String name = WebUtils.getHTTPRequestParameter(req,"name");
final String datasouces = WebUtils.getHTTPRequestParameter(req,"datasouces");
final String schema = WebUtils.getHTTPRequestParameter(req,"schema");
final String tablename = WebUtils.getHTTPRequestParameter(req,"tablename");
final String createUser = UserService.getInstance().getCurrentUserIdFromCookie(req);
try {
ExcelLinkService.getInstance().addLink(name, datasouces, schema, tablename, createUser);
WebUtils.printAsJSON(res, new JSONObject().put("status","success"));
return;
} catch (Exception e) {
e.printStackTrace();
WebUtils.printAsJSON(res, new JSONObject().put("status","fail"));
}
}
}

73
src/main/java/com/fr/plugin/decision/http/DeleteLinkHttpHandle.java

@ -0,0 +1,73 @@
package com.fr.plugin.decision.http;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.data.core.db.dml.Table;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.core.DML;
import com.fr.plugin.decision.dao.ExcelLinkService;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.Statement;
public class
DeleteLinkHttpHandle extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/delete";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
final String id = WebUtils.getHTTPRequestParameter(req,"id");
ExcelMngEntity entity = ExcelLinkService.getInstance().getLinkById(id);
if (entity == null){
WebUtils.printAsJSON(res,new JSONObject().put("status","fail"));
FineLoggerFactory.getLogger().error("HW_excel导入:链接根据Id查询结果为空");
return;
}
String connection = entity.getDatasouces();
String tableName = entity.getTablename();
String schema = entity.getSchema();
Connection conn = null;
try {
conn = JdbcUtils.getConnection(connection);
Dialect dialect = DialectFactory.generateDialect(conn);
Table table = new Table(schema, tableName);
DML.deleteTable(dialect, conn, table);
FineLoggerFactory.getLogger().info("表删除成功");
ExcelLinkService.getInstance().deleteLinkById(id);
WebUtils.printAsJSON(res,new JSONObject().put("status","success"));
} catch (Exception e) {
e.printStackTrace();
FineLoggerFactory.getLogger().info("表删除失败");
WebUtils.printAsJSON(res, new JSONObject().put("status","fail"));
} finally {
DBUtils.close(conn);
}
}
}

43
src/main/java/com/fr/plugin/decision/http/GetAllUserListHandler.java

@ -0,0 +1,43 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.bean.user.UserSearchBean;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.utils.HttpUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class GetAllUserListHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/getAllUserList";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
try {
String adminId = UserService.getInstance().getAdminUserNameList().get(0);
UserSearchBean userSearchBean = HttpUtils.readObject(req, UserSearchBean.class);
Map<String, Object> userList = UserService.getInstance().getAllUsers(adminId, userSearchBean,false);
WebUtils.printAsJSON(res, new JSONObject().put("status", "success").put("data", userList));
} catch (Exception e) {
e.printStackTrace();
WebUtils.printAsJSON(res, new JSONObject().put("status", "fail"));
}
}
}

53
src/main/java/com/fr/plugin/decision/http/GetAuthUserByLinkNameHandler.java

@ -0,0 +1,53 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.dao.ReuseEntity;
import com.fr.plugin.decision.dao.ReuseService;
import com.fr.plugin.decision.utils.HttpUtils;
import com.fr.stable.StringUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
public class GetAuthUserByLinkNameHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/getAuthUserList";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
String linkName = HttpUtils.readJson(req).getString("linkName");
if (StringUtils.isBlank(linkName)){
WebUtils.printAsJSON(res, new JSONObject().put("status", "fail"));
return;
}
JSONArray result = new JSONArray();
try {
List<ReuseEntity> entities = ReuseService.getInstance().getUserByLinkName(linkName);
for (ReuseEntity entity : entities) {
result.add(entity.getUserName());
}
WebUtils.printAsJSON(res, new JSONObject().put("status", "success").put("data", result));
} catch (Exception e) {
WebUtils.printAsJSON(res, new JSONObject().put("status", "fail"));
}
}
}

62
src/main/java/com/fr/plugin/decision/http/GetSchemaHttpHandler.java

@ -0,0 +1,62 @@
package com.fr.plugin.decision.http;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.stable.StringUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetSchemaHttpHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/getSchema";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
String connectionName = WebUtils.getHTTPRequestParameter(req, "connectionName");
Connection conn = null;
JSONArray result = new JSONArray();
// schema 添加一条为空的缺省选项
result.add(new JSONObject().put("value", "缺省").put("text","缺省"));
try{
conn = JdbcUtils.getConnection(connectionName);
Dialect dialect = DialectFactory.generateDialect(conn);
String[] schemaArray = dialect.getSchemas(conn);
for (int i=0; i<schemaArray.length; i++){
result.add(JSONObject.create().put("value", schemaArray[i]).put("text", schemaArray[i]));
}
WebUtils.printAsJSON(res, new JSONObject().put("status", "success").put("data", result));
} catch (Exception e){
e.printStackTrace();
WebUtils.printAsJSON(res, new JSONObject().put("status", "fail"));
} finally {
DBUtils.close(conn);
}
}
}

58
src/main/java/com/fr/plugin/decision/http/IfTableExistHttpHandler.java

@ -0,0 +1,58 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.Statement;
public class IfTableExistHttpHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/iftableexist";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
String connection = WebUtils.getHTTPRequestParameter(req, "connection");
String tableName = URLDecoder.decode(WebUtils.getHTTPRequestParameter(req, "tableName"));
Connection conn = JdbcUtils.getConnection(connection);
Statement smt = null;
try {
if (conn == null){
FineLoggerFactory.getLogger().error("HW_excel导入:" + connection + "数据连接创建失败");
WebUtils.printAsJSON(res,new JSONObject().put("status","fail").put("errorText",connection + "数据连接创建失败,请检查改数据连接是否正常!"));
return;
}
smt = conn.createStatement();
smt.executeQuery("select count(1) from " + tableName);
// 能正常执行说明表已存在,返回fail
FineLoggerFactory.getLogger().error("HW_excel导入:" + tableName + "已存在");
WebUtils.printAsJSON(res,new JSONObject().put("status","fail").put("errorText","表" + tableName + "已存在,请重新输入表名!"));
} catch (Exception e) {
WebUtils.printAsJSON(res,new JSONObject().put("status","success"));
} finally {
JdbcUtils.closeConn(conn,null, smt);
}
}
}

66
src/main/java/com/fr/plugin/decision/http/QueryLinkHttpHandle.java

@ -0,0 +1,66 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.dao.*;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
public class QueryLinkHttpHandle extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/querylink";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
boolean containReuse = WebUtils.getHTTPRequestBoolParameter(req,"containReuse");
final String key = WebUtils.getHTTPRequestParameter(req,"key");
final String createUser = UserService.getInstance().getCurrentUserIdFromCookie(req);
JSONArray result = JSONArray.create();
try {
List<ExcelMngEntity> entities = ExcelLinkService.getInstance().getAllLink(key, createUser);
List<ReuseEntity> reuseEntities = ReuseService.getInstance().getLinkByUserName(createUser);
for (ExcelMngEntity entity : entities) {
result.add(new JSONObject().put("id",entity.getId()).put("name",entity.getName()).put("create","true"));
}
if (containReuse) {
for (ReuseEntity entity: reuseEntities) {
result.add(new JSONObject().put("id",entity.getId()).put("name",entity.getLinkName()).put("create","false"));
}
}
WebUtils.printAsJSON(res,new JSONObject().put("data",result));
return;
} catch (Exception e) {
e.printStackTrace();
WebUtils.printAsJSON(res,new JSONObject().put("status","fail"));
}
}
}

50
src/main/java/com/fr/plugin/decision/http/QueryTableColAttrHttpHandle.java

@ -0,0 +1,50 @@
package com.fr.plugin.decision.http;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.dao.ExcelLinkService;
import com.fr.plugin.decision.dao.ExcelMngDao;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
public class QueryTableColAttrHttpHandle extends QueryTableDataHttpHandle {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/querycolattr";
}
@Override
public boolean isPublic() {
return false;
}
@Override
protected void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) throws Exception {
setQueryCount(1);
super.deal(req, res, para, result);
}
}

125
src/main/java/com/fr/plugin/decision/http/QueryTableDataHttpHandle.java

@ -0,0 +1,125 @@
package com.fr.plugin.decision.http;
import com.fr.data.core.db.ColumnInformation;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.data.core.db.dml.Table;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.dao.ExcelMngDao;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.plugin.decision.request.handler.HWAbstractHandler;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class QueryTableDataHttpHandle extends HWAbstractHandler {
private int queryCount = 5000;
private JSONObject para ;
private JSONObject result ;
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/querydata";
}
@Override
public boolean isPublic() {
return false;
}
public int getQueryCount() {
return queryCount;
}
public void setQueryCount(int queryCount) {
this.queryCount = queryCount;
}
@Override
protected void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) throws Exception {
final String name = para.getString("name");
ExcelMngEntity entity = null;
try {
entity = ExcelMngConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ExcelMngDao.class).findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name",name)));
}
});
} catch (Exception e) {
e.printStackTrace();
WebUtils.printAsJSON(res,new JSONObject().put("status","fail"));
}
String connection = entity.getDatasouces();
String tableName = entity.getTablename();
String schema = entity.getSchema();
Connection conn = null;
Statement smt = null;
List<String> primaryKeyCol = new ArrayList<>();
try {
conn = JdbcUtils.getConnection(connection);
smt = conn.createStatement();
Dialect dialect = DialectFactory.generateDialect(conn);
Table table = new Table(schema, tableName);
ResultSet resultSet = smt.executeQuery(dialect.getTopNRowSql(queryCount, table));
ColumnInformation[] columnInformations = dialect.getColumnInformation(conn, resultSet, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY);
/*
* catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列
* schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%");
* table - 表名称;可包含单字符通配符("_"),或多字符通配符("%");
*/
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet primaryKeysResult = databaseMetaData.getPrimaryKeys(null, schema, tableName);
while(primaryKeysResult.next()){
primaryKeyCol.add(primaryKeysResult.getString(4));
}
JSONArray tableData = JdbcUtils.formatRsToTableData(resultSet);
JSONArray colAttr = JdbcUtils.formatRs2ColAttr(columnInformations);
JdbcUtils.addPrimaryKeyColAttr(colAttr, primaryKeyCol);
result.put(SUCCESS,"success").put("data",
new JSONObject()
.put("tableData", tableData)
.put("colAttr", colAttr)
.put("tableAttr", new JSONObject()
.put("connection", connection)
.put("schema", schema)
.put("tableName", tableName)
.put("aliasName", name)
)
);
} catch (Exception e){
e.printStackTrace();
} finally {
DBUtils.close(smt);
DBUtils.close(conn);
}
}
}

65
src/main/java/com/fr/plugin/decision/http/RenameHttpHandle.java

@ -0,0 +1,65 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.ExcelMngConfigAccessBridge;
import com.fr.plugin.decision.dao.ExcelMngDao;
import com.fr.plugin.decision.dao.ExcelMngEntity;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RenameHttpHandle extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/rename";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
final String name = WebUtils.getHTTPRequestParameter(req, "name");
final String id = WebUtils.getHTTPRequestParameter(req,"id");
try {
final ExcelMngEntity entity = ExcelMngConfigAccessBridge.getDbAccessor().runQueryAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(ExcelMngDao.class).findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id",id)));
}
});
entity.setName(name);
ExcelMngConfigAccessBridge.getDbAccessor().runDMLAction(new DBAction<ExcelMngEntity>() {
@Override
public ExcelMngEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(ExcelMngDao.class).update(entity);
return null;
}
});
WebUtils.printAsJSON(res,new JSONObject().put("status","success"));
return;
} catch (Exception e) {
e.printStackTrace();
WebUtils.printAsJSON(res,new JSONObject().put("status","fail"));
}
}
}

41
src/main/java/com/fr/plugin/decision/http/UpdateLinkAuthHandler.java

@ -0,0 +1,41 @@
package com.fr.plugin.decision.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.dao.ReuseService;
import com.fr.plugin.decision.utils.HttpUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateLinkAuthHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/excelmng/updateLinkAuth";
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
JSONObject para = HttpUtils.readJson(req);
boolean isAdd = para.getBoolean("auth");
if (isAdd) {
ReuseService.getInstance().addUserOnLinkName(para.getString("userName"), para.getString("linkName"));
} else {
ReuseService.getInstance().deleteUserOnLinkName(para.getString("userName"), para.getString("linkName"));
}
WebUtils.printAsJSON(res, new JSONObject().put("status","success"));
}
}

23
src/main/java/com/fr/plugin/decision/request/HWHandlerProvider.java

@ -0,0 +1,23 @@
package com.fr.plugin.decision.request;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
import com.fr.plugin.decision.request.handler.ExcelFiledHandler;
import com.fr.plugin.decision.request.handler.ExcelSheetCountHandler;
import com.fr.plugin.decision.request.handler.HWFileUploadHander;
import com.fr.plugin.decision.request.handler.TableDataImport;
/**
* created by ezreal 2020/1/12
*/
public class HWHandlerProvider extends AbstractHttpHandlerProvider {
@Override
public HttpHandler[] registerHandlers() {
return new HttpHandler[]{
new HWFileUploadHander(),
new ExcelSheetCountHandler(),
new ExcelFiledHandler(),
new TableDataImport()
};
}
}

26
src/main/java/com/fr/plugin/decision/request/HWURLAliasProvider.java

@ -0,0 +1,26 @@
package com.fr.plugin.decision.request;
import com.fr.decision.fun.impl.AbstractURLAliasProvider;
import com.fr.decision.webservice.url.alias.URLAlias;
import com.fr.decision.webservice.url.alias.URLAliasFactory;
import com.fr.plugin.decision.request.handler.ExcelFiledHandler;
import com.fr.plugin.decision.request.handler.ExcelSheetCountHandler;
import com.fr.plugin.decision.request.handler.HWFileUploadHander;
import com.fr.plugin.decision.request.handler.TableDataImport;
/**
* created by ezreal 2020/1/12
*/
public class HWURLAliasProvider extends AbstractURLAliasProvider {
@Override
public URLAlias[] registerAlias() {
return new URLAlias[]{
URLAliasFactory.createPluginAlias(HWFileUploadHander.PATH, HWFileUploadHander.PATH,true),
URLAliasFactory.createPluginAlias(ExcelSheetCountHandler.PATH,ExcelSheetCountHandler.PATH,false),
URLAliasFactory.createPluginAlias(ExcelFiledHandler.PATH,ExcelFiledHandler.PATH,false),
URLAliasFactory.createPluginAlias(TableDataImport.PATH,TableDataImport.PATH,false),
};
}
}

62
src/main/java/com/fr/plugin/decision/request/handler/ExcelFiledHandler.java

@ -0,0 +1,62 @@
package com.fr.plugin.decision.request.handler;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.HWUtils;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.poi.hssf.usermodel.HSSFSheet;
import com.fr.third.org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFSheet;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* created by ezreal 2020/1/12
*/
public class ExcelFiledHandler extends HWAbstractHandler {
public static final String PATH = "/hw/excel/filed";
private final int MAX_ROW = 1000000;
@Override
public String getPath() {
return PATH;
}
@Override
protected void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) {
String attachId = para.getString("attachId");
String fileName = para.getString("fileName", StringUtils.EMPTY);
if (fileName.endsWith(".xlsx")) {
XSSFWorkbook sheets = HWUtils.getExcelWork(attachId);
if (sheets != null) {
int sheetNo = para.getInt("sheetNo");
XSSFSheet xssfSheet = sheets.getSheetAt(sheetNo);
int count = xssfSheet.getLastRowNum();//总行数
if (count >= MAX_ROW) {//大于最大行数就提示
result.put("msg", "数据大于" + MAX_ROW + "行");
return;
}
JSONArray data = HWUtils.getSheetFiled(xssfSheet);
result.put(SUCCESS, true).put("data", data);
}
} else if (fileName.endsWith(".xls")) {
HSSFWorkbook excel2003Work = HWUtils.getExcel2003Work(attachId);
if (excel2003Work != null) {
int sheetNo = para.getInt("sheetNo");
HSSFSheet sheet = excel2003Work.getSheetAt(sheetNo);
int count = sheet.getLastRowNum();//总行数
if (count >= MAX_ROW) {//大于最大行数就提示
result.put("msg", "数据大于" + MAX_ROW + "行");
return;
}
JSONArray data = HWUtils.get2003SheetFiled(sheet);
result.put(SUCCESS, true).put("data", data);
}
}
}
}

66
src/main/java/com/fr/plugin/decision/request/handler/ExcelSheetCountHandler.java

@ -0,0 +1,66 @@
package com.fr.plugin.decision.request.handler;
import com.fr.cache.Attachment;
import com.fr.cache.AttachmentSource;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.decision.HWUtils;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
* created by ezreal 2020/1/12
*/
public class ExcelSheetCountHandler extends HWAbstractHandler {
public static final String PATH = "/hw/excel/sheet";
@Override
public String getPath() {
return PATH;
}
@Override
protected void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) {
try {
String attachId = para.getString("attachId");
String fileName = para.getString("fileName", StringUtils.EMPTY);
int count = 1;
JSONArray data = JSONArray.create();
if (fileName.endsWith(".xlsx")) {
XSSFWorkbook sheets = HWUtils.getExcelWork(attachId);
if (sheets != null) {
count = sheets.getNumberOfSheets();
for (int i = 0; i < count; i++) {
JSONObject object = JSONObject.create();
object.put("value", i).put("text", sheets.getSheetName(i));
data.add(object);
}
result.put(SUCCESS, true).put("data", data);
}
} else if (fileName.endsWith(".xls")) {
HSSFWorkbook excel2003Work = HWUtils.getExcel2003Work(attachId);
if (excel2003Work != null) {
count = excel2003Work.getNumberOfSheets();
for (int i = 0; i < count; i++) {
JSONObject object = JSONObject.create();
object.put("value", i).put("text", excel2003Work.getSheetName(i));
data.add(object);
}
result.put(SUCCESS, true).put("data", data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

64
src/main/java/com/fr/plugin/decision/request/handler/HWAbstractHandler.java

@ -0,0 +1,64 @@
package com.fr.plugin.decision.request.handler;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
/**
* created by ezreal 2020/1/12
*/
public abstract class HWAbstractHandler extends BaseHttpHandler {
public static String SUCCESS="success";
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public boolean isPublic() {
return false;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
JSONObject para=getParaJSON(req);
JSONObject result=JSONObject.create().put(SUCCESS,false);
deal(req,res,para,result);
WebUtils.printAsJSON(res,result);
}
protected abstract void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) throws Exception;
/**
* 获取json参数方法
*
* @param req 请求
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public JSONObject getParaJSON(HttpServletRequest req) throws IOException, UnsupportedEncodingException {
JSONObject result = JSONObject.create();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
return new JSONObject(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

40
src/main/java/com/fr/plugin/decision/request/handler/HWFileUploadHander.java

@ -0,0 +1,40 @@
package com.fr.plugin.decision.request.handler;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.attach.AttachmentService;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* created by ezreal 2020/1/12
*/
public class HWFileUploadHander extends BaseHttpHandler {
public static final String PATH = "/hw/file/upload";
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return PATH;
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
int width = WebUtils.getHTTPRequestIntParameter(req, "width");
int height = WebUtils.getHTTPRequestIntParameter(req, "height");
String fileName = WebUtils.getHTTPRequestParameter(req, "filename");
AttachmentService.getInstance().uploadAttach(req, res, width, height, fileName);
}
}

91
src/main/java/com/fr/plugin/decision/request/handler/TableDataImport.java

@ -0,0 +1,91 @@
package com.fr.plugin.decision.request.handler;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.HWUtils;
import com.fr.plugin.decision.core.*;
import com.fr.plugin.decision.core.action.ExcelDmlAction;
import com.fr.plugin.decision.dao.ExcelLinkService;
import com.fr.plugin.decision.utils.JdbcUtils;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.poi.hssf.usermodel.HSSFSheet;
import com.fr.third.org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFSheet;
import com.fr.third.v2.org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* created by ezreal 2020/1/13
*/
public class TableDataImport extends HWAbstractHandler {
public static final String PATH="/hw/table/import";
@Override
protected void deal(HttpServletRequest req, HttpServletResponse res, JSONObject para, JSONObject result) throws Exception {
JSONArray items=para.getJSONArray("items");
JSONObject sheetInfo=para.getJSONObject("sheetInfo");
String attachId=sheetInfo.getString("attachId");
String fileName=sheetInfo.getString("fileName");
int sheetNo=sheetInfo.getInt("sheetNo");
Map<String, List> values=new HashMap<String, List>();
if(fileName.endsWith(".xlsx")){
XSSFWorkbook excelWork = HWUtils.getExcelWork(attachId);
if(excelWork!=null){
XSSFSheet sheet = excelWork.getSheetAt(sheetNo);
JSONObject tableCol=JSONObject.create();
for(int i=0;i<items.length();i++){
JSONObject o=items.getJSONObject(i);
tableCol.put(o.getString("colName"),o.getInt("excelCol"));
}
values=HWUtils.getSheetContent(sheet, sheetInfo.getInt("titleRow"), tableCol);
}
}else if(fileName.endsWith(".xls")){
HSSFWorkbook excel2003Work = HWUtils.getExcel2003Work(attachId);
if(excel2003Work!=null){
HSSFSheet sheetAt = excel2003Work.getSheetAt(sheetNo);
JSONObject tableCol=JSONObject.create();
for(int i=0;i<items.length();i++){
JSONObject o=items.getJSONObject(i);
tableCol.put(o.getString("colName"),o.getInt("excelCol"));
}
values=HWUtils.get2003SheetContent(sheetAt,sheetInfo.getInt("titleRow"),tableCol);
}
}
final String createUser = UserService.getInstance().getCurrentUserIdFromCookie(req);
String connection = para.getString("connection");
String name = para.getString("aliasName");
String schema = para.getString("schema");
String tableName = para.getString("tableName");
Connection conn = JdbcUtils.getConnection(connection);
if (conn == null){
FineLoggerFactory.getLogger().error("HW_excel导入:数据链接 " + connection + " 获取异常" );
WebUtils.printAsJSON(res,new JSONObject().put("status","fail").put("errorText","获取数据连接异常"));
return;
}
ExcelDmlAction excelDmlAction = ActionFactory.getInstance().create( para.getString("infoId"));
excelDmlAction.setExcelDmlBean( new ExcelDmlBean(connection, schema, tableName, items, values) );
JSONObject dmlResult = excelDmlAction.execute();
if (StringUtils.equals("success", dmlResult.getString("status")) && dmlResult.getBoolean("addLink")) {
ExcelLinkService.getInstance().addLink(name, connection, schema, tableName, createUser);
FineLoggerFactory.getLogger().info("HW_excel导入:FineDB 新增数据成功" + name);
}
WebUtils.printAsJSON(res, dmlResult);
}
@Override
public String getPath() {
return PATH;
}
}

25
src/main/java/com/fr/plugin/decision/utils/HttpUtils.java

@ -0,0 +1,25 @@
package com.fr.plugin.decision.utils;
import com.fr.json.JSONObject;
import com.fr.third.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
public class HttpUtils {
public static <T> T readObject(HttpServletRequest req, Class<T> cls) throws Exception {
ObjectMapper map = new ObjectMapper();
return map.readValue(req.getInputStream(), cls);
}
public static JSONObject readJson(HttpServletRequest request) throws IOException {
BufferedReader bufferReader = new BufferedReader(request.getReader());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufferReader.readLine()) != null) {
sb.append(line);
}
return new JSONObject(sb.toString());
}
}

566
src/main/java/com/fr/plugin/decision/utils/JdbcUtils.java

@ -0,0 +1,566 @@
package com.fr.plugin.decision.utils;
import com.fr.data.core.db.ColumnInformation;
import com.fr.data.core.db.DBUtils;
import com.fr.data.impl.NameDatabaseConnection;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.dialect.hive.HiveDialectConsummate;
import com.fr.report.core.A.S;
import com.fr.stable.StringUtils;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JdbcUtils {
public static Connection getConnection(String connection) {
NameDatabaseConnection db = new NameDatabaseConnection(connection);
try {
Connection conn = db.createConnection();
return conn;
} catch (Exception e) {
FineLoggerFactory.getLogger().error("HW_excel导入:" + connection + "数据连接创建失败");
}
return null;
}
public static String getCreateSql(int type, String tableName, JSONArray items){
String createSql = "";
switch (type){
case 1:
createSql = getOracleCreateSql(items,tableName);
break;
case 2:
createSql = getSqlServerCreateSql(items,tableName);
break;
case 3:
createSql = getMysqlCreateSql(items,tableName);
break;
case 4:
createSql = getPostGreCreateSql(items, tableName);
break;
case 5:
createSql = getSybaseCreateSql(items,tableName);
break;
}
FineLoggerFactory.getLogger().debug("HW_excel导入:建表语句为 " + createSql);
return createSql;
}
/*
mysql boolean 0/1
oracle char(1) 0/1 不允许为空
sqlServer bit 0/1
PostGre boolean 0/1/true/false
sybase bit 0/1 不允许为空
*/
private static String getMysqlCreateSql(JSONArray items, String tableName){
String sql = " ( ";
for (Object ja : items){
JSONObject item = new JSONObject(ja.toString());
String colname = "`" + item.getString("colName") + "`";
int colType = item.getInt("colType");
String colLen = item.getString("colLength");
String colTypeStr ;
switch (colType){
case 1:
colTypeStr = colname + " int,";
break;
case 3:
colTypeStr = colname + " boolean,";
break;
case 4:
colTypeStr = colname + " datetime,";
break;
case 5:
colTypeStr = colname + " decimal(" + colLen.split(",")[0]+","+ colLen.split(",")[1] + "),";
break;
default:
colTypeStr = colname + " varchar(" +colLen + "),";
break;
}
sql += colTypeStr;
}
return "create table "+ tableName + sql.substring(0,sql.length()-1) +" )" ;
}
private static String getSqlServerCreateSql(JSONArray items, String tableName){
String sql = " ( ";
for (Object ja : items){
JSONObject item = new JSONObject(ja.toString());
String colname = "[" + item.getString("colName") + "]" ;
int colType = item.getInt("colType");
String colLen = item.getString("colLength");
String colTypeStr ;
switch (colType){
case 1:
colTypeStr = colname + " int,";
break;
case 3:
colTypeStr = colname + " bit,";
break;
case 4:
colTypeStr = colname + " datetime,";
break;
case 5:
colTypeStr = colname + " decimal(" + colLen.split(",")[0] + "," + colLen.split(",")[1] + "),";
break;
default:
colTypeStr = colname + " varchar(" +colLen + "),";
break;
}
sql += colTypeStr;
}
return "create table "+ tableName + sql.substring(0,sql.length()-1) + " )" ;
}
private static String getOracleCreateSql(JSONArray items, String tableName){
String sql = " ( ";
for (Object ja : items){
JSONObject item = new JSONObject(ja.toString());
String colname = "\"" + item.getString("colName") + "\"";
int colType = item.getInt("colType");
String colLen = item.getString("colLength");
String colTypeStr ;
switch (colType){
case 1:
int len = Integer.parseInt(colLen) > 38 ? 38:Integer.parseInt(colLen);
colTypeStr = colname + " number(" + len + "),";
break;
case 3:
colTypeStr = colname + " char(1),";
break;
case 4:
colTypeStr = colname + " date,";
break;
case 5:
colTypeStr = colname + " decimal(" + colLen.split(",")[0] + "," + colLen.split(",")[1] + "),";
break;
default:
colTypeStr = colname + " varchar2(" +colLen + "),";
break;
}
sql += colTypeStr;
}
return "create table "+ tableName + sql.substring(0,sql.length()-1) + " )" ;
}
private static String getPostGreCreateSql(JSONArray items, String tableName){
String sql = " ( ";
for (Object ja : items){
JSONObject item = new JSONObject(ja.toString());
String colname = "\"" + item.getString("colName") + "\"";
int colType = item.getInt("colType");
String colLen = item.getString("colLength");
String colTypeStr ;
switch (colType){
case 1:
colTypeStr = colname + " integer,";
break;
case 3:
colTypeStr = colname + " boolean,";
break;
case 4:
colTypeStr = colname + " date,";
break;
case 5:
colTypeStr = colname + " decimal(" + colLen.split(",")[0] + ","+ colLen.split(",")[1] + "),";
break;
default:
colTypeStr = colname + " varchar(" + colLen + "),";
break;
}
sql += colTypeStr;
}
return "create table "+ tableName + sql.substring(0,sql.length()-1) + " )" ;
}
private static String getSybaseCreateSql(JSONArray items, String tableName){
String sql = " ( ";
for (Object ja : items){
JSONObject item = new JSONObject(ja.toString());
String colname = "[" + item.getString("colName") + "]" ;
int colType = item.getInt("colType");
String colLen = item.getString("colLength");
String colTypeStr ;
switch (colType){
case 1:
colTypeStr = colname + " int,";
break;
case 3:
colTypeStr = colname + " bit,";
break;
case 4:
colTypeStr = colname + " date,";
break;
case 5:
colTypeStr = colname + " decimal(" + colLen.split(",")[0] + "," + colLen.split(",")[1] + "),";
break;
default:
colTypeStr = colname + " varchar(" + colLen + "),";
break;
}
sql += colTypeStr;
}
return "create table "+ tableName + sql.substring(0,sql.length()-1) + " )" ;
}
public static String getInsertSql(String tableName, JSONArray items, int type){
String colStr = " (";
StringBuffer stringBuffer = new StringBuffer(" values (");
for (int i = 0, len = items.size(); i < len; i++) {
String colName = dealColName(items.getJSONObject(i).getString("colName"), type);
if (i == len - 1) {
colStr += colName + ")";
stringBuffer.append("?)");
} else {
colStr += colName + ",";
stringBuffer.append("?,");
}
}
FineLoggerFactory.getLogger().debug("HW_excel导入:插入语句为 " + "insert into " + tableName + colStr + stringBuffer.toString());
return "insert into " + tableName + colStr + stringBuffer.toString();
}
private static String dealColName(String colName, int type){
switch (type){
case 1:
case 4:
return "\"" + colName + "\"";
case 2:
case 5:
return "[" + colName + "]";
case 3:
return "`" + colName + "`";
}
return "";
}
public static String getDeleteSql(String tableName, int type){
return "delete from " + tableName;
}
public static String getDropSql(String tableName){
return "drop table " + tableName;
}
public static String getQuerySql(String tableName, int type, String schema){
switch (type){
case 1:
return "select * from " + tableName + " rownum < 5000";
case 2:
case 5:
return "select top(5000) * from " + tableName;
case 3:
case 4:
return "select * from " + tableName + " limit 0,5000";
default:
FineLoggerFactory.getLogger().debug("HW_excel导入:getQuerySql返回为空");
return "";
}
}
public static String getQueryColSql(String tableName, int type, String schema){
return "select * from " + tableName + " where 1=2";
}
/*
oracle:1
sqlserver:2
mysql:3
postgresql:4
sybase:5
*/
public static int getConnectionType(Connection conn) throws SQLException {
String DatabaseProductName = conn.getMetaData().getDatabaseProductName().trim().toUpperCase();
FineLoggerFactory.getLogger().debug("HW_excel导入:数据库 ProductName 为: " + DatabaseProductName);
if (StringUtils.contains(DatabaseProductName,"ORACLE")){
return 1;
}
if (StringUtils.contains(DatabaseProductName,"SQL SERVER")) {
return 2;
}
if (StringUtils.contains(DatabaseProductName,"MYSQL")){
return 3;
}
if (StringUtils.contains(DatabaseProductName,"POSTGRE")){
return 4;
}
if (StringUtils.contains(DatabaseProductName,"SYBASE")){
return 5;
}
return 0;
}
private static void dealPrepareStatement(PreparedStatement pstm, String value, int index, int type, int databaseType) throws SQLException {
try {
switch (type) {
case 1:
pstm.setInt(index, Double.valueOf(value).intValue());
break;
case 3:
switch (value.toUpperCase()) {
case "TRUE":
case "1":
if (databaseType == 4){
pstm.setBoolean(index, true);
} else {
pstm.setInt(index, 1);
} break;
case "FALSE":
case "0":
if (databaseType == 4){
pstm.setBoolean(index, false);
} else {
pstm.setInt(index, 0);
} break;
}
break;
case 4:
java.sql.Date date = java.sql.Date.valueOf(value);
pstm.setDate(index, date);
break;
case 5:
pstm.setFloat(index, Float.parseFloat(value));
break;
default:
if (isNumeric(value)){
pstm.setString(index, value.split("\\.")[0]);
} else {
pstm.setString(index, value);
}
}
} catch (Exception e){
pstm.setString(index, value);
}
}
/**
* 匹配是否为数字
* @param str 可能为中文也可能是-19162431.1254不使用BigDecimal的话变成-1.91624311254E7
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
Pattern pattern = Pattern.compile("-?[0-9]+(\\.0)");
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
/**
* 把从数据库中查询出来的 ResultSetMetaData 转为 JSONArray
*/
public static JSONArray formatRsToTableData(ResultSet rs) throws Exception{
ResultSetMetaData md = rs.getMetaData();
JSONArray jsonArray = new JSONArray();
while(rs.next()) {
JSONArray rowArray = new JSONArray();
for(int i=1; i<=md.getColumnCount(); i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("text", rs.getString(i));
rowArray.add(jsonObject);
}
jsonArray.add(rowArray);
}
return jsonArray;
}
public static JSONArray formatRs2ColAttr(ColumnInformation[] columnInformations){
JSONArray colsAttr = JSONArray.create();
for(int i = 0; i < columnInformations.length; i++) {
JSONObject colAttr = JSONObject.create();
colAttr.put("colType", columnInformations[i].getColumnType());
colAttr.put("colName", columnInformations[i].getColumnName());
colAttr.put("colLength", columnInformations[i].getColumnSize());
colAttr.put("id",i+1);
colAttr.put("excelCol","");
colsAttr.add(colAttr);
}
return colsAttr;
}
public static void addPrimaryKeyColAttr(JSONArray colsAttr, List<String> primaryKeyCol) {
for (Object col:colsAttr) {
String colName = ((JSONObject) col).getString("colName");
if (primaryKeyCol.contains(colName)) {
((JSONObject) col).put("primaryKey", true);
} else {
((JSONObject) col).put("primaryKey", false);
}
}
}
public static JSONArray formatRsToJsonArray(ResultSet rs) throws Exception{
ResultSetMetaData md = rs.getMetaData();
JSONArray jsonArray = new JSONArray();
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
for(int i=1; i<=md.getColumnCount(); i++) {
jsonObject.put(md.getColumnName(i), rs.getString(i));
}
jsonArray.add(jsonObject);
}
return jsonArray;
}
public static int changeStr2Type(String typeStr , int connType, int scale){
int type;
switch (typeStr.toUpperCase()){
case "INT":
case "INT4":
case "INTEGER":
type = 1; break;
case "BIT":
case "CHAR":
case "BOOL":
case "TINYINT":
case "BOOLEAN":
type = 3; break;
case "DATE":
case "DATETIME":
type = 4; break;
case "DECIMAL":
case "NUMERIC":
type = 5; break;
case "NUMBER": // oracle 整形和小数都是 number 类型,需要判断 scale
if (scale == 0) {
type = 1; break;
} else {
type = 5; break;
}
default:
type = 2;
}
return type;
}
public static int pstsExecBatch(PreparedStatement psts, JSONArray items, Map<String, List> values, int type) throws SQLException {
int count = 0;
for (int j =0; j< values.get(items.getJSONObject(0).get("colName")).size(); j++) {
for (int k=0; k<items.size();k++){
dealPrepareStatement(
psts,
values.get(items.getJSONObject(k).getString("colName")).get(j).toString(),
k+1,
items.getJSONObject(k).getInt("colType"),
type
);
}
count ++ ;
// sybase 执行 executeBatch 效率异常低,改用 execute
if(type == 5){
psts.execute();
continue;
}
psts.addBatch();
if( j!=0 && j%10000==0 ){
psts.executeBatch();
psts.clearBatch();
System.out.println("HW_excel导入:pstsExecBatch 批量执行完成");
FineLoggerFactory.getLogger().info("HW_excel导入:pstsExecBatch 批量执行完成");
}
}
System.out.println("HW_excel导入:pstsExecBatch 执行完成");
FineLoggerFactory.getLogger().info("HW_excel导入:pstsExecBatch 执行完成");
if(type == 5){
return count;
}
psts.executeBatch();
psts.clearBatch();
return count;
}
// 建表操作
public static int execCreatTable(String connection, String tableName, JSONArray items, HttpServletResponse res){
String createSql;
Statement smt = null;
Connection conn = getConnection(connection);
int line = -1;
try {
smt = conn.createStatement();
int type = JdbcUtils.getConnectionType(conn);
createSql = JdbcUtils.getCreateSql(type, tableName, items);
System.out.println("HW_excel导入:建表语句为 " + createSql);
FineLoggerFactory.getLogger().debug("HW_excel导入:建表语句为 " + createSql);
line = smt.executeUpdate(createSql);
} catch (Exception e){
e.printStackTrace();
System.out.println("HW_excel导入:建表执行异常!");
FineLoggerFactory.getLogger().info("HW_excel导入:建表执行异常!");
try {
WebUtils.printAsJSON(res,new JSONObject().put("status","fail").put("errorText","表创建失败:" + e.getLocalizedMessage()));
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
closeConn(conn, null, smt);
}
return line;
}
public static void closeConn(Connection conn, PreparedStatement psts, Statement smt){
if(conn != null){
DBUtils.closeConnection(conn);
}
if(psts != null){
DBUtils.close(psts);
}
if(smt != null){
DBUtils.close(smt);
}
}
public static boolean isHive(Connection conn){
try {
String DatabaseProductName = conn.getMetaData().getDatabaseProductName().trim().toUpperCase();
FineLoggerFactory.getLogger().debug("isHive:" + DatabaseProductName);
if (StringUtils.contains(DatabaseProductName,"HIVE")){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}

211
src/main/resources/com/fr/plugin/hw/decision/js/attr/col.attr.js

@ -0,0 +1,211 @@
;!(function () {
var EDITOR_WIDTH = 440, EDITOR_HEIGHT = 22, LABEL_WIDTH = 140;
var info = BI.inherit(BI.Widget, {
props: {
add: true,
},
_store: function () {
return BI.Models.getModel("dec.hw.table.col.attr.model", {
add: this.options.add
});
},
/*beforeInit: function (callback) {
this.store.initData(callback)
},*/
watch: {
count: function (v) {
this.table.setCount(v);
},
perItems: function () {
this.table.populate(this._formatItems(this.model.perItems));
this.table.setPage(this.model.page);
},
page:function () {
this.table.setPage(this.model.page);
//this.popularExcelBox(this.model.excelItems);
},
excelItems:function () {
this.popularExcelBox(this.model.excelItems);
}
},
mounted: function () {
this.table.setCount(this.model.count);
this.table.populate(this._formatItems(this.model.perItems));
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.absolute",
items: [{
el: {
type: "bi.vtape",
items: [{
height: 24,
el: {
type: "bi.button",
textAlign: "center",
disabled: !o.add,
text: "增加",
height: 24,
width: 100,
handler: function () {
self.store.addItems();
}
}
}, {
el: {
type: "dec.page.table",
header: [{text: "字段名"}, {text: "字段类型"}, {text: "长度"}, {text: "excel列"}, {text: "主键"}, {text: ""}],
columnSize: ["0.2", "0.2", "0.2", "0.2", "0.1", "0.1"],
perPage: 5,
ref: function (_ref) {
self.table = _ref;
},
items: self.model.perItems,
listeners: [{
eventName: "EVENT_CHANGE",
action: function (v) {
self.store.setPage(v);
}
}]
}
}]
},
top: 0, bottom: 0, left: 0, right: 0
}]
};
},
_formatItems: function (items) {
console.log("_formatItems");
var allResult=[];
var self = this, o = this.options;
self.colName = [];
self.excelBox= [];
self.primaryKeyBox = [];
for (var index = 0; index < items.length; index++) {
var item = items[index];
self.colName.push(item.colName);
var result = [];
var type = "dec.hw.table.col.attr.td";
var colName = {
type: "bi.text_editor",
disabled: !o.add,
widgetType: "bi.text_editor",
value: item.colName,
id: item.id,
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.updateItemColName(this.options.id,this.getValue());
}
}
]
};
result.push(colName);
var colType = {
type: "bi.text_value_combo",
disabled: !o.add,
widgetType: "bi.text_value_combo",
value: item.colType+"",
items: BI.Constants.getConstant("dec.hw.col.type"),
id: item.id,
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.updateItemColType(this.options.id,this.getValue()[0]);
}
}
]
};
result.push(colType);
var colLength = {
type: "bi.text_editor",
widgetType: "bi.text_editor",
disabled: !o.add,
value: item.colLength,
/*validationChecker: function (v) {
return BI.isPositiveInteger(v) && v > 0;
},
errorText: "必须是数字",*/
id: item.id,
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.updateItemColLength(this.options.id,this.getValue());
}
}
]
};
result.push(colLength);
var excelCol = {
type: "bi.text_value_combo",
widgetType: "bi.text_editor",
value: item.excelCol,
items:self.model.excelItems,
id: item.id,
ref: function (_ref) {
self.excelBox.push(_ref);
},
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.updateItemExcelCol(this.options.id,this.getValue()[0]);
}
}
]
};
result.push(excelCol);
var primaryKey = {
type: "bi.checkbox",
widgetType: "bi.checkbox",
selected: item.primaryKey,
disabled: !o.add,
id: item.id,
ref: function(_ref){
self.primaryKeyBox.push(_ref);
},
handler: function () {
var id = this.options.id;
self.store.updateItemPrimaryKey(id, this.isSelected());
/*this.isSelected() && BI.each(self.primaryKeyBox, function (index, item) {
if (id != item.options.id) {
item.setSelected(false);
}
});*/
}
};
result.push(primaryKey);
var deleteButton = {
type: "bi.button",
widgetType: "bi.button",
disabled: !o.add,
value: "删除",
handler: function () {
self.store.removeItems(this.options.id);
},
id: item.id
};
result.push(deleteButton);
allResult.push(result);
}
return allResult;
},
popularExcelBox:function (vals) {
console.log("popularExcelBox");
var self = this;
BI.each(self.excelBox, function (index, item) {
item.populate(vals);
item.setValue(self.model.perItems[index].excelCol);
})
}
});
BI.shortcut("dec.hw.table.col.attr", info);
})();

104
src/main/resources/com/fr/plugin/hw/decision/js/attr/col.attr.model.js

@ -0,0 +1,104 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
_init: function () {
this.add = this.options.add;
},
state: function () {
return {
perCount: 5,
page: 1
};
},
context: ["items", "connection", "schema", "aliasName", "tableName", "excelItems", "infoId"],
computed: {
perItems: function () {
var self = this;
var start = (self.model.page - 1) * self.model.perCount;
var end = self.model.page * self.model.perCount;
var self = this;
return BI.filter(self.model.items, function (index, item) {
return index + 1 > start && index + 1 <= end;
})
},
count: function () {
return this.model.items.length;
}
},
watch:{
count: function () {
var allPageCount = Math.ceil(this.model.count/ this.model.perCount);
if(allPageCount<=0){
allPageCount=1;
}
if (allPageCount < this.model.page) {
this.setPage(allPageCount);
}
}
},
actions: {
initData: function (callback) {
callback();
},
setPage: function (v) {
this.model.page = v;
},
addItems: function () {
this.model.items = BI.concat(this.model.items, {
id: BI.UUID(),
colName: "",
colType: "12",
colLength: 255,
excelCol: "",
primaryKey: false
})
},
removeItems: function (id) {
BI.remove(this.model.items, function (index, item) {
return item.id == id
});
},
updateItemColName:function (id, colName) {
BI.each(this.model.items,function (index, item) {
if(item.id==id){
item.colName=colName;
}
});
},
updateItemColType:function (id, colType) {
BI.each(this.model.items,function (index, item) {
if(item.id==id){
item.colType=colType;
}
});
},
updateItemColLength:function (id, colLength) {
BI.each(this.model.items,function (index, item) {
if(item.id==id){
item.colLength=colLength;
}
});
},
updateItemExcelCol:function (id, excelCol) {
BI.each(this.model.items,function (index, item) {
if(item.id==id){
item.excelCol=excelCol;
}
});
},
updateItemPrimaryKey:function (id, primaryKey) {
BI.each(this.model.items,function (index, item) {
if(item.id==id){
item.primaryKey=primaryKey;
} /*else {
item.primaryKey=false;
}*/
});
}
}
});
BI.model("dec.hw.table.col.attr.model", Model);
})();

127
src/main/resources/com/fr/plugin/hw/decision/js/attr/sheet.masker.js

@ -0,0 +1,127 @@
/**
* 用于测试上传上传文件等从上传中到成功或者失败的状态
* qcc
* 2018/3/28
*/
!(function () {
var Masker = BI.inherit(BI.Widget, {
props: {
baseCls: "dec-status-change-masker",
$testId: "dec-status-change-masker",
waitingText: BI.i18nText("Dec-Reg_Upload_Waiting"),
successText: BI.i18nText("Dec-Reg_Upload_Success"),
failText: BI.i18nText("Dec-Reg_Upload_Fail")
},
watch: {},
render: function () {
var self = this, o = this.options;
return {
type: "bi.center_adapt",
cls: "bi-z-index-mask",
items: [{
type: "bi.center_adapt",
items: [{
type: "bi.absolute",
width: 300,
height: 150,
cls: "bi-card",
items: [{
el: {
type: "bi.vtape",
items: [{
el: {
type: "bi.vertical_adapt",
items: [{
type: "bi.label",
textAlign: "right",
cls: "dec-font-weight-bold",
text: "选择sheet:",
width: 60
}, {
el: {
type: "bi.text_value_combo",
lgap: 4,
cls: "bi-border",
textAlign: "left",
// value: o.info.subjectType,
items: o.items,
// items: self.model.typeItems,
width: 200,
height: 22,
ref: function (_ref) {
self.sheet = _ref;
},
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
}
}
]
},
lgap: 10
}]
}
}, {
el: {
type: "bi.right_vertical_adapt",
lgap: 10,
items: [{
type: "bi.button",
ref: function (_ref) {
},
text: "确定",
height: 24,
handler: function () {
var value = self.sheet.getValue();
if (BI.isEmptyArray(value)) {
BI.Msg.toast("先选择sheet");
return;
}
self.options.onClickConfirm(value[0], function (result) {
if (result) {
BI.Msg.toast("成功");
self.close()
} else {
BI.Msg.toast("失败");
}
})
}
}, {
type: "bi.button",
ref: function (_ref) {
},
text: "取消",
height: 24,
level: "ignore",
handler: function () {
self.close();
}
}]
}, height: 44
}]
},
top: 40, left: 10, bottom: 0, right: 10
}]
}]
}]
};
},
close: function () {
this.fireEvent("EVENT_CLOSE");
}
});
BI.shortcut("dec.hw.sheet.select", Masker);
})();

193
src/main/resources/com/fr/plugin/hw/decision/js/attr/table.attr.js

@ -0,0 +1,193 @@
;!(function () {
var EDITOR_WIDTH = 480, EDITOR_HEIGHT = 22, LABEL_WIDTH = 100;
var info = BI.inherit(BI.Widget, {
props: {
typeItems: [],
levelItems: [],
departId: "",
departName: "",
departType: "",
institution: "",
departLevel: "",
startDate: {},
endDate: {},
add: true,
info: {}
},
_store: function () {
console.log("table.attr.js");
return BI.Models.getModel("dec.hw.table.attr.model");
},
watch: {
schemaItems:function () {
this.schema.setValue();
},
isSchemaLoaded: function (v) {
this.schema.setEnable(v);
}
},
beforeInit: function (callback) {
this.store.initData(callback);
},
render: function () {
var self = this, o = this.options, borderEditorWidth = EDITOR_WIDTH - 2;
console.log("table.attr.js");
return {
type: "bi.vertical",
width: 640,
vgap: 15,
items: [{
type: "bi.vertical_adapt",
items: [{
type: "bi.label",
textAlign: "right",
cls: "dec-font-weight-bold",
text: "数据源:",
title: "数据源",
width: LABEL_WIDTH
}, {
el: {
type: "bi.text_value_combo",
lgap: 4,
disabled: !o.add,
cls: "bi-border",
textAlign: "left",
value: o.info.connection,
items: self.model.connectionItems,
// items: self.model.typeItems,
width: borderEditorWidth,
height: EDITOR_HEIGHT,
ref: function (_ref) {
self.connection = _ref;
},
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.setConnection(this.getValue()[0]);
self.store.getSchemaItems(this.getValue()[0]);
}
}
]
},
lgap: 10
}]
}, {
type: "bi.vertical_adapt",
items: [{
type: "bi.label",
textAlign: "right",
cls: "dec-font-weight-bold",
text: "别名(*):",
title: "别名",
width: LABEL_WIDTH
}, {
el: {
type: "bi.text_editor",
lgap: 4,
cls: "bi-border",
textAlign: "left",
value: o.info.aliasName,
width: borderEditorWidth,
disabled: !o.add,
height: EDITOR_HEIGHT,
ref: function (_ref) {
self.alias = _ref;
},
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.setAliasName(this.getValue());
}
}
]
}, lgap: 10
}]
}, {
type: "bi.vertical_adapt",
items: [{
type: "bi.label",
textAlign: "right",
cls: "dec-font-weight-bold",
text: "表名(*):",
title: "表名",
width: LABEL_WIDTH
}, {
el: {
type: "bi.text_editor",
lgap: 4,
cls: "bi-border",
textAlign: "left",
width: borderEditorWidth,
disabled: !o.add,
value: o.info.tableName,
height: EDITOR_HEIGHT,
ref: function (_ref) {
self.tableName = _ref;
},
listeners: [
{
eventName: "EVENT_CHANGE",
action: function () {
self.store.setTableName(this.getValue());
}
}
]
}, lgap: 10
}]
}]
}
},
getValue: function () {
var self = this;
return {
id: self.subjectId.getValue(),
subjectName: self.subjectName.getValue(),
subjectType: self.subjectType.getValue()[0],
accountSubject: self.accountSubject.getValue()[0],
beginDate: Dec.AMB.getDynamicDateValue(self.beginDate.getValue()),
endDate: Dec.AMB.getDynamicDateValue(self.endDate.getValue()),
mark: self.mark.getValue()
}
},
setValue: function (v) {
var self = this;
self.subjectId.setValue(v.id);
self.subjectName.setValue(v.subjectName);
self.subjectType.setValue([v.subjectType]);
self.accountSubject.setValue([v.accountSubject]);
self.beginDate.setValue(Dec.AMB.createDateWidgetValue(v.beginDate));
self.endDate.setValue(Dec.AMB.createDateWidgetValue(v.endDate));
self.mark.setValue(v.mark);
},
getSchemaValue: function () {
return this.schema.getValue()
},
_itemsCreator:function (options, populate) {
var self = this, o = this.options, keyword = options.keywords && options.keywords[0];
var filter = BI.filter(self.model.schemaItems,function (i, value) {
if(BI.isEmpty(keyword)){
return true;
}
return BI.contains(value.value, keyword);
});
populate({
items: self._processSchemaItems(filter)
})
},
_processSchemaItems:function (items) {
var self = this;
return BI.map(items, function (i, v) {
var res = {
type: "bi.icon_text_item",
value: v.value,
cls: "item-check-font bi-list-item"
};
return res;
});
}
});
BI.shortcut("dec.hw.table.attr", info);
})();

73
src/main/resources/com/fr/plugin/hw/decision/js/attr/table.attr.model.js

@ -0,0 +1,73 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
_init: function () {
this.add = this.options.add;
},
state: function () {
return {
connectionItems: [],
schemaItems: [],
isSchemaLoaded: false
};
},
context: [ "connection", "schema", "aliasName", "tableName"],
actions: {
initData: function (callback) {
var self=this;
Dec.Utils.getConnections(function (res) {
console.log(res);
self.model.connectionItems =
BI.map(
/*// 根据驱动过滤下数据连接
BI.filter(res,
function (i,val) {
var reg = RegExp('MYSQL|ORACLE|SQLSERVER|POSTGRE|SYBASE');
return JSON.parse(val.connectionData).driver.toUpperCase().match(reg) != null
}),*/
res,
function (i,val) {
return BI.extend({value:"",text:""},{
text : val.connectionName,
value : val.connectionName
})
});
callback();
});
//self.model.connectionItems=[{value: "zhizao", text: "制造"}, {value: "xiaoshou", text: "销售"}];
},
setConnection:function (v) {
this.model.connection=v;
},
setSchema:function (v) {
this.model.schema=v;
},
setSchemaLoaded:function (v) {
this.model.isSchemaLoaded=v;
},
setAliasName:function (v) {
this.model.aliasName=v;
},
setTableName:function (v) {
this.model.tableName=v;
},
getSchemaItems:function (v) {
var self = this;
self.setSchemaLoaded(false);
Dec.reqGet(
"/url/excelmng/getSchema?connectionName=" + v,
null,null,
function (e) {
console.log(e);
self.model.schemaItems = e.data;
self.setSchemaLoaded(true);
}
)
}
}
});
BI.model("dec.hw.table.attr.model", Model);
})();

46
src/main/resources/com/fr/plugin/hw/decision/js/attr/td.widget.js

@ -0,0 +1,46 @@
;!(function () {
var EDITOR_WIDTH = 440, EDITOR_HEIGHT = 22, LABEL_WIDTH = 140;
var info = BI.inherit(BI.Widget, {
props: {
widgetType: "",
id: "",
isArr: false,
value: "",
errorText: "",
validationChecker: BI.emptyFn,
listeners:[],
handler: BI.emptyFn,
items: []
},
/*beforeInit: function (callback) {
this.store.initData(callback)
},*/
render: function () {
var self = this, o = this.options;
return {
id:o.id,
type: o.widgetType,
value: o.value,
text: o.value,
items: o.items,
disabled: o.disabled,
validationChecker: o.validationChecker,
errorText: o.errorText,
handler:o.handler,
listeners:o.listeners,
ref: function (_ref) {
self.showWidget = _ref;
}
}
},
getValue: function () {
var o = this.options;
var result = this.showWidget.getValue();
return o.isArr ? result[0] : result;
},
getId: function () {
return this.options.id;
}
});
BI.shortcut("dec.hw.table.col.attr.td", info);
})();

265
src/main/resources/com/fr/plugin/hw/decision/js/hw.option.js

@ -0,0 +1,265 @@
;!(function () {
var commPath = Dec.fineServletURL + "/file?path=/com/fr/plugin/hw/decision/js";
BI.$import(commPath + "/utils.js");
BI.$import(commPath + "/table.info.js");
BI.$import(commPath + "/table.info.model.js");
BI.$import(commPath + "/hw.table.add.pop.js");
BI.$import(commPath + "/hw.table.add.pop.model.js");
BI.$import(commPath + "/attr/table.attr.js");
BI.$import(commPath + "/attr/table.attr.model.js");
BI.$import(commPath + "/attr/col.attr.js");
BI.$import(commPath + "/attr/col.attr.model.js");
BI.$import(commPath + "/attr/sheet.masker.js");
BI.$import(commPath + "/attr/td.widget.js");
BI.$import(commPath + "/pane/panes.js");
BI.$import(commPath + "/pane/panes.model.js");
BI.$import(commPath + "/pane/dec.hw.excel.export.pane.js");
BI.$import(commPath + "/pane/dec.hw.excel.export.pane.model.js");
BI.$import(commPath + "/pane/left.js");
BI.$import(commPath + "/pane/left.model.js");
BI.$import(commPath + "/pane/left.linklist.item.js");
BI.$import(commPath + "/pane/left.linklist.item.model.js");
BI.$import(commPath + "/pane/left.linklist.js");
BI.$import(commPath + "/pane/left.linklist.model.js");
BI.$import(commPath + "/pane/right.js");
BI.$import(commPath + "/pane/right.model.js");
BI.$import(commPath + "/pane/right.table.js");
BI.$import(commPath + "/pane/right.table.model.js");
BI.$import(commPath + "/pane/dec.page.table.plugin.js");
BI.$import(commPath + "/pane/authPane/auth.pane.js");
BI.$import(commPath + "/pane/authPane/auth.pane.model.js");
BI.$import(commPath + "/pane/authPane/auth.pane.right.js");
BI.$import(commPath + "/pane/authPane/auth.pane.right.model.js");
BI.config("dec.constant.management.navigation", function (items) {
items.push({
value: "hw", // 地址栏显示的hash值
id: "fanruan-hw-excecl", // id
text: "Excel导入", // 文字
//cardType: "dec.mng.excelExportPane",
cardType: "dec.mng.panes",
cls: "dir-font-20" // 图标类名
});
return items;
});
/**
* 管理项
*/
BI.constant("dec.hw.col.type", [
{value: "2", text: "整数"},
{value: "3", text: "小数"},
{value: "12", text: "文本"},
{value: "16", text: "布尔"},
{value: "91", text: "日期"}
]);
BI.constant("dec.hw.col.type.int", [2, 4]);
BI.constant("dec.hw.col.type.str", [1, 12]);
BI.constant("dec.hw.col.type.bool", [-7, 16]);
BI.constant("dec.hw.col.type.date", [91, 93]);
BI.hwColTypeDeal = function(data){
BI.each(data, function (index, val) {
if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.int"), val.colType)) {
val.colType = 2;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.str"), val.colType)) {
val.colType = 12;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.bool"), val.colType)) {
val.colType = 16;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.date"), val.colType)) {
val.colType = 91;
}
});
console.log(data);
return data;
};
/**
* tab项
*/
BI.constant("dec.hw.constant.tabs", [
{value: "export", text: "Excel数据管理"},
{value: "auth", text: "Excel权限管理"}
]);
// 组件实现,效果为使用绝对布局组件放置了一个iframe
var Fanruan = BI.inherit(BI.Widget, {
props: {
baseCls: "dec-management-fanruan"
},
render: function () {
var self = this, o = this.options;
var file = {
type: "bi.multifile_editor",
ref: function (_ref) {
self.file = _ref;
},
width: 200,
// accept: "*.zip;",
url: Dec.fineServletURL + "/url/demo/test?width=32&height=32",
listeners: [
{
eventName: BI.MultifileEditor.EVENT_ERROR,
action: function (args) {
/* self.fireEvent("EVENT_ERROR");
self._closeUpload();*/
}
}, {
eventName: BI.MultifileEditor.EVENT_UPLOADED,
action: function (args) {
var files = this.getValue();
if (files[files.length - 1].errorCode) {
BI.Msg.toast(BI.i18nText(files[files.length - 1].errorMsg), {
level: "error"
});
self._closeUpload();
return;
}
var id = files[files.length - 1].attach_id;
var filename = files[files.length - 1].filename;
// self.store.analysisFile(id, filename);
}
}, {
eventName: BI.MultifileEditor.EVENT_CHANGE,
action: function () {
this.upload();
/* self._startUpload();*/
}
}
]
};
return {
type: "bi.absolute",
items: [
{
el: {
type: "bi.center_adapt",
items: [
{
el: file
}, {
el: {
type: "bi.button",
width: 200,
text: "123123",
handler: function () {
self.file.select();
}
}
}
]
},
top: 100,
left: 0,
right: 0,
bottom: 0
}, {
el: {
type: "bi.vertical_adapt",
items: [{
type: "bi.button",
text: "新建",
handler: function () {
var pane = {
type: "dec.hw.table.add.popup",
add:true,
infoId:"add",
onClickConfirm: function (val, callback) {
console.log(val);
Dec.HW.importTableData(val,function (res) {
debugger;
});
callback(true);
// self.store.addDepartment(val, callback);
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "add");
}
}
]
};
BI.Popovers.create(self.getName() + "add", {
type: "bi.popover",
header: BI.i18nText("Dec-Add_Department"),
body: pane,
width: 700,
height: 800,
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "add");
}
}
]
}).open(self.getName() + "add");
}
}, {
type: "bi.button",
text: "编辑",
handler:function () {
var pane = {
type: "dec.hw.table.add.popup",
add:false,
infoId:"edit",
onClickConfirm: function (val, callback) {
console.log(val);
Dec.HW.importTableData(val,function (res) {
debugger;
});
callback(true);
// self.store.addDepartment(val, callback);
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
};
BI.Popovers.create(self.getName() + "edit", {
type: "bi.popover",
header: BI.i18nText("Dec-Add_Department"),
body: pane,
width: 700,
height: 800,
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
}).open(self.getName() + "edit");
}
}]
},
top: 0,
left: 0
}
]
};
}
});
BI.shortcut("dec.management.fanruan_demo", Fanruan);
})();

187
src/main/resources/com/fr/plugin/hw/decision/js/hw.table.add.pop.js

@ -0,0 +1,187 @@
!(function () {
var WIDTH = 80;
var HEIGHT = 50;
var AddDepartment = BI.inherit(BI.Widget, {
props: {
baseCls: "dec-add-department-popup",
btns: [BI.i18nText(BI.i18nText("Dec-Basic_Sure")), BI.i18nText(BI.i18nText("Dec-Basic_Cancel"))],
onClickConfirm: BI.emptyFn,
info: {}
},
_store: function () {
return BI.Models.getModel("dec.model.hw.table.add.popup");
},
watch:{
importStatus: function (v) {
switch (v) {
case "importing":
this._startImport();
break;
case "abort":
this._stopImport();
break;
case "finish":
default:
this._finishImport();
}
}
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.vtape",
items: [
{
el: {
type: "dec.hw.table.info",
text: "测试",
add: o.add,
infoId:o.infoId,
aliasName: o.aliasName,
ref: function (_ref) {
self.hwTableInfo = _ref;
}
}
}, {
el: this.rebuildSouth(),
height: 44
}
]
};
},
rebuildSouth: function () {
var self = this, o = this.options;
var sure = BI.createWidget({
type: "bi.button",
ref: function (_ref) {
self.sure = _ref;
},
text: this.options.btns[0],
warningTitle: o.warningTitle,
height: 24,
handler: function () {
self.end();
}
});
var cancel = BI.createWidget({
type: "bi.button",
ref: function (_ref) {
self.cancel = _ref;
},
text: this.options.btns[1],
height: 24,
level: "ignore",
handler: function () {
self.close();
}
});
return {
type: "bi.right_vertical_adapt",
lgap: 10,
items: [cancel, sure]
};
},
getValue: function () {
return this.hwTableInfo.getValue();
},
setValue: function (info) {
this.departmentName.setValue(info.text);
},
close: function () {
this.fireEvent("EVENT_CLOSE");
},
end: function () {
var self = this;
self.store.setImportStatus("importing");
console.log("end");
if (self.getValue().infoId == "add") {
self._tableNameExistsAndImportChecker();
} else {
self._importChecker();
}
},
_tableNameExistsAndImportChecker: function(){
var self = this;
if (self.getValue().infoId == "add") {
var tableName = BI.isEmpty(self.getValue().schema)?self.getValue().tableName:self.getValue().schema+ "." + self.getValue().tableName ;
var encodeTableName = encodeURIComponent(tableName); // 编码下表名,模式中可能存在 #
Dec.reqGet(
"/url/excelmng/iftableexist?connection=" + self.getValue().connection + "&tableName=" + encodeTableName,
null,null,function(e){
if(e.status == "success"){
self._importChecker();
} else {
self.store.setImportStatus("abort");
BI.Msg.toast(e.errorText);
}
})
}
},
_importChecker: function () {
var self = this, o = this.options;
o.onClickConfirm(self.getValue(), function (res) {
if (res.status == "success") {
self.store.setImportStatus("finish");
BI.Msg.toast("操作成功!" + res.text);
} else {
self.store.setImportStatus("abort");
BI.Msg.toast("操作失败," + res.errorText);
}
})
},
_startImport: function () {
var self = this, name = this.getName() + "status";
var upload = {
type: "dec.test.status",
waitingText: "导入中",
successText: "导入成功",
failText: "导入失败",
listeners: [{
eventName: "EVENT_CLOSE",
action: function () {
BI.Maskers.hide(name);
BI.Maskers.remove(name);
}
}],
ref: function (_ref) {
self.uploadMasker = _ref;
}
};
BI.Maskers.create(name, null, {
render: upload
});
BI.Maskers.show(name);
},
_stopImport: function () {
var name = this.getName() + "status";
BI.Maskers.hide(name);
BI.Maskers.remove(name);
},
_finishImport: function () {
this.uploadMasker && this.uploadMasker.setStatus({
status: DecCst.TestStatus.SUCCESS
});
this.close();
}
});
AddDepartment.EVENT_CLICK_CONFIRM = "EVENT_CONFIRM";
BI.shortcut("dec.hw.table.add.popup", AddDepartment);
}());

15
src/main/resources/com/fr/plugin/hw/decision/js/hw.table.add.pop.model.js

@ -0,0 +1,15 @@
!(function () {
var Store = BI.inherit(Fix.Model, {
state: function(){
return{
importStatus: ""//导入的状态
}
},
actions: {
setImportStatus:function (v) {
this.model.importStatus=v;
}
}
});
BI.model("dec.model.hw.table.add.popup", Store);
})();

72
src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.js

@ -0,0 +1,72 @@
!(function () {
var AuthPane = BI.inherit(BI.Widget, {
props: {
baseCls: ""
},
_store: function () {
return BI.Models.getModel("dec.model.mng.authPane");
},
render: function () {
var self = this, o = this.options;
var left = {
type: "dec.common.resizeable_layout",
ref: function (_ref) {
self.left = _ref;
},
width: 240,
maxSize: 450,
minSize: 200,
resize: BI.bind(self.resize, this),
item: {
type: "dec.excelexport.left",
showButton: false,
cls: "bi-border-right"
}
};
var right = {
type: "dec.auth.right",
ref: function (_ref) {
self.right = _ref;
}
};
return {
type: "bi.vtape",
items: [{
type: "bi.absolute",
items: [
{
el: {
type: "bi.htape",
cls: "bi-card",
ref: function (_ref) {
self.wrapper = _ref;
},
items: [
{
el: left,
width: 240
}, {
el: right
}
]
},
top: 10, right: 10, left: 10, bottom: 10
}
]
}
]
};
},
resize: function (size) {
var self = this;
self.wrapper.options.items[0].width = size;
self.wrapper.resize();
}
});
BI.shortcut("dec.mng.authPane", AuthPane);
})();

12
src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.model.js

@ -0,0 +1,12 @@
!(function(){
var Store = BI.inherit(Fix.Model, {
state: function () {
return {
selectedLink: ""
};
},
childContext: ["selectedLink"]
});
BI.model("dec.model.mng.authPane", Store);
})();

99
src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.right.js

@ -0,0 +1,99 @@
!(function () {
var Right = BI.inherit(BI.Widget, {
props: {
baseCls: ""
},
_store: function () {
return BI.Models.getModel("dec.model.auth.right");
},
watch:{
selectedLink:function(v){
var self = this;
self.loader.setVisible(true);
self.store.setAllUser([]);
self.store.setPage(2);
self.store.initAuthData(function(){
self.store.initData(function(e){
self.loader.populate(e);
self.store.setPage(2);
}, 1);
});
},
keyword:function(v){
var self = this;
self.store.initData(function(e){
self.loader.populate(e);
self.store.setPage(2);
}, 1);
}
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.vtape",
items: [{
el:{
type: "bi.left_right_vertical_adapt",
cls: "bi-border-bottom",
items:{
left:[{
type: "bi.label",
text: "人员列表",
textAlign: "left",
hgap: 5,
lgap: 20
},{
type: "bi.search_editor",
width: 200,
watermark: "用户搜索",
listeners: [{
eventName: "EVENT_CHANGE",
action: function() {
self.store.setKeyword(this.getKeywords()[0]);
}
},{
eventName: "EVENT_CLEAR",
action: function() {
self.store.setAllUser([]);
self.store.setKeyword(BI.emptyStr);
}
}]
}],
right:[{
type: "bi.label",
text: "权限",
textAlign: "left",
hgap: 5,
rgap: 20
}]
}
},
height: 40,
},{
el:{
type: "bi.loader",
height: "90%",
invisible: true,
ref: function(_ref) {
self.loader = _ref
},
// options 表示加载的次数 times:1
itemsCreator: function (options, populate) {
self.store.initData(populate, self.model.page);
self.store.setPage(self.model.page+1) ;
},
hasNext: function (options) {
return self.model.hasNext;
}
},
tgap: 15
}]
};
}
});
BI.shortcut("dec.auth.right", Right);
})();

123
src/main/resources/com/fr/plugin/hw/decision/js/pane/authPane/auth.pane.right.model.js

@ -0,0 +1,123 @@
!(function(){
var Store = BI.inherit(Fix.Model, {
state: function () {
return {
keyword: "",
allUser:[],
authUser:[],
page: 1,
count: 100,
userName: "",
hasNext: true
};
},
context:["selectedLink"],
computed: {
},
actions: {
initData:function(callback, page){
var self = this;
Dec.HW.getAllUserData({
page:page,
count:self.model.count,
keyword:self.model.keyword
},function(e){
if (e.status) {
self.model.hasNext = e.data.hasNext;
self.model.allUser = e.data.items;
callback && callback(self._formatItems(e.data.items))
}
});
},
initAuthData:function(callback){
var self = this;
Dec.HW.getAuthUserData({
linkName: self.model.selectedLink
},function(res){
if (res.status) {
self.model.authUser = res.data;
callback && callback()
}
})
},
setAllUser: function (v) {
this.model.allUser = v
},
setKeyword: function (v) {
this.model.keyword = v
},
setPage: function (v) {
this.model.page = v
},
updateAuth: function(v){
var self = this;
Dec.HW.updateLinkAuth({
linkName: self.model.selectedLink,
userName: self.model.userName,
auth: v
},function(res){
self.initAuthData(BI.emptyFn);
})
},
_formatItems:function(v){
var self = this;
return BI.map( v, function(i,val){
var selected = BI.contains(self.model.authUser, val.id);
var item = {
type:"bi.htape",
cls: "bi-list-item-active",
ref: function(_ref) {
self.tape = _ref
},
height:24,
items:[{
el:{
type:"bi.label",
},
width:60
},{
el:{
type:"bi.label",
value: val.realName + " (" + val.username + ")",
text: val.realName + " (" + val.username + ")"
},
},{
el:{
type:"dec.auth.checkbox",
selected:selected,
value: val.id,
hoverHandler:{
moveIn:function(arguments){
self.model.userName = arguments
},
moveOut:function(){
}
},
listeners: [{
eventName: BI.Controller.EVENT_CHANGE,
action: function() {
self.updateAuth(this.isSelected());
}
}]
},
rgap:10
},{
el:{
type:"bi.label",
},
width:40
}]
}
return item;
})
}
}
});
BI.model("dec.model.auth.right", Store);
})();

86
src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.hw.excel.export.pane.js

@ -0,0 +1,86 @@
!(function () {
var ExcelExportPane = BI.inherit(BI.Widget, {
props: {
baseCls: ""
},
_store: function () {
return BI.Models.getModel("dec.model.mng.excelExportPane");
},
render: function () {
var self = this, o = this.options;
var left = {
type: "dec.common.resizeable_layout",
ref: function (_ref) {
self.left = _ref;
},
width: 240,
maxSize: 450,
minSize: 200,
resize: BI.bind(self.resize, this),
item: {
type: "dec.excelexport.left",
showButton: true,
containReuse: true,
cls: "bi-border-right"
}
};
var right = {
type: "dec.excelexport.right",
ref: function (_ref) {
self.mid = _ref;
}
};
return {
type: "bi.vtape",
items: [
/*{
type: "bi.vertical_adapt",
cls: "bi-card bi-border-bottom",
items: [
{
type: "bi.label",
text: "Excel数据管理",
textAlign: "left",
hgap: 10
}
],
height: 40
}, */{
type: "bi.absolute",
items: [
{
el: {
type: "bi.htape",
cls: "bi-card",
ref: function (_ref) {
self.wrapper = _ref;
},
items: [
{
el: left,
width: 240
}, {
el: right
}
]
},
top: 10, right: 10, left: 10, bottom: 10
}
]
}
]
};
},
resize: function (size) {
var self = this;
self.wrapper.options.items[0].width = size;
self.wrapper.resize();
}
});
BI.shortcut("dec.mng.excelExportPane", ExcelExportPane);
})();

11
src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.hw.excel.export.pane.model.js

@ -0,0 +1,11 @@
!(function () {
var Store = BI.inherit(Fix.Model, {
state: function () {
return {
selectedLink: ""
}
},
childContext: ["selectedLink"]
});
BI.model("dec.model.mng.excelExportPane", Store);
})();

88
src/main/resources/com/fr/plugin/hw/decision/js/pane/dec.page.table.plugin.js

@ -0,0 +1,88 @@
!(function () {
var i = BI.inherit(BI.Widget, {
props: {
baseCls: "dec-page-table",
perPage: 10,
showPager: !0,
columnSize: []
},
_store: function() {
return BI.Models.getModel("dec.model.page.table")
},
watch: {
sort: function(e) {
this.fireEvent(i.EVENT_SORT, e)
},
"totalCount || currentPage": function() {
this.pager.setCount(this.model.totalCount),
this.pager.setPage(this.model.currentPage),
this.pager.setAllPages(Math.ceil(this.model.totalCount / this.options.perPage))
}
},
render: function() {
var t = this
, e = this.options;
return {
type: "bi.vertical",
scrollx: true,
items: [{
type: "dec.page.table.header",
columnSize: e.columnSize,
items: e.header
}, {
type: "bi.button_group",
cls: "table-items",
layouts: [{
type: "bi.vertical",
scrollx: true
}],
items: this._createItems(e.items),
ref: function(e) {
t.listGroup = e
},
height: e.listHeight
}, {
type: "dec.pager",
height: 30,
invisible: !e.showPager,
tgap: 10,
count: e.totalCount,
pages: 0 === e.totalCount ? 1 : Math.ceil(e.totalCount / e.perPage),
curr: e.currentPage,
ref: function(e) {
t.pager = e
},
listeners: [{
eventName: i.PAGER_EVENT_CHANGE,
action: function() {
t.fireEvent(i.PAGER_EVENT_CHANGE, this.getCurrentPage())
}
}]
}]
}
},
setCount: function(e) {
this.store.setCount(e)
},
setPage: function(e) {
this.store.setPage(e)
},
populate: function(e) {
this.listGroup.populate(this._createItems(e))
},
_createItems: function(e) {
var i = this.options;
return BI.map(e, function(e, t) {
return {
type: "dec.page.table.row",
odd: BI.isOdd(e),
columnSize: i.columnSize,
item: t
}
})
}
});
i.PAGER_EVENT_CHANGE = "EVENT_CHANGE",
i.EVENT_SORT = "EVENT_SORT",
BI.shortcut("dec.page.table.plugin", i)
})();

107
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.js

@ -0,0 +1,107 @@
!(function () {
var Left = BI.inherit(BI.Widget, {
props: {
baseCls: "",
showButton: false,
containReuse: false
},
_store: function () {
return BI.Models.getModel("dec.model.excelexport.left");
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.vtape",
items: [
{
type: "bi.left_right_vertical_adapt",
cls: "bi-border-bottom",
items:{
left: [{
type: "bi.label",
text: "数据列表",
textAlign: "left",
hgap: 5,
height: 40
}],
right: [{
type: "bi.icon_button",
cls: "plus-font",
invisible: !o.showButton,
width: 16,
hgap: 10,
handler: function () {
var pane = {
type: "dec.hw.table.add.popup",
add:true,
infoId:"add",
onClickConfirm: function (tableData, callback) {
console.log(tableData);
Dec.HW.importTableData(tableData, function (res) {
if (res.status === "success") {
BI.Utils.addTables2Pack({
packId: "__my_analysis__" + BI.Utils.getCurrentUserId(),
tables: [{
tableName: tableData.tableName,
connectionName: tableData.connection
}]
}, function () {
callback(res);
self.linkListPane.populate();
});
} else {
callback(res);
self.linkListPane.populate();
}
});
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "add");
}
}
]
};
BI.Popovers.create(self.getName() + "add", {
type: "bi.popover",
header: "添加Excel导入链接",
body: pane,
width: 700,
height: 700,
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "add");
}
}
]
}).open(self.getName() + "add");
}
}]
},
height: 40
}, {
type: "dec.excelexport.left.linklist",
containReuse: o.containReuse,
ref: function (_ref) {
self.linkListPane = _ref;
}
}
]
};
},
resize: function (size) {
var self = this;
self.wrapper.options.items[0].width = size;
self.wrapper.resize();
}
});
BI.shortcut("dec.excelexport.left", Left);
})();

100
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.item.js

@ -0,0 +1,100 @@
!(function () {
var ICON_WIDTH = 26;
var Item = BI.inherit(BI.BasicButton, {
props: {
baseCls: "dec-tabledata-set-list-item",
$testId: "dec-tabledata-set-list-item",
height: 24,
value: "",
text: "",
create: false
},
_store: function () {
return BI.Models.getModel("dec.model.excelexport.left.linklist.item", this.options);
},
render: function () {
var self = this, o = this.options;
this.storeValue = o.value;
return {
type: "bi.htape",
css: o.create == "true" ? {"color":"blue"}:{},
items: [{
type: "bi.center_adapt",
width: 24,
cls: "dcm-link-font",
hgap: 5,
items: [{
type: "bi.icon"
}]
}, {
type: "bi.shelter_editor",
allowBlank: false,
value: o.value,
text: o.text,
validationChecker: BI.bind(this.store.nameChecker, this.store),
errorText: function (v) {
return BI.i18nText(BI.isEmptyString(v) ? "Dec-Data_Set_Server_Name_Empty" : "Dec-Data_Set_Server_Name_Duplicate");
},
title: function () {
return self.editor.getValue();
},
ref: function (_ref) {
self.editor = _ref;
},
listeners: [{
eventName: BI.ShelterEditor.EVENT_CONFIRM,
action: function () {
self.storeValue = this.getValue();
self.fireEvent("EVENT_RENAME", self.storeValue);
}
}]
}, {
type: "bi.vertical_adapt",
width: ICON_WIDTH * 2 ,
cls: "operations",
invisible: o.create != "true",
items: [{
type: "bi.icon_button",
cls: "rename-font",
height: o.height,
width: ICON_WIDTH,
stopPropagation: true,
title: BI.i18nText("Dec-Basic_Rename"),
handler: function () {
self.editor.focus();
}
}, {
type: "dec.bubble.combo",
el: {
type: "bi.icon_button",
cls: "default-delete-font",
height: o.height,
width: ICON_WIDTH,
title: BI.i18nText("Dec-Basic_Delete")
},
text: BI.i18nText("Dec-Data_Set_Confirm_Delete"),
onClickConfirm: function () {
self.fireEvent("EVENT_DELETE");
self.deleteCombo.hideView();
},
ref: function (_ref) {
self.deleteCombo = _ref;
}
}]
}]
};
},
getValue: function () {
return this.storeValue;
},
setValue: function (v) {
this.editor.setValue(v);
}
});
BI.shortcut("dec.excelexport.left.linklist.item", Item);
})();

18
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.item.model.js

@ -0,0 +1,18 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
context: ["names"],
computed: {},
actions: {
nameChecker: function (name) {
if (name === this.options.value) {
return true;
}
return !BI.contains(this.model.names, name);
}
}
});
BI.model("dec.model.excelexport.left.linklist.item", Model);
})();

60
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.js

@ -0,0 +1,60 @@
!(function () {
var SINGLE = BI.inherit(BI.Widget, {
props: {
baseCls: "dec-directory-left-single",
$testId: "dec-directory-left-single",
containReuse: false
},
_store: function () {
return BI.Models.getModel("dec.model.excelexport.left.linklist", this.options);
},
beforeInit: function (callback) {
this.store.initData(callback);
},
watch:{
linklist: function () {
this.linkListPane.populate(this.model.items);
this.linkListPane.setValue(this.model.selectedName);
}
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.absolute",
items: [{
el: {
type: "bi.button_group",
chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE,
layouts: [{
type: "bi.vertical"
}],
items: self.model.items,
value: self.model.selectedLink,
listeners: [{
eventName: BI.ButtonGroup.EVENT_CHANGE,
action: function (v) {
self.store.setSelectedLink(v);
}
}],
ref: function (_ref) {
self.linkListPane = _ref;
}
}, top: 10, left: 0, right: 0, bottom: 10
}]
};
},
populate: function () {
var self = this;
self.store.initData(
self.linkListPane.populate(this.model.items)
);
}
});
BI.shortcut("dec.excelexport.left.linklist", SINGLE);
})();

99
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.linklist.model.js

@ -0,0 +1,99 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
state: function () {
return {
linklist: []
};
},
context: ["selectedLink"],
computed: {
items: function () {
var self = this , o = this.options;
return BI.map(self.model.linklist, function (i, v) {
return {
type: "dec.excelexport.left.linklist.item",
value: v.name,
create: v.create,
listeners: [{
eventName: "EVENT_RENAME",
action: function (name) {
self.rename(v, name);
}
}, {
eventName: "EVENT_DELETE",
action: function () {
self.deleteLink(v.id);
}
}]
};
});
}
},
actions: {
initData: function(callback){
var self = this ;
Dec.reqGet("/url/excelmng/querylink?containReuse=" + self.options.containReuse,null,function(e){
self.model.linklist = e.data;
console.log(self.model.linklist);
BI.isFunction(callback) && callback();
},BI.emptyFn)
},
//link重命名
rename: function(item, name){
if (item.name === name) {
return;
}
var self = this;
var linkSet = BI.extend({}, item, {
id: item.id,
name: item.name
});
Dec.reqGet("/url/excelmng/rename?id="+item.id+"&name="+name,
null,
function (e) {
if (e.status === "success"){
BI.remove(self.model.linklist, function (i, v) {
return v.id === item.id;
});
self.model.linklist.unshift(BI.extend(linkSet, {
name: name
}));
if (self.model.selectedLink === linkSet.name) {
self.setSelectedDataSet(name);
}
}
},
BI.emptyFn)
},
//link删除
deleteLink: function(id){
var self = this;
Dec.reqGet("/url/excelmng/delete?id="+id,
null,
function (e) {
if (e.status === "success"){
BI.remove(self.model.linklist, function (i, v) {
return v.id === id;
});
} else {
BI.Msg.toast(BI.i18nText("Dec-Basic_Delete_Fail"), {level: "error"});
}
},
BI.emptyFn)
},
setSelectedLink: function(v){
this.model.selectedLink = v;
}
}
});
BI.model("dec.model.excelexport.left.linklist", Model);
}());

7
src/main/resources/com/fr/plugin/hw/decision/js/pane/left.model.js

@ -0,0 +1,7 @@
!(function () {
var Store = BI.inherit(Fix.Model, {
context:["selectedLink"],
childContext: ["selectedLink"]
});
BI.model("dec.model.excelexport.left", Store);
})();

70
src/main/resources/com/fr/plugin/hw/decision/js/pane/panes.js

@ -0,0 +1,70 @@
!(function () {
var panes = BI.inherit(BI.Widget, {
props: {
baseCls: ""
},
_store: function () {
return BI.Models.getModel("dec.model.mng.panes");
},
watch:{
activeTab:function(v){
this.tab.setSelect(v);
}
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.vertical",
items: [{
type: "bi.htape",
cls: "bi-card bi-border-bottom",
items: [{
el: {
type: "dec.line_segment",
cls: "dec-font-weight-bold",
layouts: [{
type: "bi.vertical_adapt"
}],
items: BI.map(BI.Constants.getConstant("dec.hw.constant.tabs"), function(e, t) {
return BI.extend({
type: "dec.line_segment_button",
hgap: 15
}, t)
}),
value: "export",
height: 40,
listeners: [{
eventName: "EVENT_CHANGE",
action: function(e) {
self.store.setSelect(e);
}
}]
},
lgap: 10
}],
height: 40
}, {
type: "bi.tab",
ref: function(_ref) {
self.tab = _ref;
},
height: "95%",
showIndex: "export",
cardCreator: function(v) {
switch (v) {
case "export":
return {
type: "dec.mng.excelExportPane"
};
case "auth":
return {
type: "dec.mng.authPane"
};
}
}
}]
}
}
});
BI.shortcut("dec.mng.panes", panes);
})();

16
src/main/resources/com/fr/plugin/hw/decision/js/pane/panes.model.js

@ -0,0 +1,16 @@
var Store = BI.inherit(Fix.Model, {
state: function () {
return {
activeTab: ""
};
},
computed: {
},
actions: {
setSelect: function (v) {
this.model.activeTab = v
}
}
});
BI.model("dec.model.mng.panes", Store);

150
src/main/resources/com/fr/plugin/hw/decision/js/pane/right.js

@ -0,0 +1,150 @@
!(function () {
var Left = BI.inherit(BI.Widget, {
props: {
baseCls: ""
},
_store: function () {
return BI.Models.getModel("dec.model.excelexport.right");
},
render: function () {
var self = this, o = this.options;
return {
type: "bi.vtape",
items: [
{
type: "bi.left_right_vertical_adapt",
cls: "bi-border-bottom",
items:{
left: [{
type: "bi.label",
text: "数据明细",
textAlign: "left",
hgap: 5,
height: 40
}],
right: [{
type: "bi.button",
text: "刷新",
level: "success",
minWidth:60,
hgap:10,
handler:function(){
if (BI.isKey(self.model.selectedLink)) {
self.table.populate();
}
}
},{
type: "bi.button",
text: "覆盖",
level: "common",
minWidth:60,
hgap:10,
handler:function () {
var pane = {
type: "dec.hw.table.add.popup",
add:false,
infoId:"cover",
aliasName: self.model.selectedLink,
onClickConfirm: function (val, callback) {
console.log(val);
Dec.HW.importTableData(val,function (res) {
debugger;
callback(res);
});
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
};
if (self.model.selectedLink === BI.emptyStr) {
BI.Msg.toast("先选择左侧链接");
return;
}
BI.Popovers.create(self.getName() + "edit", {
type: "bi.popover",
header: "覆盖",
body: pane,
width: 700,
height: 600,
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
}).open(self.getName() + "edit");
}
},{
type: "bi.button",
text: "追加",
level: "common",
minWidth:60,
hgap:10,
handler:function () {
var pane = {
type: "dec.hw.table.add.popup",
add:false,
infoId:"addTo",
aliasName: self.model.selectedLink,
onClickConfirm: function (val, callback) {
console.log(val);
Dec.HW.importTableData(val,function (res) {
callback(res);
})
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
};
if (self.model.selectedLink === BI.emptyStr) {
BI.Msg.toast("先选择左侧链接");
return;
}
BI.Popovers.create(self.getName() + "edit", {
type: "bi.popover",
header: "追加",
body: pane,
width: 700,
height: 600,
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Popovers.remove(self.getName() + "edit");
}
}
]
}).open(self.getName() + "edit");
}
}]
},
height: 40
}, {
type: "dec.excelexport.right.table",
ref:function(_ref){
self.table = _ref
}
}
]
};
}
});
BI.shortcut("dec.excelexport.right", Left);
})();

7
src/main/resources/com/fr/plugin/hw/decision/js/pane/right.model.js

@ -0,0 +1,7 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
context:["selectedLink"],
childContext: ["selectedLink"],
});
BI.model("dec.model.excelexport.right", Model);
})();

74
src/main/resources/com/fr/plugin/hw/decision/js/pane/right.table.js

@ -0,0 +1,74 @@
!(function () {
var Counter = BI.inherit(BI.Widget, {
_store: function () {
return BI.Models.getModel("dec.model.excelexport.right.table");
},
watch:{
"header||items": function (v) {
var self = this;
self.pager.setAllPages(0 === self.model.totalCount ? 1 : Math.ceil(self.model.totalCount / self.model.perCount));
self.table.populate(self.model.items, [self.model.header]);
},
selectedLink:function (v){
this.pager.setPage(1);
this.tabpane.setVisible(true);
}
},
render: function () {
var self = this, o = this.options;
return {
type:"bi.absolute",
items:[{
el:{
type:"bi.absolute",
invisible: true,
items:[{
el:{
type: "bi.preview_table",
header: [self.model.header],
items: self.model.items,
headerRowSize: 40,
ref: function (_ref) {
self.table = _ref;
}
},
top:0,bottom:0,left:0,right:0
}],
ref: function (_ref) {
self.tabpane = _ref;
}
},
top:10,bottom:30,left:10,right:10
},{
el:{
type: "dec.pager",
height: 30,
tgap: 10,
count: self.model.totalCount,
pages: 0 === self.model.totalCount ? 1 : Math.ceil(self.model.totalCount / self.model.perCount),
ref: function(_ref) {
self.pager = _ref
},
listeners: [{
eventName: "EVENT_CHANGE",
action: function() {
self.store.setPage(this.getCurrentPage());
}
}]
},
bottom:0,right:30
}]
};
},
populate: function(){
this.model.currentPage = 1;
this.pager.setPage(1);
this.store.initData();
}
});
BI.shortcut("dec.excelexport.right.table", Counter);
})();

77
src/main/resources/com/fr/plugin/hw/decision/js/pane/right.table.model.js

@ -0,0 +1,77 @@
!(function () {
var Store = BI.inherit(Fix.Model, {
state: function () {
return {
tableData:[],
headerData:[],
currentPage: 1,
totalCount: 0,
perCount: 20
};
},
context:["selectedLink"],
watch: {
selectedLink: function () {
this.model.currentPage = 1;
this.initData();
}
},
computed: {
header: function () {
var self = this;
var head = [];
var con = BI.Constants.getConstant("dec.hw.col.type") ;
BI.map( self.model.headerData,function (i, val) {
var text = BI.filter(con, function (index, v) {
return BI.isEqual(val.colType, parseInt(v.value))
})[0].text;
head.push({"text":val.colName + "(" + text + ")"})
});
return head;
},
columnSize: function () {
var self = this;
var len = self.model.header.length;
return new Array(len).fill((1/len).toFixed(2));
},
items: function () {
var startNum = this.model.perCount * (this.model.currentPage - 1);
return this.model.tableData.slice(startNum, startNum + this.model.perCount)
},
totalCount: function () {
return BI.size(this.model.tableData)
}
},
actions:{
initData: function (callback) {
var self = this;
Dec.HW.queryData({
name: self.model.selectedLink
}, function (res) {
self.model.tableData = res.data.tableData;
/*BI.each(res.tabledata.colAttr, function (index, val) {
if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.int"), val.colType)) {
val.colType = 2;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.str"), val.colType)) {
val.colType = 12;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.bool"), val.colType)) {
val.colType = 16;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.date"), val.colType)) {
val.colType = 91;
}
});*/
self.model.headerData = BI.hwColTypeDeal(res.data.colAttr);
BI.isFunction(callback) && callback();
});
},
setPage: function(val) {
this.model.currentPage = val
}
}
});
BI.model("dec.model.excelexport.right.table", Store);
})();

243
src/main/resources/com/fr/plugin/hw/decision/js/table.info.js

@ -0,0 +1,243 @@
;!(function () {
var tableInfo = BI.inherit(BI.Widget, {
props: {
add: true,
infoId:""
},
_store: function () {
return BI.Models.getModel("dec.hw.table.info.model",{
infoId:this.options.infoId,
aliasName:this.options.aliasName
});
},
beforeInit: function (callback) {
this.store.initData(callback)
},
watch: {
sheetItems: function (v) {
if (v.show) {
this.showSheetSelect(v.items);
} else {
this.hideSheetSelect()
}
},
importStatus: function (v) {
switch (v) {
case "importing":
this._startImport();
break;
case "abort":
this._stopImport();
break;
case "finish":
default:
this._finishImport();
}
}
},
render: function () {
var self = this, o = this.options;
var file = {
type: "bi.multifile_editor",
ref: function (_ref) {
self.file = _ref;
},
url: Dec.fineServletURL + "/url/hw/file/upload?width=32&height=32",
listeners: [
{
eventName: BI.MultifileEditor.EVENT_ERROR,
action: function (args) {
/* self.fireEvent("EVENT_ERROR");
self._closeUpload();*/
}
}, {
eventName: BI.MultifileEditor.EVENT_UPLOADED,
action: function (args) {
console.log("EVENT_UPLOADED");
var files = this.getValue();
if (files[files.length - 1].errorCode) {
BI.Msg.toast(BI.i18nText(files[files.length - 1].errorMsg), {
level: "error"
});
self.store.setImportStatus("abort");
return;
}
var filename = files[files.length - 1].filename;
// 新增文件格式判断
if ( !BI.endWith(filename,".xls") && !BI.endWith(filename,".xlsx")){
BI.Msg.toast(BI.i18nText("上传文件格式不正确, 请重新上传excel文件"), {
level: "error"
});
self.store.setImportStatus("abort");
return;
}
self.uploadButton.setEnable(false);
self.uploadButton.setText("已上传");
var id = files[files.length - 1].attach_id;
self.store.getExcelSheetNumber(id, filename);
}
}, {
eventName: BI.MultifileEditor.EVENT_CHANGE,
action: function () {
self.store.setImportStatus("importing");
this.upload();
/*self._startUpload();*/
}
}
]
};
var header = {
type: "bi.htape",
height: 24,
items: [
{
el:{
type: "bi.button",
textAlign: "center",
height: 24,
text: "上传文件",
ref: function (_ref) {
self.uploadButton = _ref;
},
handler: function () {
self.file.select();
}
}
}, {
el: file
}
]
};
return {
type: "bi.absolute",
items: [{
el: {
type: "bi.vtape",
items: [
{
el: header,
height: 24
},
{
type: "bi.absolute",
items: [{
el: {
type: "bi.vtape",
items: [{
height: 0.35,
el: {
type: "dec.card.vertical",
showButtons: false,
text: "表信息",
content: {
type: "dec.hw.table.attr",
add:o.add,
ref:function(_ref){
self.table = _ref;
},
info:{
connection:self.model.connection,
schema:self.model.schema,
tableName:self.model.tableName,
aliasName:o.aliasName
}
}
}
}, {
height: 0.65,
el: {
type: "dec.card.vertical",
showButtons: false,
text: "列信息",
content: {
type: "dec.hw.table.col.attr",
add:o.add
//text: "111"
}
}
}]
},
top: 0, bottom: 0, left: 0, right: 0
}]
}
]
},
top: 0, bottom: 0, left: 10, right: 10
}]
}
},
showSheetSelect: function (items) {
var self=this;
var name = this.getName() + "sheet";
BI.Maskers.create(name, null, {
render: {
type: "dec.hw.sheet.select",
items: items,
onClickConfirm:function(val,callback){
self.store.getSheetFiledWithNo(val,callback)
},
listeners: [
{
eventName: "EVENT_CLOSE",
action: function () {
BI.Maskers.hide(name);
BI.Maskers.remove(name);
}
}
]
}
});
BI.Maskers.show(name);
},
hideSheetSelect: function () {
var name = this.getName() + "sheet";
BI.Maskers.hide(name);
BI.Maskers.remove(name);
},
getValue: function () {
return {
items: this.model.items,
connection: this.model.connection,
schema: this.model.schema,
aliasName: this.model.aliasName,
tableName: this.model.tableName,
infoId: this.model.infoId,
sheetInfo:this.model.result
}
},
_startImport: function () {
var self = this, name = this.getName() + "status";
var upload = {
type: "dec.test.status",
waitingText: "导入中",
successText: "导入成功",
failText: "导入失败",
listeners: [{
eventName: "EVENT_CLOSE",
action: function () {
BI.Maskers.hide(name);
BI.Maskers.remove(name);
}
}],
ref: function (_ref) {
self.uploadMasker = _ref;
}
};
BI.Maskers.create(name, null, {
render: upload
});
BI.Maskers.show(name);
},
_stopImport: function () {
var name = this.getName() + "status";
BI.Maskers.hide(name);
BI.Maskers.remove(name);
},
_finishImport: function () {
this.uploadMasker && this.uploadMasker.setStatus({
status: DecCst.TestStatus.SUCCESS
});
}
});
BI.shortcut("dec.hw.table.info", tableInfo);
})();

158
src/main/resources/com/fr/plugin/hw/decision/js/table.info.model.js

@ -0,0 +1,158 @@
!(function () {
var Model = BI.inherit(Fix.Model, {
state: function () {
var o=this.options;
return {
items: [],
connection: "",
schema: "",
tableName: "",
excelItems: [],
infoId: o.infoId,
result: {attachId: "", fileName: "",titleRow:-1,sheetNo:-1},
sheetItems: {show: false, items: []},
importStatus: ""//导入的状态
};
},
childContext: ["items", "connection", "schema", "aliasName", "tableName", "excelItems", "infoId"],
computed: {},
watch: {
aliasName: function (v) {
//console.log(v)
},
excelItems:function (v) {
if (this.model.infoId == "add"){
this.addItems()
}
}
},
actions: {
initData: function (callback) {
var self = this, o = this.options;
console.log(self.model.infoId);
if(self.model.infoId === "add"){
callback && callback();
return;
}
Dec.HW.queryData({
name: o.aliasName
}, function (res) {
/*BI.each(res.tabledata.colAttr, function (index, val) {
if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.int"), val.colType)) {
val.colType = 2;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.str"), val.colType)) {
val.colType = 12;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.bool"), val.colType)) {
val.colType = 16;
} else if (BI.contains(BI.Constants.getConstant("dec.hw.col.type.date"), val.colType)) {
val.colType = 91;
}
});*/
self.model.items = BI.hwColTypeDeal(res.data.colAttr);
self.model.connection = res.data.tableAttr.connection;
self.model.schema = res.data.tableAttr.schema;
self.model.tableName = res.data.tableAttr.tableName;
BI.isFunction(callback) && callback();
});
},
getExcelSheetNumber: function (attachId, fileName) {
var self = this;
Dec.HW.getExcelItmes({attachId: attachId, fileName: fileName}, function (res) {
if (res.success) {
self.model.result.attachId = attachId;
self.model.result.fileName = fileName;
self.getSheetFiled(res.data);
} else {
self.model.importStatus="abort";
}
})
},
getSheetFiled: function (data) {
var self = this;
if (data.length == 1) {//只有一个sheet 的话 就不让选择了直接
Dec.HW.getSheetFiled({
attachId: self.model.result.attachId,
sheetNo: 0,
fileName: self.model.result.fileName
}, function (res) {
if (res.success) {
self.model.result.sheetNo=0;
self.model.result.titleRow=res.data[0].titleRow;
self.model.excelItems = res.data;
// items 匹配相同的列名
BI.each(self.model.items, function (index, item) {
var sameNameItem = BI.filter(self.model.excelItems, function (i, v) {
return v.text == item.colName
});
if (sameNameItem.length != 0){
item.excelCol = sameNameItem[0].value;
}
});
self.model.importStatus="finish";
} else {
self.model.importStatus="abort";
BI.Msg.toast(res.msg,{level:"error"});
}
});
} else {
self.model.sheetItems = {show: true, items: data};
}
},
getSheetFiledWithNo: function (sheetNo, callback) {
var self = this;
Dec.HW.getSheetFiled({
attachId: self.model.result.attachId,
sheetNo: sheetNo,
fileName: self.model.result.fileName
}, function (res) {
if (res.success) {
self.model.result.sheetNo=sheetNo;
self.model.result.titleRow=res.data[0].titleRow;
self.model.excelItems = res.data;
// items 匹配相同的列名
BI.each(self.model.items, function (index, item) {
var sameNameItem = BI.filter(self.model.excelItems, function (i, v) {
return v.text == item.colName
});
if (sameNameItem.length != 0){
item.excelCol = sameNameItem[0].value;
}
});
self.model.importStatus="finish";
callback && callback(true);
} else {
self.model.importStatus="abort";
BI.Msg.toast(res.msg,{level:"error"});
callback && callback(false);
}
});
},
setImportStatus:function (v) {
this.model.importStatus=v;
},
addItems:function () {
var self=this;
var result=BI.map(self.model.excelItems,function (index, item) {
return {
id:BI.UUID(),
colName:item.text,
colType:"12",
colLength: 255,
excelCol:item.value
}
});
self.model.items=BI.concat(self.model.items,result);
}
}
});
BI.model("dec.hw.table.info.model", Model);
})();

26
src/main/resources/com/fr/plugin/hw/decision/js/utils.js

@ -0,0 +1,26 @@
;!(function (res) {
Dec.HW = Dec.HW || {};
Dec.HW = $.extend(Dec.HW, {
getExcelItmes: function (config, callback) {
Dec.reqPost("/url/hw/excel/sheet", config, callback)
},
getSheetFiled: function (config, callback) {
Dec.reqPost("/url/hw/excel/filed", config, callback)
},
importTableData: function (config, callback) {
Dec.reqPost("/url/hw/table/import", config, callback)
},
getAllUserData: function (config, callback) {
Dec.reqPost("/url/excelmng/getAllUserList", config, callback)
},
getAuthUserData: function (config, callback) {
Dec.reqPost("/url/excelmng/getAuthUserList", config, callback)
},
updateLinkAuth: function (config, callback) {
Dec.reqPost("/url/excelmng/updateLinkAuth", config, callback)
},
queryData: function (config, callback) {
Dec.reqPost("/url/excelmng/querydata", config, callback)
}
})
})();
Loading…
Cancel
Save