init: 导入项目
This commit is contained in:
422
ILogBizSystem/pom.xml
Normal file
422
ILogBizSystem/pom.xml
Normal file
@@ -0,0 +1,422 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.ag.jngh</groupId>
|
||||
<artifactId>AG_ONE</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
<groupId>com.ag.jngh</groupId>
|
||||
<artifactId>ILogBizSystem</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<name>ILogBizSystem Maven Webapp</name>
|
||||
<!-- FIXME change it to the project's website -->
|
||||
<url>http://www.example.com</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.hynnet</groupId>
|
||||
<artifactId>oracle-driver-ojdbc6</artifactId>
|
||||
<version>12.1.0.1</version>
|
||||
</dependency>
|
||||
<!--<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.47</version>
|
||||
</dependency>-->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>8.0.11</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>rqsoft</groupId>
|
||||
<artifactId>raqsoftReport</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
<!--读取pdf内容 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>pdfbox</artifactId>
|
||||
<version>2.0.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.spotify</groupId>
|
||||
<artifactId>docker-client</artifactId>
|
||||
<version>8.4.0</version>
|
||||
</dependency>
|
||||
<!--添加jar-->
|
||||
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
|
||||
<dependency>
|
||||
<groupId>anjiDubboGroup</groupId>
|
||||
<artifactId>anjiDubboArtifact</artifactId>
|
||||
<version>2.8.5</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.101tec</groupId>
|
||||
<artifactId>zkclient</artifactId>
|
||||
<version>0.10</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>hessian-dubbo</groupId>
|
||||
<artifactId>hessina-dubbo</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
<!--添加jar-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mozilla</groupId>
|
||||
<artifactId>rhino</artifactId>
|
||||
<version>1.7.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-core</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-web</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-ehcache</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-spring</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-collections</groupId>
|
||||
<artifactId>commons-collections</artifactId>
|
||||
<version>3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>anji-jsonGroup</groupId>
|
||||
<artifactId>anji-jsonArtifact</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring4</artifactId>
|
||||
<version>2.1.4.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf</artifactId>
|
||||
<version>2.1.4.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<!-- http://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
<!-- http://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>2.6.0</version>
|
||||
</dependency>
|
||||
<!-- http://mvnrepository.com/artifact/com.yahoo.platform.yui/yuicompressor -->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>1.0.0.GA</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
||||
<version>4.1.0.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid</artifactId>
|
||||
<version>1.1.5</version>
|
||||
</dependency>
|
||||
<!--新增jar -->
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.9</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dom4j</groupId>
|
||||
<artifactId>dom4j</artifactId>
|
||||
<version>1.6.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>Agmozillagroup</groupId>
|
||||
<artifactId>AgmozillArtifact</artifactId>
|
||||
<version>1.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>AgrihnoGroup</groupId>
|
||||
<artifactId>AgrihnoArtifact</artifactId>
|
||||
<version>1.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>AgyuicompressGroup</groupId>
|
||||
<artifactId>AgyuicompressArtifact</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
|
||||
<!--spring mongo==******************************************start-->
|
||||
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb</artifactId>
|
||||
<version>1.8.2.RELEASE</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-commons</artifactId>
|
||||
<version>1.11.2.RELEASE</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
<version>3.0.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.offbytwo.jenkins</groupId>
|
||||
<artifactId>jenkins-client</artifactId>
|
||||
<version>0.3.8</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-spring-context</artifactId>
|
||||
<version>0.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<!--Spring整合redis-->
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>2.9.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-redis</artifactId>
|
||||
<version>1.8.3.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.belerweb</groupId>
|
||||
<artifactId>pinyin4j</artifactId>
|
||||
<version>2.5.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.ag.Psamathe</groupId>
|
||||
<artifactId>psamathe</artifactId>
|
||||
<version>3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.ag.jngh</groupId>
|
||||
<artifactId>Webplatform</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.ag.jngh</groupId>
|
||||
<artifactId>commonapi</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baidu.aip</groupId>
|
||||
<artifactId>java-sdk</artifactId>
|
||||
<version>4.16.7</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- webSocket 开始-->
|
||||
<dependency>
|
||||
<groupId>javax.websocket</groupId>
|
||||
<artifactId>javax.websocket-api</artifactId>
|
||||
<version>1.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-websocket</artifactId>
|
||||
<version>8.5.15</version>
|
||||
</dependency>-->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
</dependency>
|
||||
|
||||
<!--监控sql -->
|
||||
<dependency>
|
||||
<groupId>p6spy</groupId>
|
||||
<artifactId>p6spy</artifactId>
|
||||
<version>3.9.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>dev</id>
|
||||
<properties>
|
||||
<profile.dir>${basedir}/src/main/resources.dev</profile.dir>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>prod</id>
|
||||
<properties>
|
||||
<profile.dir>${basedir}/src/main/resources.prod</profile.dir>
|
||||
</properties>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>test</id>
|
||||
<properties>
|
||||
<profile.dir>${basedir}/src/main/resources.test</profile.dir>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<build>
|
||||
<finalName>ILogBizSystem</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<include>**/*.xml</include>
|
||||
<include>**/*.properties</include>
|
||||
<include>templates/**</include>
|
||||
</includes>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${profile.dir}</directory>
|
||||
<includes>
|
||||
<include>**/*.xml</include>
|
||||
<include>**/*.properties</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>web.xml</exclude>
|
||||
</excludes>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${profile.dir}</directory>
|
||||
<includes>
|
||||
<include>web.xml</include>
|
||||
</includes>
|
||||
<targetPath>${project.build.directory}/${project.build.finalName}/WEB-INF/</targetPath>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-clean-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</plugin>
|
||||
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.2.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>2.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>2.8.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票商品金额
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:03
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityAmount {
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票商品名称
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:07
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityName {
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票商品编号
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:01
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityNum {
|
||||
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 价格
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:06
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityPrice {
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票税信息
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:02
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityTax {
|
||||
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 发票商品税率
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:03
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityTaxRate {
|
||||
private Date word;
|
||||
private String row;
|
||||
|
||||
public Date getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(Date word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票商品类型
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:07
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityType {
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* 发票商品单位
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:05
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class CommodityUnit {
|
||||
private String word;
|
||||
private String row;
|
||||
|
||||
public String getWord() {
|
||||
return word;
|
||||
}
|
||||
|
||||
public void setWord(String word) {
|
||||
this.word = word;
|
||||
}
|
||||
|
||||
public String getRow() {
|
||||
return row;
|
||||
}
|
||||
|
||||
public void setRow(String row) {
|
||||
this.row = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
/**
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:10
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class OcrInvoiceRootData {
|
||||
private String log_id;
|
||||
private int words_result_num;
|
||||
private WordsResult words_result;
|
||||
|
||||
public String getLog_id() {
|
||||
return log_id;
|
||||
}
|
||||
|
||||
public void setLog_id(String log_id) {
|
||||
this.log_id = log_id;
|
||||
}
|
||||
|
||||
public int getWords_result_num() {
|
||||
return words_result_num;
|
||||
}
|
||||
|
||||
public void setWords_result_num(int words_result_num) {
|
||||
this.words_result_num = words_result_num;
|
||||
}
|
||||
|
||||
public WordsResult getWords_result() {
|
||||
return words_result;
|
||||
}
|
||||
|
||||
public void setWords_result(WordsResult words_result) {
|
||||
this.words_result = words_result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package com.ag.baiduapi.pojo.ocr.invoice;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:08
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class WordsResult {
|
||||
|
||||
private String InvoiceNum;
|
||||
private String SellerName;
|
||||
private List<CommodityTaxRate> CommodityTaxRate;
|
||||
private String SellerBank;
|
||||
private String Checker;
|
||||
private String TotalAmount;
|
||||
private List<CommodityAmount> CommodityAmount;
|
||||
private String InvoiceDate;
|
||||
private List<CommodityTax> CommodityTax;
|
||||
private String PurchaserName;
|
||||
private List<CommodityNum> CommodityNum;
|
||||
private String Province;
|
||||
private String City;
|
||||
private String SheetNum;
|
||||
private String Agent;
|
||||
private String PurchaserBank;
|
||||
private String Remarks;
|
||||
private String Password;
|
||||
private String SellerAddress;
|
||||
private String PurchaserAddress;
|
||||
private String InvoiceCode;
|
||||
private List<CommodityUnit> CommodityUnit;
|
||||
private String Payee;
|
||||
private String PurchaserRegisterNum;
|
||||
private List<CommodityPrice> CommodityPrice;
|
||||
private String NoteDrawer;
|
||||
private String AmountInWords;
|
||||
private String AmountInFiguers;
|
||||
private String TotalTax;
|
||||
private String InvoiceType;
|
||||
private String SellerRegisterNum;
|
||||
private List<CommodityName> CommodityName;
|
||||
private List<CommodityType> CommodityType;
|
||||
|
||||
public String getInvoiceNum() {
|
||||
return InvoiceNum;
|
||||
}
|
||||
|
||||
public void setInvoiceNum(String invoiceNum) {
|
||||
InvoiceNum = invoiceNum;
|
||||
}
|
||||
|
||||
public String getSellerName() {
|
||||
return SellerName;
|
||||
}
|
||||
|
||||
public void setSellerName(String sellerName) {
|
||||
SellerName = sellerName;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityTaxRate> getCommodityTaxRate() {
|
||||
return CommodityTaxRate;
|
||||
}
|
||||
|
||||
public void setCommodityTaxRate(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityTaxRate> commodityTaxRate) {
|
||||
CommodityTaxRate = commodityTaxRate;
|
||||
}
|
||||
|
||||
public String getSellerBank() {
|
||||
return SellerBank;
|
||||
}
|
||||
|
||||
public void setSellerBank(String sellerBank) {
|
||||
SellerBank = sellerBank;
|
||||
}
|
||||
|
||||
public String getChecker() {
|
||||
return Checker;
|
||||
}
|
||||
|
||||
public void setChecker(String checker) {
|
||||
Checker = checker;
|
||||
}
|
||||
|
||||
public String getTotalAmount() {
|
||||
return TotalAmount;
|
||||
}
|
||||
|
||||
public void setTotalAmount(String totalAmount) {
|
||||
TotalAmount = totalAmount;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityAmount> getCommodityAmount() {
|
||||
return CommodityAmount;
|
||||
}
|
||||
|
||||
public void setCommodityAmount(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityAmount> commodityAmount) {
|
||||
CommodityAmount = commodityAmount;
|
||||
}
|
||||
|
||||
public String getInvoiceDate() {
|
||||
return InvoiceDate;
|
||||
}
|
||||
|
||||
public void setInvoiceDate(String invoiceDate) {
|
||||
InvoiceDate = invoiceDate;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityTax> getCommodityTax() {
|
||||
return CommodityTax;
|
||||
}
|
||||
|
||||
public void setCommodityTax(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityTax> commodityTax) {
|
||||
CommodityTax = commodityTax;
|
||||
}
|
||||
|
||||
public String getPurchaserName() {
|
||||
return PurchaserName;
|
||||
}
|
||||
|
||||
public void setPurchaserName(String purchaserName) {
|
||||
PurchaserName = purchaserName;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityNum> getCommodityNum() {
|
||||
return CommodityNum;
|
||||
}
|
||||
|
||||
public void setCommodityNum(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityNum> commodityNum) {
|
||||
CommodityNum = commodityNum;
|
||||
}
|
||||
|
||||
public String getProvince() {
|
||||
return Province;
|
||||
}
|
||||
|
||||
public void setProvince(String province) {
|
||||
Province = province;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return City;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
City = city;
|
||||
}
|
||||
|
||||
public String getSheetNum() {
|
||||
return SheetNum;
|
||||
}
|
||||
|
||||
public void setSheetNum(String sheetNum) {
|
||||
SheetNum = sheetNum;
|
||||
}
|
||||
|
||||
public String getAgent() {
|
||||
return Agent;
|
||||
}
|
||||
|
||||
public void setAgent(String agent) {
|
||||
Agent = agent;
|
||||
}
|
||||
|
||||
public String getPurchaserBank() {
|
||||
return PurchaserBank;
|
||||
}
|
||||
|
||||
public void setPurchaserBank(String purchaserBank) {
|
||||
PurchaserBank = purchaserBank;
|
||||
}
|
||||
|
||||
public String getRemarks() {
|
||||
return Remarks;
|
||||
}
|
||||
|
||||
public void setRemarks(String remarks) {
|
||||
Remarks = remarks;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return Password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
Password = password;
|
||||
}
|
||||
|
||||
public String getSellerAddress() {
|
||||
return SellerAddress;
|
||||
}
|
||||
|
||||
public void setSellerAddress(String sellerAddress) {
|
||||
SellerAddress = sellerAddress;
|
||||
}
|
||||
|
||||
public String getPurchaserAddress() {
|
||||
return PurchaserAddress;
|
||||
}
|
||||
|
||||
public void setPurchaserAddress(String purchaserAddress) {
|
||||
PurchaserAddress = purchaserAddress;
|
||||
}
|
||||
|
||||
public String getInvoiceCode() {
|
||||
return InvoiceCode;
|
||||
}
|
||||
|
||||
public void setInvoiceCode(String invoiceCode) {
|
||||
InvoiceCode = invoiceCode;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityUnit> getCommodityUnit() {
|
||||
return CommodityUnit;
|
||||
}
|
||||
|
||||
public void setCommodityUnit(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityUnit> commodityUnit) {
|
||||
CommodityUnit = commodityUnit;
|
||||
}
|
||||
|
||||
public String getPayee() {
|
||||
return Payee;
|
||||
}
|
||||
|
||||
public void setPayee(String payee) {
|
||||
Payee = payee;
|
||||
}
|
||||
|
||||
public String getPurchaserRegisterNum() {
|
||||
return PurchaserRegisterNum;
|
||||
}
|
||||
|
||||
public void setPurchaserRegisterNum(String purchaserRegisterNum) {
|
||||
PurchaserRegisterNum = purchaserRegisterNum;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityPrice> getCommodityPrice() {
|
||||
return CommodityPrice;
|
||||
}
|
||||
|
||||
public void setCommodityPrice(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityPrice> commodityPrice) {
|
||||
CommodityPrice = commodityPrice;
|
||||
}
|
||||
|
||||
public String getNoteDrawer() {
|
||||
return NoteDrawer;
|
||||
}
|
||||
|
||||
public void setNoteDrawer(String noteDrawer) {
|
||||
NoteDrawer = noteDrawer;
|
||||
}
|
||||
|
||||
public String getAmountInWords() {
|
||||
return AmountInWords;
|
||||
}
|
||||
|
||||
public void setAmountInWords(String amountInWords) {
|
||||
AmountInWords = amountInWords;
|
||||
}
|
||||
|
||||
public String getAmountInFiguers() {
|
||||
return AmountInFiguers;
|
||||
}
|
||||
|
||||
public void setAmountInFiguers(String amountInFiguers) {
|
||||
AmountInFiguers = amountInFiguers;
|
||||
}
|
||||
|
||||
public String getTotalTax() {
|
||||
return TotalTax;
|
||||
}
|
||||
|
||||
public void setTotalTax(String totalTax) {
|
||||
TotalTax = totalTax;
|
||||
}
|
||||
|
||||
public String getInvoiceType() {
|
||||
return InvoiceType;
|
||||
}
|
||||
|
||||
public void setInvoiceType(String invoiceType) {
|
||||
InvoiceType = invoiceType;
|
||||
}
|
||||
|
||||
public String getSellerRegisterNum() {
|
||||
return SellerRegisterNum;
|
||||
}
|
||||
|
||||
public void setSellerRegisterNum(String sellerRegisterNum) {
|
||||
SellerRegisterNum = sellerRegisterNum;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityName> getCommodityName() {
|
||||
return CommodityName;
|
||||
}
|
||||
|
||||
public void setCommodityName(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityName> commodityName) {
|
||||
CommodityName = commodityName;
|
||||
}
|
||||
|
||||
public List<com.ag.baiduapi.pojo.ocr.invoice.CommodityType> getCommodityType() {
|
||||
return CommodityType;
|
||||
}
|
||||
|
||||
public void setCommodityType(List<com.ag.baiduapi.pojo.ocr.invoice.CommodityType> commodityType) {
|
||||
CommodityType = commodityType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ag.baiduapi.pojo.ocr.normal;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class OcrNormalData {
|
||||
private String logId;//返回识别ID
|
||||
private String wordsResultNum;//识别记录数
|
||||
private String direction;//朝向 0正
|
||||
|
||||
private List<OcrNormalDataWords> wordsResult;//识别内容
|
||||
|
||||
public String getLogId() {
|
||||
return logId;
|
||||
}
|
||||
|
||||
public void setLogId(String logId) {
|
||||
this.logId = logId;
|
||||
}
|
||||
|
||||
public String getWordsResultNum() {
|
||||
return wordsResultNum;
|
||||
}
|
||||
|
||||
public void setWordsResultNum(String wordsResultNum) {
|
||||
this.wordsResultNum = wordsResultNum;
|
||||
}
|
||||
|
||||
public String getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
public void setDirection(String direction) {
|
||||
this.direction = direction;
|
||||
}
|
||||
|
||||
public List<OcrNormalDataWords> getWordsResult() {
|
||||
return wordsResult;
|
||||
}
|
||||
|
||||
public void setWordsResult(List<OcrNormalDataWords> wordsResult) {
|
||||
this.wordsResult = wordsResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.ag.baiduapi.pojo.ocr.normal;
|
||||
|
||||
public class OcrNormalDataWords {
|
||||
private String words;//返回内容
|
||||
|
||||
public String getWords() {
|
||||
return words;
|
||||
}
|
||||
|
||||
public void setWords(String words) {
|
||||
this.words = words;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ag.baiduapi.service;
|
||||
|
||||
import com.ag.baiduapi.util.AipOcrUtil;
|
||||
import com.baidu.aip.contentcensor.EImgType;
|
||||
import com.baidu.aip.ocr.AipOcr;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* @Author jean
|
||||
* @Date 2022/4/19 10:33
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Service
|
||||
public class OcrServicce {
|
||||
|
||||
/**
|
||||
* 识别本地发票PDF
|
||||
* @param pdfPath 本地pdf地址
|
||||
* @return
|
||||
*/
|
||||
public String ocrLocalInvoicePdf(String pdfPath){
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
AipOcr aipOcr= AipOcrUtil.getInstance();
|
||||
JSONObject res = aipOcr.vatInvoice(pdfPath, EImgType.PDF, options);
|
||||
return res.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 识别发票图片
|
||||
* @param imagePath 图片地址
|
||||
* @param imageType LOC本地图片 URL网络图片
|
||||
* @return
|
||||
*/
|
||||
public String ocrInvoiceImage(String imagePath,String imageType){
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
AipOcr aipOcr= AipOcrUtil.getInstance();
|
||||
JSONObject res = aipOcr.vatInvoice(imagePath,"URL".equalsIgnoreCase(imageType)?EImgType.URL:EImgType.FILE, options);
|
||||
return res.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别身份证图片
|
||||
* @param idCardSite 身份证正反 F正 B反
|
||||
* @param imagePath 本地图片地址
|
||||
* @return
|
||||
*/
|
||||
public String ocrLocalIdCardImage(String idCardSite,String imagePath){
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
options.put("detect_direction", "true");
|
||||
options.put("detect_risk", "false");
|
||||
AipOcr aipOcr= AipOcrUtil.getInstance();
|
||||
String idCardSide ="F".equalsIgnoreCase(idCardSite)?"front":"back";
|
||||
JSONObject res =aipOcr.idcard(imagePath, idCardSide, options);
|
||||
return res.toString();
|
||||
}
|
||||
}
|
||||
191
ILogBizSystem/src/main/java/com/ag/baiduapi/util/AipOcrUtil.java
Normal file
191
ILogBizSystem/src/main/java/com/ag/baiduapi/util/AipOcrUtil.java
Normal file
@@ -0,0 +1,191 @@
|
||||
package com.ag.baiduapi.util;
|
||||
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.ag.baiduapi.pojo.ocr.invoice.OcrInvoiceRootData;
|
||||
import com.ag.baiduapi.pojo.ocr.normal.OcrNormalData;
|
||||
import com.ag.baiduapi.service.OcrServicce;
|
||||
import com.ag.util.PropertyUtil;
|
||||
import com.baidu.aip.ocr.AipOcr;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class AipOcrUtil {
|
||||
|
||||
|
||||
//设置APPID/AK/SK 实际项目使用需替换为真实值
|
||||
public static final String APP_ID = PropertyUtil.getProperty("BAIDU_API_APP_ID");
|
||||
public static final String API_KEY = PropertyUtil.getProperty("BAIDU_API_API_KEY");
|
||||
public static final String SECRET_KEY = PropertyUtil.getProperty("BAIDU_API_SECRET_KEY");
|
||||
|
||||
/**
|
||||
* 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
|
||||
* 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
|
||||
*/
|
||||
private static class AipOcrHolder{
|
||||
/**
|
||||
* 静态初始化器,由JVM来保证线程安全
|
||||
*/
|
||||
private static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
|
||||
}
|
||||
/**
|
||||
* 私有化构造方法
|
||||
*/
|
||||
private void AipOcr(){
|
||||
|
||||
}
|
||||
|
||||
public static AipOcr getInstance(){
|
||||
AipOcr aipOcr= AipOcrHolder.client;
|
||||
aipOcr.setConnectionTimeoutInMillis(2000);
|
||||
aipOcr.setSocketTimeoutInMillis(60000);
|
||||
|
||||
return aipOcr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别图片(普通识别)
|
||||
* @param url 图片网络地址
|
||||
* @return
|
||||
*/
|
||||
public static OcrNormalData ocrNormalUrlImage(String url){
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
options.put("language_type", "CHN_ENG");
|
||||
options.put("detect_direction", "true");//是否检测图像朝向
|
||||
options.put("detect_language", "true");// 是否检测语言
|
||||
options.put("probability", "true");//是否返回识别结果中每一行的置信度
|
||||
|
||||
AipOcr aipOcr=AipOcrUtil.getInstance();
|
||||
JSONObject res =aipOcr.basicGeneralUrl(url, options);
|
||||
|
||||
OcrNormalData ocrData= JSONUtil.toBean(res.toString(), OcrNormalData.class);
|
||||
|
||||
return ocrData;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 识别图片(高精度)
|
||||
* @param inputStream 流
|
||||
* @return
|
||||
*/
|
||||
public static OcrNormalData ocrNormalStreamImage (InputStream inputStream){
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
options.put("language_type", "CHN_ENG");
|
||||
options.put("detect_direction", "true");//是否检测图像朝向
|
||||
options.put("detect_language", "true");// 是否检测语言
|
||||
options.put("probability", "false");//是否返回识别结果中每一行的置信度
|
||||
|
||||
//输入流转为byte[]
|
||||
byte[] test = IoUtil.readBytes(inputStream);
|
||||
|
||||
AipOcr aipOcr= AipOcrUtil.getInstance();
|
||||
JSONObject res = aipOcr.basicAccurateGeneral(test, options);
|
||||
|
||||
OcrNormalData ocrData= JSONUtil.toBean(res.toString(), OcrNormalData.class);
|
||||
|
||||
return ocrData;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 本地发票PDF识别
|
||||
* @param pdfPath
|
||||
* @return
|
||||
*/
|
||||
public static OcrInvoiceRootData ocrLocalInvoicePdf(String pdfPath){
|
||||
String result=new OcrServicce().ocrLocalInvoicePdf(pdfPath);
|
||||
OcrInvoiceRootData ocrData= JSONUtil.toBean(result, OcrInvoiceRootData.class);
|
||||
return ocrData;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 本地发票PDF识别返回Json
|
||||
* @param pdfPath
|
||||
* @return
|
||||
*/
|
||||
public static String ocrLocalInvoicePdfStr(String pdfPath){
|
||||
String result=new OcrServicce().ocrLocalInvoicePdf(pdfPath);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 本地发票图片识别
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static OcrInvoiceRootData ocrLocalInvoiceImage(String imagePath){
|
||||
String result=new OcrServicce().ocrInvoiceImage(imagePath,"LOC");
|
||||
OcrInvoiceRootData ocrData= JSONUtil.toBean(result, OcrInvoiceRootData.class);
|
||||
return ocrData;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 网络发票图片识别
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static OcrInvoiceRootData ocrUrlInvoiceImage(String imagePath){
|
||||
String result=new OcrServicce().ocrInvoiceImage(imagePath,"URL");
|
||||
OcrInvoiceRootData ocrData= JSONUtil.toBean(result, OcrInvoiceRootData.class);
|
||||
return ocrData;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 本地发票图片识别返回JSON
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static String ocrLocalInvoiceImageStr(String imagePath){
|
||||
String result=new OcrServicce().ocrInvoiceImage(imagePath,"LOC");
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 网络发票图片识别返回JSON
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static String ocrUrlInvoiceImageStr(String imagePath){
|
||||
String result=new OcrServicce().ocrInvoiceImage(imagePath,"URL");
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 正面身份证本地图片识别
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static String oclLocalIdCardImageFrontStr(String imagePath){
|
||||
String result=new OcrServicce().ocrLocalIdCardImage("F",imagePath);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反面身份证本地图片识别
|
||||
* @param imagePath
|
||||
* @return
|
||||
*/
|
||||
public static String oclLocalIdCardImageBackStr(String imagePath){
|
||||
String result=new OcrServicce().ocrLocalIdCardImage("B",imagePath);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
OcrInvoiceRootData data=AipOcrUtil.ocrLocalInvoicePdf("C:\\Users\\jean\\Downloads\\47329012.pdf");
|
||||
System.out.println("=========="+JSONUtil.toJsonStr(data));
|
||||
}
|
||||
|
||||
}
|
||||
68
ILogBizSystem/src/main/java/com/ag/ci/AutoCItool.java
Normal file
68
ILogBizSystem/src/main/java/com/ag/ci/AutoCItool.java
Normal file
@@ -0,0 +1,68 @@
|
||||
package com.ag.ci;
|
||||
|
||||
import com.offbytwo.jenkins.JenkinsServer;
|
||||
import com.offbytwo.jenkins.model.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class AutoCItool {
|
||||
|
||||
public void getjobs() throws Exception{
|
||||
|
||||
String username="";
|
||||
String password="";
|
||||
String url="****";
|
||||
// JenkinsServer jenkins=new JenkinsServer(new URI(url),username,password);
|
||||
JenkinsServer jenkins = new JenkinsServer(new URI("http://192.168.1.188:9999"), "admin", "anji6686");
|
||||
Map<String,Job> jobs=jenkins.getJobs();
|
||||
for(String keymame:jobs.keySet()){
|
||||
System.out.println(keymame);
|
||||
}
|
||||
JobWithDetails jobdetails=null;
|
||||
// Job job;
|
||||
// job=jobs.get("******");
|
||||
// jobdetails=job.details();
|
||||
// Build lastbuild=jobdetails.getLastBuild();
|
||||
// BuildWithDetails buildDetails=lastbuild.details();
|
||||
// if(buildDetails.isBuilding()){
|
||||
// System.out.println("最后一次构建还没完成,还在构建中");
|
||||
// }else{
|
||||
// System.out.println("最后一次构建已完成");
|
||||
// }
|
||||
}
|
||||
|
||||
public void createjob() throws Exception{
|
||||
|
||||
File file = new File("/Users/shaoqiang/work/soft/config.xml");
|
||||
FileInputStream inputStream = new FileInputStream(file);
|
||||
byte[] bytes = new byte[0];
|
||||
bytes = new byte[inputStream.available()];
|
||||
inputStream.read(bytes);
|
||||
String str = new String(bytes);
|
||||
String jobXml="";
|
||||
JenkinsServer jenkins = new JenkinsServer(new URI("http://192.168.1.188:9999"), "admin", "anji6686");
|
||||
jenkins.createJob("pipeline_3hhh", str);
|
||||
List<Plugin> dataplugin=jenkins.getPluginManager().getPlugins();
|
||||
// dataplugin.get(0).
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static void main(String args[]){
|
||||
|
||||
AutoCItool autoCItool=new AutoCItool();
|
||||
try {
|
||||
// autoCItool.getjobs();
|
||||
autoCItool.createjob();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ag.demo.webSocket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2021/10/26.
|
||||
*/
|
||||
public class MarcoHandler_2 extends TextWebSocketHandler {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MarcoHandler_2.class);
|
||||
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) {
|
||||
LOGGER.info("WebSocket 连接建立......");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
||||
|
||||
LOGGER.info("接收到消息:" + message.getPayload());
|
||||
Thread.sleep(2000);
|
||||
//发送文本消息
|
||||
session.sendMessage(new TextMessage("Polo!"));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus){
|
||||
LOGGER.info("WebSocket 连接关闭......");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ag.demo.webSocket;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2021/10/26.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSocket
|
||||
public class WebSocketConfig implements WebSocketConfigurer {
|
||||
/**
|
||||
*
|
||||
* @param registry 该对象可以调用addHandler()来注册信息处理器。
|
||||
*/
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
registry.addHandler(marcoHandler_2(), "/marco2")
|
||||
//.addInterceptors(webSocketHandshakeInterceptor()) //声明拦截器
|
||||
.setAllowedOrigins("*"); //声明允许访问的主机列表
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public MarcoHandler_2 marcoHandler_2(){
|
||||
return new MarcoHandler_2();
|
||||
}
|
||||
|
||||
/*@Bean
|
||||
public WebSocketHandshakeInterceptor webSocketHandshakeInterceptor(){
|
||||
return new WebSocketHandshakeInterceptor();
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ag.demo.webSocket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2021/10/26.
|
||||
*/
|
||||
public class WebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandshakeInterceptor.class);
|
||||
|
||||
@Override
|
||||
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
|
||||
logger.info("在处理逻辑前 拦截webSocket!");
|
||||
// 解决The extension [x-webkit-deflate-frame] is not supported问题
|
||||
if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
|
||||
request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
|
||||
}
|
||||
return super.beforeHandshake(request, response, wsHandler, attributes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
|
||||
logger.info("在处理逻辑后 拦截webSocket!");
|
||||
super.afterHandshake(request, response, wsHandler, exception);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ag.demo.webSocket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.websocket.*;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Created by XiuYin.Cui on 2018/5/2.
|
||||
*
|
||||
* 基于注解方式的WebSocket 控制器
|
||||
*/
|
||||
|
||||
|
||||
@ServerEndpoint("/ws")
|
||||
public class WsController {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(WsController.class);
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(){
|
||||
LOGGER.info("连接建立");
|
||||
}
|
||||
|
||||
@OnClose
|
||||
public void onClose(){
|
||||
LOGGER.info("连接关闭");
|
||||
}
|
||||
|
||||
@OnMessage
|
||||
public void onMessage(String message, Session session){
|
||||
try {
|
||||
LOGGER.info("接收到消息:" + message);
|
||||
//Thread.sleep(2000);
|
||||
session.getBasicRemote().sendText("polo"); //发送消息
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable throwable){
|
||||
throw new IllegalArgumentException(throwable);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
19
ILogBizSystem/src/main/java/com/ag/demo/webSocket/index.java
Normal file
19
ILogBizSystem/src/main/java/com/ag/demo/webSocket/index.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.ag.demo.webSocket;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
/**
|
||||
* Created by XiuYin.Cui on 2018/5/2.
|
||||
*/
|
||||
@Controller
|
||||
public class index {
|
||||
|
||||
|
||||
@RequestMapping(value = "/indexWs", method = {RequestMethod.GET, RequestMethod.POST})
|
||||
public String indexWs() {
|
||||
return "indexWs";
|
||||
}
|
||||
|
||||
}
|
||||
104
ILogBizSystem/src/main/java/com/ag/edi/EdiBean.java
Normal file
104
ILogBizSystem/src/main/java/com/ag/edi/EdiBean.java
Normal file
@@ -0,0 +1,104 @@
|
||||
package com.ag.edi;
|
||||
|
||||
import org.apache.pdfbox.io.RandomAccessBuffer;
|
||||
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 16/6/20.
|
||||
*/
|
||||
public class EdiBean implements java.io.Serializable{
|
||||
|
||||
public List logerror=null;
|
||||
public InputStream datain=null;
|
||||
|
||||
public List getLogerror() {
|
||||
return logerror;
|
||||
}
|
||||
public void setLogerror(List data) {
|
||||
this.logerror = data;
|
||||
}
|
||||
|
||||
public InputStream getDatain() {
|
||||
return datain;
|
||||
}
|
||||
|
||||
public void setDatain(InputStream datain) {
|
||||
this.datain = datain;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 读取pdf文件内容
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void main(String args[]) throws IOException {
|
||||
String result = null;
|
||||
FileInputStream is = null;
|
||||
PDDocument document = null;
|
||||
try {
|
||||
is = new FileInputStream("/Users/running/work/work2019/威海ocr识别/DB_aabfejjffabc0x01FA.pdf");
|
||||
// is = new FileInputStream("/Users/shaoqiang/work/work2019/威海ocr识别/COSU 6201279260 BC.PDF");
|
||||
PDFParser parser = new PDFParser(new RandomAccessBuffer(is));
|
||||
parser.parse();
|
||||
document = parser.getPDDocument();
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
result = stripper.getText(document);
|
||||
System.out.println(result);
|
||||
// pdfToWordOfText();
|
||||
} finally {
|
||||
if (is != null) {
|
||||
is.close();
|
||||
}
|
||||
if (document != null) {
|
||||
document.close();
|
||||
}
|
||||
}
|
||||
//return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void pdfToWordOfText(){
|
||||
try {
|
||||
//pdf文件路径
|
||||
String filePath = "/Users/shaoqiang/work/work2019/威海ocr识别/HL-83014252 MXZLO BC 1ST UPDATE.PDF";
|
||||
File fdf = new File(filePath);
|
||||
//生成的word的文件路径
|
||||
String wordPath = "/Users/shaoqiang/work/work2019/威海ocr识别/ap.docx";
|
||||
//通过文件名加载文档
|
||||
PDDocument doc = PDDocument.load(fdf);
|
||||
//获取文档的页数
|
||||
int pageNumber = doc.getNumberOfPages();
|
||||
//剥离器(读取pdf文件)
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
//排序
|
||||
stripper.setSortByPosition(true);
|
||||
//设置要读取的起始页码
|
||||
stripper.setStartPage(1);
|
||||
//设置要读取的结束页码
|
||||
stripper.setEndPage(pageNumber);
|
||||
File word = new File(wordPath);
|
||||
if(!word.exists()){
|
||||
word.createNewFile();
|
||||
}
|
||||
//文件输出流
|
||||
FileOutputStream fos = new FileOutputStream(word);
|
||||
//
|
||||
Writer writer = new OutputStreamWriter(fos, "utf-8");
|
||||
stripper.writeText(doc, writer);
|
||||
writer.close();
|
||||
fos.close();
|
||||
System.out.println("转码完成");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
54
ILogBizSystem/src/main/java/com/ag/edi/IEdiService.java
Normal file
54
ILogBizSystem/src/main/java/com/ag/edi/IEdiService.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.ag.edi;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 16/6/4.
|
||||
*/
|
||||
public interface IEdiService {
|
||||
/**
|
||||
* 报文导入处理,检查船名航次是否正确
|
||||
* @param routeid
|
||||
* @param dataMap
|
||||
* @param in
|
||||
* @return
|
||||
*/
|
||||
public List processMessage(String routeid, Map dataMap, InputStream in);
|
||||
/**
|
||||
* 检查报文数据正确性
|
||||
*
|
||||
* @param bin
|
||||
*/
|
||||
public boolean checkEdiData(String edrid, Map dataMap, InputStream bin);
|
||||
public boolean checkiftbmEdiData(String edrid, Map dataMap, InputStream bin);
|
||||
/**
|
||||
* 生成船图
|
||||
* @param routeid
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
public EdiBean genEDIfile(String routeid,
|
||||
Map<String, Object> map);
|
||||
/**
|
||||
* 生成船图
|
||||
* @param routeid
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
public InputStream genEDIfileInputstream(String routeid,
|
||||
Map<String, Object> map);
|
||||
/**
|
||||
* 检查报文数据正确性联合国船图
|
||||
*
|
||||
* @param bin
|
||||
*/
|
||||
public boolean checkEdiDataunBaplie(String edrid, Map dataMap, InputStream bin) ;
|
||||
public void startEdi(String id, Map datamap);
|
||||
/**
|
||||
* 停止edi
|
||||
* @param id
|
||||
*/
|
||||
public void stopedi(String id);
|
||||
}
|
||||
80
ILogBizSystem/src/main/java/com/ag/log/AOPConfig.java
Normal file
80
ILogBizSystem/src/main/java/com/ag/log/AOPConfig.java
Normal file
@@ -0,0 +1,80 @@
|
||||
package com.ag.log;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Description:
|
||||
* Author: shaofq
|
||||
* Version: 1.0
|
||||
* Create Date: 2020-03-09 17:01:20
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class AOPConfig {
|
||||
|
||||
//用法,业务方法类添加aop注解 @OperationLog(description = "12321")
|
||||
@Around(value = "@annotation(OperationLog)")
|
||||
public Object around(ProceedingJoinPoint proceedingJoinPoint){
|
||||
Map<String,String> keyValues=null;
|
||||
String className = proceedingJoinPoint.getTarget().getClass().getName(); //切入方法所属类名
|
||||
String methodName = proceedingJoinPoint.getSignature().getName(); //切入的方法名
|
||||
Object[] params = proceedingJoinPoint.getArgs(); //目标方法传入的参数
|
||||
String param = "入参为:";
|
||||
System.out.println("【"+className+"】:"+methodName);
|
||||
if(params != null && params.length > 0){
|
||||
for(Object p : params){
|
||||
try {
|
||||
keyValues = BeanUtils.describe(p);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("===="+p.toString());
|
||||
param += p + ",";
|
||||
}
|
||||
param = param.substring(0,param.lastIndexOf(","));
|
||||
}
|
||||
System.out.println("方法环绕begin...参数:"+ Arrays.toString(proceedingJoinPoint.getArgs()));
|
||||
try {
|
||||
Object ret= proceedingJoinPoint.proceed();
|
||||
System.out.println("方法环绕end...结果:"+ret);
|
||||
return ret;
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Before(value = "@annotation(OperationLog)")
|
||||
public void doBefore(JoinPoint joinPoint){
|
||||
ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
System.out.println("方法前");
|
||||
//HttpServletRequest req= requestAttributes.getRequest();
|
||||
// System.out.println("uri:"+req.getRequestURI());
|
||||
// System.out.println("执行方法前 : " + Arrays.toString(joinPoint.getArgs()));
|
||||
}
|
||||
|
||||
@After(value = "@annotation(OperationLog)")
|
||||
public void after(JoinPoint joinPoint){
|
||||
System.out.println("执行方法后:"+ Arrays.toString(joinPoint.getArgs()));
|
||||
}
|
||||
|
||||
@AfterReturning(pointcut = "@annotation(OperationLog)",returning = "ret")
|
||||
public void doAfterReturning(Object ret){
|
||||
System.out.println("方法的返回值 : " + ret);
|
||||
}
|
||||
|
||||
@AfterThrowing(pointcut = "@annotation(OperationLog)",throwing = "ex")
|
||||
public void AfterThrowing(JoinPoint joinPoint,Throwable ex){
|
||||
System.out.println("方法执行异常 : " + ex);
|
||||
}
|
||||
}
|
||||
14
ILogBizSystem/src/main/java/com/ag/log/CustomOutlogger.java
Normal file
14
ILogBizSystem/src/main/java/com/ag/log/CustomOutlogger.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.ag.log;
|
||||
|
||||
/**
|
||||
* 日志控制台输出
|
||||
* @author shaofq
|
||||
* @since 2022-11-12
|
||||
*/
|
||||
public class CustomOutlogger extends com.p6spy.engine.spy.appender.StdoutLogger{
|
||||
|
||||
@Override
|
||||
public void logText(String text) {
|
||||
System.out.println("sql:" + text);
|
||||
}
|
||||
}
|
||||
31
ILogBizSystem/src/main/java/com/ag/log/CustomSqlLogger.java
Normal file
31
ILogBizSystem/src/main/java/com/ag/log/CustomSqlLogger.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.alibaba.nacos.client.utils.StringUtils;
|
||||
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
|
||||
/**
|
||||
* 日志输出样式
|
||||
* @author shaofq
|
||||
* @since 2022-11-12
|
||||
*/
|
||||
public class CustomSqlLogger implements MessageFormattingStrategy {
|
||||
|
||||
/**
|
||||
* Sql日志格式化
|
||||
*
|
||||
* @param connectionId: 连接ID
|
||||
* @param now: 当前时间
|
||||
* @param elapsed: 花费时间
|
||||
* @param category: 类别
|
||||
* @param prepared: 预编译SQL
|
||||
* @param sql: 最终执行的SQL
|
||||
* @param url: 数据库连接地址
|
||||
* @return 格式化日志结果
|
||||
*/
|
||||
@Override
|
||||
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
|
||||
return StringUtils.isNotBlank(sql) ? " 耗时:" + elapsed + " ms " + now +
|
||||
"\n 执行 SQL:" + sql.replaceAll("[\\s]+", " ") + "\n" : "";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.entity.log.DefineLogConfig;
|
||||
import com.ag.util.CommonUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2022/5/25.
|
||||
*/
|
||||
@Service
|
||||
public class DefineLogConfigService extends BaseService {
|
||||
|
||||
@Autowired
|
||||
private DefaultBussniessImpl bizDao;
|
||||
|
||||
@Transactional
|
||||
public void saveGrid(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
|
||||
List<DefineLogConfig> adds = CommonUtil.getBeanlist(param, null, "create", DefineLogConfig.class);
|
||||
List<DefineLogConfig> upds = CommonUtil.getBeanlist(param, null, "update", DefineLogConfig.class);
|
||||
List<DefineLogConfig> dels = CommonUtil.getBeanlist(param, null, "destroy", DefineLogConfig.class);
|
||||
String[] cols = CommonUtil.getNeedColsByJson(param, null);
|
||||
adds.forEach(x->super.setSaveUser(param, x));
|
||||
upds.forEach(x->super.setUpdateUser(param, x));
|
||||
bizDao.saveAll(adds);
|
||||
bizDao.updateAll(upds, cols, "ID");
|
||||
bizDao.deleteAll(dels, "ID");
|
||||
}
|
||||
}
|
||||
188
ILogBizSystem/src/main/java/com/ag/log/LogForCdcUtil.java
Normal file
188
ILogBizSystem/src/main/java/com/ag/log/LogForCdcUtil.java
Normal file
@@ -0,0 +1,188 @@
|
||||
package com.ag.log;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import com.ag.log.pojo.LogForCdc;
|
||||
import com.ag.log.service.CdcDataDict;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2022/5/26.
|
||||
*/
|
||||
public class LogForCdcUtil {
|
||||
|
||||
private static Log logger = LogFactory.getLog(LogForCdcUtil.class);
|
||||
|
||||
@Test
|
||||
public void testAdd() throws Exception {
|
||||
String addJsonStr = "{\"tablekey\":\"55\",\"database\":\"mysqlcdc\",\"data\":{\"name\":\"55555\",\"id\":\"55\",\"add1\":\"11\",\"add2\":\"22\"}," +
|
||||
"\"type\":\"insert\",\"table\":\"new_table\"}";
|
||||
execute(addJsonStr);
|
||||
logger.info("insert日志数据保存成功!");
|
||||
}
|
||||
@Test
|
||||
public void testEdit() throws Exception {
|
||||
String editJsonStr = "{\"tablekey\":\"333\",\"database\":\"mysqlcdc\",\"data\":{\"name\":\"ggggbbb\",\"id\":\"333\"}," +
|
||||
"\"beforedata\":{\"name\":\"gggg\",\"id\":\"333\"},\"type\":\"update\",\"table\":\"new_table\"}";
|
||||
execute(editJsonStr);
|
||||
logger.info("update日志数据保存成功!");
|
||||
}
|
||||
@Test
|
||||
public void testDel() throws Exception {
|
||||
String delJsonStr = "{\"tablekey\":\"333\",\"database\":\"mysqlcdc\",\"beforedata\":{\"name\":\"ggggbbb\",\"id\":\"333\"}," +
|
||||
"\"type\":\"delete\",\"table\":\"new_table\"}";
|
||||
execute(delJsonStr);
|
||||
logger.info("delete日志数据保存成功!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropTable() throws Exception{
|
||||
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml", "classpath:dynamicModule/modulelink.xml");
|
||||
JdbcTemplate jdbc = (JdbcTemplate) context.getBean("jdbcTemplateCdc");
|
||||
jdbc.update("DROP TABLE new_table");
|
||||
//jdbc.update("alter table new_table add column addCol varchar(20)");
|
||||
logger.info("测试日志表已删除!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.判断缓存是否存在
|
||||
* 2.判断表是否存在
|
||||
* 3.建表加入缓存
|
||||
* 4.判断字段是否追加
|
||||
* 5.增加字段并加入缓存
|
||||
* @param jsonStr
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public int execute(String jsonStr) throws Exception {
|
||||
LogForCdc log = JSON.parseObject(jsonStr, LogForCdc.class);
|
||||
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml", "classpath:dynamicModule/modulelink.xml");
|
||||
JdbcTemplate jdbc = (JdbcTemplate) context.getBean("jdbcTemplateCdc");
|
||||
String sql = null;
|
||||
if (!isExistsTable(jdbc.getDataSource().getConnection(), log)) {
|
||||
createTable(jdbc, log);
|
||||
}else {
|
||||
Set<String> colNames = getColumnsByTab(jdbc.getDataSource().getConnection(), log);
|
||||
Set<String> dataSet, addColSet = new HashSet<>();
|
||||
if (StrUtil.equals("delete", log.getType())) {
|
||||
dataSet = log.getBeforedata().keySet();
|
||||
} else {
|
||||
dataSet = log.getData().keySet();
|
||||
}
|
||||
for (String param : dataSet){
|
||||
if (!colNames.contains(param)){
|
||||
addColSet.add(param);
|
||||
}
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(addColSet)) {
|
||||
addColumns(jdbc, log, addColSet);
|
||||
}
|
||||
}
|
||||
|
||||
log.putData();
|
||||
if (StrUtil.equals("insert", log.getType()) || StrUtil.equals("update", log.getType())) {
|
||||
sql = mapToSql(log, log.getData());
|
||||
}
|
||||
if (StrUtil.equals("delete", log.getType())) {
|
||||
sql = mapToSql(log, log.getBeforedata());
|
||||
}
|
||||
return jdbc.update(sql);
|
||||
}
|
||||
|
||||
public String mapToSql(LogForCdc log, JSONObject data) {
|
||||
String col = "", val = "";
|
||||
Assert.notEmpty(data.entrySet(), "非法的新增数据!");
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
col += entry.getKey() + ",";
|
||||
if (Convert.toStr(entry.getValue()).startsWith("to_date('")) {
|
||||
val += entry.getValue() + ",";
|
||||
} else {
|
||||
val += "'" + entry.getValue() + "',";
|
||||
}
|
||||
}
|
||||
String sql = "insert into " + log.getTable();
|
||||
sql += StrUtil.join("(", subLastStr(col), ")");
|
||||
sql += StrUtil.join(" values (", subLastStr(val), ")");
|
||||
return sql;
|
||||
}
|
||||
|
||||
private String subLastStr(String param) {
|
||||
return param.substring(0, param.length() - 1);
|
||||
}
|
||||
|
||||
public static boolean isExistsTable(Connection conn, LogForCdc log) throws Exception {
|
||||
DatabaseMetaData dbMetaData = conn.getMetaData();
|
||||
String[] types = {"TABLE"};
|
||||
ResultSet tabs = null;
|
||||
try {
|
||||
tabs = dbMetaData.getTables(null, null, log.getTable(), types);
|
||||
if (tabs.next()) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
tabs.close();
|
||||
conn.close();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int createTable(JdbcTemplate jdbc, LogForCdc log) {
|
||||
String buildSql = StrUtil.join("CREATE TABLE `", log.getTable(), "` (");
|
||||
buildSql += StrUtil.join(" `type` varchar(8),");
|
||||
buildSql += StrUtil.join(" `created_on` datetime,");
|
||||
buildSql += StrUtil.join(" `created_by` varchar(30),");
|
||||
//buildSql += StrUtil.join(" `id` int(11) NOT NULL AUTO_INCREMENT,");
|
||||
Set<String> set = log.getData().keySet();
|
||||
for (String key : set) {
|
||||
buildSql += StrUtil.join("`" + key + "` varchar(255),");
|
||||
}
|
||||
buildSql += StrUtil.join(" `tablekey` varchar(255)");
|
||||
buildSql += StrUtil.join(") ENGINE=InnoDB DEFAULT CHARSET=utf8");
|
||||
try {
|
||||
jdbc.update(buildSql);
|
||||
logger.info("建表成功:"+log.getTable());
|
||||
return 1;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static Set<String> getColumnsByTab(Connection conn, LogForCdc log) throws Exception{
|
||||
DatabaseMetaData dbMetaData = conn.getMetaData();
|
||||
ResultSet rs = dbMetaData.getColumns(null, null, log.getTable(), "%");
|
||||
Set<String> columns = new HashSet<>();
|
||||
while (rs.next()){
|
||||
columns.add(rs.getString(4));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
public static void addColumns(JdbcTemplate jdbc, LogForCdc log, Collection<String> addCols) {
|
||||
try {
|
||||
for (String addCol : addCols) {
|
||||
String buildSql = StrUtil.join("alter table ", log.getTable(), " add column ", addCol, " varchar(255)");
|
||||
jdbc.update(buildSql);
|
||||
logger.info(log.getTable()+"表增加字段:"+addCol);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
11
ILogBizSystem/src/main/java/com/ag/log/OperationLog.java
Normal file
11
ILogBizSystem/src/main/java/com/ag/log/OperationLog.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.ag.log;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
|
||||
@Target({ElementType.PARAMETER, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface OperationLog {
|
||||
public String description() default "";
|
||||
}
|
||||
425
ILogBizSystem/src/main/java/com/ag/log/RemqMsgCustom.java
Normal file
425
ILogBizSystem/src/main/java/com/ag/log/RemqMsgCustom.java
Normal file
@@ -0,0 +1,425 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 消息
|
||||
* @TableName remq_msg_custom
|
||||
*/
|
||||
@TableName(value ="remq_msg_custom")
|
||||
public class RemqMsgCustom implements Serializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@TableId
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 业务数据ID
|
||||
*/
|
||||
private String businessKey;
|
||||
|
||||
/**
|
||||
* 业务数据类型
|
||||
*/
|
||||
private String businessType;
|
||||
|
||||
/**
|
||||
* 业务功能URL
|
||||
*/
|
||||
private String businessUrl;
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
private String msgInfo;
|
||||
|
||||
/**
|
||||
* 已读未读标记 0未读1已读
|
||||
*/
|
||||
private String receiveFlag;
|
||||
|
||||
/**
|
||||
* 已读时间
|
||||
*/
|
||||
private Date receiveTim;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String createdBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date createdOn;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String updatedBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date updatedOn;
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
private String chatName;
|
||||
|
||||
/**
|
||||
* S发送 R接收
|
||||
*/
|
||||
private String srFlag;
|
||||
|
||||
/**
|
||||
* 接收用户ID
|
||||
*/
|
||||
private String reUserId;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String parentId;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String msgId;
|
||||
|
||||
/**
|
||||
* 指定接收人(用户名,用户名)
|
||||
*/
|
||||
private String assignReceiveMan;
|
||||
|
||||
@TableField(exist = false)
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务数据ID
|
||||
*/
|
||||
public String getBusinessKey() {
|
||||
return businessKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务数据ID
|
||||
*/
|
||||
public void setBusinessKey(String businessKey) {
|
||||
this.businessKey = businessKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务数据类型
|
||||
*/
|
||||
public String getBusinessType() {
|
||||
return businessType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务数据类型
|
||||
*/
|
||||
public void setBusinessType(String businessType) {
|
||||
this.businessType = businessType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务功能URL
|
||||
*/
|
||||
public String getBusinessUrl() {
|
||||
return businessUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务功能URL
|
||||
*/
|
||||
public void setBusinessUrl(String businessUrl) {
|
||||
this.businessUrl = businessUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
public String getMsgInfo() {
|
||||
return msgInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
public void setMsgInfo(String msgInfo) {
|
||||
this.msgInfo = msgInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已读未读标记 0未读1已读
|
||||
*/
|
||||
public String getReceiveFlag() {
|
||||
return receiveFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已读未读标记 0未读1已读
|
||||
*/
|
||||
public void setReceiveFlag(String receiveFlag) {
|
||||
this.receiveFlag = receiveFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已读时间
|
||||
*/
|
||||
public Date getReceiveTim() {
|
||||
return receiveTim;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已读时间
|
||||
*/
|
||||
public void setReceiveTim(Date receiveTim) {
|
||||
this.receiveTim = receiveTim;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedOn(Date createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getUpdatedBy() {
|
||||
return updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedBy(String updatedBy) {
|
||||
this.updatedBy = updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getUpdatedOn() {
|
||||
return updatedOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedOn(Date updatedOn) {
|
||||
this.updatedOn = updatedOn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
public String getChatName() {
|
||||
return chatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
public void setChatName(String chatName) {
|
||||
this.chatName = chatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* S发送 R接收
|
||||
*/
|
||||
public String getSrFlag() {
|
||||
return srFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* S发送 R接收
|
||||
*/
|
||||
public void setSrFlag(String srFlag) {
|
||||
this.srFlag = srFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收用户ID
|
||||
*/
|
||||
public String getReUserId() {
|
||||
return reUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收用户ID
|
||||
*/
|
||||
public void setReUserId(String reUserId) {
|
||||
this.reUserId = reUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getParentId() {
|
||||
return parentId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setParentId(String parentId) {
|
||||
this.parentId = parentId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getMsgId() {
|
||||
return msgId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setMsgId(String msgId) {
|
||||
this.msgId = msgId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定接收人(用户名,用户名)
|
||||
*/
|
||||
public String getAssignReceiveMan() {
|
||||
return assignReceiveMan;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定接收人(用户名,用户名)
|
||||
*/
|
||||
public void setAssignReceiveMan(String assignReceiveMan) {
|
||||
this.assignReceiveMan = assignReceiveMan;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object that) {
|
||||
if (this == that) {
|
||||
return true;
|
||||
}
|
||||
if (that == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != that.getClass()) {
|
||||
return false;
|
||||
}
|
||||
RemqMsgCustom other = (RemqMsgCustom) that;
|
||||
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
|
||||
&& (this.getBusinessKey() == null ? other.getBusinessKey() == null : this.getBusinessKey().equals(other.getBusinessKey()))
|
||||
&& (this.getBusinessType() == null ? other.getBusinessType() == null : this.getBusinessType().equals(other.getBusinessType()))
|
||||
&& (this.getBusinessUrl() == null ? other.getBusinessUrl() == null : this.getBusinessUrl().equals(other.getBusinessUrl()))
|
||||
&& (this.getMsgInfo() == null ? other.getMsgInfo() == null : this.getMsgInfo().equals(other.getMsgInfo()))
|
||||
&& (this.getReceiveFlag() == null ? other.getReceiveFlag() == null : this.getReceiveFlag().equals(other.getReceiveFlag()))
|
||||
&& (this.getReceiveTim() == null ? other.getReceiveTim() == null : this.getReceiveTim().equals(other.getReceiveTim()))
|
||||
&& (this.getCreatedBy() == null ? other.getCreatedBy() == null : this.getCreatedBy().equals(other.getCreatedBy()))
|
||||
&& (this.getCreatedOn() == null ? other.getCreatedOn() == null : this.getCreatedOn().equals(other.getCreatedOn()))
|
||||
&& (this.getUpdatedBy() == null ? other.getUpdatedBy() == null : this.getUpdatedBy().equals(other.getUpdatedBy()))
|
||||
&& (this.getUpdatedOn() == null ? other.getUpdatedOn() == null : this.getUpdatedOn().equals(other.getUpdatedOn()))
|
||||
&& (this.getChatName() == null ? other.getChatName() == null : this.getChatName().equals(other.getChatName()))
|
||||
&& (this.getSrFlag() == null ? other.getSrFlag() == null : this.getSrFlag().equals(other.getSrFlag()))
|
||||
&& (this.getReUserId() == null ? other.getReUserId() == null : this.getReUserId().equals(other.getReUserId()))
|
||||
&& (this.getParentId() == null ? other.getParentId() == null : this.getParentId().equals(other.getParentId()))
|
||||
&& (this.getMsgId() == null ? other.getMsgId() == null : this.getMsgId().equals(other.getMsgId()))
|
||||
&& (this.getAssignReceiveMan() == null ? other.getAssignReceiveMan() == null : this.getAssignReceiveMan().equals(other.getAssignReceiveMan()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
|
||||
result = prime * result + ((getBusinessKey() == null) ? 0 : getBusinessKey().hashCode());
|
||||
result = prime * result + ((getBusinessType() == null) ? 0 : getBusinessType().hashCode());
|
||||
result = prime * result + ((getBusinessUrl() == null) ? 0 : getBusinessUrl().hashCode());
|
||||
result = prime * result + ((getMsgInfo() == null) ? 0 : getMsgInfo().hashCode());
|
||||
result = prime * result + ((getReceiveFlag() == null) ? 0 : getReceiveFlag().hashCode());
|
||||
result = prime * result + ((getReceiveTim() == null) ? 0 : getReceiveTim().hashCode());
|
||||
result = prime * result + ((getCreatedBy() == null) ? 0 : getCreatedBy().hashCode());
|
||||
result = prime * result + ((getCreatedOn() == null) ? 0 : getCreatedOn().hashCode());
|
||||
result = prime * result + ((getUpdatedBy() == null) ? 0 : getUpdatedBy().hashCode());
|
||||
result = prime * result + ((getUpdatedOn() == null) ? 0 : getUpdatedOn().hashCode());
|
||||
result = prime * result + ((getChatName() == null) ? 0 : getChatName().hashCode());
|
||||
result = prime * result + ((getSrFlag() == null) ? 0 : getSrFlag().hashCode());
|
||||
result = prime * result + ((getReUserId() == null) ? 0 : getReUserId().hashCode());
|
||||
result = prime * result + ((getParentId() == null) ? 0 : getParentId().hashCode());
|
||||
result = prime * result + ((getMsgId() == null) ? 0 : getMsgId().hashCode());
|
||||
result = prime * result + ((getAssignReceiveMan() == null) ? 0 : getAssignReceiveMan().hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(getClass().getSimpleName());
|
||||
sb.append(" [");
|
||||
sb.append("Hash = ").append(hashCode());
|
||||
sb.append(", id=").append(id);
|
||||
sb.append(", businessKey=").append(businessKey);
|
||||
sb.append(", businessType=").append(businessType);
|
||||
sb.append(", businessUrl=").append(businessUrl);
|
||||
sb.append(", msgInfo=").append(msgInfo);
|
||||
sb.append(", receiveFlag=").append(receiveFlag);
|
||||
sb.append(", receiveTim=").append(receiveTim);
|
||||
sb.append(", createdBy=").append(createdBy);
|
||||
sb.append(", createdOn=").append(createdOn);
|
||||
sb.append(", updatedBy=").append(updatedBy);
|
||||
sb.append(", updatedOn=").append(updatedOn);
|
||||
sb.append(", chatName=").append(chatName);
|
||||
sb.append(", srFlag=").append(srFlag);
|
||||
sb.append(", reUserId=").append(reUserId);
|
||||
sb.append(", parentId=").append(parentId);
|
||||
sb.append(", msgId=").append(msgId);
|
||||
sb.append(", assignReceiveMan=").append(assignReceiveMan);
|
||||
sb.append(", serialVersionUID=").append(serialVersionUID);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
10
ILogBizSystem/src/main/java/com/ag/log/RequestLog.java
Normal file
10
ILogBizSystem/src/main/java/com/ag/log/RequestLog.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.ag.log;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target({ElementType.PARAMETER, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface RequestLog {
|
||||
|
||||
}
|
||||
114
ILogBizSystem/src/main/java/com/ag/log/RequestLogAspect.java
Normal file
114
ILogBizSystem/src/main/java/com/ag/log/RequestLogAspect.java
Normal file
@@ -0,0 +1,114 @@
|
||||
package com.ag.log;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.log.pojo.SysOperLog;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
|
||||
import org.springframework.jdbc.support.lob.DefaultLobHandler;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* 请求日志切面
|
||||
* @author fengjun
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class RequestLogAspect extends BaseService {
|
||||
@Autowired
|
||||
private DefaultBussniessImpl bizDao;
|
||||
|
||||
/**
|
||||
* @Description: 记录请求日志
|
||||
* @return: void
|
||||
* @Author: fengjun
|
||||
* @Date: 2022/4/15
|
||||
*/
|
||||
@Before("@annotation(RequestLog)")
|
||||
public void doBefore(JoinPoint joinPoint){
|
||||
String bean = joinPoint.getArgs()[3].toString();
|
||||
//如果日志类不需要记录
|
||||
if ("UserDefineLogService".equals(bean)) {
|
||||
return;
|
||||
}
|
||||
String method = joinPoint.getArgs()[4].toString();
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
org.json.JSONObject params = (org.json.JSONObject) joinPoint.getArgs()[0];
|
||||
|
||||
String[] ignore = {"sys.date", "sys.id", "selectUseRole", "xwl", "sys.theme", "sys.dispname", "sys.roles",
|
||||
"mapMenuRes", "debugSuffix", "sys.editTheme", "bean", "method", "sys.lang","basicsLust",
|
||||
"sys.tenancyId", "sys.TENANCY_ID", "subsList", "sys.userLang","sys.useLang", "sys.logined", "useRole",
|
||||
"org.springframework.web.context.request.RequestContextListener.REQUEST_ATTRIBUTES",
|
||||
"roleIds", "sys.userIpAddress", "sys.ip", "sys.menuid","menuid", "sys.roleList"};
|
||||
Set<String> ignoreSet = new HashSet<>(Arrays.asList(ignore));
|
||||
for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
|
||||
if(StrUtil.startsWith(stringObjectEntry.getKey(), "org.springframework.")){
|
||||
continue;
|
||||
}
|
||||
if (!ignoreSet.contains(stringObjectEntry.getKey())) {
|
||||
jsonObject.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
|
||||
}
|
||||
}
|
||||
SysOperLog sysOperLog = new SysOperLog();
|
||||
sysOperLog.setId(IdUtil.simpleUUID());
|
||||
sysOperLog.setBean(bean);
|
||||
sysOperLog.setMethod(method);
|
||||
sysOperLog.setIp(super.getUserIpAddress(params));
|
||||
String param = JSON.toJSONString(jsonObject);
|
||||
if (param.length()>1999){
|
||||
param.substring(0, 1999);
|
||||
}
|
||||
sysOperLog.setParams(param);
|
||||
sysOperLog.setCreatedBy(super.getSysUserName(params));
|
||||
// sysOperLog.setCreatedOn(DateUtil.date());
|
||||
//bizDao.save(sysOperLog);
|
||||
//MapSqlParameterSource in = new MapSqlParameterSource();
|
||||
|
||||
String sql = "INSERT INTO sys_oper_log (id, bean, method, created_by, created_on, ip, params) VALUES(?, ?, ?, ?, ?, ?, ?)";
|
||||
bizDao.getJdbcTemplate().execute(sql,
|
||||
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()){
|
||||
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
|
||||
ps.setString(1, sysOperLog.getId());
|
||||
ps.setString(2, sysOperLog.getBean());
|
||||
ps.setString(3, sysOperLog.getMethod());
|
||||
ps.setString(4, sysOperLog.getCreatedBy());
|
||||
ps.setTimestamp(5, new java.sql.Timestamp(DateUtil.date().getTime()));
|
||||
ps.setString(6, sysOperLog.getIp());
|
||||
lobCreator.setClobAsString(ps, 7, sysOperLog.getParams());
|
||||
}
|
||||
});
|
||||
|
||||
/*DefineLogConfig config = new DefineLogConfig();
|
||||
config.setBean(bean);
|
||||
config.setMethod(method);
|
||||
List<DefineLogConfig> configs = bizDao.findByEqCriteria(config, DefineLogConfig.class, "BEAN", "METHOD");
|
||||
if (CollectionUtil.isEmpty(configs)){
|
||||
return;
|
||||
}
|
||||
config = configs.get(0);
|
||||
JSONObject reqParam = (JSONObject)joinPoint.getArgs()[0];
|
||||
|
||||
JSONObject datatable = JSON.parseArray(reqParam.getString(config.getControlName())).getJSONObject(0);
|
||||
JSONArray createArray = JSON.parseArray(datatable.getString("create"));
|
||||
JSONArray updateArray = JSON.parseArray(datatable.getString("update"));
|
||||
JSONArray deleteArray = JSON.parseArray(datatable.getString("destroy"));
|
||||
*/
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
235
ILogBizSystem/src/main/java/com/ag/log/SystemLogAspect.java
Normal file
235
ILogBizSystem/src/main/java/com/ag/log/SystemLogAspect.java
Normal file
@@ -0,0 +1,235 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
|
||||
/**
|
||||
* 切点类
|
||||
* @author shaofq
|
||||
*
|
||||
*/
|
||||
//@Aspect
|
||||
//@Component
|
||||
public class SystemLogAspect {
|
||||
|
||||
public SystemLogAspect(){
|
||||
}
|
||||
|
||||
//本地异常日志记录对象
|
||||
private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
|
||||
|
||||
//Service层切点
|
||||
@Pointcut("@annotation(com.ag.dynamicmodule.aop.OperationLog)")
|
||||
public void serviceAspect() {
|
||||
}
|
||||
|
||||
//Controller层切点
|
||||
// @Pointcut("@annotation(com.demodashi.aop.annotation.ControllerLogAnnotation)")
|
||||
// public void controllerAspect() {
|
||||
// }
|
||||
|
||||
/**
|
||||
* 前置通知 用于拦截Controller层记录用户的操作
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
*/
|
||||
@Before("serviceAspect()")
|
||||
public void doBefore4control(JoinPoint joinPoint) {
|
||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
HttpSession session = request.getSession();
|
||||
//读取session中的用户
|
||||
// UserVO user = (UserVO) session.getAttribute("USER");
|
||||
//请求的IP
|
||||
String ip = request.getRemoteAddr();
|
||||
try {
|
||||
//*========控制台输出=========*//
|
||||
System.out.println("=====control 前置通知开始=====");
|
||||
System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
|
||||
System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
|
||||
// System.out.println("请求人ID:" + user.getId());
|
||||
// System.out.println("请求人NAME:" + user.getName());
|
||||
System.out.println("请求IP:" + ip);
|
||||
System.out.println("=====前置通知结束=====");
|
||||
} catch (Exception e) {
|
||||
//记录本地异常日志
|
||||
logger.error("==前置通知异常==");
|
||||
logger.error("异常信息:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// @Before("serviceAspect()")
|
||||
// public void doBefore4service(JoinPoint joinPoint) {
|
||||
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
// HttpSession session = request.getSession();
|
||||
// //读取session中的用户
|
||||
// UserVO user = (UserVO) session.getAttribute("USER");
|
||||
// //获取请求ip
|
||||
// String ip = request.getRemoteAddr();
|
||||
// //获取用户请求方法的参数并序列化为JSON格式字符串
|
||||
// String params = "";
|
||||
// if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
|
||||
// for ( int i = 0; i < joinPoint.getArgs().length; i++) {
|
||||
// params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
|
||||
// }
|
||||
// }
|
||||
// try {
|
||||
// /*========控制台输出=========*/
|
||||
// System.out.println("=====service 前置通知开始=====");
|
||||
// System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
|
||||
// System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
|
||||
// System.out.println("请求人ID:" + user.getId());
|
||||
// System.out.println("请求人NAME:" + user.getName());
|
||||
// System.out.println("请求IP:" + ip);
|
||||
// System.out.println("请求参数:" + params);
|
||||
//
|
||||
// } catch (Exception ex) {
|
||||
// //记录本地异常日志
|
||||
// logger.error("==异常通知异常==");
|
||||
// logger.error("异常信息:{}", ex.getMessage());
|
||||
// }
|
||||
// }
|
||||
|
||||
@AfterReturning(pointcut="serviceAspect()", returning="returnValue")
|
||||
public void after4service(JoinPoint joinPoint, Object returnValue) {
|
||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
HttpSession session = request.getSession();
|
||||
//读取session中的用户
|
||||
// UserVO user = (UserVO) session.getAttribute("USER");
|
||||
//获取请求ip
|
||||
String ip = request.getRemoteAddr();
|
||||
//获取用户请求方法的参数并序列化为JSON格式字符串
|
||||
String params = "";
|
||||
if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
|
||||
for ( int i = 0; i < joinPoint.getArgs().length; i++) {
|
||||
params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
|
||||
}
|
||||
}
|
||||
try {
|
||||
/*========控制台输出=========*/
|
||||
System.out.println("=====service 后置通知开始=====");
|
||||
System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
|
||||
System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
|
||||
// System.out.println("请求人ID:" + user.getId());
|
||||
// System.out.println("请求人NAME:" + user.getName());
|
||||
System.out.println("请求IP:" + ip);
|
||||
System.out.println("请求参数:" + params);
|
||||
System.out.println("返回值为:" + JSONObject.toJSON(returnValue).toString());
|
||||
} catch (Exception ex) {
|
||||
//记录本地异常日志
|
||||
logger.error("==异常通知异常==");
|
||||
logger.error("异常信息:{}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常通知 用于拦截service层记录异常日志
|
||||
*
|
||||
* @param joinPoint
|
||||
* @param e
|
||||
*/
|
||||
@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
|
||||
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
|
||||
System.out.println("方法执行异常 : " + e);
|
||||
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
// HttpSession session = request.getSession();
|
||||
// //读取session中的用户
|
||||
// // UserVO user = (UserVO) session.getAttribute("USER");
|
||||
// //获取请求ip
|
||||
// String ip = request.getRemoteAddr();
|
||||
// //获取用户请求方法的参数并序列化为JSON格式字符串
|
||||
// String params = "";
|
||||
// if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
|
||||
// for ( int i = 0; i < joinPoint.getArgs().length; i++) {
|
||||
// params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
|
||||
// }
|
||||
// }
|
||||
// try {
|
||||
// /*========控制台输出=========*/
|
||||
// System.out.println("=====异常通知开始=====");
|
||||
// System.out.println("异常代码:" + e.getClass().getName());
|
||||
// System.out.println("异常信息:" + e.getMessage());
|
||||
// System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
|
||||
// System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
|
||||
// // System.out.println("请求人ID:" + user.getId());
|
||||
// // System.out.println("请求人NAME:" + user.getName());
|
||||
// System.out.println("请求IP:" + ip);
|
||||
// System.out.println("请求参数:" + params);
|
||||
//
|
||||
// System.out.println("=====异常通知结束=====");
|
||||
// } catch (Exception ex) {
|
||||
// //记录本地异常日志
|
||||
// logger.error("==异常通知异常==");
|
||||
// logger.error("异常信息:{}", ex.getMessage());
|
||||
// }
|
||||
// /*==========记录本地异常日志==========*/
|
||||
// // logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取注解中对方法的描述信息 用于service层注解
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @return 方法描述
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String getServiceMthodDescription(JoinPoint joinPoint)
|
||||
throws Exception {
|
||||
String targetName = joinPoint.getTarget().getClass().getName();
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
Object[] arguments = joinPoint.getArgs();
|
||||
Class targetClass = Class.forName(targetName);
|
||||
Method[] methods = targetClass.getMethods();
|
||||
String description = "";
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName)) {
|
||||
Class[] clazzs = method.getParameterTypes();
|
||||
if (clazzs.length == arguments.length) {
|
||||
description = method.getAnnotation(OperationLog.class).description();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return description;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取注解中对方法的描述信息 用于Controller层注解
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @return 方法描述
|
||||
* @throws Exception
|
||||
*/
|
||||
// public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
|
||||
// String targetName = joinPoint.getTarget().getClass().getName();
|
||||
// String methodName = joinPoint.getSignature().getName();
|
||||
// Object[] arguments = joinPoint.getArgs();
|
||||
// Class targetClass = Class.forName(targetName);
|
||||
// Method[] methods = targetClass.getMethods();
|
||||
// String description = "";
|
||||
// for (Method method : methods) {
|
||||
// if (method.getName().equals(methodName)) {
|
||||
// Class[] clazzs = method.getParameterTypes();
|
||||
// if (clazzs.length == arguments.length) {
|
||||
// description = method.getAnnotation(ControllerLogAnnotation. class).description();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return description;
|
||||
// }
|
||||
}
|
||||
260
ILogBizSystem/src/main/java/com/ag/log/TopicResp.java
Normal file
260
ILogBizSystem/src/main/java/com/ag/log/TopicResp.java
Normal file
@@ -0,0 +1,260 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 频道信息
|
||||
* @TableName topic_resp
|
||||
*/
|
||||
@TableName(value ="topic_resp")
|
||||
public class TopicResp implements Serializable {
|
||||
|
||||
private String checkFlag;
|
||||
|
||||
public String getCheckFlag() {
|
||||
return checkFlag;
|
||||
}
|
||||
|
||||
public void setCheckFlag(String checkFlag) {
|
||||
this.checkFlag = checkFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@TableId
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
private String topicName;
|
||||
|
||||
/**
|
||||
* 父频道名称
|
||||
*/
|
||||
private String topicParentName;
|
||||
|
||||
/**
|
||||
* 父频道ID
|
||||
*/
|
||||
private String topicParentId;
|
||||
|
||||
/**
|
||||
* 频道描述
|
||||
*/
|
||||
private String topicDescribe;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String createdBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date createdOn;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String updatedBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date updatedOn;
|
||||
|
||||
@TableField(exist = false)
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
public String getTopicName() {
|
||||
return topicName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道名称
|
||||
*/
|
||||
public void setTopicName(String topicName) {
|
||||
this.topicName = topicName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 父频道名称
|
||||
*/
|
||||
public String getTopicParentName() {
|
||||
return topicParentName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 父频道名称
|
||||
*/
|
||||
public void setTopicParentName(String topicParentName) {
|
||||
this.topicParentName = topicParentName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 父频道ID
|
||||
*/
|
||||
public String getTopicParentId() {
|
||||
return topicParentId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 父频道ID
|
||||
*/
|
||||
public void setTopicParentId(String topicParentId) {
|
||||
this.topicParentId = topicParentId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道描述
|
||||
*/
|
||||
public String getTopicDescribe() {
|
||||
return topicDescribe;
|
||||
}
|
||||
|
||||
/**
|
||||
* 频道描述
|
||||
*/
|
||||
public void setTopicDescribe(String topicDescribe) {
|
||||
this.topicDescribe = topicDescribe;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedOn(Date createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getUpdatedBy() {
|
||||
return updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedBy(String updatedBy) {
|
||||
this.updatedBy = updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getUpdatedOn() {
|
||||
return updatedOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedOn(Date updatedOn) {
|
||||
this.updatedOn = updatedOn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object that) {
|
||||
if (this == that) {
|
||||
return true;
|
||||
}
|
||||
if (that == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != that.getClass()) {
|
||||
return false;
|
||||
}
|
||||
TopicResp other = (TopicResp) that;
|
||||
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
|
||||
&& (this.getTopicName() == null ? other.getTopicName() == null : this.getTopicName().equals(other.getTopicName()))
|
||||
&& (this.getTopicParentName() == null ? other.getTopicParentName() == null : this.getTopicParentName().equals(other.getTopicParentName()))
|
||||
&& (this.getTopicParentId() == null ? other.getTopicParentId() == null : this.getTopicParentId().equals(other.getTopicParentId()))
|
||||
&& (this.getTopicDescribe() == null ? other.getTopicDescribe() == null : this.getTopicDescribe().equals(other.getTopicDescribe()))
|
||||
&& (this.getCreatedBy() == null ? other.getCreatedBy() == null : this.getCreatedBy().equals(other.getCreatedBy()))
|
||||
&& (this.getCreatedOn() == null ? other.getCreatedOn() == null : this.getCreatedOn().equals(other.getCreatedOn()))
|
||||
&& (this.getUpdatedBy() == null ? other.getUpdatedBy() == null : this.getUpdatedBy().equals(other.getUpdatedBy()))
|
||||
&& (this.getUpdatedOn() == null ? other.getUpdatedOn() == null : this.getUpdatedOn().equals(other.getUpdatedOn()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
|
||||
result = prime * result + ((getTopicName() == null) ? 0 : getTopicName().hashCode());
|
||||
result = prime * result + ((getTopicParentName() == null) ? 0 : getTopicParentName().hashCode());
|
||||
result = prime * result + ((getTopicParentId() == null) ? 0 : getTopicParentId().hashCode());
|
||||
result = prime * result + ((getTopicDescribe() == null) ? 0 : getTopicDescribe().hashCode());
|
||||
result = prime * result + ((getCreatedBy() == null) ? 0 : getCreatedBy().hashCode());
|
||||
result = prime * result + ((getCreatedOn() == null) ? 0 : getCreatedOn().hashCode());
|
||||
result = prime * result + ((getUpdatedBy() == null) ? 0 : getUpdatedBy().hashCode());
|
||||
result = prime * result + ((getUpdatedOn() == null) ? 0 : getUpdatedOn().hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(getClass().getSimpleName());
|
||||
sb.append(" [");
|
||||
sb.append("Hash = ").append(hashCode());
|
||||
sb.append(", id=").append(id);
|
||||
sb.append(", topicName=").append(topicName);
|
||||
sb.append(", topicParentName=").append(topicParentName);
|
||||
sb.append(", topicParentId=").append(topicParentId);
|
||||
sb.append(", topicDescribe=").append(topicDescribe);
|
||||
sb.append(", createdBy=").append(createdBy);
|
||||
sb.append(", createdOn=").append(createdOn);
|
||||
sb.append(", updatedBy=").append(updatedBy);
|
||||
sb.append(", updatedOn=").append(updatedOn);
|
||||
sb.append(", serialVersionUID=").append(serialVersionUID);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
249
ILogBizSystem/src/main/java/com/ag/log/TopicUserCol.java
Normal file
249
ILogBizSystem/src/main/java/com/ag/log/TopicUserCol.java
Normal file
@@ -0,0 +1,249 @@
|
||||
package com.ag.log;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 消息订阅用户表
|
||||
* @TableName topic_user_col
|
||||
*/
|
||||
@TableName(value ="topic_user_col")
|
||||
public class TopicUserCol implements Serializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@TableId
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 用户主键
|
||||
*/
|
||||
private String userId;
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String userName;
|
||||
|
||||
/**
|
||||
* 订阅频道ID
|
||||
*/
|
||||
private String topicRespId;
|
||||
|
||||
/**
|
||||
* 订阅频道名称
|
||||
*/
|
||||
private String topicRespName;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String createdBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date createdOn;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String updatedBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date updatedOn;
|
||||
|
||||
@TableField(exist = false)
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主键
|
||||
*/
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主键
|
||||
*/
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅频道ID
|
||||
*/
|
||||
public String getTopicRespId() {
|
||||
return topicRespId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅频道ID
|
||||
*/
|
||||
public void setTopicRespId(String topicRespId) {
|
||||
this.topicRespId = topicRespId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅频道名称
|
||||
*/
|
||||
public String getTopicRespName() {
|
||||
return topicRespName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅频道名称
|
||||
*/
|
||||
public void setTopicRespName(String topicRespName) {
|
||||
this.topicRespName = topicRespName;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setCreatedOn(Date createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public String getUpdatedBy() {
|
||||
return updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedBy(String updatedBy) {
|
||||
this.updatedBy = updatedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Date getUpdatedOn() {
|
||||
return updatedOn;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void setUpdatedOn(Date updatedOn) {
|
||||
this.updatedOn = updatedOn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object that) {
|
||||
if (this == that) {
|
||||
return true;
|
||||
}
|
||||
if (that == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != that.getClass()) {
|
||||
return false;
|
||||
}
|
||||
TopicUserCol other = (TopicUserCol) that;
|
||||
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
|
||||
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
|
||||
&& (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName()))
|
||||
&& (this.getTopicRespId() == null ? other.getTopicRespId() == null : this.getTopicRespId().equals(other.getTopicRespId()))
|
||||
&& (this.getTopicRespName() == null ? other.getTopicRespName() == null : this.getTopicRespName().equals(other.getTopicRespName()))
|
||||
&& (this.getCreatedBy() == null ? other.getCreatedBy() == null : this.getCreatedBy().equals(other.getCreatedBy()))
|
||||
&& (this.getCreatedOn() == null ? other.getCreatedOn() == null : this.getCreatedOn().equals(other.getCreatedOn()))
|
||||
&& (this.getUpdatedBy() == null ? other.getUpdatedBy() == null : this.getUpdatedBy().equals(other.getUpdatedBy()))
|
||||
&& (this.getUpdatedOn() == null ? other.getUpdatedOn() == null : this.getUpdatedOn().equals(other.getUpdatedOn()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
|
||||
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
|
||||
result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode());
|
||||
result = prime * result + ((getTopicRespId() == null) ? 0 : getTopicRespId().hashCode());
|
||||
result = prime * result + ((getTopicRespName() == null) ? 0 : getTopicRespName().hashCode());
|
||||
result = prime * result + ((getCreatedBy() == null) ? 0 : getCreatedBy().hashCode());
|
||||
result = prime * result + ((getCreatedOn() == null) ? 0 : getCreatedOn().hashCode());
|
||||
result = prime * result + ((getUpdatedBy() == null) ? 0 : getUpdatedBy().hashCode());
|
||||
result = prime * result + ((getUpdatedOn() == null) ? 0 : getUpdatedOn().hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(getClass().getSimpleName());
|
||||
sb.append(" [");
|
||||
sb.append("Hash = ").append(hashCode());
|
||||
sb.append(", id=").append(id);
|
||||
sb.append(", userId=").append(userId);
|
||||
sb.append(", userName=").append(userName);
|
||||
sb.append(", topicRespId=").append(topicRespId);
|
||||
sb.append(", topicRespName=").append(topicRespName);
|
||||
sb.append(", createdBy=").append(createdBy);
|
||||
sb.append(", createdOn=").append(createdOn);
|
||||
sb.append(", updatedBy=").append(updatedBy);
|
||||
sb.append(", updatedOn=").append(updatedOn);
|
||||
sb.append(", serialVersionUID=").append(serialVersionUID);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ag.log.mapper;
|
||||
|
||||
import com.ag.log.RemqMsgCustom;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Entity com.ag.log.RemqMsgCustom
|
||||
*/
|
||||
@Component
|
||||
public interface RemqMsgCustomMapper extends BaseMapper<RemqMsgCustom> {
|
||||
|
||||
int queryNoRead(String user);
|
||||
int markMsg(List<String> ids);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ag.log.mapper;
|
||||
|
||||
import com.ag.log.pojo.SysOperLog;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
/**
|
||||
* @author fengjun
|
||||
* @description 针对表【sys_oper_log(系统操作日志)】的数据库操作Mapper
|
||||
* @createDate 2022-04-18 09:57:24
|
||||
* @Entity com.ag.log.pojo.SysOperLog
|
||||
*/
|
||||
public interface SysOperLogMapper extends BaseMapper<SysOperLog> {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ag.log.mapper;
|
||||
|
||||
import com.ag.log.TopicResp;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Entity com.ag.log.TopicResp
|
||||
*/
|
||||
@Component
|
||||
public interface TopicRespMapper extends BaseMapper<TopicResp> {
|
||||
|
||||
int deleteAllByParentId(String id);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ag.log.mapper;
|
||||
|
||||
import com.ag.log.TopicUserCol;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Entity com.ag.log.TopicUserCol
|
||||
*/
|
||||
@Component
|
||||
public interface TopicUserColMapper extends BaseMapper<TopicUserCol> {
|
||||
|
||||
int deleteByUserIds(List<String> userIds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ag.log.pojo;
|
||||
|
||||
|
||||
import com.ag.base.ISerializable;
|
||||
|
||||
public class DefineDetailLog implements ISerializable {
|
||||
|
||||
private String id;
|
||||
private String mainId;
|
||||
private String colName;
|
||||
private String oldVal;
|
||||
private String newVal;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMainId() {
|
||||
return mainId;
|
||||
}
|
||||
|
||||
public void setMainId(String mainId) {
|
||||
this.mainId = mainId;
|
||||
}
|
||||
|
||||
public String getColName() {
|
||||
return colName;
|
||||
}
|
||||
|
||||
public void setColName(String colName) {
|
||||
this.colName = colName;
|
||||
}
|
||||
|
||||
public String getOldVal() {
|
||||
return oldVal;
|
||||
}
|
||||
|
||||
public void setOldVal(String oldVal) {
|
||||
this.oldVal = oldVal;
|
||||
}
|
||||
|
||||
public String getNewVal() {
|
||||
return newVal;
|
||||
}
|
||||
|
||||
public void setNewVal(String newVal) {
|
||||
this.newVal = newVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ag.log.pojo;
|
||||
|
||||
|
||||
import com.ag.base.ISerializable;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class DefineMainLog implements ISerializable {
|
||||
|
||||
private String id;
|
||||
private String bizId;
|
||||
private String keyword;
|
||||
private String bizType;
|
||||
private String menuName;
|
||||
private String cudType;
|
||||
private String createdBy;
|
||||
private java.util.Date createdOn;
|
||||
private String tenancyId;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getBizId() {
|
||||
return bizId;
|
||||
}
|
||||
|
||||
public void setBizId(String bizId) {
|
||||
this.bizId = bizId;
|
||||
}
|
||||
|
||||
public String getKeyword() {
|
||||
return keyword;
|
||||
}
|
||||
|
||||
public void setKeyword(String keyword) {
|
||||
this.keyword = keyword;
|
||||
}
|
||||
|
||||
public String getBizType() {
|
||||
return bizType;
|
||||
}
|
||||
|
||||
public void setBizType(String bizType) {
|
||||
this.bizType = bizType;
|
||||
}
|
||||
|
||||
public String getMenuName() {
|
||||
return menuName;
|
||||
}
|
||||
|
||||
public void setMenuName(String menuName) {
|
||||
this.menuName = menuName;
|
||||
}
|
||||
|
||||
public String getCudType() {
|
||||
return cudType;
|
||||
}
|
||||
|
||||
public void setCudType(String cudType) {
|
||||
this.cudType = cudType;
|
||||
}
|
||||
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public Date getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCreatedOn(Date createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
|
||||
public String getTenancyId() {
|
||||
return tenancyId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTenancyId(String tenancyId) {
|
||||
this.tenancyId = tenancyId;
|
||||
}
|
||||
}
|
||||
80
ILogBizSystem/src/main/java/com/ag/log/pojo/LogForCdc.java
Normal file
80
ILogBizSystem/src/main/java/com/ag/log/pojo/LogForCdc.java
Normal file
@@ -0,0 +1,80 @@
|
||||
package com.ag.log.pojo;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2022/5/26.
|
||||
*/
|
||||
public class LogForCdc {
|
||||
|
||||
private String tablekey;
|
||||
private String database;
|
||||
private String table;
|
||||
private String type;
|
||||
private JSONObject data;
|
||||
private JSONObject beforedata;
|
||||
|
||||
public void putData() {
|
||||
String now = StrUtil.join("to_date('", DateUtil.now(), "','yyyy-MM-dd HH24:mi:ss')");
|
||||
if (data != null) {
|
||||
data.put("tablekey", tablekey);
|
||||
data.put("type", type);
|
||||
data.put("created_on", now);
|
||||
}
|
||||
if (beforedata != null) {
|
||||
beforedata.put("tablekey", tablekey);
|
||||
beforedata.put("type", type);
|
||||
beforedata.put("created_on", now);
|
||||
}
|
||||
}
|
||||
|
||||
public String getTablekey() {
|
||||
return tablekey;
|
||||
}
|
||||
|
||||
public void setTablekey(String tablekey) {
|
||||
this.tablekey = tablekey;
|
||||
}
|
||||
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
public void setDatabase(String database) {
|
||||
this.database = database;
|
||||
}
|
||||
|
||||
public String getTable() {
|
||||
return table;
|
||||
}
|
||||
|
||||
public void setTable(String table) {
|
||||
this.table = table;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public JSONObject getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(JSONObject data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public JSONObject getBeforedata() {
|
||||
return beforedata;
|
||||
}
|
||||
|
||||
public void setBeforedata(JSONObject beforedata) {
|
||||
this.beforedata = beforedata;
|
||||
}
|
||||
}
|
||||
111
ILogBizSystem/src/main/java/com/ag/log/pojo/SysOperLog.java
Normal file
111
ILogBizSystem/src/main/java/com/ag/log/pojo/SysOperLog.java
Normal file
@@ -0,0 +1,111 @@
|
||||
package com.ag.log.pojo;
|
||||
|
||||
import com.ag.base.ISerializable;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 系统操作日志
|
||||
* @TableName sys_oper_log
|
||||
*/
|
||||
public class SysOperLog implements ISerializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String bean;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String method;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String createdBy;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private Date createdOn;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String ip;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String params;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getBean() {
|
||||
return bean;
|
||||
}
|
||||
|
||||
public void setBean(String bean) {
|
||||
this.bean = bean;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public Date getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCreatedOn(Date createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
public String getParams() {
|
||||
return params;
|
||||
}
|
||||
|
||||
public void setParams(String params) {
|
||||
this.params = params;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ag.log.service;
|
||||
|
||||
import com.ag.log.pojo.LogForCdc;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2022/5/31.
|
||||
*/
|
||||
public class CdcDataDict {
|
||||
|
||||
private static JSONObject tabJson = new JSONObject();
|
||||
|
||||
public static boolean isExistsTab(String tabName){
|
||||
return tabJson.containsKey(tabName);
|
||||
}
|
||||
|
||||
public static void putTab(LogForCdc log){
|
||||
|
||||
}
|
||||
|
||||
public static List<String> getColumns(LogForCdc log){
|
||||
return (List<String>)tabJson.get(log.getTable());
|
||||
}
|
||||
|
||||
public static boolean isContainsCols(LogForCdc log){
|
||||
List<String> columns = getColumns(log);
|
||||
JSONObject data = null;
|
||||
if (!log.getData().isEmpty()){
|
||||
data = log.getData();
|
||||
}else {
|
||||
data = log.getBeforedata();
|
||||
}
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
if (!columns.contains(key)){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void putTabCol(LogForCdc log){
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ag.log.service;
|
||||
|
||||
import com.ag.log.RemqMsgCustom;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public interface RemqMsgCustomService extends IService<RemqMsgCustom> {
|
||||
|
||||
/**
|
||||
* 查询未读消息
|
||||
* @param user
|
||||
* @return
|
||||
*/
|
||||
int queryNoRead(String user);
|
||||
|
||||
/**
|
||||
* 标记已读
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
int markMsg(List<String> ids);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.ag.log.service;
|
||||
|
||||
import com.ag.log.pojo.SysOperLog;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
/**
|
||||
* @author fengjun
|
||||
* @description 针对表【sys_oper_log(系统操作日志)】的数据库操作Service
|
||||
* @createDate 2022-04-18 09:57:24
|
||||
*/
|
||||
public interface SysOperLogService extends IService<SysOperLog> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ag.log.service;
|
||||
|
||||
import com.ag.log.TopicResp;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public interface TopicRespService extends IService<TopicResp> {
|
||||
|
||||
|
||||
int deleteAllByParentId(String id);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ag.log.service;
|
||||
|
||||
import com.ag.log.TopicUserCol;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public interface TopicUserColService extends IService<TopicUserCol> {
|
||||
|
||||
int deleteByUserId(String userId);
|
||||
int deleteByUserIds(List<String> userIds);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ag.log.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.ag.log.RemqMsgCustom;
|
||||
import com.ag.log.service.RemqMsgCustomService;
|
||||
import com.ag.log.mapper.RemqMsgCustomMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Service
|
||||
public class RemqMsgCustomServiceImpl extends ServiceImpl<RemqMsgCustomMapper, RemqMsgCustom>
|
||||
implements RemqMsgCustomService{
|
||||
|
||||
@Autowired
|
||||
private RemqMsgCustomMapper remqMsgCustomMapper;
|
||||
|
||||
@Override
|
||||
public int queryNoRead(String user) {
|
||||
return remqMsgCustomMapper.queryNoRead(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int markMsg(List<String> ids) {
|
||||
if(ids.size()>999){
|
||||
Integer tempCount=0;
|
||||
List<List<String>> lists = CollUtil.split(ids,999);
|
||||
for (List<String> list : lists) {
|
||||
tempCount+=remqMsgCustomMapper.markMsg(list);
|
||||
}
|
||||
return tempCount;
|
||||
}else{
|
||||
return remqMsgCustomMapper.markMsg(ids);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.ag.log.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.ag.log.pojo.SysOperLog;
|
||||
import com.ag.log.service.SysOperLogService;
|
||||
import com.ag.log.mapper.SysOperLogMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* @author fengjun
|
||||
* @description 针对表【sys_oper_log(系统操作日志)】的数据库操作Service实现
|
||||
* @createDate 2022-04-18 09:57:24
|
||||
*/
|
||||
@Service
|
||||
public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOperLog>
|
||||
implements SysOperLogService{
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ag.log.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.ag.log.TopicResp;
|
||||
import com.ag.log.service.TopicRespService;
|
||||
import com.ag.log.mapper.TopicRespMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Service
|
||||
public class TopicRespServiceImpl extends ServiceImpl<TopicRespMapper, TopicResp>
|
||||
implements TopicRespService{
|
||||
|
||||
@Autowired
|
||||
private TopicRespMapper mapper;
|
||||
|
||||
@Override
|
||||
public int deleteAllByParentId(String id) {
|
||||
return mapper.deleteAllByParentId(id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ag.log.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.ag.log.TopicUserCol;
|
||||
import com.ag.log.service.TopicUserColService;
|
||||
import com.ag.log.mapper.TopicUserColMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Service
|
||||
public class TopicUserColServiceImpl extends ServiceImpl<TopicUserColMapper, TopicUserCol>
|
||||
implements TopicUserColService{
|
||||
|
||||
@Autowired
|
||||
private TopicUserColMapper mapper;
|
||||
|
||||
@Override
|
||||
public int deleteByUserId(String userId) {
|
||||
QueryWrapper<TopicUserCol> wrapper = Wrappers.query();
|
||||
wrapper.eq("USER_ID",userId);
|
||||
return mapper.delete(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByUserIds(List<String> userIds) {
|
||||
if(userIds.size()>999){
|
||||
Integer tempCount=0;
|
||||
List<List<String>> lists = CollUtil.split(userIds,999);
|
||||
for (List<String> list : lists) {
|
||||
tempCount+=mapper.deleteByUserIds(list);
|
||||
}
|
||||
return tempCount;
|
||||
}else{
|
||||
return mapper.deleteByUserIds(userIds);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
101
ILogBizSystem/src/main/java/com/ag/orc/PdfOrcProcesss.java
Normal file
101
ILogBizSystem/src/main/java/com/ag/orc/PdfOrcProcesss.java
Normal file
@@ -0,0 +1,101 @@
|
||||
package com.ag.orc;
|
||||
|
||||
import org.apache.pdfbox.io.RandomAccessBuffer;
|
||||
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.List;
|
||||
|
||||
public class PdfOrcProcesss implements java.io.Serializable{
|
||||
|
||||
public List logerror=null;
|
||||
public InputStream datain=null;
|
||||
|
||||
public List getLogerror() {
|
||||
return logerror;
|
||||
}
|
||||
public void setLogerror(List data) {
|
||||
this.logerror = data;
|
||||
}
|
||||
|
||||
public InputStream getDatain() {
|
||||
return datain;
|
||||
}
|
||||
|
||||
public void setDatain(InputStream datain) {
|
||||
this.datain = datain;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 读取pdf文件内容
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void main(String args[]) throws IOException {
|
||||
String result = null;
|
||||
FileInputStream is = null;
|
||||
PDDocument document = null;
|
||||
try {
|
||||
is = new FileInputStream("/Users/running/work/work2019/威海ocr识别/DB_aabfejjffabc0x01FA.pdf");
|
||||
// is = new FileInputStream("/Users/shaoqiang/work/work2019/威海ocr识别/COSU 6201279260 BC.PDF");
|
||||
PDFParser parser = new PDFParser(new RandomAccessBuffer(is));
|
||||
parser.parse();
|
||||
document = parser.getPDDocument();
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
result = stripper.getText(document);
|
||||
System.out.println(result);
|
||||
// pdfToWordOfText();
|
||||
} finally {
|
||||
if (is != null) {
|
||||
is.close();
|
||||
}
|
||||
if (document != null) {
|
||||
document.close();
|
||||
}
|
||||
}
|
||||
//return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void pdfToWordOfText(){
|
||||
try {
|
||||
//pdf文件路径
|
||||
String filePath = "/Users/shaoqiang/work/work2019/威海ocr识别/HL-83014252 MXZLO BC 1ST UPDATE.PDF";
|
||||
File fdf = new File(filePath);
|
||||
//生成的word的文件路径
|
||||
String wordPath = "/Users/shaoqiang/work/work2019/威海ocr识别/ap.docx";
|
||||
//通过文件名加载文档
|
||||
PDDocument doc = PDDocument.load(fdf);
|
||||
//获取文档的页数
|
||||
int pageNumber = doc.getNumberOfPages();
|
||||
//剥离器(读取pdf文件)
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
//排序
|
||||
stripper.setSortByPosition(true);
|
||||
//设置要读取的起始页码
|
||||
stripper.setStartPage(1);
|
||||
//设置要读取的结束页码
|
||||
stripper.setEndPage(pageNumber);
|
||||
File word = new File(wordPath);
|
||||
if(!word.exists()){
|
||||
word.createNewFile();
|
||||
}
|
||||
//文件输出流
|
||||
FileOutputStream fos = new FileOutputStream(word);
|
||||
//
|
||||
Writer writer = new OutputStreamWriter(fos, "utf-8");
|
||||
stripper.writeText(doc, writer);
|
||||
writer.close();
|
||||
fos.close();
|
||||
System.out.println("转码完成");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by FernFlower decompiler)
|
||||
//
|
||||
|
||||
package com.ag.psamathe.api.impl;
|
||||
|
||||
import com.ag.psamathe.api.ModuleConfig;
|
||||
import com.ag.psamathe.api.pojo.ModuleVersion;
|
||||
import com.ag.psamathe.api.util.DataSourceUtil;
|
||||
import com.ag.util.ResourceUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ResourceBundle;
|
||||
import javax.sql.DataSource;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class ModuleRefreshSchedulerImpl extends AbstractModuleRefreshScheduler {
|
||||
private List<ModuleConfig> moduleConfigs;
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ModuleRefreshSchedulerImpl.class);
|
||||
private ResourceBundle rb = ResourceUtil.getResourceBundle("system");
|
||||
|
||||
public ModuleRefreshSchedulerImpl() {
|
||||
}
|
||||
|
||||
public List<ModuleConfig> queryModuleConfigs() {
|
||||
this.setModuleConfigs(this.buildModuleConfig());
|
||||
return this.moduleConfigs;
|
||||
}
|
||||
|
||||
public void setModuleConfigs(List<ModuleConfig> moduleConfigs) {
|
||||
this.moduleConfigs = moduleConfigs;
|
||||
}
|
||||
|
||||
public List<ModuleConfig> buildModuleConfig() {
|
||||
DataSource ds = null;
|
||||
String dataSourceBeanName = this.rb.getString("dataSourceBeanName");
|
||||
if (this.isContainsBean(dataSourceBeanName)) {
|
||||
JdbcTemplate jdbcTemplate = (JdbcTemplate)this.getModuleLoader().getBean(dataSourceBeanName);
|
||||
ds = jdbcTemplate.getDataSource();
|
||||
}
|
||||
|
||||
String userName = this.rb.getString("userName");
|
||||
List<ModuleVersion> versions = DataSourceUtil.getInstance().queryVersions(ds, userName);
|
||||
Assert.notEmpty(versions, "表MODULE_VERSION未配置name:======" + userName);
|
||||
List<ModuleConfig> configs = new ArrayList();
|
||||
Iterator var6 = versions.iterator();
|
||||
|
||||
while(var6.hasNext()) {
|
||||
ModuleVersion version = (ModuleVersion)var6.next();
|
||||
ModuleConfig moduleConfig = new ModuleConfig();
|
||||
ArrayList moduleUrls = new ArrayList();
|
||||
|
||||
try {
|
||||
String[] var10 = version.getJarPath().split(",");
|
||||
int var11 = var10.length;
|
||||
|
||||
for(int var12 = 0; var12 < var11; ++var12) {
|
||||
String jarPath = var10[var12];
|
||||
moduleUrls.add(new URL("file:" + jarPath));
|
||||
}
|
||||
} catch (Exception var14) {
|
||||
LOGGER.error(var14.getMessage());
|
||||
}
|
||||
|
||||
moduleConfig.setModuleUrl(moduleUrls);
|
||||
if (StringUtils.isEmpty(version.getOverridePackages())) {
|
||||
moduleConfig.setOverridePackages(this.strForList(version.getScanPackage()));
|
||||
} else {
|
||||
moduleConfig.setOverridePackages(this.strForList(version.getOverridePackages()));
|
||||
}
|
||||
|
||||
Map<String, Object> properties = new HashMap();
|
||||
properties.put("url", "127.0.0.1");
|
||||
moduleConfig.setProperties(properties);
|
||||
moduleConfig.setName(version.getName());
|
||||
moduleConfig.setEnabled(version.getEnabled() == 1);
|
||||
moduleConfig.setVersion(version.getVersion());
|
||||
moduleConfig.setDesc(version.getDesc());
|
||||
configs.add(moduleConfig);
|
||||
}
|
||||
|
||||
return configs;
|
||||
}
|
||||
|
||||
public List<String> strForList(String str) {
|
||||
return Arrays.asList(str.split(","));
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "aa";
|
||||
String[] arr = str.split(",");
|
||||
List<String> strings = Arrays.asList(arr);
|
||||
System.out.println(JSON.toJSONString(strings));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by FernFlower decompiler)
|
||||
//
|
||||
|
||||
package com.ag.psamathe.api.util;
|
||||
|
||||
import com.ag.psamathe.api.pojo.ModuleVersion;
|
||||
import com.ag.util.ResourceUtil;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.ResourceBundle;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.sql.DataSource;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DataSourceUtil {
|
||||
private static DataSourceUtil instance;
|
||||
private static final Logger log = LoggerFactory.getLogger(DataSourceUtil.class);
|
||||
private Connection conn;
|
||||
private Statement stat;
|
||||
private ResultSet rs;
|
||||
private String sql = "select * from MODULE_VERSION";
|
||||
|
||||
private DataSourceUtil() {
|
||||
}
|
||||
|
||||
public static DataSourceUtil getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new DataSourceUtil();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void initDataSourceForJNDI() throws Exception {
|
||||
Context ctx = new InitialContext();
|
||||
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/wb_oracle");
|
||||
this.conn = ds.getConnection();
|
||||
this.stat = this.conn.createStatement();
|
||||
}
|
||||
|
||||
private void initDataSourceForJDBC() throws Exception {
|
||||
log.info("mode==initDataSourceForJDBC");
|
||||
ResourceBundle rb = ResourceUtil.getResourceBundle("datasource");
|
||||
String classForName = rb.getString("jdbc.driverClassName");
|
||||
String url = rb.getString("main.url");
|
||||
String username = rb.getString("main.username");
|
||||
String password = rb.getString("main.password");
|
||||
Class.forName(classForName);
|
||||
this.conn = DriverManager.getConnection(url, username, password);
|
||||
this.stat = this.conn.createStatement();
|
||||
}
|
||||
|
||||
private void initDataSource() throws Exception {
|
||||
ResourceBundle rb = ResourceUtil.getResourceBundle("system");
|
||||
String connectModel = rb.getString("connectModel");
|
||||
if ("JDBC".equals(connectModel)) {
|
||||
this.initDataSourceForJDBC();
|
||||
}
|
||||
|
||||
if ("JNDI".equals(connectModel)) {
|
||||
this.initDataSourceForJNDI();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void initDataSource(DataSource ds) throws Exception {
|
||||
log.info("mode==JDBCTemplate");
|
||||
this.conn = ds.getConnection();
|
||||
this.stat = this.conn.createStatement();
|
||||
}
|
||||
|
||||
public List<ModuleVersion> queryVersions(DataSource ds, String userName) {
|
||||
ArrayList versions = new ArrayList();
|
||||
|
||||
try {
|
||||
if (ds != null && ds.getConnection() != null && !ds.getConnection().isClosed()) {
|
||||
this.initDataSource(ds);
|
||||
} else {
|
||||
this.initDataSource();
|
||||
}
|
||||
|
||||
this.rs = this.stat.executeQuery(this.sql + " where name='" + userName + "'");
|
||||
log.info(this.sql + " where name='" + userName + "'");
|
||||
|
||||
while(this.rs.next()) {
|
||||
ModuleVersion version = new ModuleVersion();
|
||||
version.setId(this.rs.getString("ID"));
|
||||
version.setName(this.rs.getString("NAME"));
|
||||
version.setEnabled(Integer.valueOf(this.rs.getString("ENABLED")));
|
||||
version.setVersion(this.rs.getString("VERSION"));
|
||||
version.setJarPath(this.rs.getString("JAR_PATH"));
|
||||
version.setScanPackage(this.rs.getString("SCAN_PACKAGE"));
|
||||
version.setDesc(this.rs.getString("DESC"));
|
||||
version.setOverridePackages(this.rs.getString("OVERRIDE_PACKAGES"));
|
||||
versions.add(version);
|
||||
}
|
||||
} catch (Exception var8) {
|
||||
log.error(var8.getMessage());
|
||||
} finally {
|
||||
this.closeConn();
|
||||
}
|
||||
|
||||
return versions;
|
||||
}
|
||||
|
||||
private void closeConn() {
|
||||
try {
|
||||
if (this.rs != null && !this.rs.isClosed()) {
|
||||
this.rs.close();
|
||||
}
|
||||
|
||||
if (this.stat != null && !this.stat.isClosed()) {
|
||||
this.stat.close();
|
||||
}
|
||||
|
||||
if (this.conn != null && !this.conn.isClosed()) {
|
||||
this.conn.close();
|
||||
}
|
||||
} catch (Exception var2) {
|
||||
log.error(var2.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ag.rate.account.dao;
|
||||
|
||||
import com.ag.base.IBaseRepository;
|
||||
import com.ag.entity.fee.AccountPoints;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/5/15 0015.
|
||||
*/
|
||||
@Repository
|
||||
public class AccountPointsDao {
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<AccountPoints> pointRepo;
|
||||
|
||||
public int delete(AccountPoints delAP) {
|
||||
return pointRepo.delete(delAP, "POINT_CODE", "TENANCY_ID");
|
||||
}
|
||||
|
||||
public int[] save(List<AccountPoints> accountPoints) {
|
||||
return pointRepo.saveAll(accountPoints);
|
||||
}
|
||||
|
||||
public List<AccountPoints> findByPointId(AccountPoints point) {
|
||||
return pointRepo.findByEntity(point, AccountPoints.class);
|
||||
}
|
||||
|
||||
public int[] delete(List<AccountPoints> list) {
|
||||
return pointRepo.deleteAll(list, "ID");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ag.rate.account.service;
|
||||
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.entity.fee.AccountPoints;
|
||||
import com.ag.rate.account.dao.AccountPointsDao;
|
||||
import com.ag.util.UUIDUtil;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/5/15 0015.
|
||||
*/
|
||||
@Service
|
||||
public class AccountPointsService extends BaseService {
|
||||
|
||||
@Autowired
|
||||
private AccountPointsDao apDao;
|
||||
|
||||
/**
|
||||
* ?????????
|
||||
*/
|
||||
@Transactional
|
||||
public void save(HttpServletRequest request){
|
||||
String pointId = request.getParameter("POINT_CODE");//????
|
||||
String pointName = request.getParameter("POINT_NAME");
|
||||
String ids = request.getParameter("ids");//???
|
||||
/*AccountPoints delAP = new AccountPoints();
|
||||
delAP.setPointCode(pointId);
|
||||
delAP.setTenancyId(super.getTenancyId(request));
|
||||
apDao.delete(delAP);*/
|
||||
JSONArray ja = JSONArray.parseArray(ids);
|
||||
List<AccountPoints> lst = new ArrayList<>();
|
||||
for(Object obj : ja.toArray()){
|
||||
AccountPoints accountPoints = new AccountPoints();
|
||||
accountPoints.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, accountPoints);
|
||||
accountPoints.setItemId(obj.toString());
|
||||
accountPoints.setPointCode(pointId);
|
||||
accountPoints.setPointName(pointName);
|
||||
lst.add(accountPoints);
|
||||
}
|
||||
apDao.save(lst);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void del(HttpServletRequest request){
|
||||
String ids = request.getParameter("ids");//???
|
||||
JSONArray array = JSONArray.parseArray(ids);
|
||||
List<AccountPoints> lst = new ArrayList<>();
|
||||
for(Object obj : array.toArray()){
|
||||
AccountPoints accountPoints = new AccountPoints();
|
||||
accountPoints.setId(obj.toString());
|
||||
lst.add(accountPoints);
|
||||
}
|
||||
apDao.delete(lst);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.ag.rate.tariff.dao;
|
||||
|
||||
import com.ag.base.IBaseRepository;
|
||||
import com.ag.entity.fee.Contract;
|
||||
import com.ag.entity.fee.ContractCategory;
|
||||
import com.ag.entity.fee.ContractItem;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/6/3 0003.
|
||||
*/
|
||||
@Repository
|
||||
public class ContractDao {
|
||||
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<Contract> contractRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<ContractCategory> contCateRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<ContractItem> contItemRepo;
|
||||
|
||||
public String findAll(Contract contract) {
|
||||
return contractRepo.findByEqSql(contract, "TENANCY_ID");
|
||||
}
|
||||
|
||||
public int save(Contract contract) {
|
||||
return contractRepo.save(contract);
|
||||
}
|
||||
|
||||
public int update(Contract contract, String[] requestParam) {
|
||||
return contractRepo.update(contract, requestParam,"ID");
|
||||
}
|
||||
|
||||
public int delete(Contract contract) {
|
||||
return contractRepo.delete(contract, "ID");
|
||||
}
|
||||
|
||||
public String queryCateByContract(ContractCategory contractCategory) {
|
||||
return contCateRepo.findByEqSql(contractCategory, ContractCategory.class, "TENANCY_ID","CONTRACT_ID");
|
||||
/*String sql = StringUtils.join("select b.ID, b.CATEGORY_ID,",
|
||||
"a.DESCRIPTION, a.IS_ALL, a.EFFECTIVED, a.ENABLED, a.BIZ_SCOPE, a.NOTES, b.CREATEUSER, b.CREATETIME",
|
||||
" from C_BASE_CATEGORY a,C_CONTRACT_CATEGORY b where a.ID = b.CATEGORY_ID and a.TENANCY_ID='",
|
||||
contractCategory.getTenancyId(), "' and b.CONTRACT_ID='", contractCategory.getContractId(), "'");
|
||||
return sql;*/
|
||||
}
|
||||
|
||||
public int save(ContractCategory contractCategory) {
|
||||
return contCateRepo.save(contractCategory);
|
||||
}
|
||||
|
||||
public int update(ContractCategory contractCategory, String[] requestParam) {
|
||||
return contCateRepo.update(contractCategory, requestParam,"ID");
|
||||
}
|
||||
|
||||
public int delete(ContractCategory contractCategory) {
|
||||
return contCateRepo.delete(contractCategory, "CONTRACT_ID");
|
||||
}
|
||||
|
||||
public String queryItemByCate(ContractItem item) {
|
||||
return contItemRepo.findByEqSql(item, ContractItem.class, "TENANCY_ID","CONTRACT_ID","CATEGORY_ID");
|
||||
/*String sql = StringUtils.join("select b.ID, b.ITEM_ID, b.CREATEUSER, b.CREATETIME, ",
|
||||
"a.DESCRIPTION, a.INVOICE_TYPE, a.RATE_TYPE, a.LIFE_STATUS, a.MIN_AMOUNT, a.MAX_AMOUNT, a.UNIT, ",
|
||||
"a.IS_AUTOCALC, a.IS_FORMAT, a.FORMAT_UNIT, a.CURRENCY, a.GL_CODE, a.FLAT_RATE, a.IS_ALL, " ,
|
||||
"a.ACCOUNT_TYPE, a.IS_AVERAGE, a.NOTES ",
|
||||
" from C_BASE_CHARGING_ITEM a,C_CONTRACT_ITEM b where a.ID = b.ITEM_ID and a.TENANCY_ID='",
|
||||
item.getTenancyId(), "' and b.CONTRACT_ID='", item.getContractId(), "' and b.CATEGORY_ID='",
|
||||
item.getCategoryId(), "'");
|
||||
return sql;*/
|
||||
}
|
||||
|
||||
public void deleteSql(ContractItem delCI) {
|
||||
String sql = "delete from C_CONTRACT_ITEM where CONTRACT_ID=? and CATEGORY_ID=?";
|
||||
contItemRepo.update(sql, delCI.getContractId(), delCI.getCategoryId());
|
||||
}
|
||||
public void deleteContractItem(String contractId) {
|
||||
String sql = "update C_CONTRACT_ITEM set DEL_FLAG = 1 where CONTRACT_ID=?";
|
||||
contItemRepo.update(sql,contractId);
|
||||
}
|
||||
public void save(ContractItem contractItem) {
|
||||
contItemRepo.save(contractItem);
|
||||
}
|
||||
|
||||
public List<ContractCategory> findByContract(ContractCategory contractCategory) {
|
||||
return contCateRepo.findByEntity(contractCategory, ContractCategory.class);
|
||||
}
|
||||
|
||||
public List<ContractItem> findByContract(ContractItem contractItem) {
|
||||
return contItemRepo.findByEntity(contractItem, ContractItem.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String queryContractByCategory(ContractCategory contractCategory) {
|
||||
return StringUtils.join("select a.ID,a.DESCRIPTION from C_CONTRACT a, C_CONTRACT_CATEGORY b",
|
||||
" where a.ID=b.CONTRACT_ID and CATEGORY_ID='", contractCategory.getCategoryId(),
|
||||
"' and a.TENANCY_ID='", contractCategory.getTenancyId(), "'");
|
||||
}
|
||||
|
||||
public int[] saveContCate(List<ContractCategory> ccLst) {
|
||||
return contCateRepo.saveAll(ccLst);
|
||||
}
|
||||
|
||||
public int[] delContCate(List<ContractCategory> ccLst, Object... colNames) {
|
||||
return contCateRepo.deleteAll(ccLst, colNames);
|
||||
}
|
||||
|
||||
|
||||
public int[] saveContItem(List<ContractItem> ciLst) {
|
||||
return contItemRepo.saveAll(ciLst);
|
||||
}
|
||||
public int[] delContItem(List<ContractItem> ciLst, Object... colNames) {
|
||||
return contItemRepo.deleteAll(ciLst, colNames);
|
||||
}
|
||||
|
||||
public int update(ContractItem entity, String[] requestParam) {
|
||||
return contItemRepo.update(entity, requestParam,"ID");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.ag.rate.tariff.dao;
|
||||
|
||||
import com.ag.base.IBaseRepository;
|
||||
import com.ag.entity.fee.*;
|
||||
import com.ag.util.StrUtil;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/4/11 0011.
|
||||
*/
|
||||
@Repository
|
||||
public class TariffDao {
|
||||
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<BaseCategory> cateRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<BaseChargingItem> itemRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<Tariff> tariffRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<TariffRitem> ritemRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<TariffMultistep> stepRepo;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository<ContractItem> contItemRepo;
|
||||
|
||||
|
||||
public String findAll(BaseCategory cate) {
|
||||
return cateRepo.findByEqSql(cate, "TENANCY_ID");
|
||||
}
|
||||
|
||||
public int save(BaseCategory cate) {
|
||||
return cateRepo.save(cate);
|
||||
}
|
||||
|
||||
public int update(BaseCategory cate, String[] requestParam) {
|
||||
return cateRepo.update(cate, requestParam, "ID");
|
||||
}
|
||||
|
||||
public int delete(BaseCategory cate) {
|
||||
return cateRepo.delete(cate, "ID");
|
||||
}
|
||||
|
||||
public int isUseItemByCate(String id) {
|
||||
String sql = "select count(0) from C_BASE_CHARGING_ITEM where CATEGORY_ID=?";
|
||||
return cateRepo.count(sql, id);
|
||||
}
|
||||
|
||||
public String findAll(BaseChargingItem item) {
|
||||
String sql = itemRepo.findByEqSql(item, "TENANCY_ID");
|
||||
/*sql = StrUtil.join(sql, " and EXISTS (select * from C_CATEGORY_CONTACT where TENANCY_ID='",item.getTenancyId(),
|
||||
"' and CHARGING_ID=a.id");*/
|
||||
if (!sql.toLowerCase().contains(" where ")){
|
||||
sql = StrUtil.join(sql, " where 1=1 ");
|
||||
}
|
||||
if (!StrUtil.isEmpty(item.getCategoryId())){
|
||||
sql = StrUtil.join(sql, " and CATEGORY_ID='", item.getCategoryId(),"'");
|
||||
}
|
||||
//sql = StrUtil.join(sql, ")");
|
||||
return sql;
|
||||
}
|
||||
|
||||
public List<BaseChargingItem> findBaseItemLst(BaseChargingItem item){
|
||||
return itemRepo.findByEntity(item, BaseChargingItem.class);
|
||||
}
|
||||
|
||||
public int save(BaseChargingItem item) {
|
||||
return itemRepo.save(item);
|
||||
}
|
||||
|
||||
public int update(BaseChargingItem item, String[] requestParam) {
|
||||
return itemRepo.update(item, requestParam,"ID");
|
||||
}
|
||||
|
||||
public int delete(BaseChargingItem item) {
|
||||
return itemRepo.delete(item, "ID");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public String findAll(TariffRitem ritem) {
|
||||
return ritemRepo.findByEqSql(ritem, "RULE_ID");
|
||||
}
|
||||
|
||||
public int save(TariffRitem ritem) {
|
||||
return ritemRepo.save(ritem);
|
||||
}
|
||||
|
||||
public int update(TariffRitem ritem) {
|
||||
return ritemRepo.update(ritem, "ID");
|
||||
}
|
||||
public int[] updateRitem(List<TariffRitem> ritems) {
|
||||
return ritemRepo.updateAll(ritems, "ID");
|
||||
}
|
||||
|
||||
public int deleteItemByRuleId(String ruleId) {
|
||||
String sql = "delete from C_TARIFF_RITEM where RULE_ID=?";
|
||||
return ritemRepo.update(sql, ruleId);
|
||||
}
|
||||
|
||||
public String findTariffByCategory(Tariff tariff) {
|
||||
//return tariffRepo.findByEqSql(tariff, Tariff.class, "TENANCY_ID","CHARGING_ID");
|
||||
String sql = StringUtils.join("SELECT a.ID, a.TENANCY_ID, a.FILTER_ID, b.DESCRIPTION FILTER_NAME, a.CHARGING_ID,",
|
||||
" a.RATE, a.DISCOUNT, a.CURRENCY, a.GL_CODE, a.RATE_TYPE, a.FLAT_RATE, a.MIN_AMOUNT, a.MAX_AMOUNT, a.START_FIELD, ",
|
||||
"a.END_FIELD, a.IS_VACATION, a.IS_NIGHTSHIFT, a.IS_WEEKDAY, a.IS_TIMES, a.TIME_UNIT, a.DESCRIPTION, a.NOTES, ",
|
||||
"a.CREATED_BY, a.CREATED_ON, a.UPDATED_BY, a.UPDATED_ON, a.CUSTOMERS, a.CUSTOMER_NAM, a.VOL_PRICE FROM C_TARIFF a, C_TARIFF_RULE b ",
|
||||
"where a.FILTER_ID = b.ID and a.TENANCY_ID='", tariff.getTenancyId(), "' and a.CHARGING_ID='",
|
||||
tariff.getChargingId(), "' and a.CONTRACT_ID='", tariff.getContractId(), "'");
|
||||
/*if(!StringUtils.isEmpty(tariff.getDescription())){
|
||||
String[] array = tariff.getDescription().split(",");
|
||||
for (String descript : array){
|
||||
sql = StringUtils.join(sql, " and a.DESCRIPTION like '%", StrUtil.trimString(descript), "%'");
|
||||
}
|
||||
}*/
|
||||
return sql;
|
||||
}
|
||||
|
||||
public int save(Tariff tariff) {
|
||||
return tariffRepo.save(tariff);
|
||||
}
|
||||
|
||||
public int update(Tariff tariff, String[] requestParam) {
|
||||
return tariffRepo.update(tariff, requestParam,"ID");
|
||||
}
|
||||
|
||||
public int delete(Tariff tariff) {
|
||||
return tariffRepo.delete(tariff, "ID");
|
||||
}
|
||||
|
||||
public List<Tariff> findByContract(Tariff tariff) {
|
||||
return tariffRepo.findByEntity(tariff, Tariff.class);
|
||||
}
|
||||
public List<Tariff> findByItemIdAndContractId(Tariff tariff) {
|
||||
return tariffRepo.findByEntity(tariff, Tariff.class);
|
||||
}
|
||||
|
||||
public int[] saveTariff(List<Tariff> tariffLst) {
|
||||
return tariffRepo.saveAll(tariffLst);
|
||||
}
|
||||
|
||||
public List<BaseCategory> findByInIds(String saveIds, BaseCategory cate) {
|
||||
String sql = findAll(cate);
|
||||
if (!sql.toLowerCase().contains(" where ")){
|
||||
sql = StrUtil.join(sql, " where 1=1 ");
|
||||
}
|
||||
sql = StrUtil.join(sql, " and id in('", saveIds ,"') and ENABLED=1 ");
|
||||
return cateRepo.list(sql, BaseCategory.class);
|
||||
}
|
||||
|
||||
public List<BaseChargingItem> findByInIds(String saveIds, BaseChargingItem item) {
|
||||
String sql = findAll(item);
|
||||
if (!sql.toLowerCase().contains(" where ")){
|
||||
sql = StrUtil.join(sql, " where 1=1 ");
|
||||
}
|
||||
sql = StrUtil.join(sql, " and id in('", saveIds ,"') and LIFE_STATUS=1 ");
|
||||
return itemRepo.list(sql, BaseChargingItem.class);
|
||||
}
|
||||
|
||||
public Integer findTariffNum(Tariff tariff) {
|
||||
String sql = "select count(0) from C_TARIFF where CHARGING_ID=? and CONTRACT_ID=? and TENANCY_ID=?";
|
||||
return tariffRepo.count(sql, tariff.getChargingId(), tariff.getContractId(), tariff.getTenancyId());
|
||||
}
|
||||
|
||||
public String findMultistep(TariffMultistep step) {
|
||||
return stepRepo.getSelectByEntity(step, false);
|
||||
}
|
||||
|
||||
public void saveStep(List<TariffMultistep> createLst) {
|
||||
stepRepo.saveAll(createLst);
|
||||
}
|
||||
|
||||
public void updateStep(List<TariffMultistep> updateLst, String[] needCols) {
|
||||
stepRepo.updateAll(updateLst, needCols, "ID");
|
||||
}
|
||||
|
||||
public void deleteStep(List<TariffMultistep> destroyLst) {
|
||||
stepRepo.deleteAll(destroyLst, "ID");
|
||||
}
|
||||
|
||||
public Integer queryUsedTariff(String id, String tenancyId) {
|
||||
String sql = "select count(0) from C_TARIFF a, C_CONTRACT_ITEM b where a.FILTER_ID=? and a.TENANCY_ID=? and a.CHARGING_ID = b.ITEM_ID";
|
||||
return tariffRepo.count(sql, id, tenancyId);
|
||||
}
|
||||
|
||||
|
||||
public int updateCategory(ContractItem entity) {
|
||||
return contItemRepo.update(entity, "ITEM_ID");
|
||||
}
|
||||
|
||||
public List<TariffRitem> findRitemsByContract(Tariff contract) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=?";
|
||||
String sql = "select * from C_TARIFF_RITEM where RULE_ID in("+tsql+")";
|
||||
return ritemRepo.list(sql, TariffRitem.class, contract.getContractId());
|
||||
}
|
||||
public void deleteRitemsByContract(String contractId) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=?";
|
||||
String sql = "update C_TARIFF_RITEM set DEL_FLAG = 1 where RULE_ID in("+tsql+")";
|
||||
ritemRepo.update(sql,contractId);
|
||||
}
|
||||
public void deleteRitemsByContractItem(ContractItem contractItem) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=? and CHARGING_ID = ?";
|
||||
String sql = "update C_TARIFF_RITEM set DEL_FLAG = 1 where RULE_ID in("+tsql+")";
|
||||
ritemRepo.update(sql,contractItem.getContractId(),contractItem.getItemId());
|
||||
}
|
||||
public List<TariffMultistep> findStepByContract(Tariff contract) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=?";
|
||||
String sql = "select * from C_TARIFF_MULTISTEP where TARIFF_ID in("+tsql+")";
|
||||
return stepRepo.list(sql, TariffMultistep.class, contract.getContractId());
|
||||
}
|
||||
public void deleteStepByContract(String contractId) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=?";
|
||||
String sql = "update C_TARIFF_MULTISTEP set DEL_FLAG = 1 where TARIFF_ID in("+tsql+")";
|
||||
stepRepo.update(sql, contractId);
|
||||
}
|
||||
public void deleteStepByContractItem(ContractItem contractItem) {
|
||||
String tsql = "select id from C_TARIFF where CONTRACT_ID=? and CHARGING_ID = ?";
|
||||
String sql = "update C_TARIFF_MULTISTEP set DEL_FLAG = 1 where TARIFF_ID in("+tsql+")";
|
||||
stepRepo.update(sql,contractItem.getContractId(),contractItem.getItemId());
|
||||
}
|
||||
|
||||
public int[] saveRitem(List<TariffRitem> ritems) {
|
||||
return ritemRepo.saveAll(ritems);
|
||||
}
|
||||
|
||||
public void deleteTariff(String contractId) {
|
||||
String sql = "update C_TARIFF set DEL_FLAG = 1 where CONTRACT_ID=?";
|
||||
tariffRepo.update(sql,contractId);
|
||||
}
|
||||
public void deleteTariffByContractItem( ContractItem contractItem) {
|
||||
String sql = "update C_TARIFF set DEL_FLAG = 1 where CONTRACT_ID=? and CHARGING_ID = ?";
|
||||
tariffRepo.update(sql,contractItem.getContractId(),contractItem.getItemId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,637 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.ag.base.*;
|
||||
import com.ag.entity.fee.*;
|
||||
import com.ag.entity.fee.vo.ContractVO;
|
||||
import com.ag.rate.tariff.dao.ContractDao;
|
||||
import com.ag.rate.tariff.dao.TariffDao;
|
||||
import com.ag.secp.platform.spring.SpringApplicationContext;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.ag.util.TimeUtil;
|
||||
import com.ag.util.UUIDUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import jdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/6/3 0003.
|
||||
*/
|
||||
@Service
|
||||
public class ContractService extends BaseService {
|
||||
@Autowired
|
||||
private ContractDao contractDao;
|
||||
@Autowired
|
||||
private TariffDao tariffDao;
|
||||
|
||||
@Autowired
|
||||
//return "C_" + toLower(tableName);表名带C_ 类名不带C
|
||||
private BaseRepositoryImpl feeDao;
|
||||
@Autowired
|
||||
//return toLower(tableName);表名类名一致
|
||||
private DefaultBussniessImpl bizDao;
|
||||
|
||||
/**
|
||||
* 查询合同
|
||||
*/
|
||||
public String findAllContract(HttpServletRequest request){
|
||||
Contract contract = new Contract();
|
||||
contract.setTenancyId(super.getTenancyId(request));
|
||||
return contractDao.findAll(contract);
|
||||
}
|
||||
/**
|
||||
* 保存合同(附件上传在webBuilder中实现)
|
||||
* ScriptObjectMirror对象包含了所有的request和session中的属性值,通过serverScript中传入app.get()参数获得
|
||||
* so.get("id")等同于request.getParameter("id")
|
||||
* 不建议使用该参数,将来如果脱离webBuilder,后台java部分request可复用。
|
||||
* 但使用Wb.upload方法时request对象取不到数据,此时需要用到ScriptObjectMirror对象
|
||||
*/
|
||||
public String saveContract(HttpServletRequest request, ScriptObjectMirror so){
|
||||
//Contract contract = new ParamUtil<Contract>().packPOJO(super.getRequestMap(request), Contract.class);
|
||||
Contract contract = new ParamUtil<Contract>().packPOJO(super.getScriptMap(so), Contract.class);
|
||||
contract.setId(UUIDUtil.getUUID());
|
||||
contract.setConfirmStatus(0);
|
||||
contract.setIsDefault(0);
|
||||
contract.setCalcFlag(1);
|
||||
contract.setDelFlag(0);
|
||||
if (contract.getExpiredDate() != null){
|
||||
contract.setExpiredDate(TimeUtil.getTimestamp(TimeUtil.getDate(contract.getExpiredDate()) + " 23:59:59"));
|
||||
}
|
||||
super.setSaveUser(request, contract);
|
||||
int num = contractDao.save(contract);
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_CONTRACT");
|
||||
}
|
||||
ContractVO vo = new ContractVO();
|
||||
BeanUtils.copyProperties(contract, vo);
|
||||
vo.setDateFormat(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
|
||||
return JSON.toJSONString(vo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改合同
|
||||
*/
|
||||
public String updateContract(HttpServletRequest request, ScriptObjectMirror so){
|
||||
Contract contract = new ParamUtil<Contract>().packPOJO(super.getScriptMap(so), Contract.class);
|
||||
if (contract.getExpiredDate() != null){
|
||||
contract.setExpiredDate(TimeUtil.getTimestamp(TimeUtil.getDate(contract.getExpiredDate()) + " 23:59:59"));
|
||||
}
|
||||
super.setUpdateUser(request, contract);
|
||||
int num = contractDao.update(contract, super.getRequestParam(request));
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_CONTRACT");
|
||||
}
|
||||
ContractVO vo = new ContractVO();
|
||||
BeanUtils.copyProperties(contract, vo);
|
||||
vo.setDateFormat(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
|
||||
return JSON.toJSONString(vo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除合同
|
||||
*/
|
||||
public int deleteContract(HttpServletRequest request, String id){
|
||||
Contract contract = new Contract();
|
||||
contract.setId(id);
|
||||
contract.setDelFlag(1);
|
||||
String[] updateCol = {"DEL_FLAG"};
|
||||
int num = contractDao.update(contract,updateCol);//删除合同,更新标识
|
||||
contractDao.deleteContractItem(id);//删除合同费目,更新标识
|
||||
tariffDao.deleteTariff(id);//删除费率,更新标识
|
||||
tariffDao.deleteRitemsByContract(id);//删除费率子表,更新标识
|
||||
tariffDao.deleteStepByContract(id);//删除费率阶梯,更新标识
|
||||
|
||||
ContractItem contractItem = new ContractItem();
|
||||
contractItem.setContractId(id);
|
||||
contractItem.setDelFlag(0);
|
||||
List<ContractItem> ciLst = contractDao.findByContract(contractItem);//查询合同费目列表
|
||||
//复制合同费率
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setContractId(id);
|
||||
List<Tariff> tariffLst = tariffDao.findByContract(tariff);
|
||||
String ids = "";
|
||||
for(int j = 0;j<tariffLst.size();j++){
|
||||
ids = ids + tariffLst.get(j).getId() +',';//费率id集合 逗号分隔
|
||||
}
|
||||
for(int i=0;i<ciLst.size();i++){//循环费目
|
||||
handleLog(3, ciLst.get(i).getItemId(),id, ids,tariffLst,getSysUserName(request));
|
||||
}
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_CONTRACT");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 合同号查询费类
|
||||
*/
|
||||
public String queryCateByContract(HttpServletRequest request){
|
||||
ContractCategory contractCategory = new ParamUtil<ContractCategory>().packPOJO(super.getRequestMap(request), ContractCategory.class);
|
||||
contractCategory.setTenancyId(super.getTenancyId(request));
|
||||
return contractDao.queryCateByContract(contractCategory);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存合同费类
|
||||
*/
|
||||
@Transactional
|
||||
public void saveContractCategory(HttpServletRequest request){
|
||||
String id = request.getParameter("ID");//合同号
|
||||
String ids = request.getParameter("ids");//费类号
|
||||
StringBuilder newIds = new StringBuilder();//新增id
|
||||
StringBuilder oldIds = new StringBuilder();//原始id
|
||||
//组织新增ids
|
||||
JSONArray ja = JSONArray.parseArray(ids);
|
||||
for(Object obj : ja.toArray()){
|
||||
newIds.append(obj.toString()).append(",");
|
||||
}
|
||||
//组织原始ids
|
||||
ContractCategory vo = new ContractCategory();
|
||||
vo.setTenancyId(super.getTenancyId(request));
|
||||
vo.setContractId(id);
|
||||
List<ContractCategory> oldLst = contractDao.findByContract(vo);
|
||||
for(ContractCategory old : oldLst){
|
||||
oldIds.append(old.getCategoryId()).append(",");
|
||||
}
|
||||
StrUtil.removeDu(oldIds, newIds);//old删除,new新增
|
||||
|
||||
String saveIds = StrUtil.subRightString(newIds.toString(), ",");
|
||||
BaseCategory cate = new BaseCategory();
|
||||
cate.setTenancyId(super.getTenancyId(request));
|
||||
List<BaseCategory> cateLst = tariffDao.findByInIds(saveIds.replace(",", "','"), cate);
|
||||
List<ContractCategory> saveLst = new ArrayList<ContractCategory>();
|
||||
for(BaseCategory cateEny : cateLst){
|
||||
ContractCategory saveCC = new ContractCategory();
|
||||
saveCC.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, saveCC);
|
||||
saveCC.setContractId(id);
|
||||
saveCC.setCategoryId(cateEny.getId());
|
||||
saveCC.setIsAll(cateEny.getIsAll());
|
||||
saveCC.setBizScope(cateEny.getBizScope());
|
||||
saveCC.setByagent(cateEny.getByagent());
|
||||
saveCC.setEffectived(cateEny.getEffectived());
|
||||
saveLst.add(saveCC);
|
||||
}
|
||||
|
||||
contractDao.saveContCate(saveLst);
|
||||
if("".equals(oldIds.toString())){
|
||||
return;
|
||||
}
|
||||
List<ContractCategory> delLst = new ArrayList<>();
|
||||
String[] delIds = oldIds.toString().split(",");
|
||||
for(String delId : delIds){
|
||||
ContractCategory delCC = new ContractCategory();
|
||||
delCC.setTenancyId(super.getTenancyId(request));
|
||||
delCC.setCategoryId(delId);
|
||||
delCC.setContractId(id);
|
||||
delLst.add(delCC);
|
||||
}
|
||||
contractDao.delContCate(delLst, "TENANCY_ID","CATEGORY_ID","CONTRACT_ID");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 合同号+费类 = 合同费目
|
||||
*/
|
||||
public String queryItemByCate(HttpServletRequest request){
|
||||
ContractItem item = new ParamUtil<ContractItem>().packPOJO(super.getRequestMap(request), ContractItem.class);
|
||||
item.setTenancyId(super.getTenancyId(request));
|
||||
return contractDao.queryItemByCate(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存合同费目(失效)
|
||||
*/
|
||||
@Deprecated
|
||||
@Transactional
|
||||
public void saveContractItem(HttpServletRequest request){
|
||||
String contractId = request.getParameter("CONTRACT_ID");//合同号
|
||||
String categoryId = request.getParameter("CATEGORY_ID");//费类号
|
||||
String ids = request.getParameter("ids");//费目号
|
||||
StringBuilder newIds = new StringBuilder();//新增id
|
||||
StringBuilder oldIds = new StringBuilder();//原始id
|
||||
//组织新增ids
|
||||
JSONArray ja = JSONArray.parseArray(ids);
|
||||
for(Object obj : ja.toArray()){
|
||||
newIds.append(obj.toString()).append(",");
|
||||
}
|
||||
//组织原始ids
|
||||
ContractItem vo = new ContractItem();
|
||||
vo.setTenancyId(super.getTenancyId(request));
|
||||
vo.setContractId(contractId);
|
||||
vo.setCategoryId(categoryId);
|
||||
List<ContractItem> oldLst = contractDao.findByContract(vo);
|
||||
for(ContractItem old : oldLst){
|
||||
oldIds.append(old.getItemId()).append(",");
|
||||
}
|
||||
StrUtil.removeDu(oldIds, newIds);//old删除,new新增
|
||||
|
||||
String saveIds = StrUtil.subRightString(newIds.toString(), ",").replace(",", "','");
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setTenancyId(super.getTenancyId(request));
|
||||
//增加合同费目
|
||||
List<BaseChargingItem> cateLst = tariffDao.findByInIds(saveIds, item);
|
||||
List<ContractItem> saveLst = new ArrayList<>();
|
||||
for(BaseChargingItem cateEny : cateLst){
|
||||
ContractItem saveCI = new ContractItem();
|
||||
BeanUtils.copyProperties(cateEny, saveCI);
|
||||
saveCI.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, saveCI);
|
||||
saveCI.setContractId(contractId);
|
||||
saveCI.setCategoryId(categoryId);
|
||||
saveCI.setItemId(cateEny.getId());
|
||||
saveLst.add(saveCI);
|
||||
}
|
||||
contractDao.saveContItem(saveLst);
|
||||
|
||||
|
||||
//删除合同费目
|
||||
if("".equals(oldIds.toString())){
|
||||
return;
|
||||
}
|
||||
List<ContractItem> delLst = new ArrayList<ContractItem>();
|
||||
String[] delIds = oldIds.toString().split(",");
|
||||
for(String delId : delIds){
|
||||
ContractItem delCI = new ContractItem();
|
||||
delCI.setTenancyId(super.getTenancyId(request));
|
||||
delCI.setCategoryId(categoryId);
|
||||
delCI.setContractId(contractId);
|
||||
delCI.setItemId(delId);
|
||||
delLst.add(delCI);
|
||||
}
|
||||
contractDao.delContItem(delLst, "TENANCY_ID","CATEGORY_ID","CONTRACT_ID","ITEM_ID");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加合同费目
|
||||
*/
|
||||
@Transactional
|
||||
public void addContractItem(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request){
|
||||
String ids = json.getString("ids");
|
||||
String contractId = json.getString("CONTRACT_ID");//合同号
|
||||
List<BaseChargingItem> charges = feeDao.findInIds(BaseChargingItem.class, ids, "ID");
|
||||
List<ContractItem> items = new ArrayList<>();
|
||||
for (BaseChargingItem charge : charges){
|
||||
ContractItem item = new ContractItem();
|
||||
BeanUtils.copyProperties(charge, item);
|
||||
item.setId(UUIDUtil.getUUID());
|
||||
item.setContractId(contractId);
|
||||
item.setItemId(charge.getId());
|
||||
item.setLifeStatus(1);
|
||||
super.setSaveUser(request, item);
|
||||
items.add(item);
|
||||
}
|
||||
feeDao.saveAll(items);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除合同费目
|
||||
*/
|
||||
@Transactional
|
||||
public void delContractItem(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request){
|
||||
String[] ids = StrUtil.split(json.getString("ids"), ",");
|
||||
List<ContractItem> items = new ArrayList<>();
|
||||
for (String id : ids){
|
||||
ContractItem item = new ContractItem();
|
||||
item.setId(id);
|
||||
items.add(item);
|
||||
}
|
||||
feeDao.deleteAll(items, "ID");
|
||||
|
||||
/*
|
||||
List<ContractItem> items = feeDao.findInIds(ContractItem.class, json.getString("ids"), "ID");
|
||||
SqlUtil sqlUtil = new SqlUtil();
|
||||
String itemIds = sqlUtil.getAddInIds(items, "id");
|
||||
List<ContractItemRule> itemRules = new ArrayList<>();
|
||||
for (ContractItem item : items){
|
||||
ContractItemRule rule = new ContractItemRule();
|
||||
BeanUtils.copyProperties(item, rule);
|
||||
itemRules.add(rule);
|
||||
}
|
||||
List<ContractItemRuleCondition> conditions = new ArrayList<>();
|
||||
for (ContractItem item : items){
|
||||
ContractItemRuleCondition condition = new ContractItemRuleCondition();
|
||||
BeanUtils.copyProperties(item, condition);
|
||||
conditions.add(condition);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 合同号+费目 = 合同费率
|
||||
*/
|
||||
public String findTariffByCategory(HttpServletRequest request){
|
||||
Tariff tariff = new ParamUtil<Tariff>().packPOJO(super.getRequestMap(request), Tariff.class);
|
||||
tariff.setTenancyId(super.getTenancyId(request));
|
||||
return tariffDao.findTariffByCategory(tariff);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合同复制
|
||||
*/
|
||||
@Transactional
|
||||
public String copyContract(HttpServletRequest request, ScriptObjectMirror so){
|
||||
// String copyId = request.getParameter("COPY_ID");
|
||||
String copyId = String.valueOf(so.get("COPY_ID"));
|
||||
//新建合同
|
||||
Contract contract = new ParamUtil<Contract>().packPOJO(super.getScriptMap(so), Contract.class);
|
||||
contract.setId(UUIDUtil.getUUID());
|
||||
contract.setDelFlag(0);
|
||||
super.setSaveUser(request, contract);
|
||||
|
||||
//复制合同费类
|
||||
// ContractCategory contractCategory = new ContractCategory();
|
||||
// contractCategory.setContractId(copyId);
|
||||
// contractCategory.setTenancyId(super.getTenancyId(request));
|
||||
// List<ContractCategory> ccLst = contractDao.findByContract(contractCategory);
|
||||
// for(ContractCategory contCate : ccLst){
|
||||
// contCate.setId(UUIDUtil.getUUID());
|
||||
// contCate.setContractId(contract.getId());
|
||||
// super.setSaveUser(request, contCate);
|
||||
// }
|
||||
|
||||
//复制合同费目
|
||||
ContractItem contractItem = new ContractItem();
|
||||
contractItem.setContractId(copyId);
|
||||
contractItem.setDelFlag(0);
|
||||
//contractItem.setTenancyId(super.getTenancyId(request));
|
||||
List<ContractItem> ciLst = contractDao.findByContract(contractItem);
|
||||
for(ContractItem contItem : ciLst){
|
||||
contItem.setId(UUIDUtil.getUUID());
|
||||
contItem.setContractId(contract.getId());
|
||||
super.setSaveUser(request, contItem);
|
||||
}
|
||||
|
||||
//复制合同费率
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setContractId(copyId);
|
||||
//tariff.setTenancyId(super.getTenancyId(request));
|
||||
List<Tariff> tariffLst = tariffDao.findByContract(tariff);
|
||||
//复制费率条件
|
||||
List<TariffRitem> ritems = tariffDao.findRitemsByContract(tariff);
|
||||
//复制阶梯费率
|
||||
List<TariffMultistep> steps = tariffDao.findStepByContract(tariff);
|
||||
|
||||
for(Tariff tariffCpy : tariffLst){
|
||||
String tariffId = UUIDUtil.getUUID();
|
||||
for (TariffRitem ritem : ritems){
|
||||
if (tariffCpy.getId().equals(ritem.getRuleId())){
|
||||
ritem.setRuleId(tariffId);
|
||||
ritem.setId(UUIDUtil.getUUID());
|
||||
}
|
||||
}
|
||||
for (TariffMultistep step : steps){
|
||||
if (tariffCpy.getId().equals(step.getTariffId())){
|
||||
step.setTariffId(tariffId);
|
||||
step.setId(UUIDUtil.getUUID());
|
||||
}
|
||||
}
|
||||
tariffCpy.setId(tariffId);
|
||||
tariffCpy.setContractId(contract.getId());
|
||||
super.setSaveUser(request, tariffCpy);
|
||||
}
|
||||
|
||||
//复制合同计费免费规则
|
||||
// ContractItemRule itemRule = new ContractItemRule();
|
||||
// itemRule.setContractId(copyId);
|
||||
// itemRule.setTenancyId(super.getTenancyId(request));
|
||||
// List<ContractItemRule> ruleLst = contractDao.findByContract(itemRule);
|
||||
// List<ContractItemRuleCondition> conditionLst = contractDao.findConditionByContract(itemRule);
|
||||
// changeId(ruleLst, conditionLst, contract.getId());
|
||||
|
||||
int num = contractDao.save(contract);
|
||||
//contractDao.saveContCate(ccLst);
|
||||
contractDao.saveContItem(ciLst);
|
||||
tariffDao.saveTariff(tariffLst);
|
||||
tariffDao.saveRitem(ritems);
|
||||
tariffDao.saveStep(steps);
|
||||
// contractDao.saveContItemRule(ruleLst);
|
||||
//contractDao.saveContRuleCondition(conditionLst);
|
||||
for(ContractItem contItem : ciLst){
|
||||
Tariff tariffnew = new Tariff();
|
||||
tariffnew.setContractId(contract.getId());
|
||||
tariffnew.setChargingId(contItem.getItemId());
|
||||
tariffnew.setDelFlag(0);
|
||||
List<Tariff> tariffLstNew = tariffDao.findByItemIdAndContractId(tariffnew);//根据费目id及合同id查询费率
|
||||
String ids = "";
|
||||
for(int j = 0;j<tariffLstNew.size();j++){
|
||||
ids = ids + tariffLstNew.get(j).getId() +',';//费率id集合 逗号分隔
|
||||
}
|
||||
handleLog(1, contItem.getItemId(),contract.getId(), ids,tariffLstNew,getSysUserName(request));//添加删除费率日志
|
||||
}
|
||||
|
||||
//刷新合同缓存
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_CONTRACT");
|
||||
}
|
||||
return JSON.toJSONString(contract);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 查询合同费类
|
||||
*/
|
||||
public String queryContractByCategory(HttpServletRequest request, String categoryId){
|
||||
ContractCategory contractCategory = new ContractCategory();
|
||||
contractCategory.setTenancyId(super.getTenancyId(request));
|
||||
contractCategory.setCategoryId(categoryId);
|
||||
return contractDao.queryContractByCategory(contractCategory);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合同审核
|
||||
*/
|
||||
public int verifyContract(HttpServletRequest request){
|
||||
Contract contract = new Contract();
|
||||
contract.setId(request.getParameter("ID"));
|
||||
super.setUpdateUser(request, contract);
|
||||
contract.setConfirmStatus(2);
|
||||
contract.setConfirmUser(contract.getUpdatedBy());
|
||||
contract.setConfirmDate(new Date());
|
||||
return contractDao.update(contract, null);
|
||||
}
|
||||
|
||||
public int updateContCate(HttpServletRequest request) {
|
||||
ContractCategory entity = new ParamUtil<ContractCategory>().packPOJO(super.getRequestMap(request), ContractCategory.class);
|
||||
super.setUpdateUser(request, entity);
|
||||
return contractDao.update(entity, super.getRequestParam(request));
|
||||
}
|
||||
|
||||
public int updateContItem(HttpServletRequest request) {
|
||||
ContractItem entity = new ParamUtil<ContractItem>().packPOJO(super.getRequestMap(request), ContractItem.class);
|
||||
super.setUpdateUser(request, entity);
|
||||
return contractDao.update(entity, super.getRequestParam(request));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 保存合同选择的费目
|
||||
*/
|
||||
@Transactional
|
||||
public void saveContractSelectItem(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request){
|
||||
String[] delIds = StrUtil.split(json.getString("delIds"), ",");
|
||||
String[] delItemIds = StrUtil.split(json.getString("delItemIds"), ",");
|
||||
String addIds = json.getString("addIds");
|
||||
String contractId = json.getString("contractId");//合同号
|
||||
//处理新增start
|
||||
List<BaseChargingItem> charges = feeDao.findInIds(BaseChargingItem.class, addIds, "ID");//查询基础费目其他信息
|
||||
List<ContractItem> items = new ArrayList<>();
|
||||
for (BaseChargingItem charge : charges){//组织合同费目数据
|
||||
ContractItem item = new ContractItem();
|
||||
BeanUtils.copyProperties(charge, item);
|
||||
item.setId(UUIDUtil.getUUID());
|
||||
item.setContractId(contractId);
|
||||
item.setItemId(charge.getId());
|
||||
item.setLifeStatus(1);
|
||||
item.setDelFlag(0);
|
||||
super.setSaveUser(request, item);
|
||||
items.add(item);
|
||||
}
|
||||
feeDao.saveAll(items);
|
||||
//处理新增end
|
||||
//处理删除start
|
||||
List<ContractItem> itemsDel = new ArrayList<>();
|
||||
for (String id : delIds){
|
||||
ContractItem item = new ContractItem();
|
||||
item.setId(id);
|
||||
item.setDelFlag(1);//删除标识
|
||||
itemsDel.add(item);
|
||||
}
|
||||
feeDao.updateAll(itemsDel, "ID");
|
||||
for (String itemId : delItemIds){
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setContractId(contractId);
|
||||
tariff.setChargingId(itemId);
|
||||
List<Tariff> tariffLst = tariffDao.findByItemIdAndContractId(tariff);//根据费目id及合同id查询费率
|
||||
String ids = "";
|
||||
for(int j = 0;j<tariffLst.size();j++){
|
||||
ids = ids + tariffLst.get(j).getId() +',';//费率id集合 逗号分隔
|
||||
}
|
||||
handleLog(3, itemId,contractId, ids,tariffLst,getSysUserName(request));//添加删除费率日志
|
||||
ContractItem contractItem = new ContractItem();
|
||||
contractItem.setContractId(contractId);
|
||||
contractItem.setItemId(itemId);
|
||||
tariffDao.deleteTariffByContractItem(contractItem);//删除费率,更新标识
|
||||
tariffDao.deleteRitemsByContractItem(contractItem);//删除费率子表,更新标识
|
||||
tariffDao.deleteStepByContractItem(contractItem);//删除费率阶梯,更新标识
|
||||
}
|
||||
//处理删除end
|
||||
}
|
||||
/**
|
||||
* 保存合同选择的客户
|
||||
*/
|
||||
@Transactional
|
||||
public void saveContractSelectCustom(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request){
|
||||
String[] newIds = StrUtil.split(json.getString("newIds"), ",");
|
||||
String contractId = json.getString("contractId");//合同号
|
||||
List<ContractRelation> items = new ArrayList<>();
|
||||
for (String customerId : newIds){//组织合同客户数据
|
||||
ContractRelation item = new ContractRelation();
|
||||
item.setId(UUIDUtil.getUUID());
|
||||
item.setContractId(contractId);
|
||||
item.setCustomerId(customerId);
|
||||
item.setDelFlag(0);
|
||||
item.setCreatedOn(getNow());
|
||||
item.setCreatedBy(getSysUserName(request));
|
||||
items.add(item);
|
||||
}
|
||||
bizDao.saveAll(items);
|
||||
}
|
||||
/**
|
||||
* 保存合同选择的客户
|
||||
*/
|
||||
@Transactional
|
||||
public void delContractSelectCustom(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request){
|
||||
String[] delIds = StrUtil.split(json.getString("delIds"), ",");//合同客户表主键id
|
||||
//处理删除start
|
||||
List<ContractRelation> itemsDel = new ArrayList<>();
|
||||
for (String id : delIds){
|
||||
ContractRelation item = new ContractRelation();
|
||||
item.setId(id);
|
||||
item.setDelFlag(1);//删除标识
|
||||
itemsDel.add(item);
|
||||
}
|
||||
bizDao.updateAll(itemsDel, "ID");
|
||||
//处理删除end
|
||||
}
|
||||
|
||||
/**
|
||||
* 费率增删改日志
|
||||
*/
|
||||
private void handleLog(Integer status, String itemId, String contractId, String ids, List<Tariff> tariffs, String userName){
|
||||
try {
|
||||
Contract contract = new Contract();
|
||||
contract.setId(contractId);
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setId(itemId);
|
||||
ItemProperties entity = new ItemProperties();
|
||||
entity.setItemId(itemId);
|
||||
contract = (Contract) feeDao.findById(contract, Contract.class, "ID");
|
||||
item = (BaseChargingItem) feeDao.findById(item, BaseChargingItem.class, "ID");
|
||||
List<TariffRitem> ritems = feeDao.findInIds(TariffRitem.class, ids, "RULE_ID");
|
||||
List<ItemProperties> properties = feeDao.findByEqCriteria(entity, ItemProperties.class, "ITEM_ID");
|
||||
|
||||
List<TariffOperLog> logs = new ArrayList<>();
|
||||
for (Tariff tariff : tariffs){
|
||||
String note = "", rate = "";
|
||||
for (TariffRitem ritem : ritems){
|
||||
if (ritem.getDelFlag() == null || ritem.getDelFlag() == 1){
|
||||
continue;
|
||||
}
|
||||
if(ObjectUtil.equal(tariff.getId(), ritem.getRuleId())){
|
||||
if (ObjectUtil.equal(ritem.getKeyName(), "RATE")){
|
||||
rate = Convert.toStr(ritem.getCompareVal());
|
||||
}
|
||||
}
|
||||
|
||||
if (ObjectUtil.equal(tariff.getId(), ritem.getRuleId())){
|
||||
for (ItemProperties propertie : properties){
|
||||
if (ObjectUtil.equal(propertie.getPropertyCode(), ritem.getKeyName())){
|
||||
note += propertie.getPropertyName() + ritem.getOperChar() + ritem.getCompareName() + ";";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
note = "[费率:"+rate+"]" + note;
|
||||
if (status == 1){
|
||||
note = "新增-->" + note;
|
||||
}else if(status == 2){
|
||||
note = "修改<--" + note;
|
||||
}else if(status == 3){
|
||||
note = "删除<--" + note;
|
||||
}
|
||||
TariffOperLog log = new TariffOperLog();
|
||||
log.setId(UUIDUtil.getUUID());
|
||||
log.setContractName(contract.getDescription());
|
||||
log.setItemName(item.getDescription());
|
||||
log.setCreatedBy(userName);
|
||||
log.setCreatedOn(new Date());
|
||||
log.setDescription(note);
|
||||
logs.add(log);
|
||||
}
|
||||
bizDao.saveAll(logs);
|
||||
}catch (Exception ex){
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
import com.ag.base.BaseRepositoryImpl;
|
||||
import com.ag.entity.fee.ItemProperties;
|
||||
import com.ag.entity.fee.Tariff;
|
||||
import com.ag.entity.fee.TariffRitem;
|
||||
import com.ag.entity.fee.face.ReqSource;
|
||||
import com.ag.entity.fee.face.SourceProperty;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.wb.util.WebUtil;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2020/8/5.
|
||||
*/
|
||||
@Service
|
||||
public class ItemPropService {
|
||||
@Autowired
|
||||
private BaseRepositoryImpl feeDao;
|
||||
|
||||
public void delProperties(HttpServletRequest request){
|
||||
String id = request.getParameter("ID");
|
||||
ItemProperties prop = new ItemProperties();
|
||||
prop.setId(id);
|
||||
prop = (ItemProperties)feeDao.findById(prop, ItemProperties.class, "ID");
|
||||
String sql = "SELECT * FROM C_TARIFF_RITEM WHERE KEY_NAME =?\n" +
|
||||
"AND RULE_ID IN (SELECT ID FROM C_TARIFF WHERE CHARGING_ID=?)";
|
||||
List<TariffRitem> ritems = feeDao.list(sql, TariffRitem.class, prop.getPropertyCode(), prop.getItemId());
|
||||
Assert.isTrue(CollectionUtils.isEmpty(ritems), "该元素已被使用,不可移除!");
|
||||
feeDao.delete(prop, "ID");
|
||||
}
|
||||
|
||||
public void showJSONByTariff(JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
|
||||
ReqSource reqSource = new ReqSource();
|
||||
SourceProperty sourceProperty = new SourceProperty();
|
||||
reqSource.getSourceProperties().add(sourceProperty);
|
||||
String ruleId = param.getString("ruleId");
|
||||
TariffRitem entity = new TariffRitem();
|
||||
entity.setRuleId(ruleId);
|
||||
List<TariffRitem> ritems = feeDao.findByEqCriteria(entity, TariffRitem.class, "RULE_ID");
|
||||
for (TariffRitem ritem : ritems){
|
||||
if (Objects.equals("RATE", ritem.getKeyName())){
|
||||
continue;
|
||||
}
|
||||
if (Objects.equals("=", ritem.getOperChar())) {
|
||||
sourceProperty.getProperty().put(ritem.getKeyName(), ritem.getCompareVal());
|
||||
}else {
|
||||
sourceProperty.getProperty().put(ritem.getKeyName(), ritem.getOperChar()+" "+ritem.getCompareVal());
|
||||
}
|
||||
}
|
||||
Tariff tf = new Tariff();
|
||||
tf.setId(ruleId);
|
||||
Tariff tariff = (Tariff)feeDao.findById(tf, Tariff.class, "ID");
|
||||
reqSource.setContractId(tariff.getContractId());
|
||||
reqSource.setItemId(tariff.getChargingId());
|
||||
reqSource.setTenancyId(tariff.getTenancyId());
|
||||
reqSource.setOperMan(tariff.getCreatedBy());
|
||||
WebUtil.send(response, JSON.toJSONString(reqSource));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.entity.fee.ContractRelation;
|
||||
import com.ag.util.UUIDUtil;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2019/9/10.
|
||||
* 客户合同关系
|
||||
*/
|
||||
@Service
|
||||
public class RelationService extends BaseService {
|
||||
|
||||
@Autowired
|
||||
private DefaultBussniessImpl<ContractRelation> relDao;
|
||||
|
||||
@Transactional
|
||||
public void save(HttpServletRequest request){
|
||||
String tenancyId = super.getTenancyId(request);
|
||||
String customerId = request.getParameter("customerId");
|
||||
String ids = request.getParameter("ids");
|
||||
ContractRelation source = new ContractRelation();
|
||||
source.setTenancyId(tenancyId);
|
||||
source.setCustomerId(customerId);
|
||||
|
||||
List<ContractRelation> sources = relDao.findByEntity(source, ContractRelation.class);
|
||||
JSONArray ja = JSONArray.parseArray(ids);
|
||||
List<ContractRelation> lst = new ArrayList<>();
|
||||
for(Object obj : ja.toArray()){
|
||||
boolean status = false;
|
||||
for (ContractRelation exists : sources){
|
||||
if (exists.getContractId().equals(obj.toString())){
|
||||
status = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (status){
|
||||
continue;
|
||||
}
|
||||
ContractRelation relation = new ContractRelation();
|
||||
relation.setId(UUIDUtil.getUUID());
|
||||
relation.setTenancyId(tenancyId);
|
||||
relation.setContractId(obj.toString());
|
||||
relation.setCustomerId(customerId);
|
||||
relation.setCreatedBy(super.getSysUserName(request));
|
||||
relation.setCreatedOn(super.getNow());
|
||||
lst.add(relation);
|
||||
}
|
||||
relDao.saveAll(lst);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void del(HttpServletRequest request){
|
||||
String customerId = request.getParameter("customerId");
|
||||
String ids = request.getParameter("ids");//???
|
||||
JSONArray array = JSONArray.parseArray(ids);
|
||||
List<ContractRelation> lst = new ArrayList<>();
|
||||
for(Object obj : array.toArray()){
|
||||
ContractRelation relation = new ContractRelation();
|
||||
relation.setContractId(obj.toString());
|
||||
relation.setCustomerId(customerId);
|
||||
relation.setTenancyId(super.getTenancyId(request));
|
||||
lst.add(relation);
|
||||
}
|
||||
relDao.deleteAll(lst, "CONTRACT_ID","CUSTOMER_ID", "TENANCY_ID");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.base.IBaseRepository;
|
||||
import com.ag.base.IRedisService;
|
||||
import com.ag.commonFace.ITariffExtService;
|
||||
import com.ag.entity.fee.ItemProperties;
|
||||
import com.ag.entity.fee.Tariff;
|
||||
import com.ag.entity.fee.TariffRitem;
|
||||
import com.ag.entity.fee.face.IRuleCondition;
|
||||
import com.ag.entity.fee.face.ReqSource;
|
||||
import com.ag.entity.fee.vo.TariffVO;
|
||||
import com.ag.secp.platform.spring.SpringApplicationContext;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.wb.common.KvBean;
|
||||
import com.wb.util.WebUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2019/9/11.
|
||||
*/
|
||||
@Service
|
||||
public class TariffExtService extends BaseService implements ITariffExtService {
|
||||
|
||||
/*@Autowired
|
||||
private BaseRepositoryImpl feeDao;*/
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository feeDao;
|
||||
@Autowired
|
||||
private DefaultBussniessImpl bizDao;
|
||||
|
||||
/**
|
||||
* ####费率更新的扩展功能####
|
||||
* 1、按合同号和费目编号查询所有费率和费率元素
|
||||
* 2、生成所有费率的keyDescription,规则如下:
|
||||
* 费率排除RATE元素,按C_ITEM_PROPERTY的顺序的组合
|
||||
* 组合连接串&&
|
||||
* 如果运算符不是=,元素key前增加运算符
|
||||
* 3、keyDescription重复检查
|
||||
* 有相同keyDescription抛出异常回滚提示用户重复的费率
|
||||
* 4、更新费率表的keyDescription和valDescription
|
||||
*/
|
||||
public void synDescription(String contractId, String itemId, String tenancyId){
|
||||
Assert.isTrue(!StrUtil.isEmpty(contractId), "数据异常,合同号不能为空!");
|
||||
Assert.isTrue(!StrUtil.isEmpty(itemId), "数据异常,费目编号不能为空!");
|
||||
//Assert.isTrue(!StrUtil.isEmpty(tenancyId), "数据异常,租户不能为空!");
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setContractId(contractId);
|
||||
tariff.setChargingId(itemId);
|
||||
tariff.setTenancyId(tenancyId);
|
||||
tariff.setDelFlag(0);
|
||||
List<TariffVO> tariffs = feeDao.findByEntity(tariff, TariffVO.class);
|
||||
/*ItemProperties itemProperty = new ItemProperties();
|
||||
itemProperty.setTenancyId(tenancyId);
|
||||
itemProperty.setItemId(itemId);
|
||||
List<ItemProperties> properties = feeDao.findByEqCriteria(itemProperty, ItemProperties.class, "ITEM_ID");
|
||||
String tariffIds = new SqlUtil<TariffVO>().getAddInIds(tariffs, "id");
|
||||
TariffRitem ritem = new TariffRitem();
|
||||
String sql = feeDao.findByEqSql(ritem);
|
||||
sql = StrUtil.join(sql, " where RULE_ID in (", tariffIds, ") and DEL_FLAG=0");
|
||||
List<TariffRitem> ritems = feeDao.list(sql, TariffRitem.class);*/
|
||||
//mergeTariffVO(tariffs, ritems);//费率+费率条件=组合对象
|
||||
//generateDescription(tariffs, properties);
|
||||
checkDuplicate(tariffs);
|
||||
//saveDescription(tariffs);
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void saveDescription(List<TariffVO> tariffs) {
|
||||
List<Tariff> tariffsUpd = new ArrayList<>();
|
||||
for (TariffVO tariffVO : tariffs){
|
||||
if (StrUtil.isEmpty(tariffVO.getKeyDescription())) {
|
||||
continue;
|
||||
}
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setId(tariffVO.getId());
|
||||
|
||||
tariff.setKeyDescription(tariffVO.getKeyDescription());
|
||||
tariff.setValDescription(tariffVO.getValDescription());
|
||||
tariffsUpd.add(tariff);
|
||||
}
|
||||
feeDao.updateAll(tariffsUpd, "ID");
|
||||
}
|
||||
|
||||
private void checkDuplicate(List<TariffVO> tariffs) {
|
||||
Set<String> set = new HashSet<>();
|
||||
for(TariffVO tariffVO : tariffs){
|
||||
String compareStr = tariffVO.getKeyDescription() +","+ tariffVO.getSort();
|
||||
if (set.contains(compareStr)){
|
||||
throw new RuntimeException("检查发现重复费率,请修改【"+tariffVO.getValDescription()+"】");
|
||||
}
|
||||
set.add(compareStr);
|
||||
}
|
||||
}
|
||||
|
||||
private void generateDescription(List<TariffVO> tariffs, List<ItemProperties> properties) {
|
||||
if (CollectionUtils.isEmpty(properties)){
|
||||
return;
|
||||
}
|
||||
properties.sort((a, b) -> a.getDispOrder() - b.getDispOrder());
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
for (TariffVO vo : tariffs){
|
||||
String keyDescription = "", valDescription = "", sortStr = "";
|
||||
for (ItemProperties property : properties){
|
||||
//过滤掉非查找 要素
|
||||
if (property.getIsShowOperator() == 1){
|
||||
continue;
|
||||
}
|
||||
for (IRuleCondition ritem : vo.getRitemList()){
|
||||
if (ritem.getKeyName().equals(property.getPropertyCode())){
|
||||
sortStr = StrUtil.join(sortStr, Convert.toStr(property.getDispOrder()));
|
||||
if ("=".equals(ritem.getOperChar())) {
|
||||
keyDescription = StrUtil.join(keyDescription, "&&", ritem.getCompareVal());
|
||||
String val = service.getTargetName(ritem.getKeyName(), ritem.getCompareVal());
|
||||
if (!StrUtil.isEmpty(val)) {
|
||||
valDescription = StrUtil.join(valDescription, "&&", val);
|
||||
}
|
||||
} else {
|
||||
keyDescription = StrUtil.join(keyDescription, "&&", ritem.getOperChar(), " ", ritem.getCompareVal());
|
||||
String val = service.getTargetName(ritem.getKeyName(), ritem.getCompareVal());
|
||||
if (!StrUtil.isEmpty(val)) {
|
||||
valDescription = StrUtil.join(valDescription, "&&", ritem.getOperChar(), " ", val);
|
||||
}
|
||||
//valDescription = StrUtil.join(valDescription, "&&", ritem.getOperChar(), " ", KVBuffer.getNameByCode(ritem.getKeyName(), ritem.getCompareVal()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (StrUtil.isEmpty(keyDescription)){
|
||||
continue;
|
||||
}
|
||||
vo.setKeyDescription(keyDescription.substring(2));
|
||||
vo.setValDescription(valDescription.substring(2));
|
||||
vo.setSort(Convert.toInt(sortStr));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void mergeTariffVO(List<TariffVO> tariffs, List<TariffRitem> ritems) {
|
||||
for (TariffVO vo : tariffs){
|
||||
List<TariffRitem> ritemList = new ArrayList<>();
|
||||
vo.setRitemList(ritemList);
|
||||
for (TariffRitem ritem : ritems){
|
||||
if ("RATE".equals(ritem.getKeyName())){
|
||||
continue;
|
||||
}
|
||||
if (vo.getId().equals(ritem.getRuleId())){
|
||||
ritemList.add(ritem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Map<String, String> getSpecialOperChar(String tariffId) {
|
||||
TariffRitem ritemQuery = new TariffRitem();
|
||||
ritemQuery.setRuleId(tariffId);
|
||||
String sql = feeDao.getSelectByEntity(ritemQuery, false);
|
||||
sql = StrUtil.join(sql, " and OPER_CHAR<>'=' and DEL_FLAG=0");
|
||||
List<TariffRitem> ritems = feeDao.list(sql, TariffRitem.class);
|
||||
Map<String, String> operMap = new HashMap<>();
|
||||
if (!CollectionUtils.isEmpty(ritems)){
|
||||
for (TariffRitem ritem : ritems){
|
||||
operMap.put(ritem.getKeyName(), ritem.getOperChar());
|
||||
}
|
||||
}
|
||||
return operMap;
|
||||
}
|
||||
|
||||
public void getItemProperties(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
|
||||
ItemProperties condition = new ItemProperties();
|
||||
condition.setItemId(param.getString("ITEM_ID"));
|
||||
List<ItemProperties> properties = feeDao.findByEqCriteria(condition, ItemProperties.class, "ITEM_ID");
|
||||
properties.sort((a, b)->a.getDispOrder() - b.getDispOrder());
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("ItemProperties", properties);
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
for (ItemProperties property : properties) {
|
||||
List<KvBean> kvBeanList = service.getAllByKey(property.getPropertyCode(), super.getTenancyId(param));
|
||||
json.put(property.getPropertyCode(), kvBeanList);
|
||||
}
|
||||
WebUtil.send(response, json);
|
||||
}
|
||||
|
||||
public void generateDescription(Tariff tariff, List<TariffRitem> ritems, List<ItemProperties> properties) {
|
||||
StringBuilder keyDesc = new StringBuilder();
|
||||
StringBuilder valDesc = new StringBuilder();
|
||||
String sortStr = "";
|
||||
//排序号
|
||||
for (ItemProperties property : properties) {
|
||||
//目标元素
|
||||
for (TariffRitem ritem : ritems) {
|
||||
if (ObjectUtil.equal(property.getPropertyCode(), ritem.getKeyName())) {
|
||||
//存在查找要素
|
||||
if (!StrUtil.isEmpty(ritem.getCompareName())) {
|
||||
sortStr = StrUtil.join(sortStr, Convert.toStr(property.getDispOrder()));
|
||||
//运算符=
|
||||
if (ObjectUtil.equal(ritem.getOperChar(), "=")){
|
||||
keyDesc.append("&&").append(ritem.getCompareVal());
|
||||
valDesc.append("&&").append(ritem.getCompareName());
|
||||
}else{
|
||||
keyDesc.append("&&").append(ritem.getOperChar()).append(" ").append(ritem.getCompareVal());
|
||||
valDesc.append("&&").append(ritem.getOperChar()).append(" ").append(ritem.getCompareName());
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//Assert.isTrue(!StrUtil.isEmpty(keyDesc), "费率维护异常,没找到查找要素");
|
||||
if (!StrUtil.isEmpty(keyDesc.toString())){
|
||||
tariff.setKeyDescription(keyDesc.substring(2));
|
||||
tariff.setValDescription(valDesc.substring(2));
|
||||
tariff.setSort(Convert.toInt(sortStr));
|
||||
}
|
||||
if(tariff.getEffectiveDate() != null && tariff.getExpiredDate() != null){
|
||||
tariff.setKeyDescription(tariff.getKeyDescription() + "(" +
|
||||
DateUtil.format(tariff.getEffectiveDate(), "yyyyMMdd") + "-" +
|
||||
DateUtil.format(tariff.getExpiredDate(), "yyyyMMdd") + ")");
|
||||
}
|
||||
}
|
||||
|
||||
/*public void checkRate(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
|
||||
ReqSource reqSource = JSON.parseObject(param.getString("reqSource"), ReqSource.class);
|
||||
String tariffId = param.getString("tariffId");
|
||||
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
import com.ag.base.BaseService;
|
||||
import com.ag.base.IBaseRepository;
|
||||
import com.ag.base.IRedisService;
|
||||
import com.ag.base.ParamUtil;
|
||||
import com.ag.entity.fee.*;
|
||||
import com.ag.rate.tariff.dao.TariffDao;
|
||||
import com.ag.secp.platform.spring.SpringApplicationContext;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.ag.util.UUIDUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import jdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/4/11 0011.
|
||||
*/
|
||||
@Service
|
||||
public class TariffService extends BaseService {
|
||||
@Autowired
|
||||
private TariffDao tariffDao;
|
||||
@Autowired
|
||||
private TariffExtService extService;
|
||||
@Resource(name="baseRepositoryImpl")
|
||||
private IBaseRepository feeDao;
|
||||
|
||||
/**
|
||||
* 查询费类
|
||||
*/
|
||||
public String findAllCate(HttpServletRequest request){
|
||||
BaseCategory category = new BaseCategory();
|
||||
category.setTenancyId(super.getTenancyId(request));
|
||||
return tariffDao.findAll(category);
|
||||
}
|
||||
/**
|
||||
* 保存费类
|
||||
*/
|
||||
@Transactional
|
||||
public int saveCate(HttpServletRequest request, ScriptObjectMirror so){
|
||||
/*for(Map.Entry<String, Object> en: so.entrySet()){
|
||||
System.out.println(en.getKey()+" : "+en.getValue());
|
||||
}*/
|
||||
BaseCategory category = new ParamUtil<BaseCategory>().packPOJO(super.getRequestMap(request), BaseCategory.class);
|
||||
category.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, category);
|
||||
int num = tariffDao.save(category);
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CATEGORY");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* 修改费类
|
||||
*/
|
||||
@Transactional
|
||||
public int updateCate(HttpServletRequest request){
|
||||
BaseCategory category = new ParamUtil<BaseCategory>().packPOJO(super.getRequestMap(request), BaseCategory.class);
|
||||
super.setUpdateUser(request, category);
|
||||
int num = tariffDao.update(category, super.getRequestParam(request));
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CATEGORY");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* 删除费类
|
||||
*/
|
||||
@Transactional
|
||||
public int deleteCate(HttpServletRequest request, String id){
|
||||
int ct = tariffDao.isUseItemByCate(id);
|
||||
if(ct > 0){
|
||||
callExcetion("该费类在收费项目中已使用!");
|
||||
}
|
||||
BaseCategory category = new BaseCategory();
|
||||
category.setId(id);
|
||||
int num = tariffDao.delete(category);
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CATEGORY");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 查询费目
|
||||
*/
|
||||
public String findAllItem(HttpServletRequest request){
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setCategoryId(request.getParameter("categoryId"));
|
||||
item.setTenancyId(super.getTenancyId(request));
|
||||
return tariffDao.findAll(item);
|
||||
}
|
||||
|
||||
public String convertDictByFeeItem(HttpServletRequest request){
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setTenancyId(super.getTenancyId(request));
|
||||
String sql = tariffDao.findAll(item);
|
||||
return sql;
|
||||
}
|
||||
|
||||
public List<BaseChargingItem> findBaseItemLst(HttpServletRequest request){
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setTenancyId(super.getTenancyId(request));
|
||||
return tariffDao.findBaseItemLst(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增费目
|
||||
*/
|
||||
@Transactional
|
||||
public int saveItem(HttpServletRequest request){
|
||||
BaseChargingItem item = new ParamUtil<BaseChargingItem>().packPOJO(super.getRequestMap(request), BaseChargingItem.class);
|
||||
/*Assert.isTrue(StrUtil.isNotEmpty(item.getItemCode()), "费目代码不能为空!");
|
||||
int count = feeDao.findByCount(item, "ITEM_CODE");
|
||||
Assert.isTrue(count == 0, "费目代码["+item.getItemCode()+"]已存在,请更改");*/
|
||||
item.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, item);
|
||||
item.setDelFlag(0);
|
||||
int num = tariffDao.save(item);
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CHARGING_ITEM");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* 修改费目
|
||||
*/
|
||||
@Transactional
|
||||
public int updateItem(HttpServletRequest request){
|
||||
BaseChargingItem item = new ParamUtil<BaseChargingItem>().packPOJO(super.getRequestMap(request), BaseChargingItem.class);
|
||||
Assert.isTrue(StrUtil.isNotEmpty(item.getCategoryId()), "费类不能为空!");
|
||||
/*Assert.isTrue(StrUtil.isNotEmpty(item.getItemCode()), "费目代码不能为空!");
|
||||
String checkCodeSql = feeDao.findByEqSql(item,"ITEM_CODE")+" and id<>'"+item.getId()+"'";
|
||||
int count = feeDao.count("select count(0) from ("+checkCodeSql+")");
|
||||
Assert.isTrue(count == 0, "费目代码["+item.getItemCode()+"]已存在,请更改");*/
|
||||
|
||||
//同步修改所有合同费目
|
||||
ContractItem citem = new ContractItem();
|
||||
citem.setItemId(item.getId());
|
||||
citem.setCategoryId(item.getCategoryId());
|
||||
citem.setTenancyId(item.getTenancyId());
|
||||
tariffDao.updateCategory(citem);
|
||||
super.setUpdateUser(request, item);
|
||||
int num = tariffDao.update(item, super.getRequestParam(request));
|
||||
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CHARGING_ITEM");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* 删除费目
|
||||
*/
|
||||
@Transactional
|
||||
public int deleteItem(HttpServletRequest request, String id){
|
||||
ContractItem citem = new ContractItem();
|
||||
citem.setItemId(id);
|
||||
int count = feeDao.findByCount(citem, "ITEM_ID");
|
||||
Assert.isTrue(count == 0, "费目已被使用,不能删除");
|
||||
|
||||
BaseChargingItem item = new BaseChargingItem();
|
||||
item.setId(id);
|
||||
int num = tariffDao.delete(item);
|
||||
if(num > 0 ){
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
service.refreshByDictName("C_BASE_CHARGING_ITEM");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询费率条件
|
||||
|
||||
public String findAllRule(HttpServletRequest request){
|
||||
TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
|
||||
//rule.setTenancyId(super.getTenancyId(request));
|
||||
return tariffDao.findAll(rule);
|
||||
}*/
|
||||
|
||||
/*
|
||||
public String findRuleByItem(HttpServletRequest request, String itemId){
|
||||
TariffRule rule = new TariffRule();
|
||||
//rule.setTenancyId(super.getTenancyId(request));
|
||||
rule.setIsShow(1);//0=不显示1=显示
|
||||
rule.setItemId(itemId);
|
||||
return tariffDao.findAll(rule);
|
||||
}*/
|
||||
|
||||
/*@Deprecated
|
||||
public int saveRule(HttpServletRequest request,ScriptObjectMirror so){
|
||||
Map<String, String> map = super.getRequestMap(request);
|
||||
printMap(map);
|
||||
// for(Map.Entry<String, Object> en: so.entrySet()){
|
||||
// System.out.println(en.getKey()+" : "+en.getValue());
|
||||
// }
|
||||
TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
|
||||
rule.setId(UUIDUtil.getUUID());
|
||||
super.setSaveUser(request, rule);
|
||||
//int num = tariffDao.save(rule);
|
||||
return 0;
|
||||
}
|
||||
@Deprecated
|
||||
public int updateRule(HttpServletRequest request){
|
||||
TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
|
||||
rule.setItemId(null);
|
||||
super.setUpdateUser(request, rule);
|
||||
return tariffDao.update(rule);
|
||||
}*/
|
||||
/**
|
||||
* 删除费率条件
|
||||
|
||||
@Transactional
|
||||
public int deleteRule(HttpServletRequest request, String id){
|
||||
TariffRule rule = new TariffRule();
|
||||
rule.setId(id);
|
||||
Integer used = tariffDao.queryUsedTariff(id, super.getTenancyId(request));
|
||||
Assert.isTrue(used == 0, "费率条件被使用,不能删除!");
|
||||
int num = tariffDao.delete(rule);
|
||||
if(num > 0){
|
||||
tariffDao.deleteItemByRuleId(id);
|
||||
}
|
||||
return num;
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 查询费率条件子表
|
||||
*/
|
||||
public String findItemByRule(String ruleId){
|
||||
TariffRitem item = new TariffRitem();
|
||||
item.setRuleId(ruleId);
|
||||
return tariffDao.findAll(item);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 合同、费类、费目树
|
||||
*/
|
||||
public String getTreeSql(HttpServletRequest request){
|
||||
String sql = null;
|
||||
String level = request.getParameter("level");
|
||||
String parentId = request.getParameter("parentId");
|
||||
String contractId = request.getParameter("contractId");
|
||||
String description = request.getParameter("hidContractDESC");
|
||||
//所有合同
|
||||
if("1".equals(level)){
|
||||
sql = StringUtils.join("select ID,DESCRIPTION||'(合同)' \"text\", -1 parent_id, 2 LEVELS, ID CONTRACT_ID from C_CONTRACT " ,
|
||||
" where CALC_FLAG=1");
|
||||
if(!StrUtil.isEmpty(super.getTenancyId(request))){
|
||||
sql = StrUtil.join(sql, " and TENANCY_ID='", super.getTenancyId(request),"'");
|
||||
}
|
||||
if (!StrUtil.isEmpty(description)){
|
||||
sql = StrUtil.join(sql, " and DESCRIPTION like '%", description, "%'");
|
||||
}
|
||||
}
|
||||
//合同下费类
|
||||
if("2".equals(level)){
|
||||
sql = StringUtils.join("select a.ID, a.DESCRIPTION||'(费类)' \"text\", b.CONTRACT_ID parent_id, 3 LEVELS, b.CONTRACT_ID CONTRACT_ID " ,
|
||||
" from C_BASE_CATEGORY a, C_CONTRACT_CATEGORY b",
|
||||
" where a.ID=b.CATEGORY_ID",
|
||||
" and b.CONTRACT_ID='", parentId,"'");
|
||||
}
|
||||
//合同费类下费目
|
||||
if("3".equals(level)){
|
||||
sql = StringUtils.join("select a.ID, a.DESCRIPTION||'(费目)' \"text\", 'axis_icon' as \"iconCls\",'true' as \"leaf\", b.CATEGORY_ID parent_id, 4 LEVELS, b.CONTRACT_ID CONTRACT_ID ",
|
||||
" from C_BASE_CHARGING_ITEM a, C_CONTRACT_ITEM b" ,
|
||||
" where a.id = b.ITEM_ID and b.CATEGORY_ID='",parentId,
|
||||
"' and b.CONTRACT_ID='", contractId, "'");
|
||||
}
|
||||
if(sql == null){
|
||||
sql = "select ID,DESCRIPTION \"text\", 0 parent_id, 0 LEVELS from C_BASE_CATEGORY where 1=2";
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
|
||||
|
||||
public String getTreeSqlForCheck(HttpServletRequest request){
|
||||
String sql = "";
|
||||
String level = request.getParameter("level");
|
||||
String contractId = request.getParameter("contractId");
|
||||
String description = request.getParameter("hidContractDESC");
|
||||
String confirmStatus = request.getParameter("confirmStatus");
|
||||
//所有合同
|
||||
if("1".equals(level)){
|
||||
sql = StringUtils.join("select ID, DESCRIPTION||'(合同)' \"text\", 2 LEVELS, ID CONTRACT_ID from C_CONTRACT cc " ,
|
||||
" where cc.del_flag=0");
|
||||
if(!StrUtil.isEmpty(confirmStatus)){
|
||||
sql = StrUtil.join(sql, " and EXISTS (SELECT 1 FROM C_TARIFF ct WHERE ct.CONFIRM_STATUS=",
|
||||
confirmStatus, " AND ct.CONTRACT_ID =cc.ID and ct.del_flag=0)");
|
||||
}
|
||||
if (!StrUtil.isEmpty(description)){
|
||||
sql = StrUtil.join(sql, " and DESCRIPTION like '%", description, "%'");
|
||||
}
|
||||
}
|
||||
|
||||
//合同费类下费目
|
||||
if("2".equals(level)){
|
||||
sql = StringUtils.join("select a.ID, a.DESCRIPTION \"text\", 'axis_icon' as \"iconCls\",'true' as \"leaf\", " ,
|
||||
" 3 LEVELS, b.CONTRACT_ID CONTRACT_ID ",
|
||||
" from C_BASE_CHARGING_ITEM a, C_CONTRACT_ITEM b" ,
|
||||
" where b.del_flag=0 and a.id = b.ITEM_ID and b.CONTRACT_ID='", contractId, "'");
|
||||
if(!StrUtil.isEmpty(confirmStatus)){
|
||||
sql = StrUtil.join(sql, " and EXISTS (SELECT 1 FROM C_TARIFF ct WHERE ct.CONFIRM_STATUS=",
|
||||
confirmStatus, " and ct.CONTRACT_ID = b.CONTRACT_ID and ct.CHARGING_ID = a.ID and ct.del_flag=0)");
|
||||
}
|
||||
}
|
||||
if(StrUtil.isEmpty(sql)){
|
||||
sql = "select ID,DESCRIPTION \"text\", 0 parent_id, 0 LEVELS from C_BASE_CATEGORY where 1=2";
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 新建费率
|
||||
*/
|
||||
@Transactional
|
||||
public int saveTariff(HttpServletRequest request,ScriptObjectMirror so){
|
||||
Tariff tariff = new ParamUtil<Tariff>().packPOJO(super.getRequestMap(request), Tariff.class);
|
||||
tariff.setId(UUIDUtil.getUUID());
|
||||
tariff.setChargingId(request.getParameter("hidTreeID"));
|
||||
tariff.setTenancyId(super.getTenancyId(request));
|
||||
Integer num = tariffDao.findTariffNum(tariff);
|
||||
if(num > 0){
|
||||
super.callExcetion("保存失败,费率已存在!");
|
||||
}
|
||||
super.setSaveUser(request, tariff);
|
||||
//String destroy = request.getParameter("destroy");
|
||||
//String update = request.getParameter("update");
|
||||
String create = request.getParameter("create");
|
||||
List<TariffMultistep> createLst = JSONObject.parseArray(create, TariffMultistep.class);
|
||||
//List<TariffMultistep> updateLst = JSONObject.parseArray(update,TariffMultistep.class);
|
||||
//List<TariffMultistep> destroyLst = JSONObject.parseArray(destroy,TariffMultistep.class);
|
||||
for(TariffMultistep step : createLst){
|
||||
step.setId(UUIDUtil.getUUID());
|
||||
step.setTenancyId(super.getTenancyId(request));
|
||||
step.setTariffId(tariff.getId());
|
||||
}
|
||||
tariffDao.saveStep(createLst);
|
||||
//tariffDao.updateStep(updateLst);
|
||||
//tariffDao.deleteStep(destroyLst);
|
||||
return tariffDao.save(tariff);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改费率属性及运算符
|
||||
*/
|
||||
@Transactional
|
||||
public void updateTariff(HttpServletRequest request){
|
||||
Tariff tariff = new ParamUtil<Tariff>().packPOJO(super.getRequestMap(request), Tariff.class);
|
||||
if (StrUtil.isEmpty(tariff.getId())){
|
||||
throw new RuntimeException("未选择费率!");
|
||||
}
|
||||
String contractId = request.getParameter("CONTRACT_ID");
|
||||
String itemId = request.getParameter("ITEM_ID");
|
||||
String update = request.getParameter("update");
|
||||
List<TariffRitem> updateLst = JSONObject.parseArray(update, TariffRitem.class);
|
||||
//运算符更新
|
||||
tariffDao.updateRitem(updateLst);
|
||||
//查询所有费率条件
|
||||
TariffRitem queryRitem = new TariffRitem();
|
||||
queryRitem.setRuleId(tariff.getId());
|
||||
List<TariffRitem> ritems = feeDao.findByEntity(queryRitem, TariffRitem.class);
|
||||
//查询费率要素
|
||||
ItemProperties query = new ItemProperties();
|
||||
query.setItemId(itemId);
|
||||
List<ItemProperties> properties = feeDao.findByEntity(query, ItemProperties.class);
|
||||
properties.sort((a, b)->a.getDispOrder() - b.getDispOrder());
|
||||
//生成费率key备注,val备注
|
||||
extService.generateDescription(tariff, ritems, properties);
|
||||
//更新费率主表
|
||||
tariffDao.update(tariff, super.getRequestParam(request));
|
||||
//检查重复费率
|
||||
extService.synDescription(contractId, itemId, super.getTenancyId(request));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 阶梯费率维护
|
||||
*/
|
||||
@Transactional
|
||||
public void saveMultistepRate(HttpServletRequest request){
|
||||
String create = request.getParameter("create");
|
||||
String destroy = request.getParameter("destroy");
|
||||
String update = request.getParameter("update");
|
||||
String tariffId = request.getParameter("tariffId");
|
||||
List<TariffMultistep> createLst = JSONObject.parseArray(create, TariffMultistep.class);
|
||||
List<TariffMultistep> updateLst = JSONObject.parseArray(update,TariffMultistep.class);
|
||||
List<TariffMultistep> destroyLst = JSONObject.parseArray(destroy,TariffMultistep.class);
|
||||
for(TariffMultistep step : createLst){
|
||||
step.setId(UUIDUtil.getUUID());
|
||||
step.setTenancyId(super.getTenancyId(request));
|
||||
step.setTariffId(tariffId);
|
||||
step.setDelFlag(0);
|
||||
}
|
||||
for(TariffMultistep step : destroyLst){
|
||||
step.setDelFlag(1);
|
||||
}
|
||||
tariffDao.saveStep(createLst);
|
||||
tariffDao.updateStep(updateLst, super.getJSONParam(update));
|
||||
tariffDao.updateStep(destroyLst, null);//更新删除标识
|
||||
//tariffDao.deleteStep(destroyLst);
|
||||
}
|
||||
/**
|
||||
* 删除费率
|
||||
*/
|
||||
@Transactional
|
||||
public int deleteTariff(HttpServletRequest request, String id){
|
||||
Tariff tariff = new Tariff();
|
||||
tariff.setId(id);
|
||||
return tariffDao.delete(tariff);
|
||||
}
|
||||
|
||||
public String findMultistep(HttpServletRequest request){
|
||||
//String tariffId
|
||||
TariffMultistep step = new ParamUtil<TariffMultistep>().packPOJO(super.getRequestMap(request), TariffMultistep.class);
|
||||
step.setTenancyId(super.getTenancyId(request));
|
||||
step.setDelFlag(0);
|
||||
String sql = tariffDao.findMultistep(step);
|
||||
if (StrUtil.isEmpty(step.getTariffId())){
|
||||
if (sql.toLowerCase().contains(" where ")){
|
||||
sql += " and 1=2";
|
||||
} else {
|
||||
sql += " where 1=2";
|
||||
}
|
||||
}
|
||||
return sql;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ag.rate.tariff.service;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018-03-15.
|
||||
*/
|
||||
public class TestBackCall {
|
||||
public void open(){}
|
||||
public void close(){}
|
||||
public void execute(){
|
||||
open();
|
||||
myMethod();
|
||||
close();
|
||||
}
|
||||
public void myMethod(){
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.ag.rate.tariff.test;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018-03-15.
|
||||
*/
|
||||
public interface ComputeCallBack {
|
||||
void onComputeEnd();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ag.rate.tariff.test;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018-03-15.
|
||||
*/
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
TestCallBack test = new TestCallBack();
|
||||
test.compute(60, () -> System.out.println("end back!!!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ag.rate.tariff.test;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018-03-15.
|
||||
*/
|
||||
public class TestCallBack {
|
||||
public void compute(int n, ComputeCallBack callback) {
|
||||
double qutity = 10000;
|
||||
for (int i = 0; i < n; i++) {
|
||||
qutity = qutity * 1.1;
|
||||
System.out.println((i+1)+":"+qutity);
|
||||
}
|
||||
callback.onComputeEnd();
|
||||
System.out.println("game over!");
|
||||
}
|
||||
}
|
||||
184
ILogBizSystem/src/main/java/com/ag/redis/CodeSetTemplate.java
Normal file
184
ILogBizSystem/src/main/java/com/ag/redis/CodeSetTemplate.java
Normal file
@@ -0,0 +1,184 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.wb.common.KvBean;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 缓存表查询相关,只在此类处理
|
||||
* Created by yangxh on 2021/3/18.
|
||||
*/
|
||||
@Component
|
||||
public class CodeSetTemplate {
|
||||
|
||||
private Logger logger = Logger.getLogger(CodeSetTemplate.class);
|
||||
@Autowired
|
||||
private DefaultBussniessImpl bizDao;
|
||||
|
||||
/**
|
||||
* 1.检查整个sql是否有异常
|
||||
* 1.2--异常分支,检查每个sql,有异常sql加入异常key集合,无异常继续UNION ALL拼接查询
|
||||
* 2.非s_code表查询(检查code_set中是否存在重复tableName)
|
||||
* 3.s_code表查询(检查code_set与s_code中是否有重复tableName)
|
||||
* 4。try。catch。捕获异常
|
||||
* @return
|
||||
*/
|
||||
public List<KvBean> getKvBean(){
|
||||
List<KvBean> targets = new ArrayList<>();
|
||||
String codeSetSql = "select * from code_set";
|
||||
List<Map<String, String>> codeSets = bizDao.queryForList(codeSetSql);
|
||||
String kvSql = "";
|
||||
Map<String, String> scodeMap = null;
|
||||
//存储key集合
|
||||
Set<String> tabNames = new HashSet<>();
|
||||
//存储重复key
|
||||
List<String> duTabNames = new ArrayList<>();
|
||||
/**
|
||||
* code_set中的sql组合
|
||||
*/
|
||||
for (Map<String, String> codeSet : codeSets){
|
||||
if (ObjectUtil.equal("S_CODE", codeSet.get("TABLE_NAME"))){
|
||||
scodeMap = codeSet;
|
||||
continue;
|
||||
}
|
||||
if(!tabNames.contains(codeSet.get("TABLE_NAME"))){
|
||||
tabNames.add(codeSet.get("TABLE_NAME"));
|
||||
}else {
|
||||
duTabNames.add(codeSet.get("TABLE_NAME"));
|
||||
}
|
||||
if (testSqlException(codeSet.get("COD_SQL")) == 0){
|
||||
targets.addAll(bizDao.list(codeSet.get("COD_SQL"), KvBean.class));
|
||||
}
|
||||
//kvSql = StrUtil.join(kvSql, "select * from (", codeSet.get("COD_SQL"), ") union all ");
|
||||
}
|
||||
Assert.isTrue(CollectionUtil.isEmpty(duTabNames), "code_set中缓存字典重复,请检查!【"+ JSON.toJSONString(duTabNames)+"】");
|
||||
//kvSql = kvSql.substring(0, kvSql.length() - 12);
|
||||
|
||||
|
||||
/**
|
||||
* s_code查询
|
||||
*/
|
||||
List<KvBean> scodeBeans = null;
|
||||
if(scodeMap != null && scodeMap.get("COD_SQL") != null){
|
||||
scodeBeans = bizDao.list(scodeMap.get("COD_SQL"), KvBean.class);
|
||||
Map<String, List<KvBean>> scodeTabNames = scodeBeans.stream().collect(Collectors.groupingBy(KvBean::getKeyName));
|
||||
for (Map.Entry<String, List<KvBean>> entry : scodeTabNames.entrySet()){
|
||||
if(!tabNames.contains(entry.getKey())){
|
||||
tabNames.add(entry.getKey());
|
||||
}else {
|
||||
duTabNames.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
Assert.isTrue(CollectionUtil.isEmpty(duTabNames), "code_set与s_code缓存字典重复,请检查!【"+ JSON.toJSONString(duTabNames)+"】");
|
||||
targets.addAll(scodeBeans);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* WB_KEY查询(keyName已存在则移除wb_key中数据)
|
||||
*/
|
||||
/*String wbKeySql = "select KEY_NAME, K,V from WB_KEY order by KEY_NAME ";
|
||||
List<KvBean> wbKeyBeans = bizDao.list(wbKeySql, KvBean.class);
|
||||
Iterator<KvBean> iter = wbKeyBeans.iterator();
|
||||
while (iter.hasNext()){
|
||||
KvBean kvBean = iter.next();
|
||||
for(String tabName : tabNames) {
|
||||
if (ObjectUtil.equal(kvBean.getKeyName(), tabName)){
|
||||
iter.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
/*if(kvSql.length() > 0 ){
|
||||
//出现sql异常,异常sql测试
|
||||
if (testSqlException(kvSql) == -1){
|
||||
List<String> exceptionKeys = new ArrayList<>();
|
||||
String msg = "";
|
||||
for (Map<String, String> codeSet : codeSets){
|
||||
if (testSqlException(codeSet.get("COD_SQL")) == -1){
|
||||
exceptionKeys.add(codeSet.get("TABLE_NAME"));
|
||||
}
|
||||
}
|
||||
if (CollectionUtil.isEmpty(exceptionKeys)) {
|
||||
msg = "sql异常,请检查!" + kvSql;
|
||||
}else {
|
||||
msg = "sql异常,请检查这些TABLE_NAME:" + JSON.toJSONString(exceptionKeys);
|
||||
}
|
||||
throw new RuntimeException(msg);
|
||||
}
|
||||
kvSql = StrUtil.join("select * from (", kvSql, ") tal where k is not null and v is not null");
|
||||
List<KvBean> codeSetBeans = bizDao.list(kvSql, KvBean.class);
|
||||
targets.addAll(codeSetBeans);
|
||||
}*/
|
||||
return targets;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* sql异常返回-1
|
||||
* @param testSql
|
||||
* @param params
|
||||
* @return
|
||||
*/
|
||||
private int testSqlException(String testSql, Object... params) {
|
||||
int num = 0;
|
||||
try {
|
||||
bizDao.count(StrUtil.join("select count(0) from (", testSql, ") a"), params);
|
||||
return num;
|
||||
}catch (Exception ex){
|
||||
num = -1;
|
||||
logger.error(ex.fillInStackTrace());
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public List<KvBean> getKvBeanByTableName(String tableName){
|
||||
String codeSetSql = "select * from code_set where table_name=?";
|
||||
int num = bizDao.count("select count(0) from ("+codeSetSql+") tab", tableName);
|
||||
if (num > 0 && !"s_code".equalsIgnoreCase(tableName)){
|
||||
//code_set中存在tableName(不包含s_code)
|
||||
List<Map<String, String>> codeSets = bizDao.queryForList(codeSetSql, tableName);
|
||||
return bizDao.list(codeSets.get(0).get("COD_SQL"), KvBean.class);
|
||||
}else {
|
||||
//s_code中的字典
|
||||
String scodeSql = "select COD_SQL from code_set where table_name='S_CODE'";
|
||||
List<String> codSql = bizDao.listSingleColumn(scodeSql, String.class);
|
||||
scodeSql = StrUtil.join("select * from (", codSql.get(0), " ) a WHERE a.key_name=?");
|
||||
num = bizDao.count("select count(0) from ("+scodeSql+") tab", tableName);
|
||||
if (num > 0){
|
||||
return bizDao.list(scodeSql, KvBean.class, tableName);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public boolean isContainsDefault(String tableName){
|
||||
String codeSetSql = "select * from code_set where table_name=? and table_name<>'S_CODE'";
|
||||
List<Map<String, String>> codeSets = bizDao.queryForList(codeSetSql, tableName);
|
||||
if (CollectionUtil.isEmpty(codeSets)){
|
||||
throw new RuntimeException("codeSet中【"+tableName+"】未维护");
|
||||
}
|
||||
return ObjectUtil.equal(codeSets.get(0).get("IS_DEFAULT"),"1");
|
||||
}
|
||||
|
||||
public List<String> getDefaultTabNames() {
|
||||
String codeSetSql = "select TABLE_NAME from code_set where IS_DEFAULT=1";
|
||||
return bizDao.listSingleColumn(codeSetSql, String.class);
|
||||
}
|
||||
}
|
||||
336
ILogBizSystem/src/main/java/com/ag/redis/RedisServiceImpl.java
Normal file
336
ILogBizSystem/src/main/java/com/ag/redis/RedisServiceImpl.java
Normal file
@@ -0,0 +1,336 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.ag.base.IRedisService;
|
||||
import com.ag.util.ResourceUtil;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.ag.util.UniqueObjectList;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.wb.common.KvBean;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* redis管理开放工具类
|
||||
* 逻辑处理在本类处理
|
||||
* Created by yangxh on 2021/3/18.
|
||||
*/
|
||||
@Service
|
||||
public class RedisServiceImpl implements IRedisService {
|
||||
|
||||
private Logger logger = Logger.getLogger(RedisServiceImpl.class);
|
||||
private final String TENANCY_ID = "default";
|
||||
private static String redisPrefix = "";
|
||||
|
||||
static {
|
||||
ResourceBundle resource = ResourceUtil.getResourceBundle("system");
|
||||
if (resource.containsKey("redisPrefix")){
|
||||
redisPrefix = resource.getString("redisPrefix");
|
||||
}
|
||||
redisPrefix = StrUtil.join(redisPrefix, ".sys.");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
@Autowired
|
||||
private CodeSetTemplate codeSetTemplate;
|
||||
|
||||
private String joinKey(String key){
|
||||
return StrUtil.join(redisPrefix, "_", key);
|
||||
}
|
||||
|
||||
private String getTenancyId(String tenancyId){
|
||||
if (StrUtil.isEmpty(tenancyId)){
|
||||
tenancyId = TENANCY_ID;
|
||||
}
|
||||
return tenancyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存key规则:项目_租户_keyName
|
||||
* 租户为空表示通用租户。
|
||||
* 其他租户不等于默认租户,返回数据=租户数据+默认租户数据
|
||||
*/
|
||||
@Override
|
||||
public void redisLoad() {
|
||||
List<KvBean> kvBeans = codeSetTemplate.getKvBean();
|
||||
//查询继承默认租户数据的表名
|
||||
List<String> defaultTabs = codeSetTemplate.getDefaultTabNames();
|
||||
//空租户的所有数据
|
||||
List<KvBean> emptyTenancyBeans = CollectionUtil.newArrayList();
|
||||
Iterator<KvBean> iter = kvBeans.iterator();
|
||||
while (iter.hasNext()){
|
||||
KvBean kvBean = iter.next();
|
||||
if (StrUtil.isEmpty(kvBean.getTenancyId())){
|
||||
emptyTenancyBeans.add(kvBean);
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
//空租户的数据分组
|
||||
Map<String, List<KvBean>> emptyTenancyTabNames =
|
||||
emptyTenancyBeans.stream().collect(Collectors.groupingBy(KvBean::getKeyName));
|
||||
//空租户的数据存储
|
||||
for (Map.Entry<String, List<KvBean>> entry : emptyTenancyTabNames.entrySet()){
|
||||
JSONArray array = kvBeanToArray(entry.getValue());
|
||||
redisUtil.set(joinKey(entry.getKey()), array);
|
||||
}
|
||||
|
||||
//kvBeans只含有租户的数据
|
||||
Map<String, List<KvBean>> tabNames =
|
||||
kvBeans.stream().collect(Collectors.groupingBy(x->x.getTenancyId()+"_"+x.getKeyName()));
|
||||
//存储默认(集团)租户的数据
|
||||
Map<String, List<KvBean>> defaultMap = new HashMap<>();
|
||||
for (String defaultTab : defaultTabs){
|
||||
String defaultKey = TENANCY_ID + "_" + defaultTab;
|
||||
for (Map.Entry<String, List<KvBean>> entry : tabNames.entrySet()){
|
||||
if (ObjectUtil.equal(defaultKey, entry.getKey())){
|
||||
defaultMap.put(defaultKey, entry.getValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, List<KvBean>> entry : tabNames.entrySet()){
|
||||
String defaultKey = TENANCY_ID + "_" + entry.getKey().substring(entry.getKey().indexOf("_") + 1);
|
||||
if (defaultMap.containsKey(defaultKey)){
|
||||
//其他租户加入默认租户数据
|
||||
List<KvBean> targets = new UniqueObjectList<>();
|
||||
targets.addAll(entry.getValue());
|
||||
targets.addAll(defaultMap.get(defaultKey));
|
||||
tabNames.put(entry.getKey(), targets);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("++++++++++++++++ Redis ready ++++++++++++++++");
|
||||
logger.info(" _._ \n" +
|
||||
" _.-``__ ''-._\n" +
|
||||
" _.-`` `. `_. ''-._\n" +
|
||||
" .-`` .-```. ```\\/ _.,_ ''-._\n" +
|
||||
" ( ' , .-` | `, )\n" +
|
||||
" |`-._`-...-` __...-.``-._|'` _.-'|\n" +
|
||||
" | `-._ `._ / _.-' |\n" +
|
||||
" `-._ `-._ `-./ _.-' _.-' \n" +
|
||||
" |`-._`-._ `-.__.-' _.-'_.-'|\n" +
|
||||
" | `-._`-._ _.-'_.-' |\n" +
|
||||
" `-._ `-._`-.__.-'_.-' _.-' \n" +
|
||||
" |`-._`-._ `-.__.-' _.-'_.-'|\n" +
|
||||
" | `-._`-._ _.-'_.-' |\n" +
|
||||
" `-._ `-._`-.__.-'_.-' _.-' \n" +
|
||||
" `-._ `-.__.-' _.-'\n" +
|
||||
" `-._ _.-'\n" +
|
||||
" `-.__.-'\n");
|
||||
for (Map.Entry<String, List<KvBean>> entry : tabNames.entrySet()){
|
||||
JSONArray array = kvBeanToArray(entry.getValue());
|
||||
redisUtil.set(joinKey(entry.getKey()), array);
|
||||
}
|
||||
logger.info("++++++++++++++++ Redis load success ++++++++++++++++");
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 按表名重新加载
|
||||
* @param dictName
|
||||
*/
|
||||
@Override
|
||||
public void refreshByDictName(String dictName) {
|
||||
List<KvBean> kvBeans = codeSetTemplate.getKvBeanByTableName(dictName);
|
||||
//Assert.notNull(kvBeans, "刷新redis遇到非法的请求参数:"+dictName);
|
||||
Assert.notEmpty(kvBeans, "查询结果数据为空,请检查:"+dictName);
|
||||
boolean isDefault = false;
|
||||
if (!StrUtil.isEmpty(kvBeans.get(0).getTenancyId())) {
|
||||
isDefault = codeSetTemplate.isContainsDefault(dictName);
|
||||
}
|
||||
//kvBeans.forEach(x->{if(StrUtil.isEmpty(x.getTenancyId())){x.setTenancyId(TENANCY_ID);}});
|
||||
Map<String, List<KvBean>> tabMaps = new HashMap<>();
|
||||
Map<String, List<KvBean>> emptyTenancyMaps = new HashMap<>();
|
||||
if (StrUtil.isEmpty(kvBeans.get(0).getTenancyId())){
|
||||
emptyTenancyMaps = kvBeans.stream().collect(Collectors.groupingBy(KvBean::getKeyName));
|
||||
}else {
|
||||
//按租户+名称分组
|
||||
tabMaps = kvBeans.stream().collect(Collectors.groupingBy(x -> x.getTenancyId() + "_" + x.getKeyName()));
|
||||
}
|
||||
logger.info(" Redis reload ++++++++++++++++ " + dictName);
|
||||
//如果使用集团租户并且租户数量大于0
|
||||
//获取默认租户
|
||||
if (isDefault && tabMaps.size() > 0) {
|
||||
String defaultKey = TENANCY_ID + "_" + dictName;
|
||||
List<KvBean> defaultList = tabMaps.get(defaultKey);
|
||||
for (Map.Entry<String, List<KvBean>> entry : tabMaps.entrySet()) {
|
||||
if (ObjectUtil.notEqual(entry.getKey(), defaultKey)){
|
||||
//自定义租户加入默认租户数据
|
||||
List<KvBean> targets = new UniqueObjectList<>();
|
||||
targets.addAll(entry.getValue());
|
||||
targets.addAll(defaultList);
|
||||
tabMaps.put(entry.getKey(), targets);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, List<KvBean>> entry : tabMaps.entrySet()) {
|
||||
JSONArray array = kvBeanToArray(entry.getValue());
|
||||
redisUtil.set(joinKey(entry.getKey()), array);
|
||||
}
|
||||
for (Map.Entry<String, List<KvBean>> entry : emptyTenancyMaps.entrySet()) {
|
||||
JSONArray array = kvBeanToArray(entry.getValue());
|
||||
redisUtil.set(joinKey(entry.getKey()), array);
|
||||
}
|
||||
logger.info(" Redis load success ++++++++++++++++ " + dictName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取表名所有key/value
|
||||
* @param dictName
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<KvBean> getAllByKey(String dictName) {
|
||||
return getAllByKey(dictName, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<KvBean> getAllByKey(String dictName, String tenancyId) {
|
||||
String result;
|
||||
if (redisUtil.hasKey(joinKey(dictName))){
|
||||
result = Convert.toStr(redisUtil.get(joinKey(dictName)));
|
||||
}else {
|
||||
result = Convert.toStr(redisUtil.get(joinKey(getTenancyId(tenancyId)+"_"+dictName)));
|
||||
}
|
||||
return strToKvBean(dictName, result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分页+模糊查询(不指定分页按20条数据返回,支持null)
|
||||
* @param dictName
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<KvBean> likeByKey(String dictName, String key){
|
||||
return likeByKey(dictName, key, null);
|
||||
}
|
||||
@Override
|
||||
public List<KvBean> likeByKey(String dictName, String key, String tenancyId){
|
||||
return likeByKey(dictName, key, tenancyId, 0, 20);
|
||||
}
|
||||
@Override
|
||||
public List<KvBean> likeByKey(String dictName, String key, Integer begIndex, Integer length){
|
||||
return likeByKey(dictName, key, null, begIndex, length);
|
||||
}
|
||||
@Override
|
||||
public List<KvBean> likeByKey(String dictName, String key, String tenancyId, Integer begIndex, Integer length) {
|
||||
if (StrUtil.isEmpty(key)){
|
||||
key = "";
|
||||
}
|
||||
String result;
|
||||
if (redisUtil.hasKey(joinKey(dictName))){
|
||||
result = Convert.toStr(redisUtil.like(joinKey(dictName), key, begIndex, length));
|
||||
}else {
|
||||
result = Convert.toStr(redisUtil.like(joinKey(getTenancyId(tenancyId) + "_" + dictName), key, begIndex, length));
|
||||
}
|
||||
return strToKvBean(dictName, result);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getTargetName(String dictName, String key) {
|
||||
return getTargetName(dictName, key, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<KvBean> findByMultKeys(String dictName, String keys) {
|
||||
return findByMultKeys(dictName, keys, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTargetName(String dictName, String key, String tenancyId) {
|
||||
List<KvBean> kvBeans = findByMultKeys(dictName, key, tenancyId);
|
||||
if (CollectionUtil.isEmpty(kvBeans)){
|
||||
return null;
|
||||
}
|
||||
return kvBeans.get(0).getV();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<KvBean> findByMultKeys(String dictName, String keys, String tenancyId) {
|
||||
String result;
|
||||
if (redisUtil.hasKey(joinKey(dictName))){
|
||||
result = Convert.toStr(redisUtil.accurateKey(joinKey(dictName), keys));
|
||||
}else {
|
||||
result = Convert.toStr(redisUtil.accurateKey(joinKey(getTenancyId(tenancyId)+"_"+dictName), keys));
|
||||
}
|
||||
return strToKvBean(dictName, result);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void putCustomizeKey(String key, String obj) {
|
||||
redisUtil.set(key, obj);
|
||||
}
|
||||
@Override
|
||||
public String getCustomizeKey(String key) {
|
||||
String str = Convert.toStr(redisUtil.get(key));
|
||||
if (str == null){
|
||||
str = "{}";
|
||||
}
|
||||
return str.replace("\\\"", "\"");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delKey(String key){
|
||||
redisUtil.delete(key);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private List<KvBean> strToKvBean(String dictName, String result){
|
||||
if (ObjectUtil.equal(result, "{}") || StrUtil.isEmpty(result)){
|
||||
return CollUtil.list(false);
|
||||
}
|
||||
JSONArray array = JSON.parseArray(result);
|
||||
List<KvBean> kvBeans = new ArrayList<>(array.size());
|
||||
for (int i=0; i<array.size(); i++){
|
||||
KvBean kvBean = new KvBean();
|
||||
kvBean.setKeyName(dictName);
|
||||
kvBean.setK(array.getJSONObject(i).getString("K"));
|
||||
kvBean.setV(array.getJSONObject(i).getString("V"));
|
||||
kvBean.setComv(array.getJSONObject(i).getString("COMV"));
|
||||
kvBean.setComv2(array.getJSONObject(i).getString("COMV2"));
|
||||
kvBeans.add(kvBean);
|
||||
}
|
||||
return kvBeans;
|
||||
}
|
||||
|
||||
private JSONArray kvBeanToArray(List<KvBean> kvBeans){
|
||||
JSONArray array = new JSONArray(kvBeans.size());
|
||||
for (KvBean val : kvBeans){
|
||||
JSONObject map = new JSONObject();
|
||||
map.put("K", val.getK());
|
||||
map.put("V", val.getV());
|
||||
map.put("COMV", val.getComv());
|
||||
map.put("COMV2", val.getComv2());
|
||||
array.add(map);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
}
|
||||
119
ILogBizSystem/src/main/java/com/ag/redis/RedisUtil.java
Normal file
119
ILogBizSystem/src/main/java/com/ag/redis/RedisUtil.java
Normal file
@@ -0,0 +1,119 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.ag.util.StrUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.data.redis.core.script.RedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RedisTemplate工具类
|
||||
* 所有与redis交互只在本类处理。
|
||||
*/
|
||||
@Component
|
||||
public class RedisUtil {
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate redisTemplate;
|
||||
|
||||
public void set(String key, Object obj) {
|
||||
redisTemplate.opsForValue().set(key, obj);
|
||||
//BoundValueOperations的理解对保存的值做一些细微的操作
|
||||
// BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);
|
||||
}
|
||||
|
||||
public Object get(String key) {
|
||||
//return redisTemplate.opsForValue().get(key);
|
||||
Object obj = redisTemplate.opsForValue().get(key);
|
||||
return obj;
|
||||
}
|
||||
|
||||
public boolean hasKey(String key) {
|
||||
return redisTemplate.hasKey(key);
|
||||
}
|
||||
|
||||
public Object like(String dictName, String key, Integer begIndex, Integer length) {
|
||||
if (!redisTemplate.hasKey(dictName)){
|
||||
return null;
|
||||
}
|
||||
//return redisTemplate.opsForValue().get(key);
|
||||
return redisTemplate.execute(getPageScript(), CollectionUtil.newArrayList(dictName), key, begIndex, length);
|
||||
}
|
||||
|
||||
/*private RedisScript<String> getLikeScript() {
|
||||
final String script = "local json = cjson.decode(redis.call('get',KEYS[1]))\n" +
|
||||
"local ret ={}\n" +
|
||||
"for i, v in ipairs(json) do\n" +
|
||||
" if(string.find(v.V,KEYS[2])) then\n" +
|
||||
"\t\ttable.insert(ret,{K=v.K,V=v.V})\n" +
|
||||
"\tend\n" +
|
||||
"end\n" +
|
||||
"return cjson.encode(ret)";
|
||||
return new DefaultRedisScript<>(script, String.class);
|
||||
}*/
|
||||
|
||||
private RedisScript<String> getPageScript() {
|
||||
final String script = "local json = cjson.decode(redis.call('get',KEYS[1]))\n" +
|
||||
"local beg = tonumber(ARGV[2])\n" +
|
||||
"local ed = tonumber(ARGV[3]) + beg\n" +
|
||||
"local num = 0\n" +
|
||||
"local ret ={}\n" +
|
||||
"for i, v in ipairs(json) do\n" +
|
||||
"\tif(string.find(v.V,ARGV[1]) or string.find(v.K,ARGV[1])) then\n" +
|
||||
"\t\tif(num >= beg and num < ed) then\n" +
|
||||
"\t\t\ttable.insert(ret,{K=v.K,V=v.V,COMV=v.COMV,COMV2=v.COMV2})\n" +
|
||||
"\t\tend\n" +
|
||||
"\t\tnum = num + 1\n" +
|
||||
"\t\tif(num == ed) then \n" +
|
||||
"\t\t break\n" +
|
||||
"\t\tend\n" +
|
||||
"\tend\n" +
|
||||
"end\n" +
|
||||
"return cjson.encode(ret)";
|
||||
return new DefaultRedisScript<>(script, String.class);
|
||||
}
|
||||
|
||||
public Object accurateKey(String dictName, String keys) {
|
||||
if (!redisTemplate.hasKey(dictName)){
|
||||
return null;
|
||||
}
|
||||
List<String> list = Arrays.asList(keys.split(","));
|
||||
list.removeIf(str->(StrUtil.isEmpty(str)));
|
||||
if (CollectionUtil.isEmpty(list)){
|
||||
return null;
|
||||
}
|
||||
Object[] argv = new Object[list.size()];
|
||||
for (int i=0; i<list.size();i++){
|
||||
argv[i] = list.get(i).trim();
|
||||
}
|
||||
//return redisTemplate.opsForValue().get(key);
|
||||
return redisTemplate.execute(getAccurateScript(), CollectionUtil.newArrayList(dictName), argv);
|
||||
}
|
||||
|
||||
private RedisScript<String> getAccurateScript() {
|
||||
final String script = "local json = cjson.decode(redis.call('get',KEYS[1]))\n" +
|
||||
"local ret ={}\n" +
|
||||
"for j=0,#ARGV,1 do\n" +
|
||||
"\tfor i, v in ipairs(json) do\n" +
|
||||
"\t\tif(v.K == ARGV[j]) then\n" +
|
||||
"\t\t\ttable.insert(ret,{K=v.K,V=v.V})\n" +
|
||||
"\t\t\tbreak\n" +
|
||||
"\t\tend\n" +
|
||||
"\tend\n" +
|
||||
"end\n" +
|
||||
"return cjson.encode(ret)";
|
||||
return new DefaultRedisScript<>(script, String.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void delete(String key) {
|
||||
redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
}
|
||||
153
ILogBizSystem/src/main/java/com/ag/redis/SerializeUtil.java
Normal file
153
ILogBizSystem/src/main/java/com/ag/redis/SerializeUtil.java
Normal file
@@ -0,0 +1,153 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 序列化对象工具类,用于保存和读取redis数据使用
|
||||
*/
|
||||
public class SerializeUtil {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(SerializeUtil.class);
|
||||
|
||||
/**
|
||||
* 序列化对象
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static byte[] serialize(Object object) {
|
||||
ObjectOutputStream oos = null;
|
||||
ByteArrayOutputStream baos = null;
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
// 序列化
|
||||
baos = new ByteArrayOutputStream();
|
||||
oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(object);
|
||||
bytes = baos.toByteArray();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (oos != null) {
|
||||
oos.close();
|
||||
}
|
||||
if (baos != null) {
|
||||
baos.close();
|
||||
}
|
||||
} catch (Exception e2) {
|
||||
e2.printStackTrace();
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化对象
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static Object unserialize(byte[] bytes) {
|
||||
Object obj = null;
|
||||
ByteArrayInputStream bais = null;
|
||||
try {
|
||||
// 反序列化
|
||||
bais = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bais);
|
||||
obj = ois.readObject();
|
||||
ois.close();
|
||||
bais.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭的数据源或目标。调用 close()方法可释放对象保存的资源(如打开文件)
|
||||
* 关闭此流并释放与此流关联的所有系统资源。如果已经关闭该流,则调用此方法无效。
|
||||
* @param closeable
|
||||
*/
|
||||
public static void close(Closeable closeable) {
|
||||
if (closeable != null) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (Exception e) {
|
||||
log.info("Unable to close %s", closeable, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表序列化(用于Redis整存整取)
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public static <T> byte[] serialize(List<T> value) {
|
||||
if (value == null) {
|
||||
throw new NullPointerException("Can't serialize null");
|
||||
}
|
||||
byte[] rv=null;
|
||||
ByteArrayOutputStream bos = null;
|
||||
ObjectOutputStream os = null;
|
||||
try {
|
||||
bos = new ByteArrayOutputStream();
|
||||
os = new ObjectOutputStream(bos);
|
||||
for(T obj : value){
|
||||
os.writeObject(obj);
|
||||
}
|
||||
os.writeObject(null);
|
||||
os.close();
|
||||
bos.close();
|
||||
rv = bos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("Non-serializable object", e);
|
||||
} finally {
|
||||
close(os);
|
||||
close(bos);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化列表(用于Redis整存整取)
|
||||
* @param in
|
||||
* @return
|
||||
*/
|
||||
public static <T> List<T> unserializeForList(byte[] in) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
ByteArrayInputStream bis = null;
|
||||
ObjectInputStream is = null;
|
||||
try {
|
||||
if(in != null) {
|
||||
bis=new ByteArrayInputStream(in);
|
||||
is=new ObjectInputStream(bis);
|
||||
while (true) {
|
||||
T obj = (T) is.readObject();
|
||||
if(obj == null){
|
||||
break;
|
||||
}else{
|
||||
list.add(obj);
|
||||
}
|
||||
}
|
||||
is.close();
|
||||
bis.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Caught IOException decoding %d bytes of data",
|
||||
in == null ? 0 : in.length, e);
|
||||
} catch (ClassNotFoundException e) {
|
||||
log.warn("Caught CNFE decoding %d bytes of data",
|
||||
in == null ? 0 : in.length, e);
|
||||
} finally {
|
||||
close(is);
|
||||
close(bis);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import com.ag.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2021/3/20.
|
||||
*/
|
||||
public class StringRedisSerializer implements RedisSerializer<Object> {
|
||||
private final Charset charset;
|
||||
|
||||
|
||||
public StringRedisSerializer() {
|
||||
this(Charset.forName("UTF8"));
|
||||
}
|
||||
|
||||
public StringRedisSerializer(Charset charset) {
|
||||
Assert.notNull(charset, "Charset must not be null!");
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String deserialize(byte[] bytes) {
|
||||
return (bytes == null ? null : new String(bytes, charset));
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public byte[] serialize(Object object) {
|
||||
String string = JSON.toJSONString(object);
|
||||
if (StrUtil.isEmpty(string)) {
|
||||
return null;
|
||||
}
|
||||
return string.getBytes(charset);
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public byte[] serialize(Object object) {
|
||||
String string = JSON.toJSONString(object);
|
||||
if (StrUtil.isEmpty(string)) {
|
||||
return null;
|
||||
}
|
||||
if (string.startsWith("\"")){
|
||||
string = string.substring(0, string.length()-1).substring(1);
|
||||
}
|
||||
return string.getBytes(charset);
|
||||
}
|
||||
|
||||
/*public static void main(String[] args) {
|
||||
String a ="\"a\"b\"c\"d\"";
|
||||
System.out.println(a);
|
||||
System.out.println(a.substring(0,a.length()-1).substring(1));
|
||||
}*/
|
||||
}
|
||||
47
ILogBizSystem/src/main/java/com/ag/redis/WbKeyNameUtil.java
Normal file
47
ILogBizSystem/src/main/java/com/ag/redis/WbKeyNameUtil.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package com.ag.redis;
|
||||
|
||||
import com.ag.base.IRedisService;
|
||||
import com.ag.secp.platform.spring.SpringApplicationContext;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.wb.common.KvBean;
|
||||
import com.wb.util.WebUtil;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/** @Description: 手动获取键值 keyname
|
||||
* @author: fengjun
|
||||
* @Date: 2023/2/15
|
||||
*/
|
||||
public class WbKeyNameUtil {
|
||||
|
||||
/** @Description: 获取keyname 数组
|
||||
* @return: void
|
||||
* @author: fengjun
|
||||
* @Date: 2023/2/15
|
||||
*/
|
||||
public static void getKeyName(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String keyName = request.getParameter("keyName");
|
||||
String type = request.getParameter("type");
|
||||
IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
|
||||
List<KvBean> allByKey = service.getAllByKey(keyName);
|
||||
if ("array".equals(type)) {
|
||||
JSONArray array = new JSONArray();
|
||||
allByKey.stream().map(k->{
|
||||
JSONObject object = new JSONObject();
|
||||
object.put("label",k.getV());
|
||||
object.put("value",k.getK());
|
||||
return object;
|
||||
}).forEach(array::add);
|
||||
WebUtil.send(response,array);
|
||||
return;
|
||||
}
|
||||
JSONObject object = new JSONObject();
|
||||
allByKey.forEach(k-> object.put(k.getK(),k.getV()));
|
||||
WebUtil.send(response,object);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import org.springframework.aop.framework.AdvisedSupport;
|
||||
import org.springframework.aop.framework.AopProxy;
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2019/3/4.
|
||||
*/
|
||||
|
||||
|
||||
public class AopTargetUtils {
|
||||
|
||||
|
||||
/**
|
||||
* 获取 目标对象
|
||||
* @param proxy 代理对象
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Object getTarget(Object proxy) {
|
||||
|
||||
if(!AopUtils.isAopProxy(proxy)) {
|
||||
return proxy;//不是代理对象
|
||||
}
|
||||
try {
|
||||
if (AopUtils.isJdkDynamicProxy(proxy)) {
|
||||
|
||||
return getJdkDynamicProxyTargetObject(proxy);
|
||||
} else { //cglib
|
||||
return getCglibProxyTargetObject(proxy);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
|
||||
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
|
||||
h.setAccessible(true);
|
||||
Object dynamicAdvisedInterceptor = h.get(proxy);
|
||||
|
||||
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
|
||||
advised.setAccessible(true);
|
||||
|
||||
Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
|
||||
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
|
||||
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
|
||||
h.setAccessible(true);
|
||||
AopProxy aopProxy = (AopProxy) h.get(proxy);
|
||||
|
||||
Field advised = aopProxy.getClass().getDeclaredField("advised");
|
||||
advised.setAccessible(true);
|
||||
|
||||
Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import org.apache.ibatis.io.Resources;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 16/7/15.
|
||||
*/
|
||||
public class DaoUtil {
|
||||
private static SqlSessionFactory sqlSessionFactory = null;
|
||||
|
||||
static {
|
||||
String resource = "daobase-config.xml";
|
||||
|
||||
Reader reader = null;
|
||||
try {
|
||||
reader = Resources.getResourceAsReader(resource);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
|
||||
}
|
||||
|
||||
|
||||
public static SqlSessionFactory getSqlSessionFactory() {
|
||||
return sqlSessionFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param sql
|
||||
* @return
|
||||
*/
|
||||
public static String selectOne(String sql, Object param) {
|
||||
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
String result = "";
|
||||
try {
|
||||
result = (String) session.selectOne(sql, param);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param sql
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
public static List selectList(String sql, Map map)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
List result;
|
||||
try {
|
||||
result = session.selectList(sql,map);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param sql
|
||||
* @param datastr @return
|
||||
*/
|
||||
public static List selectListforString(String sql, String datastr)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
List result;
|
||||
try {
|
||||
result = session.selectList(sql,datastr);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param sql
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
public static long selectOneForLong(String sql, Map map)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
long result;
|
||||
try {
|
||||
result = ((Long)session.selectOne(sql,map)).longValue();
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param sql
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
public static double selectOneFordouble(String sql, Map map)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
double result;
|
||||
try {
|
||||
result = ((Long) session.selectOne(sql,map)).doubleValue();
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param sql
|
||||
|
||||
* @return
|
||||
*/
|
||||
public static Object selectOneForObject(String sql , Map map)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
Object result;
|
||||
try {
|
||||
result = (Object)session.selectOne(sql,map);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void update(String sql,Map map)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
try {
|
||||
session.update(sql, map);
|
||||
|
||||
session.commit();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
public static void delete(String sql,Object object)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
try {
|
||||
session.delete(sql, object);
|
||||
|
||||
session.commit();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void update(String sql,Object object)
|
||||
{
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
try {
|
||||
session.update(sql, object);
|
||||
session.commit();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
public static int insert(String sql,Object object)
|
||||
{
|
||||
int i=0;;
|
||||
SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
|
||||
try {
|
||||
i=session.insert(sql, object);
|
||||
session.commit();
|
||||
return i;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return i;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 2017/5/12.
|
||||
*/
|
||||
public class DockerBean {
|
||||
|
||||
private String state;
|
||||
private String image;
|
||||
private String dates;
|
||||
private String names;
|
||||
private String containerid;
|
||||
|
||||
public String getContainerid() {
|
||||
return containerid;
|
||||
}
|
||||
|
||||
public void setContainerid(String containerid) {
|
||||
this.containerid = containerid;
|
||||
}
|
||||
|
||||
public String getNames() {
|
||||
return names;
|
||||
}
|
||||
|
||||
public void setNames(String names) {
|
||||
this.names = names;
|
||||
}
|
||||
|
||||
public String getDates() {
|
||||
return dates;
|
||||
}
|
||||
|
||||
public void setDates(String dates) {
|
||||
this.dates = dates;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(String image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public String getIpaddress() {
|
||||
return ipaddress;
|
||||
}
|
||||
|
||||
public void setIpaddress(String ipaddress) {
|
||||
this.ipaddress = ipaddress;
|
||||
}
|
||||
|
||||
private String ipaddress;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,658 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.spotify.docker.client.DefaultDockerClient;
|
||||
import com.spotify.docker.client.DockerClient;
|
||||
import com.spotify.docker.client.LogStream;
|
||||
import com.spotify.docker.client.exceptions.DockerException;
|
||||
import com.spotify.docker.client.messages.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 2017/5/8.
|
||||
*/
|
||||
@Component
|
||||
public class DockerCommon {
|
||||
@Autowired
|
||||
SqlSessionTemplate sqlSessionTemplate;
|
||||
|
||||
DockerClient docker;
|
||||
|
||||
|
||||
public DockerCommon() {
|
||||
|
||||
try {
|
||||
// docker = new DefaultDockerClient("unix:///var/run/docker.sock");
|
||||
docker = DefaultDockerClient.fromEnv().build();
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 把long 转换成 日期 再转换成String类型
|
||||
*/
|
||||
public String transferLongToDate(String dateFormat, Long millSec) {
|
||||
/*SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
|
||||
Date date = new Date(millSec);
|
||||
return sdf.format(date);*/
|
||||
|
||||
Long timestamp = millSec * 1000;
|
||||
String date = new java.text.SimpleDateFormat(dateFormat).format(new java.util.Date(timestamp));
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取容器
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public List listContainer() {
|
||||
Map dataMap = new HashMap();
|
||||
//List listcontainer = DaoUtil.selectList("agCommon.listcontainer", dataMap);
|
||||
List listcontainer = sqlSessionTemplate.selectList("agCommon.listcontainer",dataMap);
|
||||
List data = new ArrayList();
|
||||
try {
|
||||
List<Container> containers = docker.listContainers(DockerClient.ListContainersParam.allContainers());
|
||||
|
||||
|
||||
for (int a = 0; a < listcontainer.size(); a++) {
|
||||
|
||||
Map da = (Map) listcontainer.get(a);
|
||||
String containername = da.get("NAME").toString();
|
||||
|
||||
|
||||
for (int i = 0; i < containers.size(); i++) {
|
||||
DockerBean bean = new DockerBean();
|
||||
Container container = containers.get(i);
|
||||
String state = container.state();//????
|
||||
String image = container.image();//????
|
||||
com.google.common.collect.ImmutableList<String> listdata = container.names();
|
||||
String names = listdata.get(0).toString();
|
||||
|
||||
|
||||
/* com.google.common.collect.ImmutableList<String> listdata = container.names();
|
||||
String names = listdata.get(0).toString();
|
||||
// com.google.common.collect.ImmutableSet<AttachedNetwork> networks = container.networkSettings().networks().asMultimap();
|
||||
Map map = container.networkSettings().networks().asMultimap().asMap();
|
||||
|
||||
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Integer, String> entry = it.next();
|
||||
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
|
||||
}
|
||||
|
||||
String ipaddress = "";
|
||||
//((AttachedNetwork) networks.toArray()[0]).ipAddress();//ip??
|
||||
*/
|
||||
|
||||
|
||||
String dates = transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long) container.created());
|
||||
names = names.substring(1, names.length());
|
||||
//containername = "/" + containername;
|
||||
if (containername.equals(names)) {
|
||||
bean.setContainerid(container.id());
|
||||
bean.setIpaddress(da.get("NETWORK_IP").toString());
|
||||
bean.setImage(image);
|
||||
bean.setState(state);
|
||||
bean.setDates(dates);
|
||||
bean.setNames(names);
|
||||
data.add(bean);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 容器监控信息写入
|
||||
*/
|
||||
public void insertContainerstates() {
|
||||
try {
|
||||
List<Container> containers = docker.listContainers();
|
||||
for (int a = 0; a < containers.size(); a++) {
|
||||
|
||||
Container container = containers.get(a);
|
||||
|
||||
String datastring[] = getContainerStatus(container.id());
|
||||
Map dataMap=new HashMap();
|
||||
dataMap.put("cpuprecnt",datastring[0]);
|
||||
dataMap.put("memory",datastring[1]);
|
||||
dataMap.put("containerid",container.id());
|
||||
//DaoUtil.insert("agCommon.insertdockerlog",dataMap);
|
||||
sqlSessionTemplate.insert("agCommon.insertdockerlog",dataMap);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取容器状态
|
||||
*
|
||||
* @param id
|
||||
*/
|
||||
public String[] getContainerStatus(String id) {
|
||||
|
||||
// final ContainerInfo info = docker.inspectContainer(id);
|
||||
//docker.createNetwork()
|
||||
// info.
|
||||
try {
|
||||
ContainerStats stats = docker.stats(id);
|
||||
CpuStats cpuStats = stats.cpuStats();
|
||||
cpuStats.cpuUsage();
|
||||
|
||||
|
||||
/* Object data[]=cpuStats.cpuUsage().percpuUsage().asList().toArray();
|
||||
long usagecount=0;
|
||||
for(int i=0;i<data.length;i++){
|
||||
|
||||
usagecount=usagecount+ Long.parseLong(data[i].toString());
|
||||
}*/
|
||||
long totalcpu = cpuStats.cpuUsage().totalUsage().longValue();
|
||||
|
||||
long systemCpuUsage = cpuStats.systemCpuUsage().longValue();
|
||||
double percent = BigDecimal.valueOf(totalcpu).divide(BigDecimal.valueOf(systemCpuUsage), 4, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
|
||||
System.out.println(percent * 100);
|
||||
|
||||
long memoryuse = stats.memoryStats().usage();
|
||||
|
||||
long dive = 1024 * 1024;
|
||||
|
||||
double memory = BigDecimal.valueOf(memoryuse).divide(BigDecimal.valueOf(dive), 4, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
|
||||
|
||||
String data[] = new String[3];
|
||||
data[0] = String.valueOf(percent*100);
|
||||
data[1] = String.valueOf(memory);
|
||||
return data;
|
||||
} catch (DockerException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行命令
|
||||
* @param id
|
||||
* @param cmd
|
||||
*/
|
||||
public void execcmd(String id,String cmd){
|
||||
//cmd="/home/soft/zookeeper-3.4.8/bin/zkServer.sh start";
|
||||
//cmd="/usr/bin/mongod"
|
||||
try {
|
||||
final String[] command = {"sh", "-c", cmd};
|
||||
final ExecCreation execCreation = docker.execCreate(
|
||||
id, command, DockerClient.ExecCreateParam.attachStdout(),
|
||||
DockerClient.ExecCreateParam.attachStderr());
|
||||
final LogStream output = docker.execStart(execCreation.id());
|
||||
final String execOutput = output.readFully();
|
||||
System.out.println(execOutput);
|
||||
}catch(Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行容器命令
|
||||
*
|
||||
* @throws DockerException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public void execContainerCmd(String cmds,String containerid) throws DockerException, InterruptedException {
|
||||
String[] command = {"sh", "-c",cmds};
|
||||
|
||||
docker.startContainer(containerid);
|
||||
ExecCreation execCreation = docker.execCreate(
|
||||
containerid, command, DockerClient.ExecCreateParam.attachStdout(),
|
||||
DockerClient.ExecCreateParam.attachStderr());
|
||||
LogStream output = docker.execStart(execCreation.id());
|
||||
String execOutput = output.readFully();
|
||||
System.out.println(execOutput);
|
||||
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
try {
|
||||
final DockerClient docker = DefaultDockerClient.fromEnv().build();
|
||||
|
||||
|
||||
//??docker
|
||||
|
||||
/*
|
||||
// DockerClient docker = DefaultDockerClient.builder()
|
||||
// .uri(URI.create("http://192.168.1.203:4243"))
|
||||
// .build();
|
||||
|
||||
|
||||
final List<Container> containers = docker.listContainers();
|
||||
|
||||
Container container11 = containers.get(0);
|
||||
com.google.common.collect.ImmutableSet<AttachedNetwork> networks = container11.networkSettings().networks().asMultimap().get("bridge");
|
||||
String ipaddress = ((AttachedNetwork) networks.toArray()[0]).ipAddress();
|
||||
|
||||
//AttachedNetwork networksa=container11.networkSettings().networks().asMultimap().get("bridge");
|
||||
//container11.networkSettings().networks().asMultimap().
|
||||
System.out.println(containers.size());
|
||||
|
||||
final ContainerConfig config = ContainerConfig.builder()
|
||||
.image("ubuntu").cmd("sh", "-c", "while :; do sleep 1; done")
|
||||
.build();
|
||||
|
||||
|
||||
// final ContainerCreation container = docker.createContainer(config);
|
||||
ContainerCreation container = docker.createContainer(config, "ubunt22112aaa33015");
|
||||
//????
|
||||
docker.startContainer(container.id());
|
||||
|
||||
final List<Image> images = docker.listImages();
|
||||
final ContainerInfo info = docker.inspectContainer(container.id());
|
||||
//docker.createNetwork()
|
||||
// info.
|
||||
final ContainerStats stats = docker.stats(container.id());
|
||||
|
||||
|
||||
System.out.println("===" + info.state());
|
||||
|
||||
final List<Container> containersa = docker.listContainers();
|
||||
System.out.println(containersa.size());*/
|
||||
|
||||
|
||||
// Bind container ports to host ports
|
||||
final String[] ports = {"80", "22"};
|
||||
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
|
||||
for (String port : ports) {
|
||||
List<PortBinding> hostPorts = new ArrayList<>();
|
||||
hostPorts.add(PortBinding.of("0.0.0.0", port));
|
||||
portBindings.put(port, hostPorts);
|
||||
}
|
||||
|
||||
// Bind container port 443 to an automatically allocated available host port.
|
||||
List<PortBinding> randomPort = new ArrayList<>();
|
||||
randomPort.add(PortBinding.randomPort("0.0.0.0"));
|
||||
portBindings.put("443", randomPort);
|
||||
|
||||
final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();
|
||||
|
||||
|
||||
/**
|
||||
* network
|
||||
*/
|
||||
final String networkName = "abbb";
|
||||
final IpamConfig ipamConfig =
|
||||
IpamConfig.create("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1");
|
||||
final Ipam ipam = Ipam.builder()
|
||||
.driver("default")
|
||||
.config(singletonList(ipamConfig))
|
||||
.build();
|
||||
final Map<String, String> labels = ImmutableMap.of(
|
||||
"name", "starship", "foo", "bar");
|
||||
NetworkConfig networkConfig =
|
||||
NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam)
|
||||
.internal(false).enableIPv6(false).labels(labels)
|
||||
.build();
|
||||
// NetworkingConfig coni=NetworkingConfig.create();
|
||||
|
||||
|
||||
// Create container with exposed ports
|
||||
final ContainerConfig containerConfig = ContainerConfig.builder()
|
||||
.hostConfig(hostConfig)
|
||||
.image("dockerzook").exposedPorts(ports)
|
||||
.cmd("sh", "-c", "while :; do sleep 1; done")
|
||||
.build();
|
||||
|
||||
final ContainerCreation creation = docker.createContainer(containerConfig);
|
||||
final String id = creation.id();
|
||||
|
||||
// Inspect container
|
||||
final ContainerInfo info = docker.inspectContainer(id);
|
||||
|
||||
// Start container
|
||||
docker.startContainer(id);
|
||||
|
||||
|
||||
// String id="6047f33335b1";
|
||||
// Exec command inside running container with attached STDOUT and STDERR
|
||||
//final String[] command = {"bash", "-c", "ls"};
|
||||
final String[] command = {"sh", "-c", "/home/soft/zookeeper-3.4.8/bin/zkServer.sh start"};
|
||||
final ExecCreation execCreation = docker.execCreate(
|
||||
id, command, DockerClient.ExecCreateParam.attachStdout(),
|
||||
DockerClient.ExecCreateParam.attachStderr());
|
||||
final LogStream output = docker.execStart(execCreation.id());
|
||||
final String execOutput = output.readFully();
|
||||
System.out.println(execOutput);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void mainaa(String args[]) {
|
||||
|
||||
createNetwork();
|
||||
}
|
||||
|
||||
|
||||
public static void creatContainerWithNetwork() {
|
||||
|
||||
try {
|
||||
final DockerClient sut = new DefaultDockerClient("unix:///var/run/docker.sock");
|
||||
final String networkName = "networkname";
|
||||
final String containerName = "containerWithNetwork";
|
||||
|
||||
final String subnet = "172.20.0.0/16";
|
||||
final String ipRange = "172.20.10.0/24";
|
||||
final String gateway = "172.20.10.11";
|
||||
final IpamConfig ipamConfigToCreate =
|
||||
IpamConfig.create(subnet, ipRange, gateway);
|
||||
final Ipam ipamToCreate = Ipam.builder()
|
||||
.driver("default")
|
||||
.config(Lists.newArrayList(ipamConfigToCreate))
|
||||
.build();
|
||||
final NetworkConfig networkingConfig = NetworkConfig.builder()
|
||||
.name(networkName)
|
||||
.ipam(ipamToCreate)
|
||||
.build();
|
||||
|
||||
//ContainerConfig.NetworkingConfig.create();
|
||||
final NetworkCreation networkCreation =
|
||||
sut.createNetwork(networkingConfig);
|
||||
final ContainerConfig containerConfig =
|
||||
ContainerConfig.builder()
|
||||
.image("dockerzook")
|
||||
.cmd("sh", "-c", "while :; do sleep 1; done")
|
||||
.build();
|
||||
final ContainerCreation containerCreation = sut.createContainer(containerConfig, containerName);
|
||||
sut.startContainer(containerCreation.id());
|
||||
|
||||
// Those are some of the extra parameters that can be set along with the network connection
|
||||
final String ip = "172.20.10.1";
|
||||
final String dummyAlias = "value-does-not-matter";
|
||||
final EndpointConfig endpointConfig = EndpointConfig.builder()
|
||||
.ipamConfig(EndpointConfig.EndpointIpamConfig.builder().ipv4Address(ip).build())
|
||||
.aliases(ImmutableList.<String>of(dummyAlias))
|
||||
.build();
|
||||
|
||||
final NetworkConnection networkConnection = NetworkConnection.builder()
|
||||
.containerId(containerCreation.id())
|
||||
.endpointConfig(endpointConfig)
|
||||
.build();
|
||||
|
||||
|
||||
Network network = sut.inspectNetwork(networkCreation.id());
|
||||
Network.Container networkContainer = network.containers().get(containerCreation.id());
|
||||
final ContainerInfo containerInfo = sut.inspectContainer(containerCreation.id());
|
||||
final AttachedNetwork attachedNetwork =
|
||||
containerInfo.networkSettings().networks().get(networkName);
|
||||
|
||||
sut.disconnectFromNetwork(containerCreation.id(), networkCreation.id());
|
||||
network = sut.inspectNetwork(networkCreation.id());
|
||||
|
||||
sut.stopContainer(containerCreation.id(), 1);
|
||||
sut.removeContainer(containerCreation.id());
|
||||
sut.removeNetwork(networkCreation.id());
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建网络
|
||||
*
|
||||
* @param networkName 网络名称
|
||||
* @param subnet 子网掩码
|
||||
* @param iprange ip地址范围
|
||||
* @param getway 网关
|
||||
*/
|
||||
public void creatNetworkAddrinfo(String networkName, String subnet, String iprange, String getway) {
|
||||
|
||||
// final DockerClient docker = new DefaultDockerClient("unix:///var/run/docker.sock");
|
||||
|
||||
//创建网络段
|
||||
// final String networkName = "aaabbb55bbpp";
|
||||
final IpamConfig ipamConfig = IpamConfig.create(subnet, iprange, getway);
|
||||
// IpamConfig.create("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1");
|
||||
final Ipam ipam = Ipam.builder()
|
||||
.driver("default")
|
||||
.config(singletonList(ipamConfig))
|
||||
.build();
|
||||
final Map<String, String> labels = ImmutableMap.of(
|
||||
"name", "starship", "foo", "bar");
|
||||
final NetworkConfig networkConfig =
|
||||
NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam)
|
||||
.internal(false).enableIPv6(false).labels(labels)
|
||||
.build();
|
||||
|
||||
try {
|
||||
NetworkCreation networkCreation = docker.createNetwork(networkConfig);
|
||||
|
||||
} catch (DockerException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置端口映射,开放容器端口
|
||||
*/
|
||||
|
||||
public HostConfig portMapping(String ports[]) {
|
||||
// final String[] ports = {"2181", "229"};
|
||||
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
|
||||
for (String port : ports) {
|
||||
List<PortBinding> hostPorts = new ArrayList<>();
|
||||
hostPorts.add(PortBinding.of("0.0.0.0", port));
|
||||
portBindings.put(port, hostPorts);
|
||||
}
|
||||
|
||||
/* Bind container port 443 to an automatically allocated available host port.
|
||||
List<PortBinding> randomPort = new ArrayList<>();
|
||||
randomPort.add(PortBinding.randomPort("0.0.0.0"));
|
||||
portBindings.put("449", randomPort);*/
|
||||
|
||||
final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();
|
||||
|
||||
|
||||
return hostConfig;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建容器
|
||||
*
|
||||
* @param ip ip地址
|
||||
* @param name 容器名称
|
||||
* @param imageid 镜像
|
||||
* @param ports 端口映射
|
||||
* @param networkname 网络名称
|
||||
*/
|
||||
public String creatContainers(String ip, String name, String imageid, String ports[], String networkname) {
|
||||
|
||||
if(ports==null){
|
||||
|
||||
ports[0] = "2999";
|
||||
}
|
||||
|
||||
|
||||
HostConfig hostConfig = portMapping(ports);
|
||||
|
||||
// final String[] ports = {"2181", "8893","8890"};
|
||||
//设置ip地址192.168.0.13
|
||||
final EndpointConfig endpointConfig = EndpointConfig.builder()
|
||||
// .ipAddress("192.168.0.12").gateway("192.168.0.1")
|
||||
.ipamConfig(EndpointConfig.EndpointIpamConfig.builder().ipv4Address(ip).build())
|
||||
|
||||
.build();
|
||||
Map datamap = new HashMap();
|
||||
datamap.put(networkname, endpointConfig);
|
||||
final ContainerConfig config = ContainerConfig.builder()
|
||||
.hostConfig(hostConfig).exposedPorts(ports)
|
||||
.networkingConfig(ContainerConfig.NetworkingConfig.create(datamap))
|
||||
.image(imageid).cmd("sh", "-c", "while :; do sleep 1; done")
|
||||
.build();
|
||||
String containerid="";
|
||||
|
||||
|
||||
try {
|
||||
ContainerCreation container = docker.createContainer(config, name);
|
||||
containerid=container.id();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return containerid;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void createNetwork() {
|
||||
final DockerClient docker = new DefaultDockerClient("unix:///var/run/docker.sock");
|
||||
/*
|
||||
创建网络段
|
||||
final String networkName = "aaabbb55bbpp";
|
||||
final IpamConfig ipamConfig =
|
||||
IpamConfig.create("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1");
|
||||
final Ipam ipam = Ipam.builder()
|
||||
.driver("default")
|
||||
.config(singletonList(ipamConfig))
|
||||
.build();
|
||||
final Map<String, String> labels = ImmutableMap.of(
|
||||
"name", "starship", "foo", "bar");
|
||||
final NetworkConfig networkConfig =
|
||||
NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam)
|
||||
.internal(false).enableIPv6(false).labels(labels)
|
||||
.build();
|
||||
|
||||
try {
|
||||
NetworkCreation networkCreation = docker.createNetwork(networkConfig);
|
||||
} catch (DockerException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}*/
|
||||
|
||||
try {
|
||||
|
||||
|
||||
final String[] ports = {"2181", "229"};
|
||||
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
|
||||
for (String port : ports) {
|
||||
List<PortBinding> hostPorts = new ArrayList<>();
|
||||
hostPorts.add(PortBinding.of("0.0.0.0", port));
|
||||
portBindings.put(port, hostPorts);
|
||||
}
|
||||
|
||||
// Bind container port 443 to an automatically allocated available host port.
|
||||
List<PortBinding> randomPort = new ArrayList<>();
|
||||
randomPort.add(PortBinding.randomPort("0.0.0.0"));
|
||||
portBindings.put("449", randomPort);
|
||||
|
||||
final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();
|
||||
|
||||
|
||||
//设置ip地址192.168.0.13
|
||||
final EndpointConfig endpointConfig = EndpointConfig.builder()
|
||||
// .ipAddress("192.168.0.12").gateway("192.168.0.1")
|
||||
.ipamConfig(EndpointConfig.EndpointIpamConfig.builder().ipv4Address("192.168.0.20").build())
|
||||
|
||||
.build();
|
||||
|
||||
//networkmode指定设置的网络
|
||||
// final HostConfig hostConfig = HostConfig.builder().networkMode("aaapp").build();
|
||||
Map datamap = new HashMap();
|
||||
datamap.put("aaapp", endpointConfig);
|
||||
final ContainerConfig config = ContainerConfig.builder()
|
||||
.hostConfig(hostConfig).exposedPorts(ports)
|
||||
.networkingConfig(ContainerConfig.NetworkingConfig.create(datamap))
|
||||
.image("dockerzook").cmd("sh", "-c", "while :; do sleep 1; done")
|
||||
.build();
|
||||
|
||||
|
||||
// final ContainerCreation container = docker.createContainer(config);
|
||||
ContainerCreation container = docker.createContainer(config, "181998881");
|
||||
//????
|
||||
docker.startContainer(container.id());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void mainpp(String args[]) {
|
||||
final DockerClient docker = new DefaultDockerClient("unix:///var/run/docker.sock");
|
||||
List data = new ArrayList();
|
||||
try {
|
||||
List<Container> containers = docker.listContainers(DockerClient.ListContainersParam.allContainers());
|
||||
for (int i = 0; i < containers.size(); i++) {
|
||||
DockerBean bean = new DockerBean();
|
||||
Container container = containers.get(i);
|
||||
String state = container.state();//????
|
||||
String image = container.image();//????
|
||||
|
||||
com.google.common.collect.ImmutableList<String> listdata = container.names();
|
||||
String names = listdata.get(0).toString();
|
||||
// com.google.common.collect.ImmutableSet<AttachedNetwork> networks
|
||||
|
||||
com.google.common.collect.UnmodifiableIterator iterators = container.networkSettings().networks().asMultimap().entries().iterator();
|
||||
// Map map = container.networkSettings().networks().asMultimap().asMap();
|
||||
ImmutableSet<Map.Entry<String, AttachedNetwork>> networks = container.networkSettings().networks().entrySet();
|
||||
AttachedNetwork o = (AttachedNetwork) networks.toArray()[0];
|
||||
|
||||
// ((com.google.common.collect.ImmutableEntry)networks.toArray()[0]).getValue();
|
||||
// networks.toArray()[0]
|
||||
// ((com.google.common.collect.ImmutableEntry)networks.toArray()[0]).getValue();
|
||||
// Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
|
||||
while (iterators.hasNext()) {
|
||||
iterators.next();
|
||||
|
||||
// com.google.common.collect.SingletonImmutableSet datavalue=(com.google.common.collect.SingletonImmutableSet)entry.getValue();
|
||||
// datavalue.ipAddress();
|
||||
// System.out.println("key= " + entry.getKey() + " and value= " + datavalue.ipAddress());
|
||||
}
|
||||
|
||||
//.get("bridge");
|
||||
String ipaddress = "";
|
||||
//((AttachedNetwork) networks.toArray()[0]).ipAddress();//ip??
|
||||
// String dates = transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long) container.created());
|
||||
bean.setIpaddress(ipaddress);
|
||||
bean.setImage(image);
|
||||
bean.setState(state);
|
||||
// bean.setDates(dates);
|
||||
bean.setNames(names);
|
||||
data.add(bean);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import com.wb.util.StringUtil;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESKeySpec;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/**
|
||||
* 提供常用的加密/解密方法。
|
||||
*/
|
||||
public class Encrypter {
|
||||
/**
|
||||
* DES字符常量。
|
||||
*/
|
||||
private static final String des = "DES";
|
||||
/**
|
||||
* MD5 16进制转码时的映射字母表。
|
||||
*/
|
||||
private static final String keyMap = "C2E8D9A3B5F14607";
|
||||
|
||||
/**
|
||||
* 使用密钥通过DES算法加密指定的文本。
|
||||
*
|
||||
* @param text
|
||||
* 需要加密的文本。
|
||||
* @param key
|
||||
* 8位字节的密钥。
|
||||
* @return 加密后的文本。
|
||||
* @throws Exception
|
||||
* 加密过程发生异常。
|
||||
*/
|
||||
public static String encrypt(String text, String key) throws Exception {
|
||||
return StringUtil.encodeBase64(encrypt(text.getBytes("utf-8"), key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用密钥解密通过DES算法加密的文本。
|
||||
*
|
||||
* @param text
|
||||
* 需要解密的文本。
|
||||
* @param key
|
||||
* 8位字节的密钥。
|
||||
* @return 解密后的文本。
|
||||
* @throws Exception
|
||||
* 解密过程发生异常。
|
||||
*/
|
||||
public static String decrypt(String text, String key) throws Exception {
|
||||
return new String(decrypt(StringUtil.decodeBase64(text), key), "utf-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用密钥通过DES算法加密指定的字节。
|
||||
*
|
||||
* @param bytes
|
||||
* 需要加密的字节。
|
||||
* @param key
|
||||
* 8位字节的密钥。
|
||||
* @return 加密后的字节。
|
||||
* @throws Exception
|
||||
* 加密过程发生异常。
|
||||
*/
|
||||
public static byte[] encrypt(byte[] bytes, String key) throws Exception {
|
||||
byte[] keyBytes = key.getBytes("utf-8");
|
||||
SecureRandom sr = new SecureRandom();
|
||||
DESKeySpec dks = new DESKeySpec(keyBytes);
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(des);
|
||||
SecretKey securekey = keyFactory.generateSecret(dks);
|
||||
Cipher cipher = Cipher.getInstance(des);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
|
||||
return cipher.doFinal(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用密钥解密通过DES算法加密的字节。
|
||||
*
|
||||
* @param bytes
|
||||
* 需要解密的字节。
|
||||
* @param key
|
||||
* 8位字节的密钥。
|
||||
* @return 解密后的字节。
|
||||
* @throws Exception
|
||||
* 解密过程发生异常。
|
||||
*/
|
||||
public static byte[] decrypt(byte[] bytes, String key) throws Exception {
|
||||
byte[] keyBytes = key.getBytes("utf-8");
|
||||
SecureRandom sr = new SecureRandom();
|
||||
DESKeySpec dks = new DESKeySpec(keyBytes);
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(des);
|
||||
SecretKey securekey = keyFactory.generateSecret(dks);
|
||||
Cipher cipher = Cipher.getInstance(des);
|
||||
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
|
||||
return cipher.doFinal(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对指定文本使用MD5算法进行加密,使用此加密算法获得的值不可解密。
|
||||
*
|
||||
* @param bytes
|
||||
* 需要加密的字节。
|
||||
* @return 32位16进制字符组成的密码。
|
||||
* @throws Exception
|
||||
* 加密过程中发生异常。
|
||||
*/
|
||||
public static String getMD5(String text) throws Exception {
|
||||
return getMD5(text.getBytes("utf-8"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 对指定字节使用MD5算法进行加密,使用此加密算法获得的值不可解密。
|
||||
*
|
||||
* @param bytes
|
||||
* 需要加密的字节。
|
||||
* @return 32位16进制字符组成的密码。
|
||||
* @throws Exception
|
||||
* 加密过程中发生异常。
|
||||
*/
|
||||
public static String getMD5(byte[] bytes) throws Exception {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(bytes);
|
||||
byte bt, codes[] = md.digest();
|
||||
char str[] = new char[32];
|
||||
int i, j = 0;
|
||||
for (i = 0; i < 16; i++) {
|
||||
bt = codes[i];
|
||||
str[j++] = keyMap.charAt(bt >>> 4 & 0xf);
|
||||
str[j++] = keyMap.charAt(bt & 0xf);
|
||||
}
|
||||
return new String(str);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import com.google.common.eventbus.EventBus;
|
||||
|
||||
/**
|
||||
* 订阅中心类
|
||||
* @author running
|
||||
* @since 2020-11-01
|
||||
*/
|
||||
public class EventBusCenter {
|
||||
|
||||
private static EventBus eventBus = new EventBus();
|
||||
|
||||
private EventBusCenter() {
|
||||
|
||||
}
|
||||
|
||||
public static EventBus getInstance() {
|
||||
return eventBus;
|
||||
}
|
||||
|
||||
public static void register(Object obj) {
|
||||
eventBus.register(obj);
|
||||
}
|
||||
|
||||
public static void unregister(Object obj) {
|
||||
eventBus.unregister(obj);
|
||||
}
|
||||
|
||||
public static void post(Object obj) {
|
||||
eventBus.post(obj);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
public class Message {
|
||||
|
||||
/**
|
||||
* 类型
|
||||
*/
|
||||
public enum Type {
|
||||
|
||||
|
||||
/** 成功 */
|
||||
success,
|
||||
|
||||
/** 警告 */
|
||||
warn,
|
||||
|
||||
/** 错误 */
|
||||
error
|
||||
}
|
||||
|
||||
/** 类型 */
|
||||
private Type type;
|
||||
|
||||
/** 内容 */
|
||||
private String content;
|
||||
|
||||
/**
|
||||
* 初始化一个新创建的 Message 对象,使其表示一个空消息。
|
||||
*/
|
||||
public Message() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化一个新创建的 Message 对象
|
||||
*
|
||||
* @param type
|
||||
* 类型
|
||||
* @param content
|
||||
* 内容
|
||||
*/
|
||||
public Message(Type type, String content) {
|
||||
this.type = type;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param type
|
||||
* 类型
|
||||
* @param content
|
||||
* 内容
|
||||
* @param args
|
||||
* 参数
|
||||
*/
|
||||
public Message(Type type, String content, Object... args) {
|
||||
this.type = type;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功消息
|
||||
*
|
||||
* @param content
|
||||
* 内容
|
||||
* @param args
|
||||
* 参数
|
||||
* @return 成功消息
|
||||
*/
|
||||
public static Message success(String content, Object... args) {
|
||||
return new Message(Type.success, content, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回警告消息
|
||||
*
|
||||
* @param content
|
||||
* 内容
|
||||
* @param args
|
||||
* 参数
|
||||
* @return 警告消息
|
||||
*/
|
||||
public static Message warn(String content, Object... args) {
|
||||
return new Message(Type.warn, content, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回错误消息
|
||||
*
|
||||
* @param content
|
||||
* 内容
|
||||
* @param args
|
||||
* 参数
|
||||
* @return 错误消息
|
||||
*/
|
||||
public static Message error(String content, Object... args) {
|
||||
return new Message(Type.error, content, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取类型
|
||||
*
|
||||
* @return 类型
|
||||
*/
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置类型
|
||||
*
|
||||
* @param type
|
||||
* 类型
|
||||
*/
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内容
|
||||
*
|
||||
* @return 内容
|
||||
*/
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容
|
||||
*
|
||||
* @param content
|
||||
* 内容
|
||||
*/
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return content;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import com.wb.util.DbUtil;
|
||||
import com.wb.util.WebUtil;
|
||||
import org.apache.poi.hwpf.HWPFDocument;
|
||||
import org.apache.poi.hwpf.usermodel.*;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class ReadWord {
|
||||
|
||||
static String billNBr="", shipper="",Consignee="",notify="",customNo="",shipvoyage="" ,shipNam="",voyageNo="",startport=""
|
||||
,disport="",destport="",Receipt="",mark="",pkgs="",cargoNam="",kgs="",vol="";
|
||||
|
||||
public static void upload(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
billNBr=""; shipper="";Consignee="";notify="";customNo="";shipvoyage="";shipNam="";voyageNo="";startport="";
|
||||
disport="";destport="";Receipt="";mark="";pkgs="";cargoNam="";kgs="";vol="";
|
||||
InputStream stream = (InputStream) request.getAttribute("file");
|
||||
String filename = (String) request.getAttribute("filename");
|
||||
if (filename == null)
|
||||
filename = (String) request.getAttribute("file__name");
|
||||
int count=0;
|
||||
testWord(stream,filename);
|
||||
File destPath, syncPath;
|
||||
shipNam= shipvoyage.split("V.")[0];
|
||||
voyageNo= shipvoyage.split("V.")[1];
|
||||
String num= pkgs.split(" ")[0];
|
||||
String pagekge= pkgs.split(" ")[1];
|
||||
int piece=Integer.parseInt(num);
|
||||
Double wgk=Double.parseDouble(kgs.replace("KGS",""));
|
||||
Double volem=Double.parseDouble(vol.replace("CBM",""));
|
||||
Connection conn=null;
|
||||
PreparedStatement s=null;
|
||||
try{
|
||||
conn= DbUtil.getConnection();
|
||||
s= conn.prepareStatement("update F_VBILL_QD_HEAD set E_SHIPPER_NAM=? ,E_CONSIGNEE_NAM=?,E_NOTIFY_NAM=?,VESSEL_NAME=? ,VESSEL_VOY='"+voyageNo+"' , POL_NAME ='"+startport+"'" +
|
||||
",POD_NAME='"+disport+"',PODEST_NAME='"+destport+"',POS_NAME='"+Receipt+"', TD_MARKS_STR=?,TD_E_CARGO_NAM=?,TD_PIECE_NUM="+piece+",TD_GWEIGHT_TON="+wgk+",TD_GVOL_NUM="+volem+" where LINE_BK_NO='"+billNBr+"' ");
|
||||
// String sql ="update F_VBILL_QD_HEAD set E_SHIPPER_NAM='"+shipper+"' ,E_CONSIGNEE_NAM='"+Consignee+"',E_NOTIFY_NAM='"+notify+"',VESSEL_NAME='"+shipNam+"' ,VESSEL_VOY='"+voyageNo+"' , POL_NAME ='"+startport+"'" +
|
||||
// ",POD_NAME='"+disport+"',PODEST_NAME='"+destport+"',POS_NAME='"+Receipt+"', TD_MARKS_STR='"+mark+"',TD_E_CARGO_NAM='"+cargoNam+"',TD_PIECE_NUM="+piece+",TD_GWEIGHT_TON="+wgk+",TD_GVOL_NUM="+volem+" where LINE_BK_NO='"+billNBr+"' ";
|
||||
s.setString(1,shipper);
|
||||
s.setString(2,Consignee);
|
||||
s.setString(3,notify);
|
||||
s.setString(4,shipNam);
|
||||
s.setString(5,mark);
|
||||
s.setString(6,cargoNam);
|
||||
count= s.executeUpdate();
|
||||
|
||||
|
||||
}
|
||||
catch(Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally {
|
||||
DbUtil.close(s);
|
||||
DbUtil.close(conn);
|
||||
|
||||
WebUtil.send(response,count+"",true);
|
||||
}
|
||||
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
ReadWord test = new ReadWord();
|
||||
//String filePath="E:\\java??word??.doc";
|
||||
String filePath="E:\\23512.doc";
|
||||
// test.testWord(filePath);
|
||||
}
|
||||
public static void testWord(InputStream in, String filePath ){
|
||||
|
||||
try{
|
||||
// FileInputStream in = new FileInputStream(filePath);//????
|
||||
//???office2007 docx??
|
||||
if(filePath.toLowerCase().endsWith("docx")){
|
||||
//word 2007 ???????? ????????????????
|
||||
XWPFDocument xwpf = new XWPFDocument(in);//??word?????
|
||||
// List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();//??????
|
||||
Iterator<XWPFTable> it = xwpf.getTablesIterator();//??word????
|
||||
while(it.hasNext()){
|
||||
XWPFTable table = it.next();
|
||||
List<XWPFTableRow> rows=table.getRows();
|
||||
//???????
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
XWPFTableRow row = rows.get(i);
|
||||
//???????
|
||||
List<XWPFTableCell> cells = row.getTableCells();
|
||||
for (int j = 0; j < cells.size(); j++) {
|
||||
XWPFTableCell cell=cells.get(j);
|
||||
//???????????
|
||||
System.out.println(cell.getText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}else{
|
||||
//???office2003 doc??
|
||||
POIFSFileSystem pfs = new POIFSFileSystem(in);
|
||||
HWPFDocument hwpf = new HWPFDocument(pfs);
|
||||
Range range = hwpf.getRange();//?????????
|
||||
TableIterator it = new TableIterator(range);
|
||||
//????????
|
||||
while (it.hasNext()) {
|
||||
Table tb = (Table) it.next();
|
||||
//???????0??
|
||||
for (int i = 0; i < tb.numRows(); i++) {
|
||||
TableRow tr = tb.getRow(i);
|
||||
//???????0??
|
||||
for (int j = 0; j < tr.numCells(); j++) {
|
||||
TableCell td = tr.getCell(j);//?????
|
||||
|
||||
//????????
|
||||
for(int k=0;k<td.numParagraphs();k++){
|
||||
Paragraph para =td.getParagraph(k);
|
||||
|
||||
String s = para.text();
|
||||
//?????????
|
||||
if(null!=s&&!"".equals(s)){
|
||||
s=s.substring(0, s.length()-1);
|
||||
getString( i, j , s);
|
||||
// System.out.print(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch(Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
// System.out.print(billNBr+"=="+shipper+"=="+Consignee+"=="+notify+"=="+customNo+"=="+shipvoyage+"=="+startport+ "=="+disport+"=="+destport+"=="+Receipt+"=="+mark+"=="+pkgs+"=="+cargoNam+"=="+kgs+"=="+vol);
|
||||
}
|
||||
|
||||
private static void getString(int i,int j ,String s)
|
||||
{
|
||||
if(i==2&&j==2)
|
||||
billNBr=s;
|
||||
else if(i==3&&j==0)
|
||||
shipper+=s;
|
||||
else if(i==8&&j==0)
|
||||
Consignee+=s;
|
||||
else if(i==12&&j==0)
|
||||
notify+=s;
|
||||
else if(i==5&&j==0)
|
||||
customNo+=s;
|
||||
else if(i==15&&j==1)
|
||||
Receipt+=s;
|
||||
else if(i==17&&j==0)
|
||||
shipvoyage+=s;
|
||||
else if(i==17&&j==0)
|
||||
shipvoyage+=s;
|
||||
else if(i==17&&j==1)
|
||||
startport+=s;
|
||||
else if(i==19&&j==0)
|
||||
disport+=s;
|
||||
else if(i==19&&j==1)
|
||||
destport+=s;
|
||||
else if(i==21&&j==0)
|
||||
mark+=s;
|
||||
else if(i==21&&j==1)
|
||||
pkgs+=s;
|
||||
else if(i==21&&j==2)
|
||||
cargoNam+=s;
|
||||
else if(i==21&&j==3)
|
||||
kgs+=s;
|
||||
else if(i==21&&j==4)
|
||||
vol+=s;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* Created by shaoqiang on 8/6/16.
|
||||
*/
|
||||
public class SyscomputeUtil {
|
||||
/**
|
||||
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
|
||||
* 定精度,以后的数字四舍五入。
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @param scale 表示表示需要精确到小数点以后几位。
|
||||
* @return 两个参数的商
|
||||
*/
|
||||
public static double div(double v1, double v2, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
package com.ag.secp.platform.common;
|
||||
|
||||
import com.wb.common.Base;
|
||||
import com.wb.interact.IDE;
|
||||
import com.wb.util.WebUtil;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.ResultSet;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* 修改wb框架应用
|
||||
*/
|
||||
//@Component
|
||||
public class WbUtil {
|
||||
|
||||
|
||||
static String[] iconarr={"fa-home","fa-laptop","fa-book","fa-cogs","fa-bullhorn",
|
||||
"fa-envelope","fa-tasks","fa-bar-chart-o","fa-th-list","fa-map-marker","fa-file-text"};
|
||||
static String[] sa={"fa-home","fa-laptop","fa-book","fa-cogs","fa-bullhorn",
|
||||
"fa-envelope","fa-tasks","fa-bar-chart-o","fa-th-list","fa-map-marker","fa-file-text"};
|
||||
|
||||
private static void getModuleList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
|
||||
getBasicsList(request, response, 1);
|
||||
}
|
||||
public static void getBasicsListsession(HttpServletRequest request,HttpServletResponse response){
|
||||
String menuid=request.getParameter("subsId");
|
||||
request.getSession().setAttribute("menuid",menuid);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void getBasicsListA(HttpServletRequest request,HttpServletResponse response) throws Exception {
|
||||
String menuid=request.getParameter("subsId");
|
||||
request.getSession().setAttribute("menuid",menuid);
|
||||
int type=1;
|
||||
String userid= (String) request.getSession().getAttribute("sys.user");
|
||||
String menuida="";
|
||||
if(request.getSession().getAttribute("menuid")!=null) {
|
||||
menuida = (String) request.getSession().getAttribute("menuid");
|
||||
}
|
||||
//String iconarr[]={"fa-laptop","fa-cogs","fa-bullhorn","fa-envelope","fa-bar-chart-o"};
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String sqlRoleA="SELECT *\n" +
|
||||
" FROM wb_menu\n" +
|
||||
" WHERE menu_id IN\n" +
|
||||
" (SELECT DISTINCT parent_menu\n" +
|
||||
" FROM wb_menu wm, wb_role_resource wrr\n" +
|
||||
" WHERE wm.menu_id = wrr.menu_id\n" +
|
||||
" AND wrr.role_id IN (SELECT role_id\n" +
|
||||
" FROM wb_user_role\n" +
|
||||
" WHERE user_id ='"+userid+"'\n" +
|
||||
" AND wm.parent_menu IN\n" +
|
||||
" (SELECT menu_id\n" +
|
||||
" FROM wb_menu\n" +
|
||||
" WHERE parent_menu ='"+menuida+"' \n" +
|
||||
" AND menu_type = '0')))\n" +
|
||||
" ORDER BY order_index ";
|
||||
ResultSet roles = (ResultSet) com.wb.util.DbUtil.run(request,sqlRoleA);
|
||||
int i=0;
|
||||
while (roles.next()) {
|
||||
String icon="fa-book";
|
||||
if(iconarr[i]==null){
|
||||
icon="fa-book";
|
||||
}else{
|
||||
icon=iconarr[i];
|
||||
}
|
||||
sb.append("<li class=\"menu-list\">");
|
||||
sb.append("<a>");
|
||||
sb.append("<i class=\"fa "+icon+"\"></i>");
|
||||
sb.append("<span>"+roles.getString("MENU_NAME")+"</span>");
|
||||
sb.append("<span class=\"pull-right-container\"><i class=\"fa fa-angle-left pull-right\"></i></span>");
|
||||
sb.append("</a>");
|
||||
String sqlRoleA1 = "SELECT *\n" +
|
||||
" FROM wb_menu\n" +
|
||||
" WHERE parent_menu ='"+roles.getString("MENU_ID")+"'\n" +
|
||||
" AND menu_id IN\n" +
|
||||
" (SELECT menu_id\n" +
|
||||
" FROM wb_user_role, wb_role_resource\n" +
|
||||
" WHERE wb_user_role.role_id = wb_role_resource.role_id\n" +
|
||||
" AND user_id ='"+userid+"')\n" +
|
||||
" ORDER BY order_index";
|
||||
ResultSet roles1 = (ResultSet) com.wb.util.DbUtil.run(request,sqlRoleA1);
|
||||
sb.append("<ul class=\"sub-menu-list\">");
|
||||
while (roles1.next()) {
|
||||
|
||||
sb.append("<li>");
|
||||
sb.append("<a onclick=\"changeurl('" + roles1.getString("MENU_URL") + "','" + roles1.getString("MENU_NAME") + "','',false,'null' )\">"
|
||||
+"<i class=\"fa fa-circle-o\"></i>"+ roles1.getString("MENU_NAME") + "</a>");
|
||||
sb.append("</li>");
|
||||
|
||||
}
|
||||
sb.append("</ul>");
|
||||
sb.append("</li>");
|
||||
i++;
|
||||
}
|
||||
request.getSession().setAttribute("basicsLust", sb.toString());
|
||||
com.wb.util.WebUtil.send(response, sb.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模块列表树的节点列表。
|
||||
* @param type 数据请求来源类型,1:主页,2:权限模块,3:用户模块。
|
||||
*/
|
||||
private static void getBasicsList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
|
||||
//String iconarr[]={"fa-laptop","fa-cogs","fa-bullhorn","fa-envelope","fa-bar-chart-o"};
|
||||
//AgCommonService agCommonService = new AgCommonService();
|
||||
String username= (String) request.getSession().getAttribute("sys.user");
|
||||
String menuida="";
|
||||
if(request.getSession().getAttribute("sys.menuid")!=null) {
|
||||
menuida = (String) request.getSession().getAttribute("sys.menuid");
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String sqlRole = "SELECT *\n" +
|
||||
" FROM wb_menu\n" +
|
||||
" WHERE menu_id IN\n" +
|
||||
" (SELECT DISTINCT parent_menu\n" +
|
||||
" FROM wb_menu wm, wb_role_resource wrr\n" +
|
||||
" WHERE wm.menu_id = wrr.menu_id\n" +
|
||||
" AND wrr.role_id = '"+username+"'\n" +
|
||||
" AND wm.parent_menu IN\n" +
|
||||
" (SELECT menu_id\n" +
|
||||
" FROM wb_menu\n" +
|
||||
" WHERE parent_menu ='"+menuida+"' AND menu_type = '0'))\n" +
|
||||
" ORDER BY order_index";
|
||||
ResultSet roles = (ResultSet) com.wb.util.DbUtil.run(request,sqlRole);
|
||||
int i=0;
|
||||
while(roles.next()){
|
||||
String icon="fa-book";
|
||||
if(iconarr[i]==null){
|
||||
icon="fa-book";
|
||||
}else{
|
||||
icon=iconarr[i];
|
||||
}
|
||||
sb.append("<li class=\"menu-list\">");
|
||||
sb.append("<a>");
|
||||
sb.append("<i class=\"fa "+icon+"\"></i>");
|
||||
sb.append("<span>"+roles.getString("MENU_NAME")+"</span>");
|
||||
sb.append("<span class=\"pull-right-container\"><i class=\"fa fa-angle-left pull-right\"></i></span>");
|
||||
sb.append("</a>");
|
||||
String sqlRole1 = " select wm.*,role_id from wb_menu wm,wb_role_resource wrr where wm.menu_id=wrr.menu_id\n" +
|
||||
" and wm.parent_menu = '"+roles.getString("MENU_ID")+"' and wrr.role_id='"+username+"'\n" +
|
||||
" order by order_index";
|
||||
ResultSet role1 = (ResultSet) com.wb.util.DbUtil.run(request,sqlRole1);
|
||||
sb.append("<ul class=\"sub-menu-list\">");
|
||||
while(role1.next()){
|
||||
|
||||
sb.append("<li>");
|
||||
sb.append("<a onclick=\"changeurl('"+role1.getString("MENU_URL")+"','"+role1.getString("MENU_NAME")+"','',false,'null' )\">"
|
||||
+"<i class=\"fa fa-circle-o\"></i>"+role1.getString("MENU_NAME")+"</a>");
|
||||
sb.append("</li>");
|
||||
|
||||
}
|
||||
sb.append("</ul>");
|
||||
sb.append("</li>");
|
||||
i++;
|
||||
}
|
||||
request.setAttribute("basicsLust", sb.toString());
|
||||
}
|
||||
|
||||
public static String getStringBuffer1(JSONObject o,int i)
|
||||
{
|
||||
|
||||
StringBuffer str=new StringBuffer("<li class=\"menu-list\"><a ><i class=\""+sa[i]+"\"></i> " +
|
||||
"<span>"+o.get("text")+"</span></a><ul class=\"sub-menu-list\">");
|
||||
return str.toString();
|
||||
|
||||
}
|
||||
public static String getStringBuffer2(JSONObject o)
|
||||
{
|
||||
Object pageLink=null;
|
||||
if(!o.isNull("pageLink"))
|
||||
pageLink=o.get("pageLink").toString().replace("'", "*");
|
||||
StringBuffer str=new StringBuffer("<li><a onclick=\"changeurl('"+o.get("path")+"','"+o.get("text")+"','"+o.get("iconCls")+"',"+o.get("inframe")+" ,'"+pageLink+"' )\"> "+"<i class=\"fa fa-circle-o\"></i>"+o.get("text")+"</a></li>");
|
||||
return str.toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static String getModuleListNext(HttpServletRequest request,
|
||||
HttpServletResponse response, int type,String path2) throws Exception {
|
||||
String path = path2;
|
||||
String iconCls, fileName, pageLink, relPath, title;
|
||||
File file, base;
|
||||
int displayType = (type == 1 ? 1 : 3);
|
||||
String[] roles = com.wb.common.Session.getRoles(request);
|
||||
|
||||
if (path == null)
|
||||
base = com.wb.common.Base.modulePath;
|
||||
else {
|
||||
base = new File(com.wb.common.Base.modulePath, path);
|
||||
if (!com.wb.util.FileUtil.isAncestor(com.wb.common.Base.modulePath, base))
|
||||
com.wb.util.SysUtil.accessDenied();
|
||||
}
|
||||
path = path + "/";
|
||||
ArrayList<Entry<String, Integer>> fileNames = IDE.getSortedFile(base);
|
||||
JSONObject content = null, fileObject;
|
||||
JSONArray fileArray;
|
||||
boolean isFolder;
|
||||
StringBuffer str=new StringBuffer("");
|
||||
fileArray = new JSONArray();
|
||||
for (Entry<String, Integer> entry : fileNames) {
|
||||
fileName = entry.getKey();
|
||||
file = new File(base, fileName);
|
||||
// 文件列表取自配置文件,如果不存在返回
|
||||
if (!file.exists())
|
||||
continue;
|
||||
if (!com.wb.common.XwlBuffer.canDisplay(file, roles, displayType))
|
||||
continue;
|
||||
isFolder = file.isDirectory();
|
||||
if (isFolder) {
|
||||
if (type != 1 && !hasLoginModule(file))
|
||||
continue;
|
||||
File configFile = new File(file, "folder.json");
|
||||
if (configFile.exists())
|
||||
content = com.wb.util.JsonUtil.readObject(configFile);
|
||||
else
|
||||
content = new JSONObject();
|
||||
} else {
|
||||
// 如果设置模块权限且非模块文件则返回
|
||||
if (type != 1 && !file.getName().endsWith(".xwl"))
|
||||
continue;
|
||||
content = com.wb.common.XwlBuffer.get(path + fileName, false);
|
||||
// 无需登录的模块不允许设置权限
|
||||
if (type != 1
|
||||
&& Boolean.FALSE.equals(content.opt("loginRequired")))
|
||||
continue;
|
||||
}
|
||||
fileObject = new JSONObject();
|
||||
title = content.optString("title");
|
||||
if (title.startsWith("Str."))
|
||||
title = com.wb.common.Str.format(request, title.substring(4));
|
||||
fileObject.put("text", com.wb.util.StringUtil.select(title, fileName));
|
||||
relPath = com.wb.util.FileUtil.getModulePath(file);
|
||||
fileObject.put("path", relPath);
|
||||
fileObject.put("fileName", fileName);
|
||||
fileObject.put("inframe", Boolean.TRUE.equals(content
|
||||
.opt("inframe")));
|
||||
if (isFolder) {
|
||||
if (!hasChildren(file))
|
||||
fileObject.put("children", new JSONArray());
|
||||
|
||||
continue;
|
||||
} else {
|
||||
pageLink = (String) content.opt("pageLink");
|
||||
if (!com.wb.util.StringUtil.isEmpty(pageLink))
|
||||
fileObject.put("pageLink", pageLink);
|
||||
|
||||
fileObject.put("leaf", true);
|
||||
}
|
||||
fileObject.put("cls", "wb_pointer");
|
||||
iconCls = content.optString("iconCls");
|
||||
//if (!StringUtil.isEmpty(iconCls))
|
||||
fileObject.put("iconCls", iconCls);
|
||||
if (type == 2 && !isFolder)
|
||||
fileObject.put("checked", false);
|
||||
str.append(getStringBuffer2(fileObject));
|
||||
|
||||
|
||||
}
|
||||
return str.toString();
|
||||
}
|
||||
/**
|
||||
* 判断指定目录下是否具有需要登录的模块
|
||||
* @param path 目录路径。
|
||||
* @return true存在需要登录的模块,false不存在需要登录的模块。
|
||||
* @throws IOException
|
||||
*/
|
||||
private static boolean hasLoginModule(File path) throws IOException {
|
||||
File[] files = com.wb.util.FileUtil.listFiles(path);
|
||||
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
if (hasLoginModule(file))
|
||||
return true;
|
||||
} else {
|
||||
if (file.getName().endsWith(".xwl")) {
|
||||
JSONObject content = com.wb.common.XwlBuffer.get(com.wb.util.FileUtil
|
||||
.getModulePath(file), true);
|
||||
if (Boolean.TRUE.equals(content.opt("loginRequired")))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化主页。
|
||||
*/
|
||||
public static void initHome(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
String desktopString = com.wb.common.Resource.getString(request, "desktop", null);
|
||||
int treeWidth;
|
||||
boolean treeCollapsed, treeHidden;
|
||||
|
||||
if (desktopString == null)
|
||||
desktopString = com.wb.common.Resource.getString("sys.home.desktop", null);
|
||||
if (desktopString != null) {
|
||||
JSONObject desktop = new JSONObject(desktopString);
|
||||
treeWidth = desktop.optInt("treeWidth", 200);
|
||||
treeCollapsed = desktop.optBoolean("treeCollapsed", false);
|
||||
treeHidden = desktop.optBoolean("treeHidden", false);
|
||||
JSONArray pages = desktop.optJSONArray("pages");
|
||||
if (pages != null) {
|
||||
int i, j = pages.length(), activeIndex = desktop.optInt(
|
||||
"active", 0);
|
||||
String url, title, pageLink, params, rawUrl;
|
||||
JSONObject page, module, item;
|
||||
JSONArray tabItems = new JSONArray();
|
||||
for (i = 0; i < j; i++) {
|
||||
page = pages.optJSONObject(i);
|
||||
rawUrl = page.optString("url");
|
||||
url = com.wb.util.FileUtil.getModuleFile(rawUrl, true);
|
||||
module = com.wb.common.XwlBuffer.get(url, true);
|
||||
if (module == null) {
|
||||
if (i <= activeIndex)
|
||||
activeIndex--;
|
||||
} else {
|
||||
item = new JSONObject();
|
||||
item.put("url", rawUrl);
|
||||
title = (String) module.opt("title");
|
||||
if (title.startsWith("Str."))
|
||||
title = com.wb.common.Str.format(request, title.substring(4));
|
||||
item.put("title", com.wb.util.StringUtil.select(title, com.wb.util.FileUtil
|
||||
.getFilename(url)));
|
||||
item.put("iconCls", (String) module.opt("iconCls"));
|
||||
item.put("useIFrame", Boolean.TRUE.equals(module
|
||||
.opt("inframe")));
|
||||
params = page.optString("params");
|
||||
if (!com.wb.util.StringUtil.isEmpty(params))
|
||||
item.put("params", new JSONObject(params));
|
||||
pageLink = (String) module.opt("pageLink");
|
||||
if (!com.wb.util.StringUtil.isEmpty(pageLink))
|
||||
com.wb.util.JsonUtil.apply(item, new JSONObject(pageLink));
|
||||
tabItems.put(item);
|
||||
}
|
||||
}
|
||||
request.setAttribute("activeIndex", activeIndex);
|
||||
request.setAttribute("tabItems", com.wb.util.StringUtil.text(tabItems
|
||||
.toString()));
|
||||
}
|
||||
JSONArray portlets = desktop.optJSONArray("portlets");
|
||||
if (portlets != null) {
|
||||
int i, j = portlets.length(), k, l;
|
||||
String url, title, pageLink;
|
||||
JSONArray cols;
|
||||
JSONObject portlet, module;
|
||||
for (i = 0; i < j; i++) {
|
||||
cols = portlets.optJSONArray(i);
|
||||
l = cols.length();
|
||||
for (k = 0; k < l; k++) {
|
||||
portlet = cols.optJSONObject(k);
|
||||
url = com.wb.util.FileUtil.getModuleFile(portlet.optString("url"),
|
||||
true);
|
||||
module = com.wb.common.XwlBuffer.get(url, true);
|
||||
if (module == null) {
|
||||
cols.remove(k);
|
||||
k--;
|
||||
l--;
|
||||
continue;
|
||||
}
|
||||
title = (String) module.opt("title");
|
||||
if (title.startsWith("Str."))
|
||||
title = com.wb.common.Str.format(request, title.substring(4));
|
||||
portlet.put("title", com.wb.util.StringUtil.select(title, com.wb.util.FileUtil
|
||||
.getFilename(url)));
|
||||
portlet.put("iconCls", (String) module.opt("iconCls"));
|
||||
portlet.put("useIFrame", Boolean.TRUE.equals(module
|
||||
.opt("inframe")));
|
||||
pageLink = (String) module.opt("pageLink");
|
||||
if (!com.wb.util.StringUtil.isEmpty(pageLink))
|
||||
com.wb.util.JsonUtil.apply(portlet, new JSONObject(pageLink));
|
||||
}
|
||||
}
|
||||
request.setAttribute("portlets", com.wb.util.StringUtil.text(portlets
|
||||
.toString()));
|
||||
}
|
||||
} else {
|
||||
treeWidth = 200;
|
||||
treeCollapsed = false;
|
||||
treeHidden = false;
|
||||
}
|
||||
request.setAttribute("treeWidth", treeWidth);
|
||||
request.setAttribute("treeCollapsed", treeCollapsed);
|
||||
request.setAttribute("treeHidden", treeHidden);
|
||||
request.setAttribute("hideSetDefaultDesktop", !com.wb.common.XwlBuffer.canAccess(
|
||||
request, "m?xwl=sys/portal/home/save-default-desktop"));
|
||||
request.setAttribute("hideSetAllDesktop", !com.wb.common.XwlBuffer.canAccess(request,
|
||||
"m?xwl=sys/portal/home/save-all-desktop"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取主页应用列表树的节点列表。
|
||||
*/
|
||||
public static void getAppList(HttpServletRequest request,HttpServletResponse response) throws Exception {
|
||||
getModuleList(request, response, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前用户桌面。
|
||||
*/
|
||||
public static void saveDesktop(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
doSaveDesktop(request, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前桌面为默认桌面。
|
||||
*/
|
||||
public static void saveAsDefaultDesktop(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
doSaveDesktop(request, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前桌面为所有用户桌面。
|
||||
*/
|
||||
public static void saveAsAllDesktop(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
doSaveDesktop(request, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存桌面信息。
|
||||
* @param request 请求对象。
|
||||
* @param type 保存类型,1当前用户桌面,2默认桌面,3所有桌面
|
||||
*/
|
||||
private static void doSaveDesktop(HttpServletRequest request, int type)
|
||||
throws Exception {
|
||||
JSONObject desktop = new JSONObject();
|
||||
desktop.put("treeWidth", Integer.parseInt(request
|
||||
.getParameter("treeWidth")));
|
||||
desktop.put("treeCollapsed", Boolean.parseBoolean(request
|
||||
.getParameter("treeCollapsed")));
|
||||
desktop.put("treeHidden", Boolean.parseBoolean(request
|
||||
.getParameter("treeHidden")));
|
||||
desktop.put("pages", new JSONArray(request.getParameter("pages")));
|
||||
desktop
|
||||
.put("portlets",
|
||||
new JSONArray(request.getParameter("portlets")));
|
||||
desktop.put("active", Integer.parseInt(request.getParameter("active")));
|
||||
if (type == 1) {
|
||||
com.wb.common.Resource.set(request, "desktop", desktop.toString());
|
||||
} else {
|
||||
if (type == 3)
|
||||
com.wb.util.DbUtil
|
||||
.run(request,
|
||||
"delete from WB_RESOURCE where RES_ID like 'desktop@%'");
|
||||
com.wb.common.Resource.set("sys.home.desktop", desktop.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取权限模块列表树的节点列表。
|
||||
*/
|
||||
public static void getPermList(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
getModuleList(request, response, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户模块权限模块列表树的节点列表。
|
||||
*/
|
||||
public static void getUserPermList(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
getModuleList(request, response, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置桌面应用界面方案。
|
||||
*/
|
||||
public static void setTheme(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
String theme = request.getParameter("theme");
|
||||
|
||||
com.wb.common.Value.set(request, "theme", theme);
|
||||
com.wb.util.WebUtil.setSessionValue(request, "sys.theme", theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置移动应用界面方案。
|
||||
*/
|
||||
public static void setTouchTheme(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
String theme = request.getParameter("theme");
|
||||
|
||||
com.wb.common.Value.set(request, "touchTheme", theme);
|
||||
com.wb.util.WebUtil.setSessionValue(request, "sys.touchTheme", theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索模块目录下指定名称的模块。
|
||||
*/
|
||||
private static void searchModule(HttpServletRequest request,
|
||||
HttpServletResponse response, boolean isPerm) throws Exception {
|
||||
JSONArray array = new JSONArray();
|
||||
String query = request.getParameter("query").toLowerCase();
|
||||
|
||||
if (query.isEmpty())
|
||||
query = ".xwl";
|
||||
doSearchFile(request, Base.modulePath, query.toLowerCase(), "", "",
|
||||
array, isPerm);
|
||||
WebUtil.send(response, new JSONObject().put("rows", array));
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索主页模块目录下指定名称的模块。
|
||||
*/
|
||||
public static void searchAppModule(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
searchModule(request, response, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索权限模块目录下指定名称的模块。
|
||||
*/
|
||||
public static void searchPermModule(HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
searchModule(request, response, true);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 在指定目录下搜索文件。内部函数,用于递归搜索。
|
||||
* @param request 请求对象。
|
||||
* @param folder 目录。
|
||||
* @param searchName 查找的文件名称关键字,任何包括该关键字的文件均将被列举。
|
||||
* @param parentText 上级目录显示名称。
|
||||
* @param array 用于存放搜索结果。
|
||||
* @param isPerm 是否来自权限设置模块。
|
||||
* @return 是否完成搜索,如果搜索结果大于等于100项,将返回true,否则返回false。
|
||||
* @throws Exception 搜索过程中发生异常。
|
||||
*/
|
||||
private static boolean doSearchFile(HttpServletRequest request,
|
||||
File folder, String searchName, String parentText,
|
||||
String parentFile, JSONArray array, boolean isPerm)
|
||||
throws Exception {
|
||||
File files[] = com.wb.util.FileUtil.listFiles(folder);
|
||||
String path, title;
|
||||
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
File indexFile = new File(file, "folder.json");
|
||||
String folderTitle, folderFile;
|
||||
folderFile = file.getName();
|
||||
if (indexFile.exists()) {
|
||||
JSONObject jo = com.wb.util.JsonUtil.readObject(indexFile);
|
||||
if (!isPerm && Boolean.TRUE.equals(jo.opt("hidden")))
|
||||
continue;
|
||||
folderTitle = jo.optString("title");
|
||||
if (folderTitle.isEmpty())
|
||||
folderTitle = folderFile;
|
||||
} else
|
||||
folderTitle = folderFile;
|
||||
if (folderTitle.startsWith("Str."))
|
||||
folderTitle = com.wb.common.Str.format(request, folderTitle.substring(4));
|
||||
// 查找权限时只查找模块不查找目录
|
||||
if (!isPerm) {
|
||||
if (folderTitle.toLowerCase().indexOf(searchName) != -1) {
|
||||
JSONObject jo = new JSONObject();
|
||||
jo.put("path", parentText);
|
||||
jo.put("title", folderTitle);
|
||||
jo.put("file", folderFile);
|
||||
jo.put("parentFile", parentFile);
|
||||
array.put(jo);
|
||||
if (array.length() > 99)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (doSearchFile(request, file, searchName, com.wb.util.StringUtil.concat(
|
||||
parentText, "/", folderTitle), com.wb.util.StringUtil.concat(
|
||||
parentFile, "/", folderFile), array, isPerm))
|
||||
return true;
|
||||
} else {
|
||||
path = com.wb.util.FileUtil.getModulePath(file);
|
||||
if (path.endsWith(".xwl")) {
|
||||
JSONObject moduleData = com.wb.common.XwlBuffer.get(path, false);
|
||||
if (!isPerm
|
||||
&& Boolean.TRUE.equals(moduleData.opt("hidden")))
|
||||
continue;
|
||||
if (isPerm
|
||||
&& Boolean.FALSE.equals(moduleData
|
||||
.opt("loginRequired")))
|
||||
continue;
|
||||
title = moduleData.optString("title");
|
||||
if (title.isEmpty())
|
||||
title = path.substring(path.lastIndexOf('/') + 1);
|
||||
if (title.startsWith("Str."))
|
||||
title = com.wb.common.Str.format(request, title.substring(4));
|
||||
if (title.toLowerCase().indexOf(searchName) != -1) {
|
||||
JSONObject jo = new JSONObject();
|
||||
jo.put("path", parentText);
|
||||
jo.put("title", title);
|
||||
jo.put("file", file.getName());
|
||||
jo.put("parentFile", parentFile);
|
||||
array.put(jo);
|
||||
if (array.length() > 99)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断目录是否含可显示的子节点。
|
||||
*
|
||||
* @param dir 目录
|
||||
* @return true有子节点,false无子节点。
|
||||
*/
|
||||
private static boolean hasChildren(File dir) {
|
||||
File files[];
|
||||
files = com.wb.util.FileUtil.listFiles(dir);
|
||||
if (files == null)
|
||||
return false;
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
return true;
|
||||
} else if (!file.getName().equals("folder.json"))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 扫描模块控件下的子控件列表,获取Viewport控件,如果没有找到返回null。
|
||||
* @param
|
||||
* @return Viewport控件或null。
|
||||
*/
|
||||
private static JSONObject getViewport(JSONObject rootNode) throws Exception {
|
||||
int i, j;
|
||||
JSONObject jo;
|
||||
JSONArray items;
|
||||
JSONObject module = (JSONObject) ((JSONArray) rootNode.opt("children"))
|
||||
.opt(0);
|
||||
|
||||
items = (JSONArray) module.opt("children");
|
||||
if (items == null)
|
||||
return null;
|
||||
j = items.length();
|
||||
for (i = 0; i < j; i++) {
|
||||
jo = ((JSONObject) items.opt(i));
|
||||
if ("tviewport".equals(jo.opt("type")))
|
||||
return jo;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时间函数
|
||||
* @return
|
||||
*/
|
||||
public static Date getNowDate(){
|
||||
Date nowDate=new Date();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
try {
|
||||
nowDate=sdf.parse(sdf.format(new Date()));
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return nowDate;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package com.ag.secp.platform.filter;
|
||||
|
||||
import com.ag.util.StrUtil;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* sql注入过滤器
|
||||
*/
|
||||
public class AntiSqlInjectionFilter implements Filter {
|
||||
/**
|
||||
*排除链接
|
||||
*/
|
||||
public List<String> excludes = new ArrayList<>();
|
||||
/**
|
||||
* sql注入开关
|
||||
*/
|
||||
public boolean enabled = true;
|
||||
|
||||
@Test
|
||||
public void testPattern(){
|
||||
//String str = "' or 1=1 #";
|
||||
String str = "update\n";
|
||||
Matcher matcher=SQL_PATTERN.matcher(str.toLowerCase());
|
||||
System.out.println(matcher.find());
|
||||
}
|
||||
/**
|
||||
* 编译正则 sqlValidate()方法中有更加完整的字段防注入 可以补全下面的正则
|
||||
*/
|
||||
private static final Pattern SQL_PATTERN =
|
||||
Pattern.compile("\\b(select |update |and |or |delete |insert |trancate |" +
|
||||
"char |substr |ascii |declare |exec |count |master |into |drop |" +
|
||||
"execute " + ")\\b");
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(AntiSqlInjectionFilter.class);
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
String tempExcludes = filterConfig.getInitParameter("excludes");
|
||||
String tempEnabled = filterConfig.getInitParameter("enabled");
|
||||
if(!StringUtils.isEmpty(tempExcludes)){
|
||||
String[] url = tempExcludes.split(",");
|
||||
for (int i = 0; url != null && i < url.length; i++) {
|
||||
excludes.add(url[i]);
|
||||
}
|
||||
}
|
||||
if(!StringUtils.isEmpty(tempEnabled)){
|
||||
enabled = Boolean.parseBoolean(tempEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤 放行
|
||||
* @param servletRequest 请求
|
||||
* @param servletResponse 响应
|
||||
* @param filterChain 过滤链
|
||||
* @throws IOException IOException
|
||||
* @throws ServletException ServletException
|
||||
*/
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) servletRequest;
|
||||
HttpServletResponse res = (HttpServletResponse) servletResponse;
|
||||
SqlHttpServletRequestWrapper sqlRequest =null;
|
||||
//如果有不需要过滤的接口,放行
|
||||
if(handleExcludeURL(req,res)){
|
||||
filterChain.doFilter(servletRequest,servletResponse);
|
||||
return;
|
||||
}
|
||||
if (StrUtil.equals(req.getRequestURI(), "/transfer")){
|
||||
filterChain.doFilter(servletRequest,servletResponse);
|
||||
return;
|
||||
}
|
||||
Enumeration<String> parameterNames = req.getParameterNames();
|
||||
StringBuilder sql = new StringBuilder();
|
||||
while (parameterNames.hasMoreElements()) {
|
||||
//得到参数名
|
||||
String name = parameterNames.nextElement();
|
||||
//得到参数对应值
|
||||
String[] value = req.getParameterValues(name);
|
||||
for (int i = 0; i < value.length; i++) {
|
||||
//sql.append(value[i]);
|
||||
if (sqlValidateMatch(value[i].replaceAll("\\\\n", " "))) {
|
||||
//打印sql注入相关信息
|
||||
logger.warn("sql注入的uri===>"+req.getRequestURI());
|
||||
res.setContentType("application/json;charset=utf-8");
|
||||
res.getWriter().print("请不要尝试sql注入");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(servletRequest, res);
|
||||
/*String get = "GET";
|
||||
String post = "POST";
|
||||
//还有别的restful风格的验证也可以加入 视项目情况而定
|
||||
//有sql关键字,跳转到sql注入警告 ==>GET方式注入
|
||||
if(get.equals(req.getMethod())){
|
||||
// if (sqlValidate(sql.toString())) {
|
||||
if (sqlValidateMatch(sql.toString())) {
|
||||
//打印sql注入相关信息
|
||||
logger.warn("sql注入的uri===>"+req.getRequestURI());
|
||||
logger.warn("sql注入方式"+req.getMethod());
|
||||
res.setContentType("application/json;charset=utf-8");
|
||||
res.getWriter().print("请不要尝试sql注入");
|
||||
}
|
||||
else{
|
||||
filterChain.doFilter(servletRequest, res);
|
||||
}
|
||||
}
|
||||
//有sql关键字,跳转到sql注入警告 ==>POST方式注入
|
||||
else if(post.equals(req.getMethod())){
|
||||
sqlRequest = new SqlHttpServletRequestWrapper((HttpServletRequest) servletRequest);
|
||||
String bodyStr = getBodyString(sqlRequest.getReader());
|
||||
//这样可以判断body 不需要判断的可以添加excludes
|
||||
// if(bodyStr.contains("administrator")){
|
||||
// filterChain.doFilter(sqlRequest,servletResponse);
|
||||
// }
|
||||
// else if(sqlValidate(bodyStr)){
|
||||
// if(sqlValidate(bodyStr)){
|
||||
if(sqlValidateMatch(bodyStr)){
|
||||
//打印sql注入相关信息
|
||||
logger.warn("sql注入的uri===>"+req.getRequestURI());
|
||||
logger.warn("sql注入方式"+req.getMethod());
|
||||
res.setContentType("application/json;charset=utf-8");
|
||||
res.getWriter().print("请不要尝试sql注入");
|
||||
}
|
||||
else {
|
||||
filterChain.doFilter(sqlRequest,servletResponse);
|
||||
}
|
||||
}
|
||||
else {
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
}*/
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 效验过滤掉的sql关键字,可以手动添加
|
||||
* @param str 参数中的字符串
|
||||
* @return 是否有sql注入关键字
|
||||
*/
|
||||
protected static boolean sqlValidate(String str) {
|
||||
//统一转为小写
|
||||
str = str.toLowerCase();
|
||||
//这是sql注入的关键字 可以加 |再跟关键字进行补充 比如 |or
|
||||
String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +
|
||||
"char|declare|sitename|net user|xp_cmdshell|;|or|+|,|like'|and|exec|execute|insert|create|drop|" +
|
||||
"table|from|grant|use|group_concat|column_name|" +
|
||||
"information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
|
||||
"chr|mid|master|truncate|char|declare|or|;|--|+|,|like|//|/|%|#";
|
||||
//分隔并进行判断
|
||||
System.out.println(badStr+"badStr");
|
||||
String[] badStrs = badStr.split("\\|");
|
||||
for (int i = 0; i < badStrs.length; i++) {
|
||||
if (str.contains(" "+badStrs[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用正则表达式匹配sql注入 拦截更加智能
|
||||
* @param str 字符串
|
||||
* @return 是否有sql注入风险
|
||||
*/
|
||||
protected static boolean sqlValidateMatch(String str){
|
||||
return containsSqlInjection(str);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 字符串读取http请求的body
|
||||
* 此方法取出请求体的参数 防止post等方式的sql注入
|
||||
* 此方法会引起流重复调用报错 不建议使用
|
||||
* @param request request
|
||||
* @return 返回所有的请求体参数
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
@Deprecated
|
||||
String charReader(HttpServletRequest request) throws IOException {
|
||||
BufferedReader br = request.getReader();
|
||||
String str;
|
||||
StringBuilder wholeStr = new StringBuilder();
|
||||
while((str = br.readLine()) != null){
|
||||
wholeStr.append(str);
|
||||
}
|
||||
return wholeStr.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*获取request请求body中参数
|
||||
* @param br 流
|
||||
* @return body参数
|
||||
*/
|
||||
public static String getBodyString(BufferedReader br) {
|
||||
String inputLine;
|
||||
StringBuilder str = new StringBuilder();
|
||||
try {
|
||||
while ((inputLine = br.readLine()) != null) {
|
||||
str.append(inputLine);
|
||||
}
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println("IOException: " + e);
|
||||
}
|
||||
return str.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 该方法用于排除是否有需要过滤的白名单
|
||||
* @param request 请求
|
||||
* @param response 响应
|
||||
* @return
|
||||
*/
|
||||
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response)
|
||||
{
|
||||
if (!enabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (excludes == null || excludes.isEmpty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
String url = request.getServletPath();
|
||||
for (String pattern : excludes)
|
||||
{
|
||||
Pattern p = Pattern.compile("^" + pattern);
|
||||
Matcher m = p.matcher(url);
|
||||
if (m.find())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* 使用正则判断是否含有sql注入,返回true表示含有
|
||||
* @param str 传入的字符串
|
||||
* @return
|
||||
*/
|
||||
public static boolean containsSqlInjection(String str){
|
||||
Matcher matcher=SQL_PATTERN.matcher(str.toLowerCase());
|
||||
return matcher.find();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ag.secp.platform.filter;
|
||||
|
||||
|
||||
import javax.servlet.*;
|
||||
import java.io.IOException;
|
||||
|
||||
public class EncodingFilter implements Filter{
|
||||
|
||||
private String targetEncoding = "UTF-8";
|
||||
private FilterConfig filterConfig = null;
|
||||
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
//获取配置文件
|
||||
this.filterConfig = filterConfig;
|
||||
//获取配置文件中的编码信息
|
||||
this.targetEncoding = this.filterConfig.getInitParameter("encoding");
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
request.setCharacterEncoding(this.targetEncoding);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
this.filterConfig = null ;
|
||||
this.targetEncoding = null ;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.ag.secp.platform.filter;
|
||||
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* 重写sql注入包装器中的输入流方法,可以判断请求体
|
||||
* @author wangjianhua
|
||||
* @date 2021-03-16 14:55
|
||||
*/
|
||||
public class SqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
|
||||
HttpServletRequest orgRequest = null;
|
||||
/**
|
||||
* 保存body数据
|
||||
*/
|
||||
private final byte[] body;
|
||||
|
||||
public SqlHttpServletRequestWrapper(HttpServletRequest request) throws IOException{
|
||||
super(request);
|
||||
orgRequest = request;
|
||||
body = StreamUtils.copyToByteArray(request.getInputStream());
|
||||
}
|
||||
|
||||
// 重写几个HttpServletRequestWrapper中的方法
|
||||
/**
|
||||
* 重写获取流方法,用作body判断 否则会在过滤后丢失body
|
||||
* @return BufferedReader
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
return new BufferedReader(new InputStreamReader(getInputStream()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 重写获取流方法 避免冲突
|
||||
* @return ServletInputStream
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
@Override
|
||||
public ServletInputStream getInputStream() throws IOException {
|
||||
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
|
||||
return new ServletInputStream() {
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
return bais.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener arg0) {
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ag.secp.platform.jwt;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* Description: JWT中的信息
|
||||
* Author: songwp
|
||||
* Version: 1.0
|
||||
* Create Date: 2021/12/24
|
||||
*/
|
||||
@Data
|
||||
public class JWTInfo {
|
||||
private String alg;
|
||||
private String typ;
|
||||
private long expireTime;
|
||||
private String uid;
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.ag.secp.platform.jwt;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.exceptions.ValidateException;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import cn.hutool.jwt.JWTException;
|
||||
import cn.hutool.jwt.JWTUtil;
|
||||
import cn.hutool.jwt.JWTValidator;
|
||||
import cn.hutool.jwt.signers.JWTSignerUtil;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Description: JWT拦截类
|
||||
* Author: songwp
|
||||
* Version: 1.0
|
||||
* Create Date: 2021/12/24
|
||||
*/
|
||||
public class JWTInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
//获取请求头里的令牌
|
||||
String token = request.getHeader(ResultCode.TOKEN_KEY);
|
||||
//ResultCode.TOKEN_KEY_HEADER_AUTHORIZATION
|
||||
//ResultCode.TOKEN_KEY_HEADER_AUTHORIZATION_BEARER
|
||||
boolean isSuccess;
|
||||
try {
|
||||
//验证签名
|
||||
isSuccess = JWTUtil.verify(token, JWTTokenForHS256.getTokenSecretByte());
|
||||
//验证算法
|
||||
JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(JWTTokenForHS256.getTokenSecretByte()))
|
||||
.validateDate(DateUtil.date());
|
||||
}catch (ValidateException exception){
|
||||
isSuccess = false;
|
||||
}catch(JWTException e){
|
||||
isSuccess = false;
|
||||
}
|
||||
if(isSuccess){
|
||||
return true;
|
||||
}else {
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().println(JSONUtil.parseObj(R.failedToken()));
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.ag.secp.platform.jwt;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.exceptions.ValidateException;
|
||||
import cn.hutool.jwt.*;
|
||||
import cn.hutool.jwt.signers.JWTSignerUtil;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
/**
|
||||
* Description: JWT HS256 对称加密
|
||||
* Author: songwp
|
||||
* Version: 1.0
|
||||
* Create Date: 2021/7/13
|
||||
*/
|
||||
public class JWTTokenForHS256 {
|
||||
|
||||
//token密钥
|
||||
private static final String TOKEN_SECRET = "SDFSFEGEIFNEWERETSDFSD";
|
||||
//间隔时间
|
||||
public static final long EXPIRE_DATE = 1000*1000;
|
||||
|
||||
public static byte[] getTokenSecretByte(){
|
||||
return TOKEN_SECRET.getBytes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Description:生成token
|
||||
* @param payload
|
||||
* @param expireDate 过期间隔毫秒数
|
||||
* @return: java.lang.String
|
||||
* @Author songwp
|
||||
* Create Date 2021/12/24
|
||||
*/
|
||||
public static String createToken(Map<String,Object> payload,long expireDate) {
|
||||
|
||||
//设置头部信息
|
||||
Map<String,Object> header = new HashMap<>();
|
||||
header.put("typ","JWT");
|
||||
header.put("alg","HS256");
|
||||
//设置payload内容
|
||||
// //签发时间
|
||||
// payload.put(JWTPayload.ISSUED_AT, System.currentTimeMillis());
|
||||
// //生效时间
|
||||
// payload.put(JWTPayload.NOT_BEFORE, System.currentTimeMillis());
|
||||
//过期时间
|
||||
payload.put(JWTPayload.EXPIRES_AT, DateUtil.date(System.currentTimeMillis() + expireDate));
|
||||
return JWTUtil.createToken(header,payload,getTokenSecretByte());
|
||||
}
|
||||
|
||||
/**
|
||||
* Description:验证token
|
||||
* @param token
|
||||
* @return: boolean
|
||||
* @Author songwp
|
||||
* Create Date 2021/12/24
|
||||
*/
|
||||
public static boolean verifyToken(String token) {
|
||||
boolean isSuccess;
|
||||
|
||||
try {
|
||||
//验证签名
|
||||
isSuccess = JWTUtil.verify(token, getTokenSecretByte());
|
||||
//验证算法
|
||||
JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(getTokenSecretByte())).validateDate(DateUtil.date());
|
||||
}catch (ValidateException exception){
|
||||
isSuccess = false;
|
||||
}
|
||||
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Description:解释数据
|
||||
* @param token
|
||||
* @return: JWTInfo
|
||||
* @Author songwp
|
||||
* Create Date 2021/12/24
|
||||
*/
|
||||
public static JWTInfo parseToken(String token) {
|
||||
JWTInfo jwtInfo = new JWTInfo();
|
||||
final JWT jwt = JWTUtil.parseToken(token);
|
||||
jwtInfo.setTyp(jwt.getHeader(JWTHeader.TYPE).toString());
|
||||
jwtInfo.setAlg(jwt.getHeader(JWTHeader.ALGORITHM).toString());
|
||||
jwtInfo.setExpireTime(Long.parseLong(jwt.getPayload(JWTPayload.EXPIRES_AT).toString()));;
|
||||
jwtInfo.setName(jwt.getPayload("name").toString());
|
||||
jwtInfo.setUid(jwt.getPayload("uid").toString());
|
||||
return jwtInfo;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
88
ILogBizSystem/src/main/java/com/ag/secp/platform/jwt/R.java
Normal file
88
ILogBizSystem/src/main/java/com/ag/secp/platform/jwt/R.java
Normal file
@@ -0,0 +1,88 @@
|
||||
package com.ag.secp.platform.jwt;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Description: 统一返回结果的类
|
||||
* Author: songwp
|
||||
* Version: 1.0
|
||||
* Create Date: 2021/9/3
|
||||
*/
|
||||
|
||||
@Data
|
||||
@Accessors(chain = true)//可以进行链式操作
|
||||
public class R {
|
||||
|
||||
private int respCode;
|
||||
|
||||
private String respMsg;
|
||||
|
||||
private Map<String,Object> data = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Description:私有构造方法
|
||||
* @param
|
||||
* @return: com.ag.secp.mobile.common.R
|
||||
* @Author songwp
|
||||
* Create Date 2021/9/3
|
||||
*/
|
||||
private R(){}
|
||||
|
||||
/**
|
||||
* Description:请求成功静态方法
|
||||
* @param
|
||||
* @return: com.ag.secp.mobile.common.R
|
||||
* @Author songwp
|
||||
* Create Date 2021/9/3
|
||||
*/
|
||||
public static R success() {
|
||||
R r = new R();
|
||||
r.setRespCode(ResultCode.SUCCESS);
|
||||
r.setRespMsg(ResultCode.SUCCESS_MSG);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Description:请求失败静态方法
|
||||
* @param
|
||||
* @return: com.ag.secp.mobile.common.R
|
||||
* @Author songwp
|
||||
* Create Date 2021/9/3
|
||||
*/
|
||||
public static R failed(String failedMsg) {
|
||||
R r = new R();
|
||||
r.setRespCode(ResultCode.FAILED);
|
||||
r.setRespMsg(failedMsg);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Description:TOKEN验证失败
|
||||
* @param
|
||||
* @return: com.ag.secp.mobile.common.R
|
||||
* @Author songwp
|
||||
* Create Date 2021/9/3
|
||||
*/
|
||||
public static R failedToken() {
|
||||
R r = new R();
|
||||
r.setRespCode(ResultCode.LOGIN_REQUIRED);
|
||||
r.setRespMsg(ResultCode.TOKEN_VERIFY_ERROR);
|
||||
return r;
|
||||
}
|
||||
|
||||
public R setRData(String key,Object value) {
|
||||
this.data.put(key,value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public R setRData(Map<String,Object> map) {
|
||||
this.setData(map);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ag.secp.platform.jwt;
|
||||
|
||||
/**
|
||||
* Description: 数据返回状态码
|
||||
* Author: songwp
|
||||
* Version: 1.0
|
||||
* Create Date: 2021/9/3
|
||||
*/
|
||||
public interface ResultCode {
|
||||
|
||||
//请求成功
|
||||
int SUCCESS = 1;
|
||||
String SUCCESS_MSG = "请求成功";
|
||||
//请求失败
|
||||
int FAILED = 0;
|
||||
|
||||
String FAILED_MSG = "请求失败";
|
||||
|
||||
String FAILED_MSG_img = "图片不存在";
|
||||
|
||||
//登录--用户名或密码错误
|
||||
String USERNAME_OR_PASSWORD_ERROR_MSG = "用户名或密码错误";
|
||||
String USER_FROZEN = "账号已冻结";
|
||||
String USER_IS_NULL = "无此用户";
|
||||
String USER_IS_EXISTS = "用户名已存在";
|
||||
|
||||
String TOKEN_VERIFY_ERROR = "token验证失败";
|
||||
String TOKEN_KEY = "token";
|
||||
String TOKEN_KEY_HEADER_AUTHORIZATION = "Authorization";
|
||||
String TOKEN_KEY_HEADER_AUTHORIZATION_BEARER = "Bearer";
|
||||
|
||||
//系统繁忙,请稍候再试
|
||||
Integer SYSTEM_BUSY = -1;
|
||||
//请求参数不合法
|
||||
Integer ILLEGAL_PARAMETER = 40000;
|
||||
//需要 GET 请求
|
||||
Integer GET_REQUEST = 43001;
|
||||
//需要 POST 请求
|
||||
Integer POST_REQUEST = 43002;
|
||||
//需要 HTTPS 请求
|
||||
Integer HTTPS_REQUEST = 43003;
|
||||
//API 调用太频繁,请稍候再试
|
||||
Integer API_BUSY = 45011;
|
||||
//系统错误 (system error)
|
||||
Integer SERVE_ERROR = 61450;
|
||||
|
||||
//(Illegal token)
|
||||
Integer ILLEGAL_TOKEN = 50008;
|
||||
//Other clients logged in
|
||||
Integer OTHERCLIENTS_LOGININ = 50012;
|
||||
//Token expired
|
||||
Integer TOKEN_EXPIRED = 50014;
|
||||
//会话过期,请重新登录
|
||||
Integer LOGIN_REQUIRED = 70500;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.ag.secp.platform.microkernel;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import com.ag.log.RequestLog;
|
||||
import com.ag.psamathe.api.Module;
|
||||
import com.ag.psamathe.api.ModuleConfig;
|
||||
import com.ag.psamathe.api.ModuleLoader;
|
||||
import com.ag.psamathe.api.ModuleManager;
|
||||
import com.ag.psamathe.api.impl.SpringModule;
|
||||
import com.ag.util.ResourceUtil;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.wb.common.Base;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
@Component
|
||||
public class ModuleManageProcess {
|
||||
|
||||
@Autowired
|
||||
private ModuleLoader moduleLoader;
|
||||
@Autowired
|
||||
private ModuleManager moduleManager;
|
||||
|
||||
/**
|
||||
* 部署模式
|
||||
* @param
|
||||
*/
|
||||
@RequestLog
|
||||
public Object deployModule(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request, String beanName, String methodName) throws Exception {
|
||||
Module module = moduleManager.find(ResourceUtil.getString("system", "userName"));
|
||||
ApplicationContext context = ((SpringModule) module).getApplicationContext();
|
||||
//doAction执行了Action接口的execute方法
|
||||
return runBeanMethod(jsonObject, response, request, context, beanName, methodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取jar包的开发者模式
|
||||
*
|
||||
* @param
|
||||
*/
|
||||
private long lastModifid = 0;
|
||||
@RequestLog
|
||||
public synchronized Object developerForJar(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request, String beanName, String methodName) throws Exception {
|
||||
long on = System.currentTimeMillis();
|
||||
ModuleConfig config = buildModuleConfig();
|
||||
Module module;
|
||||
try {
|
||||
if (Long.parseLong(config.getVersion()) > lastModifid)//add by liaw 2021-3-4 重新打包修改时间变化后再加载
|
||||
{
|
||||
|
||||
lastModifid = Long.parseLong(config.getVersion());
|
||||
module = moduleLoader.load(config);
|
||||
Module removed = moduleManager.register(module);//add by liaw 2021-3-4 记录加载的模块
|
||||
if (removed != null){
|
||||
removed.destroy();
|
||||
}
|
||||
|
||||
System.out.println("module load times::" + ((System.currentTimeMillis() - on)));
|
||||
|
||||
} else {
|
||||
module = moduleManager.find(config.getName());//已经加载过,直接使用上次加载的模块
|
||||
System.out.println("module find times::" + ((System.currentTimeMillis() - on)));
|
||||
}
|
||||
}catch (Exception ex){
|
||||
ex.printStackTrace();
|
||||
throw new RuntimeException("jar包读取失败,请检查jar包路径!");
|
||||
}
|
||||
ApplicationContext context = ((SpringModule) module).getApplicationContext();
|
||||
//doAction执行了Action接口的execute方法
|
||||
return runBeanMethod(jsonObject, response, request, context, beanName, methodName);
|
||||
}
|
||||
|
||||
private Object runBeanMethod(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request, ApplicationContext context, String beanName, String methodName){
|
||||
Object result;
|
||||
Method method;
|
||||
try {
|
||||
String springName = StrUtil.firstToLower(beanName);
|
||||
if (context.containsBean(springName)) {
|
||||
result = context.getBean(springName);
|
||||
} else {
|
||||
result = context.getBean(StrUtil.firstToUpper(beanName));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException("beanName不正确, 请检查![" + beanName + "]");
|
||||
}
|
||||
try {
|
||||
method = result.getClass().getMethod(methodName, JSONObject.class, HttpServletResponse.class, HttpServletRequest.class);
|
||||
}catch (Exception ex){
|
||||
throw new RuntimeException("方法名不正确, 请检查![" + methodName + "]");
|
||||
}
|
||||
return ReflectionUtils.invokeMethod(method, result, jsonObject, response, request);
|
||||
}
|
||||
|
||||
public ModuleConfig buildModuleConfig() {
|
||||
|
||||
List<URL> urls = new ArrayList<>();
|
||||
List<String> scanPackages = new ArrayList<>();
|
||||
ModuleConfig moduleConfig = new ModuleConfig();
|
||||
long lastModify = 0;
|
||||
try {
|
||||
ResourceBundle resource = ResourceUtil.getResourceBundle("system");
|
||||
String[] arrs = resource.getString("dynamicJarPath").split(",");
|
||||
for (String arr : arrs) {
|
||||
if (com.ag.util.StrUtil.isEmpty(arr)) {
|
||||
continue;
|
||||
}
|
||||
String path = arr;
|
||||
File file = new File(arr);
|
||||
if (!file.isAbsolute()) {
|
||||
file = new File(Base.path, arr);
|
||||
path = file.getCanonicalPath();
|
||||
}
|
||||
if (file.lastModified() > lastModify) {//判断修改时间,大于上次修改时间,则记录新的修改时间
|
||||
lastModify = file.lastModified();
|
||||
}
|
||||
urls.add(new URL("file:" + path));
|
||||
}
|
||||
String[] scans = resource.getString("scanPackages").split(",");
|
||||
for (String arr : scans) {
|
||||
if (com.ag.util.StrUtil.isEmpty(arr)) {
|
||||
continue;
|
||||
}
|
||||
scanPackages.add(arr);
|
||||
}
|
||||
moduleConfig.setName("demo");
|
||||
moduleConfig.setVersion(Convert.toStr(lastModify));//将修改时间做为版本号记录,供管理开发模式热加载使用
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
moduleConfig.setModuleUrl(urls);
|
||||
moduleConfig.setOverridePackages(scanPackages);
|
||||
|
||||
return moduleConfig;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ag.secp.platform.microkernel;
|
||||
|
||||
import com.ag.base.DefaultBussniessImpl;
|
||||
import com.ag.psamathe.api.pojo.ModuleVersion;
|
||||
import com.ag.util.ResourceUtil;
|
||||
import com.ag.util.UUIDUtil;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2021/7/27.
|
||||
*/
|
||||
@Service
|
||||
public class ModuleVersionService {
|
||||
|
||||
@Autowired
|
||||
private DefaultBussniessImpl bizDao;
|
||||
final String userName = ResourceUtil.getString("system", "userName");
|
||||
|
||||
public void replace(JSONObject object, HttpServletResponse response, HttpServletRequest request){
|
||||
ModuleVersion version = new ModuleVersion();
|
||||
version.setVersion(UUIDUtil.getUUID().substring(14));
|
||||
version.setName(userName);
|
||||
bizDao.update(version, "NAME");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ag.secp.platform.microkernel;
|
||||
|
||||
import com.ag.secp.platform.spring.BeanMange;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Created by yangxh on 2019/5/22.
|
||||
*/
|
||||
public class ReflectServerMethod {
|
||||
private static Log log = LogFactory.getLog(ReflectServerMethod.class);
|
||||
|
||||
public static void isReflect(String className, String methodName, HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
//有可能在扩展工程中
|
||||
BeanMange beanMange = new BeanMange();
|
||||
beanMange.bean = className.substring(className.lastIndexOf(".")+1, className.length());
|
||||
beanMange.method = methodName;
|
||||
beanMange.request = request;
|
||||
beanMange.response = response;
|
||||
beanMange.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断className是否在主工程, 是返回true
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static boolean isPresent(String name) {
|
||||
try {
|
||||
Thread.currentThread().getContextClassLoader().loadClass(name);
|
||||
return true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ag.secp.platform.office.excel;
|
||||
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018/1/7.
|
||||
*/
|
||||
public class ExpPoiSimExcel {
|
||||
|
||||
/**
|
||||
* 导出excel文档
|
||||
* @param data
|
||||
* @param isFilePath
|
||||
* @param osFilePath
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String expExcel(List data,String isFilePath,String osFilePath)throws Exception{
|
||||
Workbook wb=ExpPoiSimExcel.fillExcelDataWithTemplate(data,isFilePath);
|
||||
ExpPoiSimExcel.export( wb,osFilePath);
|
||||
return osFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环处理数据
|
||||
* @param data
|
||||
* @param isFilePath
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Workbook fillExcelDataWithTemplate(List data, String isFilePath)throws Exception{
|
||||
InputStream is = new FileInputStream(isFilePath);
|
||||
POIFSFileSystem fs=new POIFSFileSystem(is);
|
||||
Workbook wb=new HSSFWorkbook(fs);
|
||||
Sheet sheet=wb.getSheetAt(0);
|
||||
//得到标题行列数
|
||||
int cellNums=sheet.getRow(1).getLastCellNum();
|
||||
int rowIndex=2;
|
||||
for (int i= 0; data !=null && i < data.size();i++) {
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
List slist = (List) data.get(i);
|
||||
for (int j = 0; j < cellNums; j++) {
|
||||
row.createCell(j).setCellValue(String.valueOf(slist.get(j)));
|
||||
}
|
||||
}
|
||||
return wb;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件
|
||||
* @param wb
|
||||
* @param osFileName
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void export(Workbook wb, String osFileName)throws Exception{
|
||||
File outFile = new File(osFileName);
|
||||
OutputStream out= new FileOutputStream(outFile);
|
||||
wb.write(out);
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// try {
|
||||
// List data = new ArrayList();
|
||||
// TStudent tStudent = new TStudent();
|
||||
// tStudent.setName("1");
|
||||
// tStudent.setSex("1");
|
||||
// tStudent.setAge((short) 10);
|
||||
// tStudent.setGradeCod("G101");
|
||||
// data.add(tStudent);
|
||||
// String isFilePath = "D:\\test\\student.xls";
|
||||
// String osFilePath = "D:\\test\\s" + System.currentTimeMillis() + ".xls";
|
||||
// ExpPoiSimExcel.expExcel(data,isFilePath,osFilePath);
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
package com.ag.secp.platform.office.excel;
|
||||
|
||||
import com.ag.util.ExcelPoiUtil;
|
||||
import org.apache.poi.POIXMLDocument;
|
||||
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.openxml4j.opc.OPCPackage;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.io.*;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018/1/5.
|
||||
*/
|
||||
public class ImpExcel {
|
||||
/**
|
||||
* 转换excle 2003和2007
|
||||
* @param in
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws InvalidFormatException
|
||||
*/
|
||||
public static Workbook create(InputStream in) throws
|
||||
IOException,InvalidFormatException {
|
||||
if (!in.markSupported()) {
|
||||
in = new PushbackInputStream(in, 8);
|
||||
}
|
||||
if (POIFSFileSystem.hasPOIFSHeader(in)) {
|
||||
return new HSSFWorkbook(in);
|
||||
}
|
||||
if (POIXMLDocument.hasOOXMLHeader(in)) {
|
||||
return new XSSFWorkbook(OPCPackage.open(in));
|
||||
}
|
||||
throw new IllegalArgumentException("你的excel版本目前poi解析不了");
|
||||
}
|
||||
/**
|
||||
* 获取excel数据list
|
||||
*
|
||||
* @Title
|
||||
* @Description TODO(获取excel数据list)
|
||||
* @param stream
|
||||
* @param startRow
|
||||
* @param startCell
|
||||
* *@param sheetIndex
|
||||
* @return
|
||||
*/
|
||||
public static List<HashMap<Integer, String>> readExcelEmptyBody(InputStream stream, int startRow,
|
||||
int endRow, int startCell, int endCell, int sheetIndex) {
|
||||
if (startRow < endRow && endRow != -1) {
|
||||
return null;
|
||||
}
|
||||
if (startCell < endCell && endCell != -1) {
|
||||
return null;
|
||||
}
|
||||
Workbook wb =null;
|
||||
List<HashMap<Integer, String>> resultList = new ArrayList<HashMap<Integer, String>>();
|
||||
|
||||
try {
|
||||
wb = create(stream);
|
||||
} catch (InvalidFormatException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
Sheet sheet=null;
|
||||
int sheets= wb.getNumberOfSheets();
|
||||
int rows=0;
|
||||
for(int m=0;m<sheets;m++){
|
||||
rows = wb.getSheetAt(m).getLastRowNum();
|
||||
|
||||
if(rows>0){
|
||||
sheet = wb.getSheetAt(m);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(endRow != -1) {
|
||||
rows = endRow;
|
||||
}
|
||||
for (int i = startRow; i <= rows; i++) {
|
||||
Row row = sheet.getRow(i);
|
||||
if(row == null){
|
||||
continue;
|
||||
}
|
||||
int cells = row.getLastCellNum();
|
||||
if (endCell != -1) {
|
||||
cells = endCell;
|
||||
}
|
||||
int count = 0;
|
||||
HashMap<Integer, String> cellMap = new HashMap<Integer, String>();
|
||||
for (int j = startCell; j <= cells; j++) {
|
||||
Cell cell = row.getCell(j);
|
||||
String cellStr = getStringCellValue(cell);
|
||||
//System.out.print("\t" + cellStr);
|
||||
if(cellStr!=""||!cellStr.equals(""))
|
||||
cellMap.put(count, cellStr);
|
||||
count++;
|
||||
|
||||
}
|
||||
resultList.add(cellMap);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
/**
|
||||
* 获取excel数据list
|
||||
*
|
||||
* @Title
|
||||
* @Description TODO(获取excel数据list)
|
||||
* @param stream
|
||||
* @param startRow 开始行数 从0 开始
|
||||
* @param startCell 开始列
|
||||
* @param endCell 开始列
|
||||
* @param startCell 开始列
|
||||
* *@param sheetIndex
|
||||
* @return
|
||||
*/
|
||||
public static List readExcelBody(InputStream stream, int startRow,
|
||||
int endRow, int startCell, int endCell, int sheetIndex) {
|
||||
if (startRow < endRow && endRow != -1) {
|
||||
return null;
|
||||
}
|
||||
if (startCell < endCell && endCell != -1) {
|
||||
return null;
|
||||
}
|
||||
List resultList = new ArrayList();
|
||||
try {
|
||||
Workbook wb = create(stream);
|
||||
Sheet sheet = wb.getSheetAt(sheetIndex);
|
||||
int rows = sheet.getLastRowNum();
|
||||
if (rows <= 0) {
|
||||
sheet = wb.getSheetAt(wb.getActiveSheetIndex());
|
||||
rows = sheet.getLastRowNum();
|
||||
}
|
||||
|
||||
if (endRow != -1) {
|
||||
rows = endRow;
|
||||
}
|
||||
for (int i = startRow; i <= rows; i++) {
|
||||
Row row = sheet.getRow(i);
|
||||
if (row == null) continue;
|
||||
int cells = row.getLastCellNum();
|
||||
if (endCell != -1) {
|
||||
cells = endCell;
|
||||
}
|
||||
if (cells==-1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int count = 0;
|
||||
Map cellMap = new HashMap();
|
||||
for (int j = startCell; j <= cells; j++) {
|
||||
Cell cell = row.getCell(j);
|
||||
String cellStr = getStringCellValue(cell);
|
||||
|
||||
cellMap.put(count, cellStr);
|
||||
count++;
|
||||
|
||||
}
|
||||
|
||||
resultList.add(cellMap);
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
List<Integer> nullArr = new ArrayList<Integer>();
|
||||
nullArr.add(null);
|
||||
resultList.removeAll(nullArr);
|
||||
|
||||
return resultList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取excel数据list
|
||||
*
|
||||
* @Title
|
||||
* @Description TODO(获取excel数据list)
|
||||
* @param stream
|
||||
* @param startRow
|
||||
* @param startCell
|
||||
* *@param sheetName 使用工作表的名称
|
||||
* @return
|
||||
*/
|
||||
public static List readExcelBody(InputStream stream, int startRow,
|
||||
int endRow, int startCell, int endCell, String sheetName) {
|
||||
if (startRow < endRow && endRow != -1) {
|
||||
return null;
|
||||
}
|
||||
if (startCell < endCell && endCell != -1) {
|
||||
return null;
|
||||
}
|
||||
List resultList = new ArrayList();
|
||||
try {
|
||||
Workbook wb = create(stream);
|
||||
Sheet sheet = wb.getSheet(sheetName);
|
||||
int rows = sheet.getLastRowNum();
|
||||
|
||||
|
||||
if (endRow != -1) {
|
||||
rows = endRow;
|
||||
}
|
||||
for (int i = startRow; i <= rows; i++) {
|
||||
Row row = sheet.getRow(i);
|
||||
|
||||
int cells = row.getLastCellNum();
|
||||
if (endCell != -1) {
|
||||
cells = endCell;
|
||||
}
|
||||
if (cells==-1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int count = 0;
|
||||
Map cellMap = new HashMap();
|
||||
for (int j = startCell; j <= cells; j++) {
|
||||
Cell cell = row.getCell(j);
|
||||
String cellStr = getStringCellValue(cell);
|
||||
|
||||
cellMap.put(count, cellStr);
|
||||
count++;
|
||||
|
||||
}
|
||||
|
||||
resultList.add(cellMap);
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
List<Integer> nullArr = new ArrayList<Integer>();
|
||||
nullArr.add(null);
|
||||
resultList.removeAll(nullArr);
|
||||
|
||||
return resultList;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title 获取列值string
|
||||
* @Description TODO(这里用一句话描述这个方法的作用)
|
||||
* @param cell
|
||||
* @return
|
||||
*/
|
||||
private static String getStringCellValue(Cell cell) {
|
||||
String strCell = "";
|
||||
if (cell == null) {
|
||||
return "";
|
||||
}
|
||||
switch (cell.getCellType()) {
|
||||
case Cell.CELL_TYPE_FORMULA:
|
||||
try {
|
||||
/*
|
||||
* 此处判断使用公式生成的字符串有问题,因为HSSFDateUtil.isCellDateFormatted(cell)判断过程中cell
|
||||
* .getNumericCellValue();方法会抛出java.lang.NumberFormatException异常
|
||||
*/
|
||||
if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
||||
Date date = cell.getDateCellValue();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
strCell = sdf.format(date);
|
||||
// strCell = (date.getYear() + 1900) + "-" +
|
||||
// (date.getMonth() + 1) +"-" +
|
||||
// date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
|
||||
break;
|
||||
} else {
|
||||
strCell = String.valueOf(cell.getNumericCellValue());
|
||||
}
|
||||
} catch (IllegalStateException e) {
|
||||
strCell = String.valueOf(cell.getRichStringCellValue());
|
||||
}
|
||||
break;
|
||||
case Cell.CELL_TYPE_STRING:
|
||||
strCell = cell.getStringCellValue();
|
||||
break;
|
||||
case Cell.CELL_TYPE_NUMERIC:
|
||||
if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
||||
double d = cell.getNumericCellValue();
|
||||
Date date = HSSFDateUtil.getJavaDate(d);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
strCell = sdf.format(date);
|
||||
break;
|
||||
} else {
|
||||
//strCell = String.valueOf(cell.getNumericCellValue());
|
||||
DecimalFormat df = new DecimalFormat("0");
|
||||
strCell = df.format(cell.getNumericCellValue());
|
||||
break;
|
||||
}
|
||||
case Cell.CELL_TYPE_BOOLEAN:
|
||||
strCell = String.valueOf(cell.getBooleanCellValue());
|
||||
break;
|
||||
case Cell.CELL_TYPE_BLANK:
|
||||
strCell = "";
|
||||
break;
|
||||
default:
|
||||
strCell = "";
|
||||
break;
|
||||
}
|
||||
return strCell;
|
||||
}
|
||||
//判断Excel表格是否有内容
|
||||
public static int excelIsNull(InputStream stream) {
|
||||
int rows = 0;
|
||||
try {
|
||||
Workbook wb = new HSSFWorkbook(stream);
|
||||
Sheet sheet = wb.getSheetAt(0);
|
||||
rows = sheet.getLastRowNum();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
File file = new File("F://船舶总计划0401.xls");
|
||||
|
||||
InputStream in = null;
|
||||
try {
|
||||
in = new FileInputStream(file);
|
||||
//ExcelPoiUtil.excelIsNull(in);
|
||||
List resultList= ExcelPoiUtil.readExcelBody(in, 3, -1, 0, -1, 0);
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ag.secp.platform.office.pdf;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import com.ag.util.StrUtil;
|
||||
import com.raqsoft.report.model.ReportDefine;
|
||||
import com.raqsoft.report.usermodel.Context;
|
||||
import com.raqsoft.report.usermodel.Engine;
|
||||
import com.raqsoft.report.usermodel.IReport;
|
||||
import com.raqsoft.report.util.ReportUtils;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Description: 通过润乾报表动态生成pdf,输出到服务器目录
|
||||
* Author: agsoft
|
||||
* Version: 1.0
|
||||
* Create Date: 2020-06-02 09:36:26
|
||||
*/
|
||||
public class ExportPdfWithRqsoft {
|
||||
|
||||
|
||||
/**
|
||||
* 生成pdf文件
|
||||
*
|
||||
* @param reporttemplatename 报表模板名称
|
||||
* @param reporttemplatePath 报表模板存放路径
|
||||
* @param pdffileGenpath 报表文件生成路径
|
||||
* @param paramMap 报表查询参数
|
||||
* @param filename 报表生成的文件名
|
||||
*/
|
||||
public void genPdf(String reporttemplatename, String reporttemplatePath, String pdffileGenpath, Map paramMap, String filename) {
|
||||
//保证报表名称的完整性
|
||||
int iTmp = 0;
|
||||
if ((iTmp = reporttemplatename.lastIndexOf(".rpx")) <= 0) {
|
||||
reporttemplatename = reporttemplatename + ".rpx";
|
||||
iTmp = 0;
|
||||
}
|
||||
String reportFile = reporttemplatePath + reporttemplatename;
|
||||
Context cxt = new Context();
|
||||
try {
|
||||
ReportDefine rd = (ReportDefine) ReportUtils.read(reportFile);
|
||||
for (Object key : paramMap.entrySet()) {
|
||||
cxt.setParamValue(key.toString(), paramMap.get(key).toString());//报表需要传递的参数
|
||||
}
|
||||
Engine engine = new Engine(rd, cxt); //构造报表引擎
|
||||
IReport iReport = engine.calc(); //运算报表
|
||||
if (StrUtil.isEmpty(filename))
|
||||
filename = DateUtil.format(new Date(), "yyyy-MM-dd") + "-" + UUID.randomUUID() + ".pdf";
|
||||
ReportUtils.exportToPDF(pdffileGenpath + filename, iReport);
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ag.secp.platform.office.word;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.ObjectWrapper;
|
||||
import freemarker.template.Template;
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2017/12/15.
|
||||
*/
|
||||
public class ExpFtlSimWord {
|
||||
/**
|
||||
* ftl生成word
|
||||
* @param params
|
||||
* @param path
|
||||
* @param ftlFile
|
||||
* @param osFilePath
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void createDoc(Map params,String path,String ftlFile,String osFilePath) throws IOException {
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.setDefaultEncoding("UTF-8");
|
||||
configuration.setDirectoryForTemplateLoading(new File(path));
|
||||
Template t = null;
|
||||
try {
|
||||
t = configuration.getTemplate(ftlFile, "UTF-8");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
File outFile = new File(osFilePath);
|
||||
Writer out = null;
|
||||
try {
|
||||
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
try {
|
||||
t.process(params, out, ObjectWrapper.BEANS_WRAPPER);
|
||||
out.close();
|
||||
} catch (TemplateException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ag.secp.platform.office.word;
|
||||
|
||||
/**
|
||||
* poi生成word
|
||||
* 复杂循序的例子
|
||||
* Created by Administrator on 2018/1/1.
|
||||
*/
|
||||
public class ExpPoiComWord {
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user