master
RENCHAO 1 month ago
parent 3b8afb310c
commit 4932096ba3

@ -20,110 +20,127 @@
<artifactId>audit-sdk</artifactId>
<scope>system</scope>
<version>1.5.4</version>
<!-- <systemPath>${project.basedir}/src/main/resources/lib/audit-sdk-1.5.4.jar</systemPath>-->
<systemPath>${project.basedir}/src/main/resources/lib/audit-sdk-1.5.4-jar-with-dependencies.jar</systemPath>
<systemPath>${project.basedir}/src/main/resources/lib/audit-sdk-1.6.0.jar</systemPath>
<!-- <systemPath>${project.basedir}/src/main/resources/lib/audit-sdk-1.5.5-jar-with-dependencies.jar</systemPath>-->
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-openssl-static</artifactId>
<scope>system</scope>
<version>2.0.39.Final</version>
<systemPath>${project.basedir}/src/main/resources/lib/netty-tcnative-openssl-static-2.0.39.Final.jar</systemPath>
</dependency>
<dependency>
<groupId>org.chainmaker.sdk</groupId>
<artifactId>shanghai</artifactId>
<scope>system</scope>
<version>1.0.0</version>
<systemPath>${project.basedir}/src/main/resources/lib/chainmaker-sdk-2.3.2.jar</systemPath>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.60</version>
</dependency>
<!-- &lt;!&ndash;添加slf4j-api&ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>ch.qos.logback</groupId>-->
<!-- <artifactId>logback-classic</artifactId>-->
<!-- <version>1.2.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.commons</groupId>-->
<!-- <artifactId>commons-pool2</artifactId>-->
<!-- <version>2.11.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.yaml</groupId>-->
<!-- <artifactId>snakeyaml</artifactId>-->
<!-- <version>1.33</version>-->
<!-- </dependency>-->
<!-- &lt;!&ndash;java-sdk中的依赖 &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>commons-collections</groupId>-->
<!-- <artifactId>commons-collections</artifactId>-->
<!-- <version>3.2.2</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.netty</groupId>-->
<!-- <artifactId>netty-handler</artifactId>-->
<!-- <version>4.1.53.Final</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.grpc</groupId>-->
<!-- <artifactId>grpc-api</artifactId>-->
<!-- <version>1.40.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.grpc</groupId>-->
<!-- <artifactId>grpc-netty</artifactId>-->
<!-- <version>1.40.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.grpc</groupId>-->
<!-- <artifactId>grpc-stub</artifactId>-->
<!-- <version>1.40.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.grpc</groupId>-->
<!-- <artifactId>grpc-protobuf</artifactId>-->
<!-- <version>1.40.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>cn.hutool</groupId>-->
<!-- <artifactId>hutool-core</artifactId>-->
<!-- <version>5.8.18</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.alibaba</groupId>-->
<!-- <artifactId>fastjson</artifactId>-->
<!-- <version>1.2.62</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.bouncycastle</groupId>-->
<!-- <artifactId>bcpkix-jdk15on</artifactId>-->
<!-- <version>1.60</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.commons</groupId>-->
<!-- <artifactId>commons-lang3</artifactId>-->
<!-- <version>3.14.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.googlecode.aviator</groupId>-->
<!-- <artifactId>aviator</artifactId>-->
<!-- <version>5.4.1</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.github.houbb</groupId>-->
<!-- <artifactId>sensitive-word</artifactId>-->
<!-- <version>0.16.1</version>-->
<!-- </dependency>-->
<!--添加slf4j-api-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.33</version>
</dependency>
<!--java-sdk中的依赖 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
<version>4.1.53.Final</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-api</artifactId>
<version>1.40.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.40.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.40.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.40.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.32</version>
</dependency>
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>sensitive-word</artifactId>
<version>0.16.1</version>
</dependency>
<dependency>
<groupId>com.googlecode.aviator</groupId>
<artifactId>aviator</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>abi</artifactId>
<version>5.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -5,109 +5,162 @@ import cn.dreamdt.audit.domain.ChainMessage;
import cn.dreamdt.audit.domain.MessageBean;
import cn.dreamdt.audit.main.DataAudit;
import cn.dreamdt.audit.maker.chain.ChainConsumer;
import cn.dreamdt.audit.util.AuditUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.ssl.OpenSsl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @author ren_chao
*/
public class Demo01 {
// uniTrust.clientDid
private static final String CLIENT_DID = "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm";
public static void main(String[] args) {
// setParent(Demo01.class.getClassLoader());
DataAudit dataAudit = DataAudit.create(AuditConfig.builder()
.appCode("jtktph").appKey("240710105317v53eyAsWrsQRXYYAMWm").serverUrl("https://116.128.191.6:2031/DreamWeb")
.logFilePath("C:\\Users\\RENCHAO\\Desktop\\temp-sss\\log").chainConsumer(new MyChainConsumerImpl()).build());
dataAudit.subscribeChain(null,null,null);
// 数据上链 测试数据
JSONObject bizData = new JSONObject();
bizData.put("behaviorId", "00570000000000000000121");
bizData.put("behaviorId", "20240701798445635972400");
bizData.put("platformCid", "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm");
bizData.put("ccid", "did:unitrust:7CXMdXzSmNrGk3mWPe9jpsHg2HmU");
bizData.put("sceneCode", "77");
bizData.put("startTime", "2024-07-05 16:43:52");
bizData.put("endTime", "2024-07-05 16:43:52");
// bizData.put("endTime", "2024-07-05 16:43:52");
// bizData.put("endTime", "");
bizData.put("tripDistance", "5544.000");
bizData.put("hashData", "5f89452b52a9df1fe0060c8ac3de5b6ffea3e6855cf307db31ac0359d67d7888");
bizData.put("state", "1");
bizData.put("state", 1);
//调用合约
MessageBean messageBean = dataAudit.invoke("CAMC", "saveAssetData", bizData,"00570000000000000000121");
System.out.println("=========================\n");
System.out.println(messageBean);
System.out.println("\n=========================");
System.out.println("=============json============\n");
System.out.println(JSON.toJSONString(messageBean));
System.out.println("\n=========================");
Map<String, String> map = new HashMap<>();
map.put("behaviorId", "00570000000000000000121");
map.put("behaviorId", "20240701798445635972400"); // 失败的
// map.put("behaviorId", "00571000000000000000126"); // 成功d
MessageBean query = dataAudit.query("CAMC", "findAssetData", map);
// MessageBean query = dataAudit.query("CAMC", "findAssetData", "17e38900edca0112ca9f2132c60492a758760b1099c8451dbcdf8d666cf447ba");
System.out.println("=============query============\n");
System.out.println(query);
System.out.println("\n=========================");
// 数据批量上链 测试数据
JSONArray bizDataArray = new JSONArray();
JSONObject bizData1 = new JSONObject();
bizData1.put("behaviorId", "00470000000000000000171");
bizData1.put("platformCid", "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm");
bizData1.put("ccid", "did:unitrust:7CXMdXzSmNrGk3mWPe9jpsHg2HmU");
bizData1.put("sceneCode", "77");
bizData1.put("startTime", "2024-07-05 16:43:52");
bizData1.put("endTime", "2024-07-05 16:43:52");
bizData1.put("tripDistance", "5544.000");
bizData1.put("hashData", "099513e015663a8b1d9183a8beae1ccb286893092e597669ca015dee9a8a89ee");
bizData1.put("state", "1");
bizDataArray.add(bizData1);
JSONObject bizData2 = new JSONObject();
bizData2.put("behaviorId", "00470000000000000000125");
bizData2.put("platformCid", "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm");
bizData2.put("ccid", "did:unitrust:7CXMdXzSmNrGk3mWPe9jpsHg2HmU");
bizData2.put("sceneCode", "77");
bizData2.put("startTime", "2024-07-05 16:43:52");
bizData2.put("endTime", "2024-07-05 16:43:52");
bizData2.put("tripDistance", "5544.000");
bizData2.put("hashData", "fd238cf96c983d68684e17c867d01192355df3f12bb69a954300b4ed608b61cf");
bizData2.put("state", "1");
bizDataArray.add(bizData2);
// JSONArray bizDataArray = new JSONArray();
// JSONObject bizData1 = new JSONObject();
// bizData1.put("behaviorId", "00470000000000000000171");
// bizData1.put("platformCid", "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm");
// bizData1.put("ccid", "did:unitrust:7CXMdXzSmNrGk3mWPe9jpsHg2HmU");
// bizData1.put("sceneCode", "77");
// bizData1.put("startTime", "2024-07-05 16:43:52");
// bizData1.put("endTime", "2024-07-05 16:43:52");
// bizData1.put("tripDistance", "5544.000");
// bizData1.put("hashData", "099513e015663a8b1d9183a8beae1ccb286893092e597669ca015dee9a8a89ee");
// bizData1.put("state", "1");
// bizDataArray.add(bizData1);
//
//
// JSONObject bizData2 = new JSONObject();
// bizData2.put("behaviorId", "00470000000000000000125");
// bizData2.put("platformCid", "did:unitrust:6r5eR9TPcSNRCGYjfEsDxbXjm9Cm");
// bizData2.put("ccid", "did:unitrust:7CXMdXzSmNrGk3mWPe9jpsHg2HmU");
// bizData2.put("sceneCode", "77");
// bizData2.put("startTime", "2024-07-05 16:43:52");
// bizData2.put("endTime", "2024-07-05 16:43:52");
// bizData2.put("tripDistance", "5544.000");
// bizData2.put("hashData", "fd238cf96c983d68684e17c867d01192355df3f12bb69a954300b4ed608b61cf");
// bizData2.put("state", "1");
// bizDataArray.add(bizData2);
//
// //调用合约
// ArrayList<String> bizIndexList = new ArrayList<>();
// bizIndexList.add("00470000000000000000171");
// bizIndexList.add("00470000000000000000125");
//
// MessageBean messageBean2 = dataAudit.batchInvoke("CAMC", "findAssetData", bizDataArray, bizIndexList);
while (true) {
System.out.println("====================");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//调用合约
ArrayList<String> bizIndexList = new ArrayList<>();
bizIndexList.add("00470000000000000000171");
bizIndexList.add("00470000000000000000125");
MessageBean messageBean2 = dataAudit.batchInvoke("CAMC", "findAssetData", bizDataArray, bizIndexList);
}
private static void setParent(ClassLoader classLoader) {
try {
Field parent = ClassLoader.class.getDeclaredField("parent");
parent.setAccessible(true);
CustomClassLoader loader = new CustomClassLoader(classLoader.getParent());
parent.set(classLoader,loader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class CustomClassLoader extends ClassLoader {
public CustomClassLoader(ClassLoader parent) {
super(parent);
}
@Override
public URL getResource(String name) {
try {
if (name.endsWith("sdk_config.yml")
|| name.endsWith("crypto.yml")
|| name.endsWith("OrgSignCert.crt")
|| name.endsWith("SignCert.crt")
|| name.endsWith("SignKey.key")
|| name.endsWith("TlsCert.crt")
|| name.endsWith("TlsKey.key")) {
return new URL("file:C:/Users/RENCHAO/Desktop/temp-sss/cc/" + name);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return getParent().getResource(name);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return getParent().loadClass(name);
}
}
static class MyChainConsumerImpl implements ChainConsumer {
@Override
public void onMessage(ChainMessage chainMessage) {
System.out.println("============回掉结果=============\n\n");
System.out.println(chainMessage);
System.out.println("\n\n=========================");
System.out.println("============回掉结果json=============\n\n");
System.out.println("============回调结果json=============\n");
System.out.println(JSON.toJSONString(chainMessage));
System.out.println("\n\n=========================");
System.out.println("\n=========================");
}
}

@ -0,0 +1,77 @@
package com.renchao;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author ren_chao
*/
public class Demo02 {
public static void main(String[] args) throws IOException {
String root = "./abc/dd/";
String file = "tt.txt";
Path path = Paths.get(root, file);
System.out.println(path.toString());
// setParent(Demo02.class.getClassLoader());
//
//
// URL resource = Demo02.class.getClassLoader().getResource("crypto.yml");
//
//
// try(InputStream inputStream = resource.openStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
// String line;
// while ((line = br.readLine()) != null) {
// System.out.println(line);
// }
//
// }
// System.out.println(resource);
}
private static void setParent(ClassLoader classLoader) {
try {
Field parent = ClassLoader.class.getDeclaredField("parent");
parent.setAccessible(true);
CustomClassLoader loader = new CustomClassLoader(classLoader.getParent());
parent.set(classLoader,loader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class CustomClassLoader extends ClassLoader {
public CustomClassLoader(ClassLoader parent) {
super(parent);
}
@Override
public URL getResource(String name) {
try {
if ("crypto.yml".equals(name)) {
return new URL("file:C:/Users/RENCHAO/Desktop/temp-sss/bb/" + name);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return super.getResource(name);
}
}
}

@ -0,0 +1,21 @@
-----BEGIN CERTIFICATE-----
MIIDbzCCAxagAwIBAgIQWKQdbIzXXGI0HyTMVQqaSDAKBggqgRzPVQGDdTCBhzEL
MAkGA1UEBhMCQ04xMzAxBgNVBAoMKuW4guWkp+aVsOaNruS4reW/gy3nm5HnrqHp
k74uY20tMzl1cWhoazloMzELMAkGA1UECwwCY2ExNjA0BgNVBAMMLWNhLuW4guWk
p+aVsOaNruS4reW/gy3nm5HnrqHpk74uY20tMzl1cWhoazloMzAeFw0yNDA0MDMw
NTIxNTRaFw0yOTA0MDIwNTIxNTRaMIHCMQswCQYDVQQGEwJDTjEPMA0GA1UECAwG
5LiK5rW3MQ8wDQYDVQQHDAbkuIrmtbcxMzAxBgNVBAoMKuW4guWkp+aVsOaNruS4
reW/gy3nm5HnrqHpk74uY20tMzl1cWhoazloMzEOMAwGA1UECxMFYWRtaW4xTDBK
BgNVBAMMQ+Wkp+aVsOaNruS4reW/g+euoeeQhuWRmC3luILlpKfmlbDmja7kuK3l
v4Mt55uR566h6ZO+LmNtLTM5dXFoaGs5aDMwWTATBgcqhkjOPQIBBggqgRzPVQGC
LQNCAARRDwc9DKv7hy24Zn6tdnaK7vJjFSHK7Y/OZW6jx8RoE5E/AzcxtmBYtHMr
B10cuTs/aEnqtI7sIO5bnkLFzEx0o4IBJTCCASEwHQYDVR0OBBYEFAVn3B0+DHsp
6b4mPtaqOjbzNZk9MA4GA1UdDwEB/wQEAwIDODAJBgNVHRMEAjAAMB8GA1UdIwQY
MBaAFJSwbf0W4Y1mITjqfSm22chUqkK0MEEGCCsGAQUFBwEBBDUwMzAxBggrBgEF
BQcwAYYlaHR0cDovL29zY3AxLmJsb2NrY2hhaW4uc2guY2Vnbi5jbi92MTA+BgNV
HR8ENzA1MDOgMaAvhi1odHRwOi8vbGRhcDEuYmxvY2tjaGFpbi5zaC5jZWduLmNu
L3YxL2FsbC5jcmwwQQYDVR0gBDowODA2BggqgRyG7zqBFTAqMCgGCCsGAQUFBwIB
FhxodHRwOi8vd3d3LnNoZWNhLmNvbS9wb2xpY3kvMAoGCCqBHM9VAYN1A0cAMEQC
ID2SIp0MsD7ImramHmazo6gjQdLxq5hUILVsFRUMz8+pAiAHCdZ6OwASFamka0Bn
rdfj97z29ERgrsJ6gSnL2D9Meg==
-----END CERTIFICATE-----

@ -0,0 +1,6 @@
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg2e6nVOJwcfqXZO20
OK+4SAbLlIqoivBGTGHUuge9FaagCgYIKoEcz1UBgi2hRANCAARRDwc9DKv7hy24
Zn6tdnaK7vJjFSHK7Y/OZW6jx8RoE5E/AzcxtmBYtHMrB10cuTs/aEnqtI7sIO5b
nkLFzEx0
-----END PRIVATE KEY-----

@ -1,20 +1,24 @@
enableRemoteConfig: false #是否启用远程配置
logLevel: fine #日志级别 info error
version: v2
chainConfigList:
- # 链ID
chainId: "ZW_C8458AD_002"
# 组织ID
orgId: "测试514-碳普惠测试链2.cm-l7wv90h523"
#组织证书路径
orgCrtPath: "cert/zxzj/org/OrgSignCert.crt"
orgCrtPath: "cert/org/OrgSignCert.crt"
# 客户端用户交易私钥路径
userTlsKeyPath: "cert/zxzj/user/TlsKey.key"
userTlsKeyPath: "cert/user/TlsKey.key"
# 客户端用户交易证书路径
userTlsCrtPath: "cert/zxzj/user/TlsCert.crt"
userTlsCrtPath: "cert/user/TlsCert.crt"
# 客户端用户交易签名私钥路径(若未设置将使用user_key_file_path)
userSignKeyPath: "cert/zxzj/user/SignKey.key"
userSignKeyPath: "cert/user/SignKey.key"
# 客户端用户交易签名证书路径(若未设置将使用user_crt_file_path)
userSignCrtPath: "cert/zxzj/user/SignCert.crt"
userSignCrtPath: "cert/user/SignCert.crt"
userEncTlsKeyPath: "cert/user/EncTlsKey.key"
userEncTlsCrtPath: "cert/user/EncTlsCert.crt"
# grpc客户端最大接受容量(MB)
rpcMaxReceiveMessageSize: 32
# 交易结果是否订阅获取
@ -24,11 +28,13 @@ chainConfigList:
caConfigPath: "crypto.yml"
nodeList:
- # 节点地址格式为IP:端口:连接数有两个端口使用rpc的端口
addr: "116.128.190.190:9020"
addr: "116.128.191.6:2032"
# addr: "116.128.190.190:9020"
# 节点连接数
connectCount: 10
# RPC连接是否启用双向TLS认证
enableTls: true
# TLS hostname
tlsHostName: "consensus1-69vkhheorg.cm-l7wv90h523"
chainTlsHostName: "consensus1-69vkhheorg.cm-l7wv90h523"

@ -194,7 +194,6 @@
</excludes>
<filtering>false</filtering>
</resource>
<!--打成JAR包时 合并 额外引入的JAR包库 -->
<resource>
<directory>src/main/resources/libx</directory>
<targetPath>BOOT-INF/lib/</targetPath>

@ -3,7 +3,7 @@
<parent>
<groupId>com.jiuyv.sptcc</groupId>
<artifactId>carbon-dataprocess</artifactId>
<version>0.4.2-SNAPSHOT</version>
<version>0.4.4-SNAPSHOT</version>
</parent>
<artifactId>carbon-dataprocess-api</artifactId>

@ -1,5 +1,6 @@
package com.jiuyv.sptcc.carbon.dataprocess.api;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ReqChainResultDTO;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ReqSignResultDTO;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ResultDTO;
import org.springframework.web.bind.annotation.PostMapping;
@ -19,4 +20,10 @@ public interface CarbonDataApi {
*/
@PostMapping(PREFIX + "/sign")
ResultDTO<Void> signResult(@RequestBody ReqSignResultDTO signResultDTO);
/**
*
*/
@PostMapping(PREFIX + "/chainResult")
ResultDTO<Void> chainResultCallback(@RequestBody ReqChainResultDTO chainResultDTO);
}

@ -0,0 +1,19 @@
package com.jiuyv.sptcc.carbon.dataprocess.dto;
import java.io.Serializable;
/**
* @author ren_chao
*/
public class ReqChainResultDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String txId;
public String getTxId() {
return txId;
}
public void setTxId(String txId) {
this.txId = txId;
}
}

@ -4,7 +4,7 @@
<parent>
<groupId>com.jiuyv.sptcc</groupId>
<artifactId>carbon-dataprocess</artifactId>
<version>0.4.2-SNAPSHOT</version>
<version>0.4.4-SNAPSHOT</version>
</parent>
<artifactId>carbon-dataprocess-service</artifactId>
@ -87,15 +87,6 @@
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>

@ -0,0 +1,24 @@
package com.jiuyv.sptcc.carbon.dataprocess.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author ren_chao
*/
@Component
@ConfigurationProperties(prefix = "carbon-data-process")
public class DataProcessProperties {
/**
*
*/
private boolean enableUpChain = true;
public boolean getEnableUpChain() {
return enableUpChain;
}
public void setEnableUpChain(boolean enableUpChain) {
this.enableUpChain = enableUpChain;
}
}

@ -1,19 +1,27 @@
package com.jiuyv.sptcc.carbon.dataprocess.config;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import feign.Logger;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author ren_chao
*/
@Configuration
public class FeignConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(FeignConfiguration.class);
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.FULL;
}
@ -23,6 +31,16 @@ public class FeignConfiguration {
*/
@Bean
public ErrorDecoder errorDecoder() {
return (methodKey, response) -> new ServiceException("系统服务调用异常");
return (methodKey, response) -> {
String res;
try {
res = IOUtils.toString(response.body().asReader(StandardCharsets.UTF_8));
} catch (IOException e) {
LOGGER.info("读取服务调用异常body出错", e);
res = "";
}
LOGGER.info("Feign服务{}调用异常:{}", methodKey, res);
return new ServiceException("系统服务调用异常:" + res);
};
}
}

@ -0,0 +1,41 @@
package com.jiuyv.sptcc.carbon.dataprocess.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author ren_chao
*/
@Component
@ConfigurationProperties(prefix = "sms")
public class SmsProperties {
private boolean enable = false;
private String sendUrl;
private List<String> phoneList;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getSendUrl() {
return sendUrl;
}
public void setSendUrl(String sendUrl) {
this.sendUrl = sendUrl;
}
public List<String> getPhoneList() {
return phoneList;
}
public void setPhoneList(List<String> phoneList) {
this.phoneList = phoneList;
}
}

@ -3,8 +3,10 @@ package com.jiuyv.sptcc.carbon.dataprocess.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiuyv.sptcc.carbon.dataprocess.api.CarbonDataApi;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ReqChainResultDTO;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ReqSignResultDTO;
import com.jiuyv.sptcc.carbon.dataprocess.dto.ResultDTO;
import com.jiuyv.sptcc.carbon.dataprocess.service.IDataAuditService;
import com.jiuyv.sptcc.carbon.dataprocess.service.ISignResultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,11 +23,15 @@ public class CarbonDataController implements CarbonDataApi {
private static final Logger LOGGER = LoggerFactory.getLogger(CarbonDataController.class);
private final ISignResultService signResultService;
private final IDataAuditService dataAuditService;
private final ObjectMapper objectMapper;
public CarbonDataController(ISignResultService signResultService, ObjectMapper objectMapper) {
public CarbonDataController(ISignResultService signResultService,
IDataAuditService dataAuditService,
ObjectMapper objectMapper) {
this.signResultService = signResultService;
this.dataAuditService = dataAuditService;
this.objectMapper = objectMapper;
}
@ -40,6 +46,15 @@ public class CarbonDataController implements CarbonDataApi {
return ResultDTO.success();
}
/**
*
*/
@Override
public ResultDTO<Void> chainResultCallback(ReqChainResultDTO chainResultDTO) {
dataAuditService.callback(chainResultDTO.getTxId());
return ResultDTO.success();
}
private String objectToString(Object o) {
try {

@ -1,67 +1,29 @@
package com.jiuyv.sptcc.carbon.dataprocess.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcCalcFactor;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import com.jiuyv.sptcc.carbon.dataprocess.feign.SmsSendFeign;
import com.jiuyv.sptcc.carbon.dataprocess.service.ICalculateReductionService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IDataAuditService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IPushReductionService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IReadFileService;
import com.jiuyv.sptcc.carbon.dataprocess.service.ISignResultService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.protocol.https.Handler;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
* @author ren_chao
@ -83,14 +45,12 @@ public class TestController {
private ISignResultService signResultService;
@Autowired
private ObjectMapper objectMapper;
private IDataAuditService dataAuditService;
@Autowired
private SmsSendFeign smsSendFeign;
@GetMapping("test000")
public String test000(@RequestParam("date") String date) {
// readFileService.readFileAndInsertDatabase(date);
return "OK!!!";
}
@Autowired
private ApplicationContext applicationContext;
@GetMapping("test00")
public String test00(@RequestParam("date") String date) {
@ -123,117 +83,58 @@ public class TestController {
}
@PostMapping("/test44")
public String test44(@Validated(GroupA.class) @RequestBody User user) {
return "GroupA OK!!!";
}
@PostMapping("/test55")
public String test55(@Validated(GroupB.class) @RequestBody User user) {
return "GroupB OK!!!";
}
@GetMapping("/test66")
public String test66() {
dataAuditService.upChain();
return "OK OK OK!!!";
}
public static class User {
@NotBlank(message = "名称不能为空", groups = GroupA.class)
private String name;
@Email(message = "email格式不正确", groups = GroupB.class)
private String email;
@Max(message = "年龄必须小于100", value = 100)
@Min(message = "年龄必须大于5", value = 5)
private Integer age;
@ListValue(message = "请输入0或1", values = {0, 1}, groups = {GroupA.class, GroupB.class})
private Integer sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@GetMapping("/test77")
public String test77() {
dataAuditService.queryUpChainResult();
return "OK OK OK!!!";
}
@GetMapping("/test888")
public String test888(@RequestParam("sms") String sms, @RequestParam("code") String code, @RequestParam("phoneNo") String phoneNo) {
System.out.println("=================================");
System.out.println(sms);
System.out.println(code);
System.out.println(phoneNo);
System.out.println("=================================");
@Documented
// 指定校验器
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface ListValue {
String message() default "请输入指定的值!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
return smsSendFeign.send(phoneNo, sms, code);
int[] values() default {};
}
public static class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
private final Set<Integer> set = new HashSet<>();
// 初始化方法
@Override
public void initialize(ListValue constraintAnnotation) {
set.addAll(Arrays.stream(constraintAnnotation.values()).boxed().collect(Collectors.toList()));
}
public static void main(String[] args) {
BcCalcFactor calcFactor = new BcCalcFactor();
calcFactor.setEnd(LocalDateTime.parse("20240801000000", REQ_SDF));
calcFactor.setStart(LocalDateTime.parse("20240820000000", REQ_SDF));
// 校验逻辑value就是需要校验的值
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
long l = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
getCalcFactor("20240809000000", calcFactor);
}
}
System.out.println(":::" + (System.currentTimeMillis() - l));
interface GroupA {
}
interface GroupB {
}
private static final DateTimeFormatter REQ_SDF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private static BcCalcFactor getCalcFactor(String intoTransTime, BcCalcFactor calcFactor) {
public static void main(String[] args) throws InterruptedException {
final Base64.Decoder decoder = Base64.getDecoder();
final byte[] aa = decoder.decode("dW5tYXJzaGFsIGFyZ3MgZXJyb3I6IGludmFsaWQgY2hhcmFjdGVyICciJyBhZnRlciBhcnJheSBlbGVtZW50");
System.out.println(new String(aa));
LocalDateTime time = LocalDateTime.parse(intoTransTime, REQ_SDF);
if (calcFactor == null || time.isAfter(calcFactor.getEnd()) || time.isBefore(calcFactor.getStart())) {
if (calcFactor == null) {
LOGGER.error("未查询到排放因子数据:{}", intoTransTime);
throw new ServiceException("未查询到排放因子数据");
}
}
return calcFactor;
}
}

@ -1,6 +1,7 @@
package com.jiuyv.sptcc.carbon.dataprocess.domain;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
*
@ -41,16 +42,13 @@ public class BcCalcFactor implements Serializable {
*/
private String factor;
/**
*
*/
private String startTime;
/**
*
*/
private String endTime;
private LocalDateTime start;
private LocalDateTime end;
public Long getFactorId() {
return factorId;
}
@ -122,4 +120,20 @@ public class BcCalcFactor implements Serializable {
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public LocalDateTime getStart() {
return start;
}
public void setStart(LocalDateTime start) {
this.start = start;
}
public LocalDateTime getEnd() {
return end;
}
public void setEnd(LocalDateTime end) {
this.end = end;
}
}

@ -152,14 +152,15 @@ public class BcTravelNotice implements Serializable {
/**
*
* INIT:,
* AUDIT_FAILED:,
* UP_CHAIN_FAILED:,
* SUCCESS:
* AUDIT_SUCCESS("调用合约成功"),
* AUDIT_FAILED("调用合约失败"),
* CHAIN_SUCCESS("上链成功"),
* CHAIN_FAILED("上链失败");
*/
private String chainStatus;
/**
* ID
* ID
*/
private String chainTxId;
@ -215,7 +216,7 @@ public class BcTravelNotice implements Serializable {
private Integer sendCount;
/**
* -1:1:2: 3:
* -1:1:2: 3:
*/
private Integer signStatus;

@ -6,10 +6,11 @@ package com.jiuyv.sptcc.carbon.dataprocess.enums;
* @author ren_chao
*/
public enum ChainStatusEnum {
INIT("提交上链"),
AUDIT_FAILED("稽核规则校验失败"),
UP_CHAIN_FAILED("上链失败失败"),
SUCCESS("上链成功");
INIT("初始化"),
AUDIT_SUCCESS("调用合约成功"),
AUDIT_FAILED("调用合约失败"),
CHAIN_SUCCESS("上链成功"),
CHAIN_FAILED("上链失败");
private final String msg;

@ -0,0 +1,16 @@
package com.jiuyv.sptcc.carbon.dataprocess.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
*
* @author ren_chao
*/
@FeignClient(url = "${sms.sendUrl}", name = "msgSendFeign")
public interface SmsSendFeign {
@GetMapping
String send(@RequestParam("phoneNo") String phoneNo, @RequestParam("sms") String sms, @RequestParam("code") String code);
}

@ -6,6 +6,7 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* TBL_BC_TRAVEL_NOTICEMapper
@ -15,16 +16,14 @@ import java.util.Map;
@Mapper
public interface BcTravelNoticeMapper {
int insert(BcTravelNotice record);
int updateBySeqNo(BcTravelNotice travelNotice);
BcTravelNotice selectBySeqNo(@Param("seqNo") Long seqNo);
List<BcTravelNotice> selectPageByStatus(@Param("status") String status,
@Param("chainStatus") String chainStatus,
@Param("start") Integer start,
@Param("end") Integer end);
int updateBySeqNo(BcTravelNotice record);
List<BcTravelNotice> selectPageByStatus(@Param("status") String status, @Param("start") Integer start,
@Param("count") Integer count);
Integer selectCountByStatus(@Param("status") String status);
Integer selectCountByStatus(@Param("status") String status, @Param("chainStatus") String chainStatus);
List<BcTravelNotice> selectListByBatchNo(@Param("batchNo") String batchNo);
@ -33,7 +32,28 @@ public interface BcTravelNoticeMapper {
List<BcTravelNotice> selectPageBySignStatus(@Param("signStatus") Integer signStatus, @Param("start") Integer start,
@Param("count") Integer count);
Long selectCountByFileName(@Param("fileName") String fileName);
List<BcTravelNotice> selectTravelNoticeList(Map<String, Object> queryMap);
int selectCountByFileName(@Param("fileName") String fileName);
void updateChainStatusByTxId(@Param("chainStatus") String chainStatus, @Param("txId") String txId);
int updateChainStatusByTravelNos(@Param("list") List<String> list,
@Param("chainStatus") String chainStatus,
@Param("txId") String txId);
int updateStatusBySeqNos(@Param("list") List<String> list,
@Param("status") String status,
@Param("batchNo") String batchNo);
Integer selectTxIdCountByChainStatus(@Param("chainStatus") String chainStatus);
List<String> selectTxIdLimitByChainStatus(@Param("chainStatus") String chainStatus,
@Param("count") Integer count);
void batchInsert(List<BcTravelNotice> list);
Set<String> selectTravelNoListByTravelNoList(@Param("list") List<BcTravelNotice> list);
List<BcTravelNotice> selectTravelNoticePage(Map<String, Object> queryMap);
void updateBatchBySeqNo(@Param("list") List<BcTravelNotice> list);
}

@ -1,7 +1,10 @@
package com.jiuyv.sptcc.carbon.dataprocess.quartz;
import com.jiuyv.sptcc.carbon.dataprocess.config.SmsProperties;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import com.jiuyv.sptcc.carbon.dataprocess.feign.SmsSendFeign;
import com.jiuyv.sptcc.carbon.dataprocess.service.ICalculateReductionService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IDataAuditService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IPushReductionService;
import com.jiuyv.sptcc.carbon.dataprocess.service.IReadFileService;
import com.jiuyv.sptcc.carbon.dataprocess.service.ISignResultService;
@ -10,6 +13,9 @@ import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* xxl
@ -18,20 +24,31 @@ import org.springframework.stereotype.Component;
@Component
public class CarbonDataTask {
private static final Logger LOGGER = LoggerFactory.getLogger(CarbonDataTask.class);
private static final String CODE = "utf-8";
private final IReadFileService readFileService;
private final ICalculateReductionService calculateReductionService;
private final IPushReductionService pushReductionService;
private final ISignResultService signResultService;
private final IDataAuditService dataAuditService;
private final SmsSendFeign smsSendFeign;
private final SmsProperties smsProperties;
public CarbonDataTask(IReadFileService readFileService,
ICalculateReductionService calculateReductionService,
IPushReductionService pushReductionService,
ISignResultService signResultService) {
ISignResultService signResultService,
IDataAuditService dataAuditService,
SmsSendFeign smsSendFeign,
SmsProperties smsProperties) {
this.readFileService = readFileService;
this.calculateReductionService = calculateReductionService;
this.pushReductionService = pushReductionService;
this.signResultService = signResultService;
this.dataAuditService = dataAuditService;
this.smsSendFeign = smsSendFeign;
this.smsProperties = smsProperties;
}
/**
@ -56,12 +73,15 @@ public class CarbonDataTask {
@XxlJob(value = "readFileTask")
public void readFileTask() {
try {
readFileService.readFileAndInsertDatabase(XxlJobHelper.getJobParam());
int count = readFileService.readFileAndInsertDatabase(XxlJobHelper.getJobParam());
smsSend("中台数据读取成功,记录数:" + count);
} catch (ServiceException e) {
LOGGER.error(e.getMessage(), e);
smsSend("中台数据读取异常:" + e.getMessage());
throw e;
} catch (Exception e) {
LOGGER.error("未知异常", e);
smsSend("中台数据读取异常:" + e.getMessage());
throw e;
}
}
@ -115,4 +135,50 @@ public class CarbonDataTask {
}
}
/**
*
*/
@XxlJob(value = "upChainTask")
public void upChainTask() {
try {
dataAuditService.upChain();
} catch (ServiceException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (Exception e) {
LOGGER.error("未知异常", e);
throw e;
}
}
/**
*
*/
@XxlJob(value = "queryUpChainResultTask")
public void queryUpChainResultTask() {
try {
dataAuditService.queryUpChainResult();
} catch (ServiceException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (Exception e) {
LOGGER.error("未知异常", e);
throw e;
}
}
private void smsSend(String sms) {
List<String> phoneList = smsProperties.getPhoneList();
if (smsProperties.isEnable() && !CollectionUtils.isEmpty(phoneList)) {
for (String phone : phoneList) {
String res = smsSendFeign.send(phone, sms, CODE);
if ("success".equals(res)) {
LOGGER.info("短信发送成功,手机[{}],消息[{}]", phone, sms);
} else {
LOGGER.error("短信发送失败:[{}]", res);
}
}
}
}
}

@ -1,8 +1,5 @@
package com.jiuyv.sptcc.carbon.dataprocess.service;
import com.jiuyv.sptcc.carbon.pushgate.dto.GResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.ResBatchComputationDTO;
/**
*
*
@ -15,8 +12,4 @@ public interface ICalculateReductionService {
*/
void calculate();
/**
*
*/
void updateReduction(GResultDTO<ResBatchComputationDTO> resultDTO);
}

@ -1,9 +1,7 @@
package com.jiuyv.sptcc.carbon.dataprocess.service;
import com.jiuyv.sptcc.carbon.pushgate.dto.GResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.chain.ChainInfoDTO;
import java.util.List;
import java.util.Map;
/**
* @author ren_chao
@ -18,13 +16,11 @@ public interface IDataAuditService {
/**
*
*/
void callback();
void callback(String txId);
/**
*
*/
void queryUpChainResult();
void updateReduction(GResultDTO<List<ChainInfoDTO>> resultDTO);
}

@ -17,8 +17,4 @@ public interface IPushReductionService {
*/
void escalation();
/**
*
*/
void updateStatus(List<BcTravelNotice> bcTravelNoticeList, String status, String currentTime, String batchNo);
}

@ -9,10 +9,11 @@ public interface IReadFileService {
/**
*
*/
void readFileAndInsertDatabase(String dateStr);
int readFileAndInsertDatabase(String dateStr);
/**
*
*/
void getDictionary();
}

@ -1,7 +1,14 @@
package com.jiuyv.sptcc.carbon.dataprocess.service.impl;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BusSpotCheck;
import com.jiuyv.sptcc.carbon.dataprocess.domain.SubwaySpotCheck;
import com.jiuyv.sptcc.carbon.dataprocess.enums.CarbonDataEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.ChainStatusEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.IndustryCodeEnum;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import com.jiuyv.sptcc.carbon.dataprocess.feign.CarbonDataProcessFeign;
import com.jiuyv.sptcc.carbon.dataprocess.mapper.BcTravelNoticeMapper;
@ -12,13 +19,16 @@ import com.jiuyv.sptcc.carbon.pushgate.dto.GResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.BatchComputationReqVo;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.ResBatchComputationDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.ResComputationDTO;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@ -36,16 +46,20 @@ public class CalculateReductionServiceImpl implements ICalculateReductionService
private final CarbonDataProcessFeign carbonDataProcessFeign;
private final ICalculateReductionService calculateReductionService;
/**
* 使objectMapper
*/
private final ObjectMapper objectMapper;
public CalculateReductionServiceImpl(BcTravelNoticeMapper travelNoticeMapper,
SysDateMapper sysDateMapper,
CarbonDataProcessFeign carbonDataProcessFeign,
@Lazy ICalculateReductionService calculateReductionService) {
CarbonDataProcessFeign carbonDataProcessFeign) {
this.travelNoticeMapper = travelNoticeMapper;
this.sysDateMapper = sysDateMapper;
this.carbonDataProcessFeign = carbonDataProcessFeign;
this.calculateReductionService = calculateReductionService;
this.objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@ -54,13 +68,22 @@ public class CalculateReductionServiceImpl implements ICalculateReductionService
*/
@Override
public synchronized void calculate() {
Integer count = travelNoticeMapper.selectCountByStatus(CarbonDataEnum.PROCESSING.getCode());
Integer count = travelNoticeMapper.selectCountByStatus(CarbonDataEnum.PROCESSING.getCode(), null);
LOGGER.info(">>>> 开始计算碳减排量,总记录数:{}", count);
if (count == 0) {
return;
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i += PAGE_COUNT) {
LOGGER.info(">>>> 计算第{}页,{}-{}", i / PAGE_COUNT + 1, i + 1, i + PAGE_COUNT);
int pageCount = count / PAGE_COUNT + 1;
for (int i = 1; i <= pageCount; i++) {
LOGGER.info(">>>> 计算第{}页", i);
List<BcTravelNotice> bcTravelNoticeList = travelNoticeMapper
.selectPageByStatus(CarbonDataEnum.PROCESSING.getCode(), i, PAGE_COUNT);
.selectPageByStatus(CarbonDataEnum.PROCESSING.getCode(), null, 1, PAGE_COUNT);
if (CollectionUtils.isEmpty(bcTravelNoticeList)) {
break;
}
// 计算hash
bcTravelNoticeList.forEach(this::spotCheckHash);
List<BatchComputationReqVo.RawData> collect = bcTravelNoticeList.stream().map(bcTravelNotice -> {
BatchComputationReqVo.RawData rawData = new BatchComputationReqVo.RawData();
rawData.setBaseFactor(bcTravelNotice.getBaseFactor());
@ -79,29 +102,75 @@ public class CalculateReductionServiceImpl implements ICalculateReductionService
throw new ServiceException("计算错误");
}
// 更新计算结果
calculateReductionService.updateReduction(resultDTO);
Map<String, String> hashDataMap = bcTravelNoticeList.stream()
.collect(Collectors.toMap(BcTravelNotice::getSeqNo, BcTravelNotice::getHashData));
List<BcTravelNotice> tnList = getUpdateTravelNoticeList(resultDTO.getContent().getEmissionReductions(), hashDataMap);
travelNoticeMapper.updateBatchBySeqNo(tnList);
}
LOGGER.info(">>>> 计算完成,耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
}
private List<BcTravelNotice> getUpdateTravelNoticeList(List<ResComputationDTO> ers, Map<String, String> hashDataMap) {
String currentTime = sysDateMapper.currentTime();
return ers.stream().map(res -> {
BcTravelNotice tn = new BcTravelNotice();
String seqNo = res.getDataId();
tn.setSeqNo(seqNo);
tn.setHashData(hashDataMap.get(seqNo));
tn.setCarbonFootprint(res.getEmissionReduction());
tn.setReductionCalculateTime(currentTime);
tn.setStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode());
tn.setChainStatus(ChainStatusEnum.INIT.toString());
return tn;
}).collect(Collectors.toList());
}
/**
*
* hash
*/
@Transactional
@Override
public void updateReduction(GResultDTO<ResBatchComputationDTO> resultDTO) {
List<ResComputationDTO> emissionReductions = resultDTO.getContent().getEmissionReductions();
String currentTime = sysDateMapper.currentTime();
emissionReductions.forEach(res -> {
BcTravelNotice bcTravelNotice = new BcTravelNotice();
bcTravelNotice.setSeqNo(res.getDataId());
bcTravelNotice.setCarbonFootprint(res.getEmissionReduction());
bcTravelNotice.setReductionCalculateTime(currentTime);
bcTravelNotice.setStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode());
travelNoticeMapper.updateBySeqNo(bcTravelNotice);
});
private void spotCheckHash(BcTravelNotice travelNotice) {
if (IndustryCodeEnum.SUBWAY.getCode().equals(travelNotice.getIndustryCode())) {
SubwaySpotCheck spotCheck = new SubwaySpotCheck();
spotCheck.setTravelNo(travelNotice.getTravelNo());
spotCheck.setIntoTransTime(travelNotice.getIntoTransTime());
spotCheck.setInDeviceNo(travelNotice.getInDeviceNo());
spotCheck.setInStationName(travelNotice.getInStationName());
spotCheck.setOutTransTime(travelNotice.getOutTransTime());
spotCheck.setOutDeviceNo(travelNotice.getOutDeviceNo());
spotCheck.setOutStationName(travelNotice.getOutStationName());
spotCheck.setMileage(travelNotice.getMileage());
travelNotice.setHashData(sm3Hash(spotCheck));
} else {
BusSpotCheck spotCheck = new BusSpotCheck();
spotCheck.setTravelNo(travelNotice.getTravelNo());
spotCheck.setIntoTransTime(travelNotice.getIntoTransTime());
spotCheck.setLineNo(travelNotice.getLineNo());
spotCheck.setMileage(travelNotice.getMileage());
travelNotice.setHashData(sm3Hash(spotCheck));
}
}
private String sm3Hash(Object data) {
byte[] bytes = convertToJson(data).getBytes(StandardCharsets.UTF_8);
SM3Digest digest = new SM3Digest();
digest.update(bytes, 0, bytes.length);
byte[] output = new byte[digest.getDigestSize()];
digest.doFinal(output, 0);
return Hex.toHexString(output);
}
private String convertToJson(Object o) {
try {
return objectMapper.writeValueAsString(o);
} catch (Exception e) {
LOGGER.error("原始数据序列化错误", e);
throw new ServiceException("原始数据序列化错误");
}
}
}

@ -1,24 +1,25 @@
package com.jiuyv.sptcc.carbon.dataprocess.service.impl;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice;
import com.jiuyv.sptcc.carbon.dataprocess.enums.CarbonDataEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.ChainStatusEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.IndustryCodeEnum;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import com.jiuyv.sptcc.carbon.dataprocess.feign.DataAuditFeign;
import com.jiuyv.sptcc.carbon.dataprocess.mapper.BcTravelNoticeMapper;
import com.jiuyv.sptcc.carbon.dataprocess.service.IDataAuditService;
import com.jiuyv.sptcc.carbon.pushgate.api.DataAuditApi;
import com.jiuyv.sptcc.carbon.pushgate.dto.chain.ChainResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.common.ResultCode;
import com.jiuyv.sptcc.carbon.pushgate.dto.GResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.chain.AssetDataVo;
import com.jiuyv.sptcc.carbon.pushgate.dto.chain.BatchAssetDataVo;
import com.jiuyv.sptcc.carbon.pushgate.dto.chain.ChainInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@ -30,16 +31,13 @@ import java.util.stream.Collectors;
public class DataAuditServiceImpl implements IDataAuditService {
private static final Logger LOGGER = LoggerFactory.getLogger(DataAuditServiceImpl.class);
private static final Integer PAGE_COUNT = 500;
private static final Integer PAGE_COUNT = 1000;
private final BcTravelNoticeMapper travelNoticeMapper;
private final DataAuditFeign dataAuditFeign;
private final IDataAuditService dataAuditService;
public DataAuditServiceImpl(BcTravelNoticeMapper travelNoticeMapper, DataAuditFeign dataAuditFeign,
@Lazy IDataAuditService dataAuditService) {
public DataAuditServiceImpl(BcTravelNoticeMapper travelNoticeMapper, DataAuditFeign dataAuditFeign) {
this.travelNoticeMapper = travelNoticeMapper;
this.dataAuditFeign = dataAuditFeign;
this.dataAuditService = dataAuditService;
}
/**
@ -47,47 +45,51 @@ public class DataAuditServiceImpl implements IDataAuditService {
*/
@Override
public void upChain() {
Integer count = travelNoticeMapper.selectCountByStatus(CarbonDataEnum.PROCESSING.getCode());
LOGGER.info(">>>> 开始上链,总记录数:{}", count);
Integer count = travelNoticeMapper.selectCountByStatus(null, ChainStatusEnum.INIT.toString());
LOGGER.info(">>>> 开始调用合约,总记录数:{}", count);
if (count == 0) {
return;
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i += PAGE_COUNT) {
LOGGER.info(">>>> 上链第{}页,{}-{}", i / PAGE_COUNT + 1, i + 1, i + PAGE_COUNT);
int pageCount = count / PAGE_COUNT + 1;
for (int i = 1; i <= pageCount; i++) {
LOGGER.info(">>>> 调用合约第{}页", i);
List<BcTravelNotice> bcTravelNoticeList = travelNoticeMapper
.selectPageByStatus(CarbonDataEnum.PROCESSING.getCode(), i, PAGE_COUNT);
.selectPageByStatus(null, ChainStatusEnum.INIT.toString(), 1, PAGE_COUNT);
if (CollectionUtils.isEmpty(bcTravelNoticeList)) {
break;
}
List<AssetDataVo> collect = bcTravelNoticeList.stream().map(bcTravelNotice -> {
AssetDataVo rawData = new AssetDataVo();
rawData.setBehaviorId(bcTravelNotice.getTravelNo());
// TODO 确定所属场景方cid
rawData.setPlatformId("???");
rawData.setCcid(bcTravelNotice.getCcid());
rawData.setSceneCode(bcTravelNotice.getIndustryCode());
// TODO 时间转换 如果缺少进站时间或出站时间?
rawData.setStartTime(bcTravelNotice.getIntoTransTime());
rawData.setEndTime(bcTravelNotice.getOutTransTime());
rawData.setTripDistance(Double.valueOf(bcTravelNotice.getMileage()));
if (IndustryCodeEnum.SUBWAY.getCode().equals(bcTravelNotice.getIndustryCode())) {
rawData.setEndTime(bcTravelNotice.getOutTransTime());
}
rawData.setTripDistance(bcTravelNotice.getMileage());
rawData.setHashData(bcTravelNotice.getHashData());
// TODO 确定状态
rawData.setState(0);
rawData.setState(1);
return rawData;
}).collect(Collectors.toList());
BatchAssetDataVo batchAssetDataVo = new BatchAssetDataVo();
batchAssetDataVo.setAssetDataVoList(collect);
GResultDTO<List<ChainInfoDTO>> resultDTO = dataAuditFeign.batchUpChain(batchAssetDataVo);
GResultDTO<Map<String, List<String>>> resultDTO = dataAuditFeign.concurrentBatchUpChain(batchAssetDataVo);
if (!ResultCode.SUCCESS.getCode().equals(resultDTO.getRespCode())) {
LOGGER.error("上链出错");
throw new ServiceException("上链出错");
throw new ServiceException("网关服务异常");
}
// 更新计算结果
// TODO 如果这步失败,重复上链?
dataAuditService.updateReduction(resultDTO);
Map<String, List<String>> content = resultDTO.getContent();
content.forEach((k, v) -> {
if (DataAuditApi.AUDIT_FAIL.equals(k)) {
travelNoticeMapper.updateChainStatusByTravelNos(v, ChainStatusEnum.AUDIT_FAILED.toString(), null);
} else {
travelNoticeMapper.updateChainStatusByTravelNos(v, ChainStatusEnum.AUDIT_SUCCESS.toString(), k);
}
});
}
LOGGER.info(">>>> 初始上链完成,耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
LOGGER.info(">>>> 调用合约完成,耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
}
@ -95,8 +97,9 @@ public class DataAuditServiceImpl implements IDataAuditService {
*
*/
@Override
public void callback() {
// TODO 接收区块链系统回调 更新上链结果
public void callback(String txId) {
LOGGER.info("上链成功回调:{}", txId);
travelNoticeMapper.updateChainStatusByTxId(ChainStatusEnum.CHAIN_SUCCESS.toString(), txId);
}
/**
@ -104,24 +107,37 @@ public class DataAuditServiceImpl implements IDataAuditService {
*/
@Override
public void queryUpChainResult() {
// TODO 主动查询一直没有回调的数据
}
/**
*
*/
@Transactional
@Override
public void updateReduction(GResultDTO<List<ChainInfoDTO>> resultDTO) {
List<ChainInfoDTO> content = resultDTO.getContent();
content.forEach(info -> {
BcTravelNotice bcTravelNotice = new BcTravelNotice();
bcTravelNotice.setChainStatus(ChainStatusEnum.INIT.toString());
bcTravelNotice.setSeqNo(info.getBehaviorId());
bcTravelNotice.setChainTxId(info.getTxId());
travelNoticeMapper.updateBySeqNo(bcTravelNotice);
});
Integer count = travelNoticeMapper.selectTxIdCountByChainStatus(ChainStatusEnum.AUDIT_SUCCESS.toString());
LOGGER.info(">>>> 开始查询上链结果,需要查询的总记录数:{}", count);
if (count == 0) {
return;
}
long startTime = System.currentTimeMillis();
int pageCount = count / PAGE_COUNT + 1;
for (int i = 1; i <= pageCount; i++) {
LOGGER.info(">>>> 查询第{}页", i);
List<String> travelNoList = travelNoticeMapper
.selectTxIdLimitByChainStatus(ChainStatusEnum.AUDIT_SUCCESS.toString(), PAGE_COUNT);
if (CollectionUtils.isEmpty(travelNoList)) {
break;
}
GResultDTO<ChainResultDTO> resultDTO = dataAuditFeign.query(travelNoList);
if (!ResultCode.SUCCESS.getCode().equals(resultDTO.getRespCode())) {
throw new ServiceException("网关服务异常");
}
ChainResultDTO res = resultDTO.getContent();
// 更新成功的
if (!CollectionUtils.isEmpty(res.getSuccessTravelNoList())) {
travelNoticeMapper.updateChainStatusByTravelNos(res.getSuccessTravelNoList(),
ChainStatusEnum.CHAIN_SUCCESS.toString(), null);
}
// 更新失败的
if (!CollectionUtils.isEmpty(res.getFailTravelNoList())) {
travelNoticeMapper.updateChainStatusByTravelNos(res.getFailTravelNoList(),
ChainStatusEnum.CHAIN_FAILED.toString(), null);
}
}
LOGGER.info(">>>> 查询上链结果完成,耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
}
}

@ -32,7 +32,7 @@ public class DataManageServiceImpl implements IDataManageService {
@Override
public List<BcTravelNotice> getTravelNoticePage(Map<String, Object> queryMap) {
return travelNoticeMapper.selectTravelNoticePage(queryMap);
return travelNoticeMapper.selectTravelNoticeList(queryMap);
}
@Override

@ -1,9 +1,10 @@
package com.jiuyv.sptcc.carbon.dataprocess.service.impl;
import com.jiuyv.sptcc.carbon.dataprocess.config.DataProcessProperties;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice;
import com.jiuyv.sptcc.carbon.dataprocess.enums.CarbonDataEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.ChainStatusEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.IndustryCodeEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.SignStatusEnum;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
import com.jiuyv.sptcc.carbon.dataprocess.feign.CarbonDataProcessFeign;
import com.jiuyv.sptcc.carbon.dataprocess.mapper.BcTravelNoticeMapper;
@ -14,9 +15,8 @@ import com.jiuyv.sptcc.carbon.pushgate.dto.GResultDTO;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.DeliveryReqVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@ -41,15 +41,15 @@ public class PushReductionServiceImpl implements IPushReductionService {
private final SysDateMapper sysDateMapper;
private final CarbonDataProcessFeign carbonDataProcessFeign;
private final IPushReductionService pushReductionService;
private final boolean isUpChain;
public PushReductionServiceImpl(BcTravelNoticeMapper travelNoticeMapper, SysDateMapper sysDateMapper,
CarbonDataProcessFeign carbonDataProcessFeign,
@Lazy IPushReductionService pushReductionService) {
DataProcessProperties dataProcessProperties) {
this.travelNoticeMapper = travelNoticeMapper;
this.sysDateMapper = sysDateMapper;
this.carbonDataProcessFeign = carbonDataProcessFeign;
this.pushReductionService = pushReductionService;
this.isUpChain = dataProcessProperties.getEnableUpChain();
}
@ -58,16 +58,23 @@ public class PushReductionServiceImpl implements IPushReductionService {
*/
@Override
public synchronized void escalation() {
Integer count = travelNoticeMapper.selectCountByStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode());
String chainStatus = isUpChain ? ChainStatusEnum.CHAIN_SUCCESS.toString() : null;
Integer count = travelNoticeMapper.selectCountByStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode(), chainStatus);
LOGGER.info(">>>> 开始上报数据,总记录数:{}", count);
if (count == 0) {
return;
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i += PAGE_COUNT) {
LOGGER.info(">>>> 上报第{}页{}-{}", i / PAGE_COUNT + 1, i + 1, i + PAGE_COUNT);
int pageCount = count / PAGE_COUNT + 1;
for (int i = 1; i <= pageCount; i++) {
LOGGER.info(">>>> 上报第{}页", i);
String currentTime = sysDateMapper.currentTime();
// 有重复推送问题
String batchNo = sysDateMapper.getTravelNoticeBatchNo();
List<BcTravelNotice> bcTravelNoticeList = travelNoticeMapper.selectPageByStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode(), i, PAGE_COUNT);
List<BcTravelNotice> bcTravelNoticeList = travelNoticeMapper
.selectPageByStatus(CarbonDataEnum.WAIT_FOR_SEND.getCode(), chainStatus, 1, PAGE_COUNT);
if (CollectionUtils.isEmpty(bcTravelNoticeList)) {
break;
}
List<DeliveryReqVo.Info> collect = bcTravelNoticeList.stream().map(bcTravelNotice -> {
DeliveryReqVo.Info info = new DeliveryReqVo.Info();
info.setSerialNo(bcTravelNotice.getTravelNo());
@ -77,7 +84,7 @@ public class PushReductionServiceImpl implements IPushReductionService {
info.setReduction(bcTravelNotice.getCarbonFootprint());
info.setDeliveryCount(bcTravelNotice.getSendCount());
info.setDataConfirmationTime(LocalDateTime.parse(bcTravelNotice.getDataConfirmationTime(),SDF_14).format(SDF));
info.setDataConfirmationTime(LocalDateTime.parse(bcTravelNotice.getDataConfirmationTime(), SDF_14).format(SDF));
info.setReductionCalculateTime(LocalDateTime.parse(bcTravelNotice.getReductionCalculateTime(), SDF_14).format(SDF));
info.setDataDeliveryTime(LocalDateTime.parse(currentTime, SDF_14).format(SDF));
@ -100,39 +107,19 @@ public class PushReductionServiceImpl implements IPushReductionService {
deliveryReqVo.setData(collect);
GResultDTO<String> resultDTO = carbonDataProcessFeign.delivery(deliveryReqVo);
List<String> seqNoList = bcTravelNoticeList.stream().map(BcTravelNotice::getSeqNo).collect(Collectors.toList());
if (ResultCode.SUCCESS.getCode().equals(resultDTO.getRespCode())) {
// 推送成功
pushReductionService.updateStatus(bcTravelNoticeList, CarbonDataEnum.SUCCESS.getCode(), currentTime, batchNo);
travelNoticeMapper.updateStatusBySeqNos(seqNoList, CarbonDataEnum.SUCCESS.getCode(), batchNo);
} else {
LOGGER.info(">>>> 第{}页推送失败{}-{}", i / PAGE_COUNT + 1, i + 1, i + PAGE_COUNT);
LOGGER.info(">>>> 第{}页推送失败", i);
// 推送失败
pushReductionService.updateStatus(bcTravelNoticeList, CarbonDataEnum.FAILED.getCode(), currentTime, batchNo);
travelNoticeMapper.updateStatusBySeqNos(seqNoList, CarbonDataEnum.FAILED.getCode(), null);
}
}
LOGGER.info(">>>> 推送完成,耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
}
/**
*
*/
@Transactional
@Override
public void updateStatus(List<BcTravelNotice> bcTravelNoticeList, String status, String currentTime, String batchNo) {
bcTravelNoticeList.forEach(travelNotice -> {
BcTravelNotice bcTravelNotice = new BcTravelNotice();
bcTravelNotice.setSeqNo(travelNotice.getSeqNo());
bcTravelNotice.setStatus(status);
bcTravelNotice.setDataDeliveryTime(currentTime);
bcTravelNotice.setSendCount(travelNotice.getSendCount() + 1);
if (CarbonDataEnum.SUCCESS.getCode().equals(status)) {
bcTravelNotice.setBusinessCompletionTime(travelNotice.getBusinessCompletionTime());
bcTravelNotice.setBatchNo(batchNo);
bcTravelNotice.setSignStatus(SignStatusEnum.ISSUING.getCode());
}
travelNoticeMapper.updateBySeqNo(bcTravelNotice);
});
}
private String getBusinessCompletionTime(BcTravelNotice travelNotice) {
String industryCode = travelNotice.getIndustryCode();
if (IndustryCodeEnum.SUBWAY.getCode().equals(industryCode)) {

@ -1,23 +1,18 @@
package com.jiuyv.sptcc.carbon.dataprocess.service.impl;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.jiuyv.sptcc.carbon.auth.common.enums.OrgCodeEnum;
import com.jiuyv.sptcc.carbon.auth.common.enums.ScenCodeEnum;
import com.jiuyv.sptcc.carbon.auth.web.request.GetUserRequest;
import com.jiuyv.sptcc.carbon.auth.web.request.GetUserBatchRequest;
import com.jiuyv.sptcc.carbon.auth.web.response.R;
import com.jiuyv.sptcc.carbon.auth.web.response.ResultCode;
import com.jiuyv.sptcc.carbon.auth.web.response.UserHistoryResponse;
import com.jiuyv.sptcc.carbon.auth.web.response.UserHistoryBatchResponse;
import com.jiuyv.sptcc.carbon.dataprocess.config.sftp.SftpChannelPool;
import com.jiuyv.sptcc.carbon.dataprocess.config.sftp.SftpProperties;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcCalcFactor;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcSubwayMileage;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice;
import com.jiuyv.sptcc.carbon.dataprocess.domain.BusSpotCheck;
import com.jiuyv.sptcc.carbon.dataprocess.domain.SubwaySpotCheck;
import com.jiuyv.sptcc.carbon.dataprocess.enums.CarbonDataEnum;
import com.jiuyv.sptcc.carbon.dataprocess.enums.IndustryCodeEnum;
import com.jiuyv.sptcc.carbon.dataprocess.exception.ServiceException;
@ -33,14 +28,13 @@ import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.DictionaryReqVo;
import com.jiuyv.sptcc.carbon.pushgate.dto.reduction.ResDictionaryDTO;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@ -48,14 +42,17 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@ -66,6 +63,7 @@ import java.util.zip.ZipInputStream;
@Service
public class ReadFileServiceImpl implements IReadFileService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadFileServiceImpl.class);
private static final int BATCH_SIZE = 2000;
/**
*
@ -82,7 +80,10 @@ public class ReadFileServiceImpl implements IReadFileService {
private static final DateTimeFormatter SDF = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter REQ_SDF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private static final DecimalFormat DF = new DecimalFormat("#.000");
private static final DecimalFormat MILEAGE_DF = new DecimalFormat("#.000");
private static final DecimalFormat STATION_ID_DF = new DecimalFormat("0000");
private final Map<String, BcCalcFactor> calcFactorCache = new HashMap<>();
private final BcTravelNoticeMapper bcTravelNoticeMapper;
private final BcSubwayMileageMapper subwayMileageMapper;
@ -94,11 +95,6 @@ public class ReadFileServiceImpl implements IReadFileService {
private final SftpChannelPool sftpChannelPool;
/**
* 使objectMapper
*/
private final ObjectMapper objectMapper;
private final String remoteDir;
private final String fileSuffix;
private final String tempDir;
@ -121,73 +117,62 @@ public class ReadFileServiceImpl implements IReadFileService {
this.remoteDir = sftpProperties.getRemoteDir();
this.fileSuffix = sftpProperties.getFileSuffix();
this.tempDir = sftpProperties.getTempDir();
this.objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
/**
*
*/
@Override
public synchronized void readFileAndInsertDatabase(String dateStr) {
public synchronized int readFileAndInsertDatabase(String dateStr) {
String currentTime = sysDateMapper.currentTime();
if (StringUtils.isBlank(dateStr)) {
dateStr = LocalDate.parse(currentTime.substring(0, 8), SDF).minusDays(1).format(SDF);
}
String fileName = dateStr + fileSuffix;
// 下载并解压文件
ChannelSftp sftpChannel = sftpChannelPool.getSftpChannel();
LOGGER.info(">>>> 获取sftpChannel成功");
try (InputStream inputStream = sftpChannel.get(remoteDir + fileName);
ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry nextEntry;
while ((nextEntry = zipInputStream.getNextEntry()) != null && !nextEntry.isDirectory()) {
String filePath = tempDir + nextEntry.getName();
LOGGER.info(">>>> 下载并解压:{}", filePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
IOUtils.copy(zipInputStream, fileOutputStream);
}
}
LOGGER.info(">>>> 文件下载成功");
} catch (IOException | SftpException e) {
LOGGER.error("获取文件出错", e);
throw new ServiceException("获取文件出错");
} finally {
sftpChannelPool.closeChannel(sftpChannel);
}
// 读取文件入库
String csvName = fileName.replace("zip", "csv");
String csvPath = tempDir + csvName;
LOGGER.info(">>>> 开始读取文件:{}", csvPath);
File file = getFile(dateStr, currentTime);
String csvName = file.getName();
long startTime = System.currentTimeMillis();
// 是否第一次读取
boolean notFirst = bcTravelNoticeMapper.selectCountByFileName(csvName) != 0;
Long count = bcTravelNoticeMapper.selectCountByFileName(csvName);
try (FileInputStream fis = new FileInputStream(csvPath);
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
// 跳到指定行开始读取
seek(br, count);
String line;
while ((line = br.readLine()) != null) {
LOGGER.debug("插入数据:{}", line);
insertData(line, currentTime, csvName);
int count = 0;
while (true) {
List<BcTravelNotice> list = getBcTravelNoticeList(br, csvName);
if (CollectionUtils.isEmpty(list)) {
break;
}
if (notFirst) {
list = filterDuplicates(list);
if (CollectionUtils.isEmpty(list)) {
continue;
}
}
// 授权校验及其他信息配置
authVerify(list, currentTime);
bcTravelNoticeMapper.batchInsert(list);
count += list.size();
}
LOGGER.info(">>>> 文件入库成功");
LOGGER.info(">>>> 文件入库成功。记录数{},耗时:{}秒", count, (System.currentTimeMillis() - startTime) / 1000);
return count;
} catch (IOException e) {
LOGGER.error("读取文件出错", e);
throw new ServiceException("读取文件出错");
} finally {
try {
Files.delete(Paths.get(csvPath));
Files.delete(file.toPath());
} catch (IOException e) {
LOGGER.error("文件删除失败", e);
}
}
}
/**
*
*/
private List<BcTravelNotice> filterDuplicates(List<BcTravelNotice> list) {
Set<String> TravelNoList = bcTravelNoticeMapper.selectTravelNoListByTravelNoList(list);
return list.stream().filter(tn -> !TravelNoList.contains(tn.getTravelNo())).collect(Collectors.toList());
}
/**
*
*/
@ -214,6 +199,42 @@ public class ReadFileServiceImpl implements IReadFileService {
}
/**
*
*/
private File getFile(String dateStr, String currentTime) {
if (StringUtils.isBlank(dateStr)) {
dateStr = LocalDate.parse(currentTime.substring(0, 8), SDF).minusDays(1).format(SDF);
}
String fileName = dateStr + fileSuffix;
// 下载并解压文件
ChannelSftp sftpChannel = sftpChannelPool.getSftpChannel();
LOGGER.info(">>>> 获取sftpChannel成功");
try (InputStream inputStream = sftpChannel.get(remoteDir + fileName);
ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry nextEntry;
while ((nextEntry = zipInputStream.getNextEntry()) != null && !nextEntry.isDirectory()) {
String filePath = tempDir + nextEntry.getName();
LOGGER.info(">>>> 下载并解压:{}", filePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
IOUtils.copy(zipInputStream, fileOutputStream);
}
}
LOGGER.info(">>>> 文件下载成功");
} catch (IOException | SftpException e) {
LOGGER.error("获取文件出错", e);
throw new ServiceException("获取文件出错");
} finally {
sftpChannelPool.closeChannel(sftpChannel);
}
final File file = new File(tempDir, fileName.replace("zip", "csv"));
LOGGER.info(">>>> 开始读取文件:{}", file.getAbsolutePath());
return file;
}
private List<BcSubwayMileage> buildSubwayMileageList(Map<String, Double> data) {
List<BcSubwayMileage> list = new ArrayList<>();
for (Map.Entry<String, Double> entry : data.entrySet()) {
@ -221,7 +242,7 @@ public class ReadFileServiceImpl implements IReadFileService {
String[] split = entry.getKey().split("-");
subwayMileage.setInStationId(split[0]);
subwayMileage.setOutStationId(split[1]);
subwayMileage.setMileage(DF.format(entry.getValue()));
subwayMileage.setMileage(MILEAGE_DF.format(entry.getValue()));
list.add(subwayMileage);
}
return list;
@ -230,28 +251,51 @@ public class ReadFileServiceImpl implements IReadFileService {
private BcCalcFactor getCalcFactor(String intoTransTime, String sceneCode) {
BcCalcFactor bcCalcFactor = bcCalcFactorMapper.selectByTime(intoTransTime, sceneCode);
if (bcCalcFactor == null) {
LOGGER.error("未查询到排放因子数据:{}", intoTransTime);
throw new ServiceException("未查询到排放因子数据");
BcCalcFactor calcFactor = calcFactorCache.get(sceneCode);
LocalDateTime time = LocalDateTime.parse(intoTransTime, REQ_SDF);
if (calcFactor == null || time.isAfter(calcFactor.getEnd()) || time.isBefore(calcFactor.getStart())) {
calcFactor = bcCalcFactorMapper.selectByTime(intoTransTime, sceneCode);
if (calcFactor == null) {
LOGGER.error("未查询到排放因子数据:{}", intoTransTime);
throw new ServiceException("未查询到排放因子数据");
}
calcFactor.setStart(LocalDateTime.parse(calcFactor.getStartTime(), REQ_SDF));
calcFactor.setEnd(LocalDateTime.parse(calcFactor.getEndTime(), REQ_SDF));
calcFactorCache.put(sceneCode, calcFactor);
}
return bcCalcFactor;
return calcFactor;
}
private List<BcTravelNotice> getBcTravelNoticeList(BufferedReader br, String fileName) throws IOException {
List<BcTravelNotice> list = new ArrayList<>();
String line;
while ((line = br.readLine()) != null && list.size() < BATCH_SIZE) {
LOGGER.debug("获取记录:{}", line);
BcTravelNotice travelNotice = getBcTravelNotice(line, fileName);
if (travelNotice != null) {
checkAbnormalData(travelNotice);
list.add(travelNotice);
}
}
return list;
}
/**
*
*/
private void insertData(String line, String dataConfirmationTime, String fileName) {
private BcTravelNotice getBcTravelNotice(String line, String fileName) {
String[] split = line.split(",");
BcTravelNotice travelNotice = new BcTravelNotice();
travelNotice.setSourceFileName(fileName);
travelNotice.setTravelNo(handleValue(split[0]));
String travelNo = handleValue(split[0]);
if (StringUtils.isBlank(travelNo)) {
LOGGER.info("该条记录缺少流水号:{}", line);
return null;
}
travelNotice.setSeqNo("CARBON" + travelNo);
travelNotice.setTravelNo(travelNo);
travelNotice.setIndustryCode(handleValue(split[1]));
travelNotice.setUserId(handleValue(split[2]));
travelNotice.setCcid(handleValue(split[3]));
travelNotice.setInStationId(handleValue(split[4]));
travelNotice.setOutStationId(handleValue(split[5]));
travelNotice.setInStationId(handleStationId(split[4]));
travelNotice.setOutStationId(handleStationId(split[5]));
travelNotice.setOpenChannel(handleValue(split[6]));
travelNotice.setIntoTransTime(handleTime(split[7]));
travelNotice.setOutTransTime(handleTime(split[8]));
@ -266,118 +310,124 @@ public class ReadFileServiceImpl implements IReadFileService {
travelNotice.setOutStationName(handleValue(split[17]));
travelNotice.setOutDeviceNo(handleValue(split[18]));
travelNotice.setOutDeviceSerialNo(handleValue(split[19]));
// 检查异常数据
if (isAbnormalData(travelNotice)) {
return;
}
BcCalcFactor bcCalcFactor;
if (IndustryCodeEnum.SUBWAY.getCode().equals(travelNotice.getIndustryCode())) {
bcCalcFactor = getCalcFactor(travelNotice.getOutTransTime(), IndustryCodeEnum.SUBWAY.getCode());
// 计算里程 查不到里程,设置 里程计算错误
if (!calculateMileage(travelNotice)) {
travelNotice.setStatus(CarbonDataEnum.MILEAGE_ERROR.getCode());
bcTravelNoticeMapper.insert(travelNotice);
return;
}
} else {
bcCalcFactor = getCalcFactor(travelNotice.getIntoTransTime(), IndustryCodeEnum.BUS.getCode());
// 计算里程
travelNotice.setMileage(String.format("%.3f", bcCalcFactor.getAverageMileage()));
}
if (authVerify(travelNotice, dataConfirmationTime)) {
travelNotice.setStatus(CarbonDataEnum.PROCESSING.getCode());
travelNotice.setMethodId(bcCalcFactor.getMethodId());
travelNotice.setBaseFactor(bcCalcFactor.getBaseFactor());
travelNotice.setFactor(bcCalcFactor.getFactor());
// 计算hash
spotCheckHash(travelNotice);
} else {
travelNotice.setStatus(CarbonDataEnum.UNAUTHORIZED.getCode());
}
travelNotice.setDataConfirmationTime(dataConfirmationTime);
bcTravelNoticeMapper.insert(travelNotice);
return travelNotice;
}
/**
*
*/
private boolean isAbnormalData(BcTravelNotice travelNotice) {
private void checkAbnormalData(BcTravelNotice travelNotice) {
String industryCode = travelNotice.getIndustryCode();
if (!IndustryCodeEnum.SUBWAY.getCode().equals(industryCode)
&& !IndustryCodeEnum.BUS.getCode().equals(industryCode)) {
insertAbnormalData(travelNotice, "既不是公交也不是地铁");
return true;
travelNotice.setStatus(CarbonDataEnum.INIT.getCode());
travelNotice.setRemark("既不是公交也不是地铁");
return;
}
if (IndustryCodeEnum.SUBWAY.getCode().equals(industryCode)) {
if (travelNotice.getInStationId() == null) {
insertAbnormalData(travelNotice, "地铁没有进站编码");
return true;
travelNotice.setStatus(CarbonDataEnum.INIT.getCode());
travelNotice.setRemark("地铁没有进站编码");
return;
}
if (travelNotice.getOutTransTime() == null) {
insertAbnormalData(travelNotice, "地铁没有出站时间");
return true;
travelNotice.setStatus(CarbonDataEnum.INIT.getCode());
travelNotice.setRemark("地铁没有出站时间");
return;
}
}
if (IndustryCodeEnum.BUS.getCode().equals(industryCode) && travelNotice.getIntoTransTime() == null) {
insertAbnormalData(travelNotice, "公交没有进站时间");
return true;
travelNotice.setStatus(CarbonDataEnum.INIT.getCode());
travelNotice.setRemark("公交没有进站时间");
}
return false;
}
private void insertAbnormalData(BcTravelNotice travelNotice, String remark) {
travelNotice.setStatus(CarbonDataEnum.INIT.getCode());
travelNotice.setRemark(remark);
bcTravelNoticeMapper.insert(travelNotice);
}
/**
*
*
* @return true
*/
private boolean authVerify(BcTravelNotice travelNotice, String currentTime) {
GetUserRequest request = new GetUserRequest();
request.setCcid(travelNotice.getCcid());
String industryCode = travelNotice.getIndustryCode();
if (IndustryCodeEnum.BUS.getCode().equals(industryCode)) {
request.setScenCode(ScenCodeEnum.BUS.getCode());
request.setTransTime(LocalDateTime.parse(travelNotice.getIntoTransTime(), REQ_SDF));
} else if (IndustryCodeEnum.SUBWAY.getCode().equals(industryCode)) {
request.setScenCode(ScenCodeEnum.SUBLINE.getCode());
request.setTransTime(LocalDateTime.parse(travelNotice.getOutTransTime(), REQ_SDF));
} else {
return false;
}
request.setRequestId(travelNotice.getTravelNo());
private void authVerify(List<BcTravelNotice> tnList, String currentTime) {
GetUserBatchRequest request = new GetUserBatchRequest();
request.setRequestId("RequestId");
request.setReqTime(currentTime);
request.setOrgCode(OrgCodeEnum.DATAPROCESS.getCode());
List<GetUserBatchRequest.AuthRequest> list = tnList.stream().map(this::buildAuthRequest)
.filter(Objects::nonNull).collect(Collectors.toList());
request.setList(list);
LOGGER.debug(">>>> 开始授权查询");
R<UserHistoryResponse> r = carbonAuthFeign.getUserByCid(request);
R<UserHistoryBatchResponse> r = carbonAuthFeign.getUserByCidBatch(request);
LOGGER.debug(">>>> 授权查询结果:{}", r.getCode());
if (!ResultCode.SUCCESS.getCode().equals(r.getCode())) {
return false;
throw new ServiceException("授权查询异常");
}
return !CollectionUtils.isEmpty(r.getData().getList());
Set<String> passSet = r.getData().getList().stream().filter(UserHistoryBatchResponse.AuthRecord::getAuthFlag)
.map(UserHistoryBatchResponse.AuthRecord::getTravelNo).collect(Collectors.toSet());
for (BcTravelNotice tn : tnList) {
if (tn.getStatus() != null) {
continue;
}
if (passSet.contains(tn.getTravelNo())) {
tn.setStatus(CarbonDataEnum.PROCESSING.getCode());
// 其他信息(里程和因子)
appendInfo(tn);
} else {
tn.setStatus(CarbonDataEnum.UNAUTHORIZED.getCode());
}
tn.setDataConfirmationTime(currentTime);
}
}
/**
* ()
*/
private void appendInfo(BcTravelNotice tn) {
BcCalcFactor calcFactor = getCalcFactor(tn.getIntoTransTime(), tn.getIndustryCode());
tn.setMethodId(calcFactor.getMethodId());
tn.setBaseFactor(calcFactor.getBaseFactor());
tn.setFactor(calcFactor.getFactor());
if (IndustryCodeEnum.SUBWAY.getCode().equals(tn.getIndustryCode())) {
calculateMileage(tn);
} else {
tn.setMileage(MILEAGE_DF.format(calcFactor.getAverageMileage()));
}
}
private GetUserBatchRequest.AuthRequest buildAuthRequest(BcTravelNotice tn) {
if (tn.getStatus() != null) {
return null;
}
GetUserBatchRequest.AuthRequest authRequest = new GetUserBatchRequest.AuthRequest();
authRequest.setCcid(tn.getCcid());
authRequest.setTravelNo(tn.getTravelNo());
String industryCode = tn.getIndustryCode();
if (IndustryCodeEnum.BUS.getCode().equals(industryCode)) {
authRequest.setScenCode(ScenCodeEnum.BUS.getCode());
authRequest.setTransTime(LocalDateTime.parse(tn.getIntoTransTime(), REQ_SDF));
return authRequest;
}
if (IndustryCodeEnum.SUBWAY.getCode().equals(industryCode)) {
authRequest.setScenCode(ScenCodeEnum.SUBLINE.getCode());
authRequest.setTransTime(LocalDateTime.parse(tn.getOutTransTime(), REQ_SDF));
return authRequest;
}
return null;
}
/**
* false
*
*/
private boolean calculateMileage(BcTravelNotice travelNotice) {
private void calculateMileage(BcTravelNotice travelNotice) {
// 只有地铁计算里程 查不到里程,记里程异常状态
LOGGER.debug(">>>> 计算里程");
String mileage = subwayMileageMapper
.selectMileage(travelNotice.getInStationId(), travelNotice.getOutStationId());
String mileage = subwayMileageMapper.selectMileage(travelNotice.getInStationId(), travelNotice.getOutStationId());
if (mileage == null) {
return false;
travelNotice.setStatus(CarbonDataEnum.MILEAGE_ERROR.getCode());
} else {
travelNotice.setMileage(mileage);
return true;
}
}
@ -403,63 +453,13 @@ public class ReadFileServiceImpl implements IReadFileService {
}
/**
* hash
*
*/
private void spotCheckHash(BcTravelNotice travelNotice) {
if (IndustryCodeEnum.SUBWAY.getCode().equals(travelNotice.getIndustryCode())) {
SubwaySpotCheck spotCheck = new SubwaySpotCheck();
spotCheck.setTravelNo(travelNotice.getTravelNo());
spotCheck.setIntoTransTime(travelNotice.getIntoTransTime());
spotCheck.setInDeviceNo(travelNotice.getInDeviceNo());
spotCheck.setInStationName(travelNotice.getInStationName());
spotCheck.setOutTransTime(travelNotice.getOutTransTime());
spotCheck.setOutDeviceNo(travelNotice.getOutDeviceNo());
spotCheck.setOutStationName(travelNotice.getOutStationName());
spotCheck.setMileage(travelNotice.getMileage());
travelNotice.setHashData(sm3Hash(spotCheck));
} else {
BusSpotCheck spotCheck = new BusSpotCheck();
spotCheck.setTravelNo(travelNotice.getTravelNo());
spotCheck.setIntoTransTime(travelNotice.getIntoTransTime());
spotCheck.setLineNo(travelNotice.getLineNo());
spotCheck.setMileage(travelNotice.getMileage());
travelNotice.setHashData(sm3Hash(spotCheck));
}
}
private String sm3Hash(Object data) {
byte[] bytes = convertToJson(data).getBytes(StandardCharsets.UTF_8);
SM3Digest digest = new SM3Digest();
digest.update(bytes, 0, bytes.length);
byte[] output = new byte[digest.getDigestSize()];
digest.doFinal(output, 0);
return Hex.toHexString(output);
}
/**
*
*/
private void seek(BufferedReader br, Long offset) throws IOException {
if (offset == null) {
return;
}
String line;
for (int i = 0; i < offset; i++) {
line = br.readLine();
if (line == null) {
break;
}
}
}
private String convertToJson(Object o) {
try {
return objectMapper.writeValueAsString(o);
} catch (Exception e) {
LOGGER.error("原始数据序列化错误", e);
throw new ServiceException("原始数据序列化错误");
private String handleStationId(String value) {
if ("\\N".equals(value) || StringUtils.isBlank(value)) {
return null;
}
return STATION_ID_DF.format(Integer.parseInt(value));
}
}

@ -7,11 +7,23 @@ server:
connection-timeout: 60000
threads:
max: 200
eureka:
instance:
appname: ${spring.application.name}
lease-expiration-duration-in-seconds: 90
lease-renewal-interval-in-seconds: 10
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
enabled: true
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: http://192.168.10.165:18888/eureka/
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
#url: jdbc:oracle:thin:@(DESCRIPTION=(FAILOVER=on)(LOAD_BALANCE=off)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=130.252.200.62)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=130.252.200.62)(PORT=1521)))(CONNECT_DATA=(SERVER = DEDICATED)(SID = orcl)))
url: jdbc:oracle:thin:@(DESCRIPTION=(FAILOVER=on)(LOAD_BALANCE=off)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.10.201)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.10.201)(PORT=1521)))(CONNECT_DATA=(SERVER = DEDICATED)(SID = jyorcl)))
username: tanphdev
password: tanphdev
@ -28,14 +40,6 @@ spring:
user:
password: markettest
name: markettest
cache:
type: caffeine
cache-names:
- changeStationCache
- mileageCache
- calcFactorCache
caffeine:
spec: initialCapacity=10,maximumSize=500,expireAfterWrite=60s
jackson:
default-property-inclusion: non_null
@ -57,6 +61,7 @@ mybatis:
carbon-data-process:
enableUpChain: true
sftp:
host: 172.16.12.108
port: 22
@ -96,6 +101,12 @@ xxl:
#执行器Log文件定期清理功能指定日志保存天数日志文件过期自动删除。限制至少保持3天否则功能不生效
#-1表示永不删除
logretentiondays: -1
logging:
level:
com.jiuyv.sptcc.carbon.dataprocess: debug
#logging:
# level:
# com.jiuyv.sptcc.carbon.dataprocess.mapper: debug
sms:
enable: false
sendUrl: http://localhost:18878/smsBridge/wl/SmsServlet
phone-list:
- 13900000000

@ -1,18 +1,5 @@
server:
port: 18818
eureka:
instance:
appname: ${spring.application.name}
lease-expiration-duration-in-seconds: 90
lease-renewal-interval-in-seconds: 10
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
enabled: true
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: http://192.168.10.165:18888/eureka/
spring:
config:

@ -3,7 +3,7 @@
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiuyv.sptcc.carbon.dataprocess.mapper.BcSubwayMileageMapper">
<cache eviction="LRU" size="10000"/>
<resultMap id="BaseResultMap" type="com.jiuyv.sptcc.carbon.dataprocess.domain.BcSubwayMileage">
<id property="inStationId" column="IN_STATION_ID" jdbcType="VARCHAR"/>
<id property="outStationId" column="OUT_STATION_ID" jdbcType="VARCHAR"/>
@ -17,7 +17,7 @@
IN_STATION_NAME,OUT_STATION_NAME
</sql>
<select id="selectSubwayMileagePage" resultMap="BaseResultMap">
<select id="selectSubwayMileagePage" resultMap="BaseResultMap" useCache="false">
select
<include refid="Base_Column_List" />
from TBL_BC_SUBWAY_MILEAGE

@ -70,176 +70,7 @@
CREATE_TIME,LST_UPD_USER,LST_UPD_TIME
</sql>
<select id="selectBySeqNo" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from TBL_BC_TRAVEL_NOTICE
where SEQ_NO = #{seqNo,jdbcType=VARCHAR}
</select>
<select id="selectPageByStatus" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM (
SELECT row_number() OVER (ORDER BY SEQ_NO) rn, t.*
FROM TBL_BC_TRAVEL_NOTICE t
WHERE t.STATUS=#{status}
)
WHERE rn BETWEEN #{start} AND #{count}
</select>
<select id="selectCountByStatus" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE WHERE STATUS = #{status}
</select>
<select id="selectListByBatchNo" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM TBL_BC_TRAVEL_NOTICE
WHERE BATCH_NO=#{batchNo}
</select>
<select id="selectCountBySignStatus" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE WHERE SIGN_STATUS = #{signStatus} AND SIGN_QUERY_COUNT &lt; 6
</select>
<select id="selectPageBySignStatus" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM (
SELECT row_number() OVER (ORDER BY SEQ_NO) rn, t.*
FROM TBL_BC_TRAVEL_NOTICE t
WHERE t.SIGN_STATUS=#{signStatus} AND t.SIGN_QUERY_COUNT &lt; 6
)
WHERE rn BETWEEN #{start} AND #{count}
</select>
<select id="selectCountByFileName" resultType="java.lang.Long">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE WHERE SOURCE_FILE_NAME = #{fileName}
</select>
<select id="selectTravelNoticePage" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM TBL_BC_TRAVEL_NOTICE
<where>
<if test="seqNo != null and seqNo != ''">
and SEQ_NO = #{seqNo,jdbcType=VARCHAR}
</if>
<if test="travelNo != null and travelNo != ''">
and TRAVEL_NO = #{travelNo,jdbcType=VARCHAR}
</if>
<if test="startTime != null and startTime != ''">
and CREATE_TIME >= #{startTime,jdbcType=VARCHAR}
</if>
<if test="endTime != null and endTime != ''">
and CREATE_TIME &lt;= #{endTime,jdbcType=VARCHAR}
</if>
</where>
</select>
<insert id="insert" keyColumn="SEQ_NO" keyProperty="seqNo"
parameterType="com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice" useGeneratedKeys="true">
<selectKey keyProperty="seqNo" order="BEFORE" resultType="java.lang.String">
select TO_CHAR(SYSDATE, 'YYYYMMDD') || TO_CHAR(SEQ_BC_TRAVEL.nextVal, 'FM00000000') from dual
</selectKey>
insert into TBL_BC_TRAVEL_NOTICE
<trim prefix="(" suffix=")" suffixOverrides=",">
SEQ_NO,
<if test="methodId != null">METHOD_ID,</if>
<if test="baseFactor != null">BASE_FACTOR,</if>
<if test="factor != null">FACTOR,</if>
<if test="travelNo != null">TRAVEL_NO,</if>
<if test="industryCode != null">INDUSTRY_CODE,</if>
<if test="userId != null">USER_ID,</if>
<if test="ccid != null">CCID,</if>
<if test="inStationId != null">IN_STATION_ID,</if>
<if test="outStationId != null">OUT_STATION_ID,</if>
<if test="openChannel != null">OPEN_CHANNEL,</if>
<if test="intoTransTime != null">INTO_TRANS_TIME,</if>
<if test="outTransTime != null">OUT_TRANS_TIME,</if>
<if test="cardNo != null">CARD_NO,</if>
<if test="inTransactionSerialNo != null">IN_TRANSACTION_SERIAL_NO,</if>
<if test="inStationName != null">IN_STATION_NAME,</if>
<if test="inDeviceNo != null">IN_DEVICE_NO,</if>
<if test="inDeviceSerialNo != null">IN_DEVICE_SERIAL_NO,</if>
<if test="lineNo != null">LINE_NO,</if>
<if test="lineName != null">LINE_NAME,</if>
<if test="outTransactionSerialNo != null">OUT_TRANSACTION_SERIAL_NO,</if>
<if test="outStationName != null">OUT_STATION_NAME,</if>
<if test="outDeviceNo != null">OUT_DEVICE_NO,</if>
<if test="outDeviceSerialNo != null">OUT_DEVICE_SERIAL_NO,</if>
<if test="batchNo != null">BATCH_NO,</if>
<if test="mileage != null">MILEAGE,</if>
<if test="dataConfirmationTime != null">DATA_CONFIRMATION_TIME,</if>
<if test="carbonFootprint != null">CARBON_FOOTPRINT,</if>
<if test="chainStatus != null">CHAIN_STATUS,</if>
<if test="chainTxId != null">CHAIN_TX_ID,</if>
<if test="hashData != null">HASH_DATA,</if>
<if test="sourceFileName != null">SOURCE_FILE_NAME,</if>
<if test="reductionCalculateTime != null">REDUCTION_CALCULATE_TIME,</if>
<if test="dataDeliveryTime != null">DATA_DELIVERY_TIME,</if>
<if test="status != null">STATUS,</if>
<if test="remark != null">REMARK,</if>
<if test="businessCompletionTime != null">BUSINESS_COMPLETION_TIME,</if>
<if test="nextSendTime != null">NEXT_SEND_TIME,</if>
<if test="sendCount != null">SEND_COUNT,</if>
<if test="signStatus != null">SIGN_STATUS,</if>
<if test="signQueryCount != null">SIGN_QUERY_COUNT,</if>
CREATE_USER,
CREATE_TIME,
LST_UPD_USER,
LST_UPD_TIME
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
#{seqNo,jdbcType=CHAR},
<if test="methodId != null">#{methodId,jdbcType=VARCHAR},</if>
<if test="baseFactor != null">#{baseFactor,jdbcType=VARCHAR},</if>
<if test="factor != null">#{factor,jdbcType=VARCHAR},</if>
<if test="travelNo != null">#{travelNo,jdbcType=VARCHAR},</if>
<if test="industryCode != null">#{industryCode,jdbcType=VARCHAR},</if>
<if test="userId != null">#{userId,jdbcType=VARCHAR},</if>
<if test="ccid != null">#{ccid,jdbcType=VARCHAR},</if>
<if test="inStationId != null">#{inStationId,jdbcType=VARCHAR},</if>
<if test="outStationId != null">#{outStationId,jdbcType=VARCHAR},</if>
<if test="openChannel != null">#{openChannel,jdbcType=VARCHAR},</if>
<if test="intoTransTime != null">#{intoTransTime,jdbcType=CHAR},</if>
<if test="outTransTime != null">#{outTransTime,jdbcType=CHAR},</if>
<if test="cardNo != null">#{cardNo,jdbcType=VARCHAR},</if>
<if test="inTransactionSerialNo != null">#{inTransactionSerialNo,jdbcType=VARCHAR},</if>
<if test="inStationName != null">#{inStationName,jdbcType=VARCHAR},</if>
<if test="inDeviceNo != null">#{inDeviceNo,jdbcType=VARCHAR},</if>
<if test="inDeviceSerialNo != null">#{inDeviceSerialNo,jdbcType=VARCHAR},</if>
<if test="lineNo != null">#{lineNo,jdbcType=VARCHAR},</if>
<if test="lineName != null">#{lineName,jdbcType=VARCHAR},</if>
<if test="outTransactionSerialNo != null">#{outTransactionSerialNo,jdbcType=VARCHAR},</if>
<if test="outStationName != null">#{outStationName,jdbcType=VARCHAR},</if>
<if test="outDeviceNo != null">#{outDeviceNo,jdbcType=VARCHAR},</if>
<if test="outDeviceSerialNo != null">#{outDeviceSerialNo,jdbcType=VARCHAR},</if>
<if test="batchNo != null">#{batchNo,jdbcType=VARCHAR},</if>
<if test="mileage != null">#{mileage,jdbcType=VARCHAR},</if>
<if test="dataConfirmationTime != null">#{dataConfirmationTime,jdbcType=CHAR},</if>
<if test="carbonFootprint != null">#{carbonFootprint,jdbcType=VARCHAR},</if>
<if test="chainStatus != null">#{chainStatus,jdbcType=VARCHAR},</if>
<if test="chainTxId != null">#{chainTxId,jdbcType=VARCHAR},</if>
<if test="hashData != null">#{hashData,jdbcType=VARCHAR},</if>
<if test="sourceFileName != null">#{sourceFileName,jdbcType=VARCHAR},</if>
<if test="reductionCalculateTime != null">#{reductionCalculateTime,jdbcType=CHAR},</if>
<if test="dataDeliveryTime != null">#{dataDeliveryTime,jdbcType=CHAR},</if>
<if test="status != null">#{status,jdbcType=VARCHAR},</if>
<if test="remark != null">#{remark,jdbcType=VARCHAR},</if>
<if test="businessCompletionTime != null">#{businessCompletionTime,jdbcType=CHAR},</if>
<if test="nextSendTime != null">#{nextSendTime,jdbcType=CHAR},</if>
<if test="sendCount != null">#{sendCount,jdbcType=DECIMAL},</if>
<if test="signStatus != null">#{signStatus,jdbcType=DECIMAL},</if>
<if test="signQueryCount != null">#{signQueryCount,jdbcType=DECIMAL},</if>
'admin', to_char(current_timestamp,'YYYYMMDDHH24MISS'),
'admin', to_char(current_timestamp,'YYYYMMDDHH24MISS')
</trim>
</insert>
<update id="updateBySeqNo" parameterType="com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice">
update TBL_BC_TRAVEL_NOTICE
<sql id="update_set">
<set>
<if test="methodId != null">
METHOD_ID = #{methodId,jdbcType=VARCHAR},
@ -374,8 +205,255 @@
LST_UPD_TIME = #{lstUpdTime,jdbcType=CHAR},
</if>
</set>
</sql>
<select id="selectPageByStatus" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM (
SELECT row_number() OVER (ORDER BY SEQ_NO) rn, t.*
FROM TBL_BC_TRAVEL_NOTICE t
<where>
<if test="status != null">
AND t.STATUS = #{status,jdbcType=VARCHAR}
</if>
<if test="chainStatus != null">
AND t.CHAIN_STATUS = #{chainStatus,jdbcType=VARCHAR}
</if>
</where>
)
WHERE rn BETWEEN #{start} AND #{end}
</select>
<select id="selectCountByStatus" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE
<where>
<if test="status != null">
AND STATUS = #{status,jdbcType=VARCHAR}
</if>
<if test="chainStatus != null">
AND CHAIN_STATUS = #{chainStatus,jdbcType=VARCHAR}
</if>
</where>
</select>
<select id="selectListByBatchNo" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM TBL_BC_TRAVEL_NOTICE
WHERE BATCH_NO=#{batchNo}
</select>
<select id="selectCountBySignStatus" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE WHERE SIGN_STATUS = #{signStatus} AND SIGN_QUERY_COUNT &lt; 6
</select>
<select id="selectPageBySignStatus" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM (
SELECT row_number() OVER (ORDER BY SEQ_NO) rn, t.*
FROM TBL_BC_TRAVEL_NOTICE t
WHERE t.SIGN_STATUS=#{signStatus} AND t.SIGN_QUERY_COUNT &lt; 6
)
WHERE rn BETWEEN #{start} AND #{count}
</select>
<select id="selectTravelNoticeList" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM TBL_BC_TRAVEL_NOTICE
<where>
<if test="seqNo != null and seqNo != ''">
and SEQ_NO = #{seqNo,jdbcType=VARCHAR}
</if>
<if test="travelNo != null and travelNo != ''">
and TRAVEL_NO = #{travelNo,jdbcType=VARCHAR}
</if>
<if test="startTime != null and startTime != ''">
and CREATE_TIME >= #{startTime,jdbcType=VARCHAR}
</if>
<if test="endTime != null and endTime != ''">
and CREATE_TIME &lt;= #{endTime,jdbcType=VARCHAR}
</if>
<if test="status != null and status != ''">
and STATUS = #{status,jdbcType=VARCHAR}
</if>
<if test="signStatus != null and signStatus != ''">
and SIGN_STATUS = #{signStatus,jdbcType=VARCHAR}
</if>
<if test="chainStatus != null and chainStatus != ''">
and CHAIN_STATUS = #{chainStatus,jdbcType=VARCHAR}
</if>
</where>
</select>
<select id="selectCountByFileName" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE
WHERE SOURCE_FILE_NAME = #{fileName}
</select>
<select id="selectTxIdCountByChainStatus" resultType="java.lang.Integer">
SELECT COUNT(*) FROM TBL_BC_TRAVEL_NOTICE
WHERE CHAIN_STATUS = #{chainStatus}
</select>
<select id="selectTxIdLimitByChainStatus" resultType="java.lang.String">
SELECT TRAVEL_NO
FROM (
SELECT row_number() OVER (ORDER BY SEQ_NO) rn, t.TRAVEL_NO
FROM TBL_BC_TRAVEL_NOTICE t
WHERE t.CHAIN_STATUS = #{chainStatus}
)
WHERE rn BETWEEN 1 AND #{count}
</select>
<select id="selectTravelNoListByTravelNoList" resultType="java.lang.String">
WITH travel_list AS (
SELECT '' AS TRAVEL_NO FROM dual WHERE 1=0
<foreach collection="list" item="tn">
UNION ALL SELECT #{tn.travelNo} FROM dual
</foreach>
)
SELECT tn.TRAVEL_NO
FROM TBL_BC_TRAVEL_NOTICE tn
JOIN travel_list tl ON tn.TRAVEL_NO = tl.TRAVEL_NO
</select>
<insert id="batchInsert">
insert into TBL_BC_TRAVEL_NOTICE (
SEQ_NO,
METHOD_ID,
BASE_FACTOR,
FACTOR,
TRAVEL_NO,
INDUSTRY_CODE,
USER_ID,
CCID,
IN_STATION_ID,
OUT_STATION_ID,
OPEN_CHANNEL,
INTO_TRANS_TIME,
OUT_TRANS_TIME,
CARD_NO,
IN_TRANSACTION_SERIAL_NO,
IN_STATION_NAME,
IN_DEVICE_NO,
IN_DEVICE_SERIAL_NO,
LINE_NO,
LINE_NAME,
OUT_TRANSACTION_SERIAL_NO,
OUT_STATION_NAME,
OUT_DEVICE_NO,
OUT_DEVICE_SERIAL_NO,
MILEAGE,
DATA_CONFIRMATION_TIME,
SOURCE_FILE_NAME,
STATUS,
REMARK,
CREATE_USER,
CREATE_TIME,
LST_UPD_USER,
LST_UPD_TIME
)
<foreach collection="list" item="tn" separator="UNION ALL">
SELECT
#{tn.seqNo,jdbcType=VARCHAR} AS SEQ_NO,
#{tn.methodId,jdbcType=VARCHAR} AS METHOD_ID,
#{tn.baseFactor,jdbcType=VARCHAR} AS BASE_FACTOR,
#{tn.factor,jdbcType=VARCHAR} AS FACTOR,
#{tn.travelNo,jdbcType=VARCHAR} AS TRAVEL_NO,
#{tn.industryCode,jdbcType=VARCHAR} AS INDUSTRY_CODE,
#{tn.userId,jdbcType=VARCHAR} AS USER_ID,
#{tn.ccid,jdbcType=VARCHAR} AS CCID,
#{tn.inStationId,jdbcType=VARCHAR} AS IN_STATION_ID,
#{tn.outStationId,jdbcType=VARCHAR} AS OUT_STATION_ID,
#{tn.openChannel,jdbcType=VARCHAR} AS OPEN_CHANNEL,
#{tn.intoTransTime,jdbcType=CHAR} AS INTO_TRANS_TIME,
#{tn.outTransTime,jdbcType=CHAR} AS OUT_TRANS_TIME,
#{tn.cardNo,jdbcType=VARCHAR} AS CARD_NO,
#{tn.inTransactionSerialNo,jdbcType=VARCHAR} AS IN_TRANSACTION_SERIAL_NO,
#{tn.inStationName,jdbcType=VARCHAR} AS IN_STATION_NAME,
#{tn.inDeviceNo,jdbcType=VARCHAR} AS IN_DEVICE_NO,
#{tn.inDeviceSerialNo,jdbcType=VARCHAR} AS IN_DEVICE_SERIAL_NO,
#{tn.lineNo,jdbcType=VARCHAR} AS LINE_NO,
#{tn.lineName,jdbcType=VARCHAR} AS LINE_NAME,
#{tn.outTransactionSerialNo,jdbcType=VARCHAR} AS OUT_TRANSACTION_SERIAL_NO,
#{tn.outStationName,jdbcType=VARCHAR} AS OUT_STATION_NAME,
#{tn.outDeviceNo,jdbcType=VARCHAR} AS OUT_DEVICE_NO,
#{tn.outDeviceSerialNo,jdbcType=VARCHAR} AS OUT_DEVICE_SERIAL_NO,
#{tn.mileage,jdbcType=VARCHAR} AS MILEAGE,
#{tn.dataConfirmationTime,jdbcType=CHAR} AS DATA_CONFIRMATION_TIME,
#{tn.sourceFileName,jdbcType=VARCHAR} AS SOURCE_FILE_NAME,
#{tn.status,jdbcType=VARCHAR} AS STATUS,
#{tn.remark,jdbcType=VARCHAR} AS REMARK,
'admin' AS CREATE_USER,
to_char(current_timestamp,'YYYYMMDDHH24MISS') AS CREATE_TIME,
'admin' AS LST_UPD_USER,
to_char(current_timestamp,'YYYYMMDDHH24MISS') AS LST_UPD_TIME
FROM dual
</foreach>
</insert>
<update id="updateBySeqNo" parameterType="com.jiuyv.sptcc.carbon.dataprocess.domain.BcTravelNotice">
update TBL_BC_TRAVEL_NOTICE
<include refid="update_set"/>
where SEQ_NO = #{seqNo,jdbcType=VARCHAR}
</update>
<update id="updateChainStatusByTxId">
update TBL_BC_TRAVEL_NOTICE
SET CHAIN_STATUS = #{chainStatus,jdbcType=VARCHAR}
WHERE CHAIN_TX_ID = #{txId,jdbcType=VARCHAR}
</update>
<update id="updateChainStatusByTravelNos">
update TBL_BC_TRAVEL_NOTICE
SET CHAIN_STATUS = #{chainStatus,jdbcType=VARCHAR}
<if test="txId != null and txId != ''">
,CHAIN_TX_ID = #{txId,jdbcType=VARCHAR}
</if>
WHERE TRAVEL_NO IN
<foreach collection="list" item="travelNo" separator="," open="(" close=")">
#{travelNo}
</foreach>
</update>
<update id="updateStatusBySeqNos">
update TBL_BC_TRAVEL_NOTICE
SET STATUS = #{status,jdbcType=VARCHAR},
SEND_COUNT = SEND_COUNT + 1,
DATA_DELIVERY_TIME = to_char(current_timestamp,'YYYYMMDDHH24MISS')
<if test="batchNo != null">
,BATCH_NO = #{batchNo,jdbcType=VARCHAR},
BUSINESS_COMPLETION_TIME = to_char(current_timestamp,'YYYYMMDDHH24MISS'),
SIGN_STATUS = 0
</if>
WHERE SEQ_NO IN
<foreach collection="list" item="seqNo" separator="," open="(" close=")">
#{seqNo}
</foreach>
</update>
<update id="updateBatchBySeqNo">
MERGE INTO TBL_BC_TRAVEL_NOTICE target
USING (
SELECT '' AS SEQ_NO, '' AS CARBON_FOOTPRINT, '' AS REDUCTION_CALCULATE_TIME, '' AS STATUS, '' AS CHAIN_STATUS
FROM dual WHERE 1=0
<foreach collection="list" item="tn">
UNION ALL
SELECT #{tn.seqNo}, #{tn.carbonFootprint}, #{tn.reductionCalculateTime}, #{tn.status}, #{tn.chainStatus}
FROM dual
</foreach>
) source
ON (target.SEQ_NO = source.SEQ_NO)
WHEN MATCHED THEN
UPDATE SET
target.CARBON_FOOTPRINT = source.CARBON_FOOTPRINT,
target.REDUCTION_CALCULATE_TIME = source.REDUCTION_CALCULATE_TIME,
target.STATUS = source.STATUS,
target.CHAIN_STATUS = source.CHAIN_STATUS
</update>
</mapper>

@ -3,7 +3,7 @@
<groupId>com.jiuyv.sptcc</groupId>
<artifactId>carbon-dataprocess</artifactId>
<version>0.4.2-SNAPSHOT</version>
<version>0.4.4-SNAPSHOT</version>
<packaging>pom</packaging>
<name>carbon-dataprocess</name>
@ -27,8 +27,8 @@
<spring.cloud.version>2021.0.2</spring.cloud.version>
<logback.version>1.2.11</logback.version>
<spring-boot.version>2.6.7</spring-boot.version>
<carbon-pushgate-api.version>0.9.0</carbon-pushgate-api.version>
<carbon-auth-api.version>0.3.0</carbon-auth-api.version>
<carbon-pushgate-api.version>0.10.1-SNAPSHOT</carbon-pushgate-api.version>
<carbon-auth-api.version>0.8.0</carbon-auth-api.version>
</properties>
<dependencyManagement>

@ -0,0 +1,85 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-datacenter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>agile-datacenter-api</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-common</artifactId>
<version>${agile-common.version}</version>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<!-- 自定义验证注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,31 @@
package com.jiuyv.sptccc.agile.api.fegin;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.*;
import com.jiuyv.sptccc.agile.common.core.domain.R;
import feign.Response;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public interface SjztLinePassengerFeginApi{
/** 查询 t+1线路客流 */
@PostMapping(value="/sjzt/querySjztLinePassengerNonrtime")
public Response querySjztLinePassengerNonrtime(@RequestBody ReqSjztLinePassengerNonrtimeQueryDTO reqInfo) throws Exception;
/** 查询 实时线路客流*/
@PostMapping(value="/sjzt/querySjztLinePassengerRealtime")
public R<List<ResSjztLinePassengerRealtimeQueryDTO>> querySjztLinePassengerRealtime(@RequestBody ReqSjztLinePassengerRealtimeQueryDTO reqInfo) throws Exception;
/** 查询 实时线路累计客流 */
@PostMapping(value="/sjzt/querySjztLinePassengerTotal")
public R<List<ResSjztLinePassengerTotalQueryDTO>> querySjztLinePassengerTotal(@RequestBody ReqSjztLinePassengerTotalQueryDTO reqInfo) throws Exception;
}

@ -0,0 +1,33 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
import javax.validation.constraints.NotNull;
/**
* t+1线_
* @author zhoul
* @date 2024-08-14
*/
public class ReqSjztLinePassengerNonrtimeQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* |yyyy-MM-dd
*/
@NotNull(message="日期不能为空")
private String txnDate;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
}

@ -0,0 +1,54 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
import javax.validation.constraints.NotNull;
/**
* 线_
* @author zhoul
* @date 2024-08-14
*/
public class ReqSjztLinePassengerRealtimeQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* |yyyy-MM-dd
*/
private String txnDate;
/**
* |Y
*/
@NotNull(message="时间段不能为空")
private Integer timeCode;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
}

@ -0,0 +1,54 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
import javax.validation.constraints.NotNull;
/**
* 线_
* @author zhoul
* @date 2024-08-14
*/
public class ReqSjztLinePassengerTotalQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* |yyyy-MM-dd
*/
private String txnDate;
/**
* |Y
*/
@NotNull(message="时间段不能为空")
private Integer timeCode;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
}

@ -0,0 +1,276 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
/**
* t+1线_
* @author zhoul
* @date 2024-08-14
*/
public class ResSjztLinePassengerNonrtimeQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private String txnDate;
/**
*
*/
private String settleCenterCode;
/**
*
*/
private Integer timeCode;
/**
* /线
*/
private String inLineCode;
/**
*
*/
private Long totalCnt;
/**
* /
*/
private Long outTxnCnt;
/**
*
*/
private Long inStationCnt;
/**
*
*/
private Long jtkInStationCnt;
/**
*
*/
private Long jtkBusTransferCnt;
/**
*
*/
private Long jtkMetroTransferCnt;
/**
*
*/
private Long ewmInStationCnt;
/**
*
*/
private Long qrBusTransferCnt;
/**
*
*/
private Long qrMetroTransferCnt;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getJtkBusTransferCnt(){
return jtkBusTransferCnt;
}
/**
* Set
*/
public void setJtkBusTransferCnt(Long jtkBusTransferCnt){
this.jtkBusTransferCnt = jtkBusTransferCnt;
}
/**
* Get
*/
public Long getJtkMetroTransferCnt(){
return jtkMetroTransferCnt;
}
/**
* Set
*/
public void setJtkMetroTransferCnt(Long jtkMetroTransferCnt){
this.jtkMetroTransferCnt = jtkMetroTransferCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
/**
* Get
*/
public Long getQrBusTransferCnt(){
return qrBusTransferCnt;
}
/**
* Set
*/
public void setQrBusTransferCnt(Long qrBusTransferCnt){
this.qrBusTransferCnt = qrBusTransferCnt;
}
/**
* Get
*/
public Long getQrMetroTransferCnt(){
return qrMetroTransferCnt;
}
/**
* Set
*/
public void setQrMetroTransferCnt(Long qrMetroTransferCnt){
this.qrMetroTransferCnt = qrMetroTransferCnt;
}
//拼接为文件的格式,方便调整
// public String toFileString(String splitStr) {
// return txnDate + splitStr + settleCenterCode
// + splitStr + timeCode + splitStr + inLineCode + splitStr + totalCnt
// + splitStr + outTxnCnt + splitStr + inStationCnt + splitStr + jtkInStationCnt
// + splitStr + jtkBusTransferCnt + splitStr + jtkMetroTransferCnt
// + splitStr + ewmInStationCnt + splitStr + qrBusTransferCnt
// + splitStr + qrMetroTransferCnt;
// }
// public String toFileTitle(String splitStr) {
// return "txnDate" + splitStr + "settleCenterCode"
// + splitStr + "timeCode" + splitStr + "inLineCode" + splitStr + "totalCnt"
// + splitStr + "outTxnCnt" + splitStr + "inStationCnt" + splitStr + "jtkInStationCnt"
// + splitStr + "jtkBusTransferCnt" + splitStr + "jtkMetroTransferCnt"
// + splitStr + "ewmInStationCnt" + splitStr + "qrBusTransferCnt"
// + splitStr + "qrMetroTransferCnt";
// }
public String toFileString(String splitStr) {
return settleCenterCode + splitStr + timeCode + splitStr + inLineCode + splitStr + txnDate
+ splitStr + totalCnt + splitStr + outTxnCnt + splitStr + inStationCnt
+ splitStr + jtkInStationCnt + splitStr + qrBusTransferCnt+"\n";
}
public String toFileTitle(String splitStr) {
return "settleCenterCode" + splitStr + "timeCode" + splitStr + "inLineCode" + splitStr +"txnDate"
+ splitStr + "totalCnt" + splitStr + "outTxnCnt" + splitStr + "inStationCnt"
+ splitStr + "jtkInStationCnt" + splitStr + "qrBusTransferCnt"+"\n";
}
}

@ -0,0 +1,176 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
/**
* 线_
* @author zhoul
* @date 2024-08-14
*/
public class ResSjztLinePassengerRealtimeQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private String txnDate;
/**
*
*/
private String settleCenterCode;
/**
*
*/
private Integer timeCode;
/**
* /线
*/
private String inLineCode;
/**
*
*/
private Long totalCnt;
/**
* /
*/
private Long outTxnCnt;
/**
*
*/
private Long inStationCnt;
/**
*
*/
private Long jtkInStationCnt;
/**
*
*/
private Long ewmInStationCnt;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
}

@ -0,0 +1,248 @@
package com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger;
/**
* 线_
* @author zhoul
* @date 2024-08-14
*/
public class ResSjztLinePassengerTotalQueryDTO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private String txnDate;
/**
*
*/
private String settleCenterCode;
/**
*
*/
private Integer timeCode;
/**
* /线
*/
private String inLineCode;
/**
*
*/
private Long totalCnt;
/**
* /
*/
private Long outTxnCnt;
/**
*
*/
private Long inStationCnt;
/**
*
*/
private Long jtkInStationCnt;
/**
*
*/
private Long jtkBusTransferCnt;
/**
*
*/
private Long jtkMetroTransferCnt;
/**
*
*/
private Long ewmInStationCnt;
/**
*
*/
private Long qrBusTransferCnt;
/**
*
*/
private Long qrMetroTransferCnt;
/**
* Get
*/
public String getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(String txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getJtkBusTransferCnt(){
return jtkBusTransferCnt;
}
/**
* Set
*/
public void setJtkBusTransferCnt(Long jtkBusTransferCnt){
this.jtkBusTransferCnt = jtkBusTransferCnt;
}
/**
* Get
*/
public Long getJtkMetroTransferCnt(){
return jtkMetroTransferCnt;
}
/**
* Set
*/
public void setJtkMetroTransferCnt(Long jtkMetroTransferCnt){
this.jtkMetroTransferCnt = jtkMetroTransferCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
/**
* Get
*/
public Long getQrBusTransferCnt(){
return qrBusTransferCnt;
}
/**
* Set
*/
public void setQrBusTransferCnt(Long qrBusTransferCnt){
this.qrBusTransferCnt = qrBusTransferCnt;
}
/**
* Get
*/
public Long getQrMetroTransferCnt(){
return qrMetroTransferCnt;
}
/**
* Set
*/
public void setQrMetroTransferCnt(Long qrMetroTransferCnt){
this.qrMetroTransferCnt = qrMetroTransferCnt;
}
}

@ -0,0 +1,49 @@
package com.jiuyv.sptccc.agile.api.fegin.fallback;
import java.util.List;
import org.springframework.cloud.openfeign.FallbackFactory;
import com.jiuyv.sptccc.agile.api.fegin.SjztLinePassengerFeginApi;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerNonrtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ResSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ResSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.common.core.domain.R;
import feign.Response;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public class SjztLinePassengerFallback implements FallbackFactory<SjztLinePassengerFeginApi> {
@Override
public SjztLinePassengerFeginApi create(Throwable throwable)
{
return new SjztLinePassengerFeginApi()
{
@Override
public Response querySjztLinePassengerNonrtime(
ReqSjztLinePassengerNonrtimeQueryDTO reqInfo) throws Exception {
return Response.builder().body("error".getBytes()).build();
}
@Override
public R<List<ResSjztLinePassengerRealtimeQueryDTO>> querySjztLinePassengerRealtime(
ReqSjztLinePassengerRealtimeQueryDTO reqInfo) throws Exception {
return R.fail(throwable.getMessage());
}
@Override
public R<List<ResSjztLinePassengerTotalQueryDTO>> querySjztLinePassengerTotal(
ReqSjztLinePassengerTotalQueryDTO reqInfo) throws Exception {
return R.fail(throwable.getMessage());
}
};
}
}

@ -0,0 +1,283 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-datacenter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>agile-datacenter-service</artifactId>
<properties>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-datacenter-api</artifactId>
<exclusions>
<exclusion>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-common</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--因为devtools的问题所以agile-common必须和里面版本统一.
使用最新的API包里面的即可-->
<dependency>
<groupId>com.jiuyv.sptcc.agile</groupId>
<artifactId>agile-common</artifactId>
<version>${agile-common.version}</version>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--动态健康监控 可以用于动态感知配置变化-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--整合prometheus-->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<!-- SpringBoot集成mybatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- collections工具类 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- json logstash encoder -->
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- SpringBoot 拦截器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<!-- 测试类相关-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-wiremock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<!--支持私有jar包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
</configuration>
</execution>
</executions>
<configuration>
<fork>true</fork>
<mainClass>com.jiuyv.sptccc.agile.DataCenterServiceApplication</mainClass>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>

@ -0,0 +1,42 @@
package com.jiuyv.sptccc.agile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
*
* @author admin
*/
@EnableFeignClients
@EnableEurekaClient
@EnableScheduling
@EnableTransactionManagement
@SpringBootApplication(exclude = {GroovyTemplateAutoConfiguration.class})
@ImportResource({ "classpath:spring/applicationContext.xml" })//事务控制
public class DataCenterServiceApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(DataCenterServiceApplication.class);
public static void main(String[] args) {
SpringApplication.run(DataCenterServiceApplication.class, args);
LOGGER.info("(♥◠‿◠)ノ゙ 模块启动成功゙ \n"+
" ___ ___ ___ \n"+
" |\\ \\ |\\ \\ / /| \n"+
" \\ \\ \\ \\ \\ \\/ / / \n"+
" __ \\ \\ \\ \\ \\ / / \n"+
" |\\ \\\\_\\ \\ \\/ / / \n"+
" \\ \\________\\ __/ / / \n"+
" \\|________| |\\___/ / \n"+
" \\|___|/ \n"
);
}
}

@ -0,0 +1,16 @@
package com.jiuyv.sptccc.agile;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* web
*
* @author admin
*/
public class DataCenterServiceServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DataCenterServiceApplication.class);
}
}

@ -0,0 +1,25 @@
package com.jiuyv.sptccc.agile.business.common.constant;
/**
*
*/
public class SyncDatacenterConstants
{
private SyncDatacenterConstants() {
throw new IllegalStateException("Utility class");
}
/** 日期转换用 */
public static final String FORMAT_DATETIME ="yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_DATEDAY ="yyyy-MM-dd";
public static final String FORMAT_DATETIME_SIMPLE ="yyyyMMddHHmmss";
public static final String FORMAT_DATEDAY_SIMPLE ="yyyyMMdd";
/** 文件名后缀 */
public static final String FILEEXT_CSV =".csv";
public static final String FILEEXT_ZIP =".zip";
/** 文件名 */
public static final String FILENAME_LINE_PASSENGER_NONRTIME ="line_passenger_nonrtime_";
public static final String FILENAME_LINE_PASSENGER_NONRTIME_W ="line_passenger_nonrtime_%s.zip";
}

@ -0,0 +1,127 @@
package com.jiuyv.sptccc.agile.business.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerNonrtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ResSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ResSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.business.common.constant.SyncDatacenterConstants;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal;
import com.jiuyv.sptccc.agile.business.service.ISjztLinePassengerService;
import com.jiuyv.sptccc.agile.common.annotation.LogIgnore;
import com.jiuyv.sptccc.agile.common.constant.Constants;
import com.jiuyv.sptccc.agile.common.core.domain.R;
import com.jiuyv.sptccc.agile.common.utils.ServletUtils;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
@RestController
@RequestMapping("/sjzt")
public class SjztLinePassengerController {
@Autowired
private ISjztLinePassengerService sjztLinePassengerService;
@LogIgnore
@PostMapping("/querySjztLinePassengerNonrtime")
public void querySjztLinePassengerNonrtime(HttpServletResponse response,@RequestBody ReqSjztLinePassengerNonrtimeQueryDTO reqInfo) throws Exception {
//先去sftp服务器检索是否已有文件
String fileName = ServletUtils.urlEncode(String.format(SyncDatacenterConstants.FILENAME_LINE_PASSENGER_NONRTIME_W
,reqInfo.getTxnDate().replace("-", "")));
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
Path path = sjztLinePassengerService.querySjztLinePassengerNonrtime(reqInfo);
File file = path.toFile();
if(file != null) {
OutputStream outputStream = response.getOutputStream();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
response.setContentLength(inputStream.available());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
} finally {
//上传到sftp并删除文件
file.deleteOnExit();
}
}else {
response.sendError(HttpStatus.NOT_FOUND.value(), "File not found");
}
}
@PostMapping("/querySjztLinePassengerRealtime")
public R<List<ResSjztLinePassengerRealtimeQueryDTO>> querySjztLinePassengerRealtime(@RequestBody ReqSjztLinePassengerRealtimeQueryDTO reqInfo) throws Exception {
List<TblSjztLinePassengerRealtime> list = sjztLinePassengerService.querySjztLinePassengerNonrtime(reqInfo);
List<ResSjztLinePassengerRealtimeQueryDTO> data = new ArrayList<>();
for(TblSjztLinePassengerRealtime x:list) {
ResSjztLinePassengerRealtimeQueryDTO vo = new ResSjztLinePassengerRealtimeQueryDTO();
vo.setTxnDate(DateFormatUtils.format(x.getTxnDate(), Constants.FORMAT_DATEDAY_SIMPLE));
vo.setSettleCenterCode(x.getSettleCenterCode());
vo.setTimeCode(x.getTimeCode());
vo.setInLineCode(x.getInLineCode());
vo.setTotalCnt(x.getTotalCnt());
vo.setOutTxnCnt(x.getOutTxnCnt());
vo.setInStationCnt(x.getInStationCnt());
vo.setJtkInStationCnt(x.getJtkInStationCnt());
// vo.setJtkBusTransferCnt(x.getJtkBusTransferCnt());
// vo.setJtkMetroTransferCnt(x.getJtkMetroTransferCnt());
vo.setEwmInStationCnt(x.getEwmInStationCnt());
// vo.setQrBusTransferCnt(x.getQrBusTransferCnt());
// vo.setQrMetroTransferCnt(x.getQrMetroTransferCnt());
data.add(vo);
}
return R.ok(data);
}
@PostMapping("/querySjztLinePassengerTotal")
public R<List<ResSjztLinePassengerTotalQueryDTO>> querySjztLinePassengerTotal(@RequestBody ReqSjztLinePassengerTotalQueryDTO reqInfo)throws Exception {
List<TblSjztLinePassengerTotal> list = sjztLinePassengerService.querySjztLinePassengerNonrtime(reqInfo);
List<ResSjztLinePassengerTotalQueryDTO> data = new ArrayList<>();
for(TblSjztLinePassengerTotal x:list) {
ResSjztLinePassengerTotalQueryDTO vo = new ResSjztLinePassengerTotalQueryDTO();
vo.setTxnDate(DateFormatUtils.format(x.getTxnDate(), Constants.FORMAT_DATEDAY_SIMPLE));
vo.setSettleCenterCode(x.getSettleCenterCode());
vo.setTimeCode(x.getTimeCode());
vo.setInLineCode(x.getInLineCode());
vo.setTotalCnt(x.getTotalCnt());
vo.setOutTxnCnt(x.getOutTxnCnt());
vo.setInStationCnt(x.getInStationCnt());
vo.setJtkInStationCnt(x.getJtkInStationCnt());
vo.setJtkBusTransferCnt(x.getJtkBusTransferCnt());
vo.setJtkMetroTransferCnt(x.getJtkMetroTransferCnt());
vo.setEwmInStationCnt(x.getEwmInStationCnt());
vo.setQrBusTransferCnt(x.getQrBusTransferCnt());
vo.setQrMetroTransferCnt(x.getQrMetroTransferCnt());
data.add(vo);
}
return R.ok(data);
}
}

@ -0,0 +1,227 @@
package com.jiuyv.sptccc.agile.business.entity;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
/**
* t+1线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerNonrtime implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/** 日期 */
private Date txnDate;
/** 刷卡行业 */
private String settleCenterCode;
/** 时间段 */
private Integer timeCode;
/** 地铁车站号/公交线路号 */
private String inLineCode;
/** 总交易数 */
private Long totalCnt;
/** 总公交上客交易数/地铁出站交易数 */
private Long outTxnCnt;
/** 总地铁进站交易数 */
private Long inStationCnt;
/** 交通卡刷卡数(地铁只统计进站) */
private Long jtkInStationCnt;
/** 交通卡从公交换乘刷卡数 */
private Long jtkBusTransferCnt;
/** 交通卡从地铁换乘刷卡数 */
private Long jtkMetroTransferCnt;
/** 扫码数 */
private Long ewmInStationCnt;
/** 扫码从公交换乘刷卡数 */
private Long qrBusTransferCnt;
/** 扫码从地铁换乘刷卡数 */
private Long qrMetroTransferCnt;
/**
* Get
*/
public Date getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(Date txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getJtkBusTransferCnt(){
return jtkBusTransferCnt;
}
/**
* Set
*/
public void setJtkBusTransferCnt(Long jtkBusTransferCnt){
this.jtkBusTransferCnt = jtkBusTransferCnt;
}
/**
* Get
*/
public Long getJtkMetroTransferCnt(){
return jtkMetroTransferCnt;
}
/**
* Set
*/
public void setJtkMetroTransferCnt(Long jtkMetroTransferCnt){
this.jtkMetroTransferCnt = jtkMetroTransferCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
/**
* Get
*/
public Long getQrBusTransferCnt(){
return qrBusTransferCnt;
}
/**
* Set
*/
public void setQrBusTransferCnt(Long qrBusTransferCnt){
this.qrBusTransferCnt = qrBusTransferCnt;
}
/**
* Get
*/
public Long getQrMetroTransferCnt(){
return qrMetroTransferCnt;
}
/**
* Set
*/
public void setQrMetroTransferCnt(Long qrMetroTransferCnt){
this.qrMetroTransferCnt = qrMetroTransferCnt;
}
}

@ -0,0 +1,227 @@
package com.jiuyv.sptccc.agile.business.entity;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerRealtime implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/** 日期 */
private Date txnDate;
/** 刷卡行业 */
private String settleCenterCode;
/** 时间段 */
private Integer timeCode;
/** 地铁车站号/公交线路号 */
private String inLineCode;
/** 总交易数 */
private Long totalCnt;
/** 总公交上客交易数/地铁出站交易数 */
private Long outTxnCnt;
/** 总地铁进站交易数 */
private Long inStationCnt;
/** 交通卡刷卡数(地铁只统计进站) */
private Long jtkInStationCnt;
/** 交通卡从公交换乘刷卡数 */
private Long jtkBusTransferCnt;
/** 交通卡从地铁换乘刷卡数 */
private Long jtkMetroTransferCnt;
/** 扫码数 */
private Long ewmInStationCnt;
/** 扫码从公交换乘刷卡数 */
private Long qrBusTransferCnt;
/** 扫码从地铁换乘刷卡数 */
private Long qrMetroTransferCnt;
/**
* Get
*/
public Date getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(Date txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getJtkBusTransferCnt(){
return jtkBusTransferCnt;
}
/**
* Set
*/
public void setJtkBusTransferCnt(Long jtkBusTransferCnt){
this.jtkBusTransferCnt = jtkBusTransferCnt;
}
/**
* Get
*/
public Long getJtkMetroTransferCnt(){
return jtkMetroTransferCnt;
}
/**
* Set
*/
public void setJtkMetroTransferCnt(Long jtkMetroTransferCnt){
this.jtkMetroTransferCnt = jtkMetroTransferCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
/**
* Get
*/
public Long getQrBusTransferCnt(){
return qrBusTransferCnt;
}
/**
* Set
*/
public void setQrBusTransferCnt(Long qrBusTransferCnt){
this.qrBusTransferCnt = qrBusTransferCnt;
}
/**
* Get
*/
public Long getQrMetroTransferCnt(){
return qrMetroTransferCnt;
}
/**
* Set
*/
public void setQrMetroTransferCnt(Long qrMetroTransferCnt){
this.qrMetroTransferCnt = qrMetroTransferCnt;
}
}

@ -0,0 +1,227 @@
package com.jiuyv.sptccc.agile.business.entity;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerTotal implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/** 日期 */
private Date txnDate;
/** 刷卡行业 */
private String settleCenterCode;
/** 时间段 */
private Integer timeCode;
/** 地铁车站号/公交线路号 */
private String inLineCode;
/** 总交易数 */
private Long totalCnt;
/** 总公交上客交易数/地铁出站交易数 */
private Long outTxnCnt;
/** 总地铁进站交易数 */
private Long inStationCnt;
/** 交通卡刷卡数(地铁只统计进站) */
private Long jtkInStationCnt;
/** 交通卡从公交换乘刷卡数 */
private Long jtkBusTransferCnt;
/** 交通卡从地铁换乘刷卡数 */
private Long jtkMetroTransferCnt;
/** 扫码数 */
private Long ewmInStationCnt;
/** 扫码从公交换乘刷卡数 */
private Long qrBusTransferCnt;
/** 扫码从地铁换乘刷卡数 */
private Long qrMetroTransferCnt;
/**
* Get
*/
public Date getTxnDate(){
return txnDate;
}
/**
* Set
*/
public void setTxnDate(Date txnDate){
this.txnDate = txnDate;
}
/**
* Get
*/
public String getSettleCenterCode(){
return settleCenterCode;
}
/**
* Set
*/
public void setSettleCenterCode(String settleCenterCode){
this.settleCenterCode = settleCenterCode;
}
/**
* Get
*/
public Integer getTimeCode(){
return timeCode;
}
/**
* Set
*/
public void setTimeCode(Integer timeCode){
this.timeCode = timeCode;
}
/**
* Get/线
*/
public String getInLineCode(){
return inLineCode;
}
/**
* Set/线
*/
public void setInLineCode(String inLineCode){
this.inLineCode = inLineCode;
}
/**
* Get
*/
public Long getTotalCnt(){
return totalCnt;
}
/**
* Set
*/
public void setTotalCnt(Long totalCnt){
this.totalCnt = totalCnt;
}
/**
* Get/
*/
public Long getOutTxnCnt(){
return outTxnCnt;
}
/**
* Set/
*/
public void setOutTxnCnt(Long outTxnCnt){
this.outTxnCnt = outTxnCnt;
}
/**
* Get
*/
public Long getInStationCnt(){
return inStationCnt;
}
/**
* Set
*/
public void setInStationCnt(Long inStationCnt){
this.inStationCnt = inStationCnt;
}
/**
* Get
*/
public Long getJtkInStationCnt(){
return jtkInStationCnt;
}
/**
* Set
*/
public void setJtkInStationCnt(Long jtkInStationCnt){
this.jtkInStationCnt = jtkInStationCnt;
}
/**
* Get
*/
public Long getJtkBusTransferCnt(){
return jtkBusTransferCnt;
}
/**
* Set
*/
public void setJtkBusTransferCnt(Long jtkBusTransferCnt){
this.jtkBusTransferCnt = jtkBusTransferCnt;
}
/**
* Get
*/
public Long getJtkMetroTransferCnt(){
return jtkMetroTransferCnt;
}
/**
* Set
*/
public void setJtkMetroTransferCnt(Long jtkMetroTransferCnt){
this.jtkMetroTransferCnt = jtkMetroTransferCnt;
}
/**
* Get
*/
public Long getEwmInStationCnt(){
return ewmInStationCnt;
}
/**
* Set
*/
public void setEwmInStationCnt(Long ewmInStationCnt){
this.ewmInStationCnt = ewmInStationCnt;
}
/**
* Get
*/
public Long getQrBusTransferCnt(){
return qrBusTransferCnt;
}
/**
* Set
*/
public void setQrBusTransferCnt(Long qrBusTransferCnt){
this.qrBusTransferCnt = qrBusTransferCnt;
}
/**
* Get
*/
public Long getQrMetroTransferCnt(){
return qrMetroTransferCnt;
}
/**
* Set
*/
public void setQrMetroTransferCnt(Long qrMetroTransferCnt){
this.qrMetroTransferCnt = qrMetroTransferCnt;
}
}

@ -0,0 +1,16 @@
package com.jiuyv.sptccc.agile.business.entity.vo;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerNonrtime;
/**
* t+1线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerNonrtimeVO extends TblSjztLinePassengerNonrtime implements java.io.Serializable {
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,16 @@
package com.jiuyv.sptccc.agile.business.entity.vo;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerRealtimeVO extends TblSjztLinePassengerRealtime implements java.io.Serializable {
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,16 @@
package com.jiuyv.sptccc.agile.business.entity.vo;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public class TblSjztLinePassengerTotalVO extends TblSjztLinePassengerTotal implements java.io.Serializable {
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,23 @@
package com.jiuyv.sptccc.agile.business.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.cursor.Cursor;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerNonrtime;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerNonrtimeVO;
/**
* t+1线
* @author zhoul
* @date 2024-08-14
*/
@Mapper
public interface TblSjztLinePassengerNonrtimeMapper{
/** 查询集合 */
@Options(fetchSize = 5000)
Cursor<TblSjztLinePassengerNonrtime> selectList(TblSjztLinePassengerNonrtimeVO paramMap);
}

@ -0,0 +1,22 @@
package com.jiuyv.sptccc.agile.business.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerRealtimeVO;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
@Mapper
public interface TblSjztLinePassengerRealtimeMapper{
/** 查询集合 */
List<TblSjztLinePassengerRealtime> selectList(TblSjztLinePassengerRealtimeVO paramMap);
}

@ -0,0 +1,22 @@
package com.jiuyv.sptccc.agile.business.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerTotalVO;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
@Mapper
public interface TblSjztLinePassengerTotalMapper{
/** 查询集合 */
List<TblSjztLinePassengerTotal> selectList(TblSjztLinePassengerTotalVO paramMap);
}

@ -0,0 +1,26 @@
package com.jiuyv.sptccc.agile.business.service;
import java.nio.file.Path;
import java.util.List;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerNonrtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal;
/**
* 线
* @author zhoul
* @date 2024-08-14
*/
public interface ISjztLinePassengerService {
/** 查询T+1实时客流 */
Path querySjztLinePassengerNonrtime(ReqSjztLinePassengerNonrtimeQueryDTO reqInfo) throws Exception;
/** 查询实时客流 */
List<TblSjztLinePassengerRealtime> querySjztLinePassengerNonrtime(ReqSjztLinePassengerRealtimeQueryDTO reqInfo)throws Exception;
/** 查询实时客流 */
List<TblSjztLinePassengerTotal> querySjztLinePassengerNonrtime(ReqSjztLinePassengerTotalQueryDTO reqInfo) throws Exception;;
}

@ -0,0 +1,174 @@
package com.jiuyv.sptccc.agile.business.service.impl;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ibatis.cursor.Cursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerNonrtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerRealtimeQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ReqSjztLinePassengerTotalQueryDTO;
import com.jiuyv.sptccc.agile.api.fegin.dto.linepassenger.ResSjztLinePassengerNonrtimeQueryDTO;
import com.jiuyv.sptccc.agile.business.common.constant.SyncDatacenterConstants;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerNonrtime;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime;
import com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerNonrtimeVO;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerRealtimeVO;
import com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerTotalVO;
import com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerNonrtimeMapper;
import com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerRealtimeMapper;
import com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerTotalMapper;
import com.jiuyv.sptccc.agile.business.service.ISjztLinePassengerService;
import com.jiuyv.sptccc.agile.common.constant.Constants;
import com.jiuyv.sptccc.agile.common.core.BaseManagerUtils;
import com.jiuyv.sptccc.agile.common.core.domain.BaseTime;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
/**
* t+1线
* @author zhoul
* @date 2024-08-14
*/
@Service("sjztLinePassengerService")
public class SjztLinePassengerServiceImpl implements ISjztLinePassengerService {
private static final Logger LOGGER = LoggerFactory.getLogger(SjztLinePassengerServiceImpl.class);
@Autowired
private TblSjztLinePassengerNonrtimeMapper tblSjztLinePassengerNonrtimeMapper;
@Autowired
private TblSjztLinePassengerRealtimeMapper tblSjztLinePassengerRealtimeMapper;
@Autowired
private TblSjztLinePassengerTotalMapper tblSjztLinePassengerTotalMapper;
@Transactional
@Override
public Path querySjztLinePassengerNonrtime(ReqSjztLinePassengerNonrtimeQueryDTO reqInfo) throws Exception {
Path tempTxtFile = Files.createTempFile(SyncDatacenterConstants.FILENAME_LINE_PASSENGER_NONRTIME, SyncDatacenterConstants.FILEEXT_CSV);
TblSjztLinePassengerNonrtimeVO param = new TblSjztLinePassengerNonrtimeVO();
param.setTxnDate(DateUtils.parseDate(reqInfo.getTxnDate(), Constants.FORMAT_DATEDAY.length()==reqInfo.getTxnDate().length()
?Constants.FORMAT_DATEDAY: Constants.FORMAT_DATEDAY_SIMPLE));
boolean flag = false;
try (Cursor<TblSjztLinePassengerNonrtime> stream = tblSjztLinePassengerNonrtimeMapper.selectList(param);
BufferedWriter writer = Files.newBufferedWriter(tempTxtFile, StandardOpenOption.WRITE)) {
//表头
ResSjztLinePassengerNonrtimeQueryDTO vo = new ResSjztLinePassengerNonrtimeQueryDTO();
writer.write(vo.toFileTitle(","));
Iterator<TblSjztLinePassengerNonrtime> data = stream.iterator();
List<TblSjztLinePassengerNonrtime> lists;
while(!(lists=readLines(data, 20000)).isEmpty()) {
StringBuilder str = new StringBuilder();
for(TblSjztLinePassengerNonrtime x:lists) {
vo = new ResSjztLinePassengerNonrtimeQueryDTO();
vo.setTxnDate(DateFormatUtils.format(x.getTxnDate(), Constants.FORMAT_DATEDAY_SIMPLE));
vo.setSettleCenterCode(x.getSettleCenterCode());
vo.setTimeCode(x.getTimeCode());
vo.setInLineCode(x.getInLineCode());
vo.setTotalCnt(x.getTotalCnt());
vo.setOutTxnCnt(x.getOutTxnCnt());
vo.setInStationCnt(x.getInStationCnt());
vo.setJtkInStationCnt(x.getJtkInStationCnt());
vo.setJtkBusTransferCnt(x.getJtkBusTransferCnt());
vo.setJtkMetroTransferCnt(x.getJtkMetroTransferCnt());
vo.setEwmInStationCnt(x.getEwmInStationCnt());
vo.setQrBusTransferCnt(x.getQrBusTransferCnt());
vo.setQrMetroTransferCnt(x.getQrMetroTransferCnt());
str.append(vo.toFileString(","));
}
writer.write(str.toString());
}
flag = stream.isConsumed();
}catch (Exception e) {
LOGGER.info("querySjztLinePassengerNonrtime read error>>",e);
flag = false;
Files.deleteIfExists(tempTxtFile);//删除临时文件
}
if(flag) {
Path tempZipFile = Files.createTempFile(SyncDatacenterConstants.FILENAME_LINE_PASSENGER_NONRTIME, SyncDatacenterConstants.FILEEXT_ZIP);
try (FileOutputStream fos = new FileOutputStream(tempZipFile.toFile());
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream fis = new FileInputStream(tempTxtFile.toFile())) {
ZipEntry zipEntry = new ZipEntry(tempTxtFile.getFileName().toString());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
}catch (Exception e) {
LOGGER.info("querySjztLinePassengerNonrtime zip error>>",e);
return null;
}
finally {
Files.deleteIfExists(tempTxtFile);//删除临时文件
}
return tempZipFile;
}
return null;
}
private List<TblSjztLinePassengerNonrtime> readLines(Iterator<TblSjztLinePassengerNonrtime> data,int number) throws Exception {
List<TblSjztLinePassengerNonrtime> list = new ArrayList<>();
while(data.hasNext()) {
list.add(data.next());
if(list.size()>=number) {
break;
}
}
return list;
}
@Override
public List<TblSjztLinePassengerRealtime> querySjztLinePassengerNonrtime(
ReqSjztLinePassengerRealtimeQueryDTO reqInfo) throws Exception {
TblSjztLinePassengerRealtimeVO param = new TblSjztLinePassengerRealtimeVO();
if(StringUtils.isNotBlank(reqInfo.getTxnDate())) {
param.setTxnDate(DateUtils.parseDate(reqInfo.getTxnDate(), Constants.FORMAT_DATEDAY.length()==reqInfo.getTxnDate().length()
?Constants.FORMAT_DATEDAY: Constants.FORMAT_DATEDAY_SIMPLE));
}else {//默认当天
BaseTime timeVO = BaseManagerUtils.getSystemTime();
param.setTxnDate(DateUtils.parseDate(timeVO.getDateDay(), Constants.FORMAT_DATEDAY));
}
param.setTimeCode(reqInfo.getTimeCode());
return tblSjztLinePassengerRealtimeMapper.selectList(param);
}
@Override
public List<TblSjztLinePassengerTotal> querySjztLinePassengerNonrtime(
ReqSjztLinePassengerTotalQueryDTO reqInfo) throws Exception {
TblSjztLinePassengerTotalVO param = new TblSjztLinePassengerTotalVO();
if(StringUtils.isNotBlank(reqInfo.getTxnDate())) {
param.setTxnDate(DateUtils.parseDate(reqInfo.getTxnDate(), Constants.FORMAT_DATEDAY.length()==reqInfo.getTxnDate().length()
?Constants.FORMAT_DATEDAY: Constants.FORMAT_DATEDAY_SIMPLE));
}else {//默认当天
BaseTime timeVO = BaseManagerUtils.getSystemTime();
param.setTxnDate(DateUtils.parseDate(timeVO.getDateDay(), Constants.FORMAT_DATEDAY));
}
param.setTimeCode(reqInfo.getTimeCode());
return tblSjztLinePassengerTotalMapper.selectList(param);
}
}

@ -0,0 +1,19 @@
package com.jiuyv.sptccc.agile.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 使
* @author zhouliang
*
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogIgnore {
}

@ -0,0 +1,36 @@
package com.jiuyv.sptccc.agile.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*
*
* @author admin
*/
@Component
@ConfigurationProperties(prefix = "console")
public class ConsoleConfig {
/** 项目名称 */
private String name;
/** 版本 */
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}

@ -0,0 +1,20 @@
package com.jiuyv.sptccc.agile.common.constant;
/**
*
*
* @author admin
*/
public class Constants {
/** 一个固定的密钥,用于配置文件内容加密/解密 */
public static final String SM4_SECERT_KEY = "a14751855ccb428d982c33dfa3535a57";
/** 日期格式 */
public static final String FORMAT_DATEDAY = "yyyy-MM-dd";
public static final String FORMAT_DATEDAY_SIMPLE ="yyyyMMdd";
/** 默认时区 */
public static final String DEFAULT_TIMEZONE = "+08:00";
}

@ -0,0 +1,47 @@
package com.jiuyv.sptccc.agile.common.core;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jiuyv.sptccc.agile.common.core.domain.BaseTime;
import com.jiuyv.sptccc.agile.common.utils.spring.SpringUtils;
import com.jiuyv.sptccc.agile.system.mapper.ISysTimeBaseMapper;
/**
* 使
* @author zhouliang
*
*/
public class BaseManagerUtils {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseManagerUtils.class);
private BaseManagerUtils() {
throw new IllegalStateException("Utility class");
}
/** 获取系统的时间*/
public static BaseTime getSystemTime() {
//强行从数据库获取,如果没有也不报错
BaseTime timeVO = null;
try{
ISysTimeBaseMapper tmapper=SpringUtils.getBean(ISysTimeBaseMapper.class);
timeVO=tmapper.selectSysCurrentTime();
}catch (Exception e) {
//正常是不会走到这里面的,只是兼容写法而已
LOGGER.error("Exception in obtaining database time。Using System Time Substitution");
timeVO = new BaseTime();
timeVO.setUtcTime(Instant.now());
}
timeVO.setDate(Date.from(timeVO.getUtcTime()));
timeVO.setDateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withLocale(Locale.SIMPLIFIED_CHINESE).withZone(ZoneId.of(timeVO.getTimeZone())).format(timeVO.getUtcTime()));
timeVO.setDateDay(timeVO.getDateTime().substring(0, 10));
return timeVO;
}
}

@ -0,0 +1,81 @@
package com.jiuyv.sptccc.agile.common.core.domain;
import java.time.Instant;
import java.util.Date;
/**
*
* @author zhouliang
*
*/
public class BaseTime implements java.io.Serializable {
/** default Serial Version UID*/
private static final long serialVersionUID = 1L;
/** 当前时区 */
private String timeZone ="+08:00";
/** 当前时区 YYYY-MM-DD */
private String dateDay;
/** 当前时区 YYYY-MM-DD HH:MM:SS */
private String dateTime;
/** 当前时区日期 */
private Date date;
/** UTC-0 带时区时间 */
private Instant utcTime;
/** UTC-0 带时区时间 */
private String utcTimeStr;
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String getDateDay() {
return dateDay;
}
public void setDateDay(String dateDay) {
this.dateDay = dateDay;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dataTime) {
this.dateTime = dataTime;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Instant getUtcTime() {
return utcTime;
}
public void setUtcTime(Instant utcTime) {
this.utcTime = utcTime;
}
public String getUtcTimeStr() {
return utcTimeStr;
}
public void setUtcTimeStr(String utcTimeStr) {
this.utcTimeStr = utcTimeStr;
}
}

@ -0,0 +1,37 @@
package com.jiuyv.sptccc.agile.common.enums;
import java.util.HashMap;
import java.util.Map;
import org.springframework.lang.Nullable;
/**
*
*
* @author admin
*/
public enum HttpMethod
{
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
private static final Map<String, HttpMethod> mappings = new HashMap<>(16);
static
{
for (HttpMethod httpMethod : values())
{
mappings.put(httpMethod.name(), httpMethod);
}
}
@Nullable
public static HttpMethod resolve(@Nullable String method)
{
return (method != null ? mappings.get(method) : null);
}
public boolean matches(String method)
{
return (this == resolve(method));
}
}

@ -0,0 +1,14 @@
package com.jiuyv.sptccc.agile.common.enums;
/**
*
* 便
* @author zhouliang
*
*/
public interface IDictEnum {
public String getCode();
public String getMsg();
}

@ -0,0 +1,73 @@
package com.jiuyv.sptccc.agile.common.exception;
/**
*
*
* @author admin
*/
public final class ServiceException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
*
*/
private Integer code;
/**
*
*/
private String message;
/**
*
*
* {@link CommonResult#getDetailMessage()}
*/
private String detailMessage;
/**
*
*/
public ServiceException()
{
}
public ServiceException(String message)
{
this.message = message;
}
public ServiceException(String message, Integer code)
{
this.message = message;
this.code = code;
}
public String getDetailMessage()
{
return detailMessage;
}
public String getMessage()
{
return message;
}
public Integer getCode()
{
return code;
}
public ServiceException setMessage(String message)
{
this.message = message;
return this;
}
public ServiceException setDetailMessage(String detailMessage)
{
this.detailMessage = detailMessage;
return this;
}
}

@ -0,0 +1,26 @@
package com.jiuyv.sptccc.agile.common.exception;
/**
*
*
* @author admin
*/
public class UtilException extends RuntimeException
{
private static final long serialVersionUID = 8247610319171014183L;
public UtilException(Throwable e)
{
super(e.getMessage(), e);
}
public UtilException(String message)
{
super(message);
}
public UtilException(String message, Throwable throwable)
{
super(message, throwable);
}
}

@ -0,0 +1,61 @@
package com.jiuyv.sptccc.agile.common.utils;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @author zhouliang
*
*/
public abstract class JsonUtil {
/**
* The Constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
private JsonUtil() {
throw new IllegalStateException("Utility class");
}
/**
* The object mapper.
*/
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//允许单引号
}
public static ObjectMapper JsonMapper(){
return objectMapper;
}
/**
* json
*
* @param object the object
* @return the string
*/
public static String toJSONString(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
LOGGER.error("convert failed", e);
return "";
}
}
}

@ -0,0 +1,29 @@
package com.jiuyv.sptccc.agile.common.utils;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import com.jiuyv.sptccc.agile.common.utils.spring.SpringUtils;
/**
* i18n
*
* @author admin
*/
public class MessageUtils
{
/**
* spring messageSource
*
* @param code
* @param args
* @return
*/
public static String message(String code, Object... args)
{
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}

@ -0,0 +1,62 @@
package com.jiuyv.sptccc.agile.common.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.jiuyv.sptccc.agile.common.constant.Constants;
/**
*
*
* @author admin
*/
public class ServletUtils
{
/**
* request
*/
public static HttpServletRequest getRequest()
{
ServletRequestAttributes requestAttributes = getRequestAttributes();
if(null != requestAttributes) {
return requestAttributes.getRequest();
}
return null;
}
public static ServletRequestAttributes getRequestAttributes()
{
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if(null != attributes) {
return (ServletRequestAttributes) attributes;
}
return null;
}
/**
*
*
* @param str
* @return
*/
public static String urlEncode(String str)
{
try
{
return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
}
catch (UnsupportedEncodingException e)
{
return "";
}
}
}

@ -0,0 +1,61 @@
package com.jiuyv.sptccc.agile.common.utils;
/**
*
*
* @author admin
*/
public class StriUtils
{
/**
* 0使size size
*
* @param num
* @param size
* @return
*/
public static final String padl(final Number num, final int size)
{
return padl(num.toString(), size, '0');
}
/**
* ssizesize
*
* @param s
* @param size
* @param c
* @return
*/
public static final String padl(final String s, final int size, final char c)
{
final StringBuilder sb = new StringBuilder(size);
if (s != null)
{
final int len = s.length();
if (s.length() <= size)
{
for (int i = size - len; i > 0; i--)
{
sb.append(c);
}
sb.append(s);
}
else
{
return s.substring(len - size, len);
}
}
else
{
for (int i = size; i > 0; i--)
{
sb.append(c);
}
}
return sb.toString();
}
}

@ -0,0 +1,103 @@
package com.jiuyv.sptccc.agile.common.utils.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import com.jiuyv.sptccc.agile.common.utils.StriUtils;
import org.apache.commons.lang3.StringUtils;
/**
* IP
*
* @author admin
*/
public class IpUtils {
/**
* IP
*
* @param request
* @return IP
*/
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
}
/**
* IP
*
* @return IP
*/
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
}
return "127.0.0.1";
}
/**
*
*
* @return
*/
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
}
return "未知";
}
/**
* unknown IP
*
* @param ip IP
* @return unknown IP
*/
public static String getMultistageReverseProxyIp(String ip) {
// 多级反向代理检测
if (ip != null && ip.indexOf(",") >= 0) {
final String[] ips = ip.trim().split(",");
for (String subIp : ips) {
if (false == isUnknown(subIp)) {
ip = subIp;
break;
}
}
}
return ip;
}
/**
* HTTP
*
* @param checkString
* @return
*/
public static boolean isUnknown(String checkString) {
return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
}
}

@ -0,0 +1,68 @@
package com.jiuyv.sptccc.agile.common.utils.sm4;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
/**
* Created with IntelliJ IDEA.
*
* @author Shawffer
* @description:
* @date: 2022-07-19
* @time: 17:04
*/
public class Sm4Util {
public static final String ALGORITHM_NAME = "SM4";
public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
public static final String ALGORITHM_NAME_ECB_NOPADDING = "SM4/ECB/NoPadding";
public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS7Padding";
public static final String ALGORITHM_NAME_CBC_NOPADDING = "SM4/CBC/NoPadding";
/**
* SM412816
*/
public static final int DEFAULT_KEY_SIZE = 128;
static {
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encrypt_ECB_Padding(byte[] key, byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
private static Cipher generateECBCipher(String algorithmName, int mode, byte[] key)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidKeyException {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
cipher.init(mode, sm4Key);
return cipher;
}
public static String encryptEcb(String key, String text) throws Exception {
return Base64.encodeBase64String(Sm4Util.encrypt_ECB_Padding(Hex.decodeHex(key),text.getBytes("UTF-8")));
}
public static byte[] decrypt_ECB_Padding(byte[] key, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
public static String decryptEcb(String key, String text) throws Exception {
return new String(Sm4Util.decrypt_ECB_Padding(Hex.decodeHex(key), Base64.decodeBase64((text))));
}
}

@ -0,0 +1,71 @@
package com.jiuyv.sptccc.agile.common.utils.spring;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.jiuyv.sptccc.agile.common.utils.StriUtils;
/**
* spring 便springbean
*
* @author admin
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
setBeanFactory(beanFactory);
}
public static void setBeanFactory(ConfigurableListableBeanFactory beanFactory) {
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
setContext(applicationContext);
}
public static void setContext(ApplicationContext applicationContext) {
SpringUtils.applicationContext = applicationContext;
}
/**
*
*
* @param name
* @return Object bean
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* requiredType
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
}

@ -0,0 +1,189 @@
package com.jiuyv.sptccc.agile.framework.aspectj;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.jiuyv.sptccc.agile.common.enums.HttpMethod;
import com.jiuyv.sptccc.agile.common.utils.JsonUtil;
import com.jiuyv.sptccc.agile.common.utils.ServletUtils;
import com.jiuyv.sptccc.agile.common.utils.ip.IpUtils;
/**
*
* @author zhouliang
*
*/
@Aspect
@Component
public class GlobalLogAspect
{
private static final Logger log = LoggerFactory.getLogger(GlobalLogAspect.class);
private static final ThreadLocal<Long> timeTreadLocal = new ThreadLocal<>();
//不输出任何日志
private static final String LogIgnorePath = "@annotation(com.jiuyv.sptccc.agile.common.annotation.LogIgnore)";
//扫描所有Controller
private static final String ControllerPath = "execution(* *..*.*Controller.*(..))";
//不输出这个转发的
private static final String InitBinderPath = "@annotation(org.springframework.web.bind.annotation.InitBinder)";
//请求Controller输出日志
@Pointcut(ControllerPath+"&&!"+LogIgnorePath+"&&!"+InitBinderPath)
public void controllerAspect() {
}
//请求日志记录
@Before("controllerAspect()")
public void before(JoinPoint joinPoint) {
timeTreadLocal.set(System.currentTimeMillis());
// 接收请求,记录完整请求内容
//获取请求的request
HttpServletRequest request = ServletUtils.getRequest();
String methodName = getMethodName(joinPoint);
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
String userName="none";
String keyValue = setRequestValue(joinPoint,request.getMethod());
log.info("{}-req:User={},Ip={},Uri={},Method={},ContentType={}",methodName,userName,ip,request.getRequestURI(),request.getMethod(),request.getContentType());
log.info("{}-req:Params={}",methodName, keyValue);
}
//后置返回
@AfterReturning(pointcut = "controllerAspect()",returning = "result")
public void doAfterReturning(JoinPoint joinPoint,Object result) {
long startTime = timeTreadLocal.get();
double callTime = (System.currentTimeMillis() - startTime) / 1000.0;
String methodName = getMethodName(joinPoint);
String returnstr = null;
if(result!=null) {
returnstr=JsonUtil.toJSONString(result);
}
log.info("{}-res:Success,Time={}s,Data={}",methodName, callTime, returnstr);
timeTreadLocal.remove();
}
//后置异常返回
@AfterThrowing(pointcut = "controllerAspect()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
long startTime = timeTreadLocal.get();
double callTime = (System.currentTimeMillis() - startTime) / 1000.0;
String methodName = getMethodName(joinPoint);
log.info("{}-res:Failure,Time={}s,Error={}",methodName, callTime,e.getMessage());
timeTreadLocal.remove();
}
/** 获取方法名称*/
private String getMethodName(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取被拦截的方法
Method method = methodSignature.getMethod();
String className = method.getDeclaringClass().getCanonicalName();
String methodName = className.substring(className.lastIndexOf(".")+1) + "." + method.getName();
return methodName;
}
/**
*
*/
private String setRequestValue(JoinPoint joinPoint, String requestMethod)
{
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
{
String params = argsArrayToString(joinPoint.getArgs());
return params;
}
else
{
Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
return paramsMap.toString();
}
}
/**
*
*/
private String argsArrayToString(Object[] paramsArray)
{
String params = "";
if (paramsArray != null && paramsArray.length > 0)
{
for (Object o : paramsArray)
{
if (o!=null && !isFilterObject(o))
{
try
{
Object jsonObj = JsonUtil.toJSONString(o);
params += jsonObj.toString() + " ";
}
catch (Exception e)
{
}
}
}
}
return params.trim();
}
/**
*
*
* @param o
* @return truefalse
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o)
{
Class<?> clazz = o.getClass();
if (clazz.isArray())
{
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
}
else if (Collection.class.isAssignableFrom(clazz))
{
Collection collection = (Collection) o;
for (Object value : collection)
{
if(value instanceof MultipartFile) {
return true;
}
}
return false;
}
else if (Map.class.isAssignableFrom(clazz))
{
Map map = (Map) o;
for (Object value : map.entrySet())
{
Map.Entry entry = (Map.Entry) value;
if(entry.getValue() instanceof MultipartFile) {
return true;
}
}
return false;
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
}

@ -0,0 +1,46 @@
package com.jiuyv.sptccc.agile.framework.config;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
Environment env;
@Override
protected void configure(HttpSecurity security) throws Exception {
String actuatorPath = env.getProperty("management.endpoints.web.base-path");
if(StringUtils.isBlank(actuatorPath)) {
actuatorPath = "/actuator";
}
//优化一下根路径
String servletPath = env.getProperty("server.servlet.context-path");
if(StringUtils.isNotBlank(servletPath)) {
if(servletPath.endsWith("/")) {
servletPath=servletPath.substring(0,servletPath.length()-1);
}
servletPath=servletPath.replaceAll("[^/]+", "**");
}else {
servletPath="";
}
security.csrf().disable();
security.requestMatcher(new AntPathRequestMatcher(servletPath+actuatorPath+"/**"))
.authorizeRequests()
.antMatchers(servletPath+actuatorPath+"/shutdown","/**"+servletPath+actuatorPath+"/serviceregistry","/**"+servletPath+actuatorPath+"/refresh")
.access("hasIpAddress(\"127.0.0.1\")")
.antMatchers(servletPath+actuatorPath+"/**").authenticated()
.and().httpBasic();
}
}

@ -0,0 +1,31 @@
package com.jiuyv.sptccc.agile.framework.config;
import java.util.TimeZone;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
*
*
* @author admin
*/
@Configuration
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
@MapperScan("com.jiuyv.sptccc.agile.**.mapper")
public class ApplicationConfig
{
/**
*
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization()
{
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
}
}

@ -0,0 +1,150 @@
package com.jiuyv.sptccc.agile.framework.config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.jcraft.jsch.Session;
import com.jiuyv.sptccc.agile.common.constant.Constants;
import com.jiuyv.sptccc.agile.common.utils.sm4.Sm4Util;
/**
* sftp
* @author zhouliang
*
*/
@Component
@ConfigurationProperties(prefix = "filesftp")
public class SftpConfigProperties implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* ip
*/
private String host;
/**
*
*/
private int port=22;
/**
*
*/
private String username;
/**
*
*/
private String password;
/**
* location
*/
private int location;
/** 全局上传主路径 */
private String uploadPath;
/** 连接池配置*/
private transient GenericObjectPoolConfig<Session> poolConfig;
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(int port) {
this.port = port;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
try {
return Sm4Util.decryptEcb(Constants.SM4_SECERT_KEY, password);
}catch (Exception e) {
// 兼容写法,不加密也可以
}
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the location
*/
public int getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(int location) {
this.location = location;
}
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
/**
* @return the poolConfig
*/
public GenericObjectPoolConfig<Session> getPoolConfig() {
return poolConfig;
}
/**
* @param poolConfig the poolConfig to set
*/
public void setPoolConfig(GenericObjectPoolConfig<Session> poolConfig) {
this.poolConfig = poolConfig;
}
}

@ -0,0 +1,65 @@
package com.jiuyv.sptccc.agile.framework.web.exception;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.jiuyv.sptccc.agile.common.core.domain.R;
import com.jiuyv.sptccc.agile.common.utils.JsonUtil;
/**
*
*
* @author admin
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
*
*/
@ExceptionHandler(BindException.class)
public R<Object> handleBindException(BindException e) {
log.error(e.getMessage(), e);
String message = e.getAllErrors().get(0).getDefaultMessage();
return R.fail(message);
}
/**
*
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("数据校验出现问题{},异常类型:{}", e.getMessage(), e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String, String> errorMap = new HashMap<>();
bindingResult.getFieldErrors().forEach((fieldError) -> {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
});
return R.fail(JsonUtil.toJSONString(errorMap));
}
/**
*
*/
@ExceptionHandler(Exception.class)
public R<Object> handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
response.setStatus(301);
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return R.fail(e.getMessage());
}
}

@ -0,0 +1,15 @@
package com.jiuyv.sptccc.agile.system.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.jiuyv.sptccc.agile.common.core.domain.BaseTime;
@Mapper
public interface ISysTimeBaseMapper {
/**
* -yyyyMMddHHmmss
* @return
*/
BaseTime selectSysCurrentTime();
}

@ -0,0 +1,53 @@
# 项目相关配置
console:
# 版本
version: 1.0
# 开发环境配置
server:
port: 18083 #本地
tomcat:
# tomcat的URI编码
uri-encoding: UTF-8
# 连接数满后的排队数默认为100
accept-count: 1000
threads:
# tomcat最大线程数默认为200
max: 200
# Tomcat启动初始化的线程数默认值10
min-spare: 10
# 日志配置
logging:
level:
com.jiuyv.sptccc.agile: info
root: info
spring:
application:
name: datacenter-service
devtools:
restart:
enabled: true
datasource: #数据源配置
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://172.16.12.105:5432/keliubao
username: postgres
password: postgres
#用于缓存下载的文件
filesftp:
host: 172.16.12.108
port: 22
username: flink
password: flink123
uploadPath: /home/flink/sysfile/cache-datacenter
poolConfig:
maxTotal: 25
maxIdle: 5
minIdle: 1
maxWait: PT3M
minEvictableIdleTime: PT15M
timeBetweenEvictionRuns: PT1M
softMinEvictableIdleTime: PT10M

@ -0,0 +1,49 @@
# Spring配置
spring:
application:
name: datacenter-service
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
jackson:
date-format: yyyy-MM-dd HH:mm:ss # 常用的时间格式
default-property-inclusion: non_null # 忽略空对象
serialization:
fail-on-empty-beans: false # 序列化空对象时不抛出异常
indent-output: true # 输出格式化为缩进的JSON
write-dates-as-timestamps: false # 日期序列化为时间戳而不是ISO-8601格式
deserialization:
fail-on-unknown-properties: false # 反序列化时忽略未知的属性
# MyBatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.jiuyv.sptccc.agile.**
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
feign:
httpclient:
enabled: false
okhttp:
enabled: true
compression:
request:
enabled: true
response:
enabled: true
useGzipDecoder: true
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
shutdown:
enabled: true

@ -0,0 +1,6 @@
Application Version: ${console.version}
Spring Boot Version: ${spring-boot.version}
////////////////////////////////////////////////////////////////////
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////

@ -0,0 +1,43 @@
console:
version: 1.0
# Spring配置
spring:
application:
name : datacenter-service
profiles:
#部署时带上自身名字sms-service-dev
active: dev
cloud:
config:
#本地可以置为关闭false
enabled: false
discovery:
service-id: config-service #使用服务名
enabled: false
name: ${spring.application.name}
profile: ${spring.profiles.active}
fail-fast: true
security:
user:
name: sptcc
password: 123456
# 配置eureka客户端信息
eureka:
instance:
appname: ${spring.application.name}
lease-expiration-duration-in-seconds: 30
lease-renewal-interval-in-seconds: 10
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
metadata-map:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
client:
enabled: true
registry-fetch-interval-seconds: 1
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://172.16.12.109:8761/eureka/

@ -0,0 +1,3 @@
#错误消息
not.null=* 必须填写
length.not.valid=长度必须在{min}到{max}个字符之间

@ -0,0 +1,134 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!-- LOG目录 -->
<property name="LOG_HOME" value="logs"/>
<!-- JSON_LOG目录 -->
<property name="JSON_LOG_HOME" value="logs/jsonlog"/>
<!-- spring.application.name 作为参数 -->
<springProperty scope="context" name="APP_NAME" source="spring.application.name"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 按天压缩日志 -->
<appender name="ZIP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/${APP_NAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${APP_NAME}.log.%d{yyyy-MM-dd}.%i.log.zip</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 不压缩日志,保留7天 -->
<appender name="DEFAULT_INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${APP_NAME}.log.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<maxHistory>7</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- LOGSTASH,输出seuleth项,保留7天 -->
<appender name="LOGSTASH" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${JSON_LOG_HOME}/${APP_NAME}.json.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<maxHistory>7</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder charset="UTF-8" class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<pattern>
<pattern>
{
"timestamp": "%d{yyyy-MM-dd HH:mm:ss.SSS}",
"severity": "%level",
"service": "${APP_NAME:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"parent": "%X{X-B3-ParentSpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<!-- 按天压缩Json日志 -->
<appender name="JSON_ZIP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${JSON_LOG_HOME}/${APP_NAME}.json.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${JSON_LOG_HOME}/${APP_NAME}.log.%d{yyyy-MM-dd}.%i.json.log.zip</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder charset="UTF-8" class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<pattern>
<pattern>
{
"timestamp": "%d{yyyy-MM-dd HH:mm:ss.SSS}",
"severity": "%level",
"service": "${APP_NAME:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"parent": "%X{X-B3-ParentSpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.jiuyv.sptccc.agile.thirdparty.dao" level="debug"/>
<root>
<level value="INFO"/>
<appender-ref ref="STDOUT"/>
<appender-ref ref="ZIP_FILE"/>
<appender-ref ref="DEFAULT_INFO_FILE"/>
<appender-ref ref="LOGSTASH"/>
<appender-ref ref="JSON_ZIP_FILE"/>
</root>
</configuration>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- t+1线路客流 -->
<mapper namespace="com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerNonrtimeMapper">
<sql id="_select">
a.txn_date, a.settle_center_code, a.time_code, a.in_line_code, a.total_cnt, a.out_txn_cnt,
a.in_station_cnt, a.jtk_in_station_cnt, a.jtk_bus_transfer_cnt,
a.jtk_metro_transfer_cnt, a.ewm_in_station_cnt, a.qr_bus_transfer_cnt,
a.qr_metro_transfer_cnt
</sql>
<select id="selectList" resultType="com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerNonrtime" parameterType="com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerNonrtimeVO">
select
<include refid="_select"/>
from tbl_sjzt_line_passenger_nonrtime a
<where>
and a.txn_date = #{txnDate}
<if test="timeCode != null">and a.time_code = #{timeCode}</if>
</where>
</select>
</mapper>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 实时线路客流 -->
<mapper namespace="com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerRealtimeMapper">
<sql id="_select">
a.txn_date, a.settle_center_code, a.time_code, a.in_line_code, a.total_cnt, a.out_txn_cnt,
a.in_station_cnt, a.jtk_in_station_cnt, a.jtk_bus_transfer_cnt,
a.jtk_metro_transfer_cnt, a.ewm_in_station_cnt, a.qr_bus_transfer_cnt,
a.qr_metro_transfer_cnt
</sql>
<!-- 查询集合 -->
<select id="selectList" resultType="com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerRealtime" parameterType="com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerRealtimeVO">
select
<include refid="_select"/>
from tbl_sjzt_line_passenger_realtime a
<where>
and a.txn_date = #{txnDate}
and a.time_code = #{timeCode}
</where>
</select>
</mapper>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 实时线路累计客流 -->
<mapper namespace="com.jiuyv.sptccc.agile.business.mapper.TblSjztLinePassengerTotalMapper">
<sql id="_select">
a.txn_date, a.settle_center_code, a.time_code, a.in_line_code, a.total_cnt, a.out_txn_cnt,
a.in_station_cnt, a.jtk_in_station_cnt, a.jtk_bus_transfer_cnt,
a.jtk_metro_transfer_cnt, a.ewm_in_station_cnt, a.qr_bus_transfer_cnt,
a.qr_metro_transfer_cnt
</sql>
<!-- 查询集合 -->
<select id="selectList" resultType="com.jiuyv.sptccc.agile.business.entity.TblSjztLinePassengerTotal" parameterType="com.jiuyv.sptccc.agile.business.entity.vo.TblSjztLinePassengerTotalVO">
select
<include refid="_select"/>
from tbl_sjzt_line_passenger_total a
<where>
and a.txn_date = #{txnDate}
and a.time_code = #{timeCode}
</where>
</select>
</mapper>

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jiuyv.sptccc.agile.system.mapper.ISysTimeBaseMapper">
<select id="selectSysCurrentTime" resultType="com.jiuyv.sptccc.agile.common.core.domain.BaseTime">
SELECT now() AS utcTime
</select>
</mapper>

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

Loading…
Cancel
Save