From f310a63c7d34984ccead34eb81943f60aac124d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=B9=B3?= Date: Thu, 30 Nov 2023 14:53:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E9=A1=B9=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dataManage.iml | 284 ++++++++ pom.xml | 246 +++++++ src/main/java/com/drht/datamanage/App.java | 75 ++ .../datamanage/DataManageApplication.java | 19 + .../drht/datamanage/ServletInitializer.java | 12 + .../java/com/drht/datamanage/base/Base.xml | 185 +++++ .../datamanage/cache/ChannelIntCache.java | 21 + .../datamanage/cache/CommandInitCache.java | 90 +++ .../drht/datamanage/cache/RequestCache.java | 5 + .../config/FastJson2JsonRedisSerializer.java | 43 ++ .../datamanage/config/MyBatisPlusConfig.java | 22 + .../drht/datamanage/config/SwaggerConfig.java | 61 ++ .../drht/datamanage/dao/HourlyDataDao.java | 21 + .../drht/datamanage/dao/MinuteDataDao.java | 10 + .../drht/datamanage/dao/RealTimeDataDao.java | 11 + .../exception/AnalysisException.java | 30 + .../datamanage/exception/CommonException.java | 56 ++ .../drht/datamanage/exception/ResultCode.java | 27 + .../handler/CheckDeviceInChannelHandler.java | 65 ++ .../handler/CheckMsgInChannelHandler.java | 78 ++ .../handler/ReplyDeviceInChannelHandler.java | 45 ++ .../handler/SendChannelHandler.java | 20 + .../listener/NettyServerListener.java | 27 + .../com/drht/datamanage/model/HourlyData.java | 88 +++ .../com/drht/datamanage/model/MinuteData.java | 85 +++ .../drht/datamanage/model/RealTimeData.java | 50 ++ .../drht/datamanage/model/msg/CommandMsg.java | 36 + .../datamanage/model/msg/ReplyKafkaMsg.java | 25 + .../drht/datamanage/model/msg/SendMsg.java | 80 ++ .../com/drht/datamanage/protocols/Cn0001.java | 24 + .../com/drht/datamanage/protocols/Cn2011.java | 72 ++ .../com/drht/datamanage/protocols/Cn2051.java | 94 +++ .../com/drht/datamanage/protocols/Cn2601.java | 95 +++ .../com/drht/datamanage/protocols/Cn9015.java | 40 + .../datamanage/service/HourlyDataService.java | 12 + .../service/Impl/HourlyDataServiceImpl.java | 22 + .../service/Impl/MinuteDataServiceImpl.java | 23 + .../service/Impl/RealTimeDataServiceImpl.java | 26 + .../datamanage/service/MinuteDataService.java | 10 + .../service/RealTimeDataService.java | 11 + .../com/drht/datamanage/service/Reply.java | 11 + .../com/drht/datamanage/service/Send.java | 10 + .../java/com/drht/datamanage/test/Test.java | 116 +++ .../drht/datamanage/util/AnalysisUtil.java | 242 +++++++ .../com/drht/datamanage/util/CommonUtil.java | 34 + .../com/drht/datamanage/util/DateUtils.java | 683 ++++++++++++++++++ .../com/drht/datamanage/util/HelperUtil.java | 90 +++ .../datamanage/util/LinuxCommandUtil.java | 44 ++ .../java/com/drht/datamanage/util/QnUtil.java | 12 + .../datamanage/util/SpringContextUtil.java | 31 + src/main/resources/application.properties | 13 + src/main/resources/logback.xml | 54 ++ .../resources/mapping/HourlyDataMapper.xml | 6 + .../resources/mapping/MinuteDataMapper.xml | 5 + .../resources/mapping/RealTimeDataMapper.xml | 5 + 55 files changed, 3602 insertions(+) create mode 100644 dataManage.iml create mode 100644 pom.xml create mode 100644 src/main/java/com/drht/datamanage/App.java create mode 100644 src/main/java/com/drht/datamanage/DataManageApplication.java create mode 100644 src/main/java/com/drht/datamanage/ServletInitializer.java create mode 100644 src/main/java/com/drht/datamanage/base/Base.xml create mode 100644 src/main/java/com/drht/datamanage/cache/ChannelIntCache.java create mode 100644 src/main/java/com/drht/datamanage/cache/CommandInitCache.java create mode 100644 src/main/java/com/drht/datamanage/cache/RequestCache.java create mode 100644 src/main/java/com/drht/datamanage/config/FastJson2JsonRedisSerializer.java create mode 100644 src/main/java/com/drht/datamanage/config/MyBatisPlusConfig.java create mode 100644 src/main/java/com/drht/datamanage/config/SwaggerConfig.java create mode 100644 src/main/java/com/drht/datamanage/dao/HourlyDataDao.java create mode 100644 src/main/java/com/drht/datamanage/dao/MinuteDataDao.java create mode 100644 src/main/java/com/drht/datamanage/dao/RealTimeDataDao.java create mode 100644 src/main/java/com/drht/datamanage/exception/AnalysisException.java create mode 100644 src/main/java/com/drht/datamanage/exception/CommonException.java create mode 100644 src/main/java/com/drht/datamanage/exception/ResultCode.java create mode 100644 src/main/java/com/drht/datamanage/handler/CheckDeviceInChannelHandler.java create mode 100644 src/main/java/com/drht/datamanage/handler/CheckMsgInChannelHandler.java create mode 100644 src/main/java/com/drht/datamanage/handler/ReplyDeviceInChannelHandler.java create mode 100644 src/main/java/com/drht/datamanage/handler/SendChannelHandler.java create mode 100644 src/main/java/com/drht/datamanage/listener/NettyServerListener.java create mode 100644 src/main/java/com/drht/datamanage/model/HourlyData.java create mode 100644 src/main/java/com/drht/datamanage/model/MinuteData.java create mode 100644 src/main/java/com/drht/datamanage/model/RealTimeData.java create mode 100644 src/main/java/com/drht/datamanage/model/msg/CommandMsg.java create mode 100644 src/main/java/com/drht/datamanage/model/msg/ReplyKafkaMsg.java create mode 100644 src/main/java/com/drht/datamanage/model/msg/SendMsg.java create mode 100644 src/main/java/com/drht/datamanage/protocols/Cn0001.java create mode 100644 src/main/java/com/drht/datamanage/protocols/Cn2011.java create mode 100644 src/main/java/com/drht/datamanage/protocols/Cn2051.java create mode 100644 src/main/java/com/drht/datamanage/protocols/Cn2601.java create mode 100644 src/main/java/com/drht/datamanage/protocols/Cn9015.java create mode 100644 src/main/java/com/drht/datamanage/service/HourlyDataService.java create mode 100644 src/main/java/com/drht/datamanage/service/Impl/HourlyDataServiceImpl.java create mode 100644 src/main/java/com/drht/datamanage/service/Impl/MinuteDataServiceImpl.java create mode 100644 src/main/java/com/drht/datamanage/service/Impl/RealTimeDataServiceImpl.java create mode 100644 src/main/java/com/drht/datamanage/service/MinuteDataService.java create mode 100644 src/main/java/com/drht/datamanage/service/RealTimeDataService.java create mode 100644 src/main/java/com/drht/datamanage/service/Reply.java create mode 100644 src/main/java/com/drht/datamanage/service/Send.java create mode 100644 src/main/java/com/drht/datamanage/test/Test.java create mode 100644 src/main/java/com/drht/datamanage/util/AnalysisUtil.java create mode 100644 src/main/java/com/drht/datamanage/util/CommonUtil.java create mode 100644 src/main/java/com/drht/datamanage/util/DateUtils.java create mode 100644 src/main/java/com/drht/datamanage/util/HelperUtil.java create mode 100644 src/main/java/com/drht/datamanage/util/LinuxCommandUtil.java create mode 100644 src/main/java/com/drht/datamanage/util/QnUtil.java create mode 100644 src/main/java/com/drht/datamanage/util/SpringContextUtil.java create mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/logback.xml create mode 100644 src/main/resources/mapping/HourlyDataMapper.xml create mode 100644 src/main/resources/mapping/MinuteDataMapper.xml create mode 100644 src/main/resources/mapping/RealTimeDataMapper.xml diff --git a/dataManage.iml b/dataManage.iml new file mode 100644 index 0000000..5afa10c --- /dev/null +++ b/dataManage.iml @@ -0,0 +1,284 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0abb856 --- /dev/null +++ b/pom.xml @@ -0,0 +1,246 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.6.RELEASE + + + + com.drht + dataManage + war + 1.0-SNAPSHOT + + dataManage + + + + 1.8 + Finchley.SR3 + + 2.5.0 + 1.8.7 + + 3.3.1.tmp + 3.3.1.tmp + + + + com.corundumstudio.socketio + netty-socketio + 1.7.13 + + + io.netty + netty-common + + + io.netty + netty-transpor + + + io.netty + netty-buffer + + + io.netty + netty-handler + + + io.netty + netty-codec-http + + + io.netty + netty-codec + + + io.netty + netty-resolver + + + io.netty + netty-transport + + + io.netty + netty-transport-native-epoll + + + + + io.netty + netty-all + 4.1.98.Final + + + com.alibaba + fastjson + 1.2.83 + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + com.drhb + common + 1.0-SNAPSHOT + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + true + + + + cn.hutool + hutool-all + 5.3.9 + + + com.google.code.gson + gson + 2.8.5 + + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + com.github.xiaoymin + swagger-bootstrap-ui + ${swagger.ui.version} + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.2.RELEASE + + + com.drht.datamanage.DataManageApplication + + + + + repackage + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.3 + + false + + + + + + + + src/main/java + + + + **/*.xml + + + + false + + + + + src/main/resources + + **/*.xml + **/*.properties + + + + + + + + + nexus + Nexus Repository + http://39.98.199.134:8081/repository/maven-public/ + + true + + + true + + + + + + + nexus + Nexus Plugin Repository + http://39.98.199.134:8081/repository/maven-public/ + + true + + + true + + + + \ No newline at end of file diff --git a/src/main/java/com/drht/datamanage/App.java b/src/main/java/com/drht/datamanage/App.java new file mode 100644 index 0000000..c2f3cc6 --- /dev/null +++ b/src/main/java/com/drht/datamanage/App.java @@ -0,0 +1,75 @@ +package com.drht.datamanage; + +import com.drht.datamanage.handler.CheckDeviceInChannelHandler; +import com.drht.datamanage.handler.CheckMsgInChannelHandler; +import com.drht.datamanage.handler.ReplyDeviceInChannelHandler; +import com.drht.datamanage.handler.SendChannelHandler; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.LineBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; +import io.netty.handler.codec.string.StringEncoder; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.timeout.ReadTimeoutHandler; +import lombok.extern.slf4j.Slf4j; + +import static io.netty.channel.ChannelOption.ALLOCATOR; + +/** + * + * + */ +@Slf4j +public class App { + + public static void run() { + log.info("初始化netty"); + // accept线程组,用来接受连接 + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + + // I/O线程组, 用于处理业务逻辑 + EventLoopGroup workerGroup = new NioEventLoopGroup(1); + + try { + // 服务端启动引导 + ServerBootstrap b = new ServerBootstrap(); + + b.group(bossGroup, workerGroup) // 绑定两个线程组 + .channel(NioServerSocketChannel.class) // 指定通道类型 + .option(ChannelOption.SO_BACKLOG, 10) // 设置TCP连接的缓冲区 + .option(ChannelOption.RCVBUF_ALLOCATOR,new FixedRecvByteBufAllocator(1000*1024)) + .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别 + .childHandler( + new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链 + pipeline.addLast(new LineBasedFrameDecoder(1000*1024)); // 读取第一步处理,功能是一次读一行 + pipeline.addLast(new StringDecoder()); // 转成字符串 + pipeline.addLast(new StringEncoder()); // 编码成二进制 + pipeline.addLast(new SendChannelHandler()); // 发送消息 + pipeline.addLast(new ReadTimeoutHandler(90)); // 超时处理,90秒未接收到数据认为设备离线 + pipeline.addLast(new CheckMsgInChannelHandler()); // 检查消息格式、crc校验等 + pipeline.addLast(new CheckDeviceInChannelHandler()); // 检查设备是否可用 + pipeline.addLast(new ReplyDeviceInChannelHandler()); // 回复消息 + } + }); + + // 通过bind启动服务 + ChannelFuture f = b.bind(7001).sync(); + // 阻塞主线程,知道网络服务被关闭 + f.channel().closeFuture().sync(); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + workerGroup.shutdownGracefully(); + bossGroup.shutdownGracefully(); + } + } +} + diff --git a/src/main/java/com/drht/datamanage/DataManageApplication.java b/src/main/java/com/drht/datamanage/DataManageApplication.java new file mode 100644 index 0000000..4d14e3a --- /dev/null +++ b/src/main/java/com/drht/datamanage/DataManageApplication.java @@ -0,0 +1,19 @@ +package com.drht.datamanage; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableFeignClients +@Slf4j +public class DataManageApplication{ + public static void main(String[] args) { + SpringApplication.run(DataManageApplication.class, args); + } +} diff --git a/src/main/java/com/drht/datamanage/ServletInitializer.java b/src/main/java/com/drht/datamanage/ServletInitializer.java new file mode 100644 index 0000000..8fa8cf0 --- /dev/null +++ b/src/main/java/com/drht/datamanage/ServletInitializer.java @@ -0,0 +1,12 @@ +package com.drht.datamanage; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +public class ServletInitializer extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(DataManageApplication.class); + } + +} diff --git a/src/main/java/com/drht/datamanage/base/Base.xml b/src/main/java/com/drht/datamanage/base/Base.xml new file mode 100644 index 0000000..e10b9f7 --- /dev/null +++ b/src/main/java/com/drht/datamanage/base/Base.xml @@ -0,0 +1,185 @@ + + + + + ${hql} + + + ${returnClause} + + + + ${joinon.style} JOIN ${joinon.table} ON ${joinon.table}.${joinon.field} = + + + ${table}.${joinon.field} + ${table}.${joinon.tofield} + + + ${joinon.totable}.${joinon.tofield} + + + + AND ${joinon.param} + + + + + + + + + + AND ${table}.${criterion.condition} + + + AND ${table}.${criterion.condition} + #{criterion.value} + + + AND ${table}.${criterion.condition} + #{criterion.value} AND #{criterion.secondValue} + + + AND ${table}.${criterion.condition} + + #{listItem} + + + + + + + + + + + + + + + + + + + + + + + + + INSERT INTO ${table} + + + + f_${mod.varName}, + + + + + + + #{mod.varValue}, + + + + + + + + UPDATE ${table} + + + + f_${mod.varName} = #{mod.varValue}, + + + + f_${mod.varName} = f_version+1, + + + + WHERE f_${model[0].varName} = #{model[0].varValue} and f_version=#{version} + + + + + UPDATE ${list[0].table} + + + + ${mod.varName} = CASE ${list[0].model[0].varName} + + + WHEN '${i.model[0].varValue}' THEN '${i.model[index].varValue}' + + + END, + + + + WHERE ${list[0].model[0].varName} IN + + #{i.model[0].varValue} + + + + + + DELETE FROM ${table} + WHERE f_${model[0].varName} = #{model[0].varValue} + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/drht/datamanage/cache/ChannelIntCache.java b/src/main/java/com/drht/datamanage/cache/ChannelIntCache.java new file mode 100644 index 0000000..906f73b --- /dev/null +++ b/src/main/java/com/drht/datamanage/cache/ChannelIntCache.java @@ -0,0 +1,21 @@ +package com.drht.datamanage.cache; + +import io.netty.channel.ChannelHandlerContext; + +import java.util.HashMap; +import java.util.Map; + +public class ChannelIntCache { + + private static Map cache=new HashMap<>(); + + private ChannelIntCache() { + + } + + public static Map getCache() { + return cache; + } + + +} diff --git a/src/main/java/com/drht/datamanage/cache/CommandInitCache.java b/src/main/java/com/drht/datamanage/cache/CommandInitCache.java new file mode 100644 index 0000000..99074f8 --- /dev/null +++ b/src/main/java/com/drht/datamanage/cache/CommandInitCache.java @@ -0,0 +1,90 @@ +package com.drht.datamanage.cache; + +import com.drht.datamanage.protocols.*; +import com.drht.datamanage.service.Reply; +import com.drht.datamanage.service.Send; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +@Service +public class CommandInitCache { + + private static Map replyCache=new HashMap<>(); + + private static Map sendCache=new HashMap<>(); + + + + private static Cn2601 cn2601; + private static Cn9015 cn9015; + private static Cn0001 cn0001; + private static Cn2051 cn2051; + private static Cn2011 cn2011; + + public static Cn9015 getCn9015() { + return cn9015; + } + + @Autowired + public void setCn9900(Cn9015 cn9015) { + CommandInitCache.cn9015 = cn9015; + } + + public Cn2601 getCn2601() { + return cn2601; + } + @Autowired + public void setCn2601(Cn2601 cn2601) { + CommandInitCache.cn2601 = cn2601; + } + + public Cn2011 getCn2011() { + return cn2011; + } + @Autowired + public void setCn2011(Cn2011 cn2011) { + CommandInitCache.cn2011 = cn2011; + } + + public Cn2051 getCn2051() { + return cn2051; + } + + @Autowired + public void setCn2051(Cn2051 cn2051) { + CommandInitCache.cn2051 = cn2051; + } + + public static Cn0001 getCn0001() { + return cn0001; + } + @Autowired + public void setCn0001(Cn0001 cn0001) { + CommandInitCache.cn0001 = cn0001; + } + + private CommandInitCache() { + + } + + public static Map getReplyCache() { + if (replyCache.size()==0){ + replyCache=new HashMap<>(); + sendCache=new HashMap<>(); + replyCache.put("2601", cn2601); + replyCache.put("2051", cn2051); + replyCache.put("9015", cn9015); + replyCache.put("0001", cn0001); + replyCache.put("2011", cn2011); + } + return replyCache; + } + public static Map getSendCache() { + if (sendCache.size()==0){ + } + return sendCache; + } +} \ No newline at end of file diff --git a/src/main/java/com/drht/datamanage/cache/RequestCache.java b/src/main/java/com/drht/datamanage/cache/RequestCache.java new file mode 100644 index 0000000..f6f2cff --- /dev/null +++ b/src/main/java/com/drht/datamanage/cache/RequestCache.java @@ -0,0 +1,5 @@ +package com.drht.datamanage.cache; + +public class RequestCache { + +} diff --git a/src/main/java/com/drht/datamanage/config/FastJson2JsonRedisSerializer.java b/src/main/java/com/drht/datamanage/config/FastJson2JsonRedisSerializer.java new file mode 100644 index 0000000..bb34467 --- /dev/null +++ b/src/main/java/com/drht/datamanage/config/FastJson2JsonRedisSerializer.java @@ -0,0 +1,43 @@ +package com.drht.datamanage.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +import java.nio.charset.Charset; + +/** + * @ClassName FastJson2JsonRedisSerializer + * @Description TODO + * @Author chaixueteng + * @Date 2020/3/24 20:16 + */ +public class FastJson2JsonRedisSerializer implements RedisSerializer { + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + + private Class clazz; + + public FastJson2JsonRedisSerializer(Class clazz) { + super(); + this.clazz = clazz; + } + + @Override + public byte[] serialize(T t) throws SerializationException { + if (t == null) { + return new byte[0]; + } + return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); + } + + @Override + public T deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length <= 0) { + return null; + } + String str = new String(bytes, DEFAULT_CHARSET); + + return (T) JSON.parseObject(str, clazz); + } +} diff --git a/src/main/java/com/drht/datamanage/config/MyBatisPlusConfig.java b/src/main/java/com/drht/datamanage/config/MyBatisPlusConfig.java new file mode 100644 index 0000000..953584a --- /dev/null +++ b/src/main/java/com/drht/datamanage/config/MyBatisPlusConfig.java @@ -0,0 +1,22 @@ +package com.drht.datamanage.config; + +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + + +@Configuration +@EnableTransactionManagement +public class MyBatisPlusConfig { + /** + * 分页插件 + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); + paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); + return new PaginationInterceptor(); + } +} diff --git a/src/main/java/com/drht/datamanage/config/SwaggerConfig.java b/src/main/java/com/drht/datamanage/config/SwaggerConfig.java new file mode 100644 index 0000000..6fbf314 --- /dev/null +++ b/src/main/java/com/drht/datamanage/config/SwaggerConfig.java @@ -0,0 +1,61 @@ +package com.drht.datamanage.config; + +import io.swagger.annotations.ApiOperation; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Parameter; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.ArrayList; +import java.util.List; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + + @Bean + public Docket createRestApi() { + List pars = ParameterBuilder(); + return new Docket(DocumentationType.SWAGGER_2).enable(true) + .groupName("德润数据管理") + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.drht.datamanage.controller")) + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(pars); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("dataManagementSystem") + .description("德润数据管理") + .version("1.0") + .contact("zp") + .build(); + } + + + public List ParameterBuilder(){ + ParameterBuilder ticketPar = new ParameterBuilder(); + List pars = new ArrayList(); + //header中的ticket参数非必填,传空也可以 + ticketPar.name("token").description("user token") + .modelRef(new ModelRef("string")).parameterType("header") + .required(false).build(); + //根据每个方法名也知道当前方法在设置什么参数 + pars.add(ticketPar.build()); + return pars; + } +} + diff --git a/src/main/java/com/drht/datamanage/dao/HourlyDataDao.java b/src/main/java/com/drht/datamanage/dao/HourlyDataDao.java new file mode 100644 index 0000000..c2c00f7 --- /dev/null +++ b/src/main/java/com/drht/datamanage/dao/HourlyDataDao.java @@ -0,0 +1,21 @@ +package com.drht.datamanage.dao; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.toolkit.Constants; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.drht.datamanage.model.HourlyData; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * @description: + * @author: xuxianwei + * @time: 2020/9/15 15:46 + */ +@Mapper +public interface HourlyDataDao extends BaseMapper { + +} diff --git a/src/main/java/com/drht/datamanage/dao/MinuteDataDao.java b/src/main/java/com/drht/datamanage/dao/MinuteDataDao.java new file mode 100644 index 0000000..02eef03 --- /dev/null +++ b/src/main/java/com/drht/datamanage/dao/MinuteDataDao.java @@ -0,0 +1,10 @@ +package com.drht.datamanage.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.drht.datamanage.model.MinuteData; +import org.apache.ibatis.annotations.Mapper; + + +@Mapper +public interface MinuteDataDao extends BaseMapper { +} diff --git a/src/main/java/com/drht/datamanage/dao/RealTimeDataDao.java b/src/main/java/com/drht/datamanage/dao/RealTimeDataDao.java new file mode 100644 index 0000000..ad4c32d --- /dev/null +++ b/src/main/java/com/drht/datamanage/dao/RealTimeDataDao.java @@ -0,0 +1,11 @@ +package com.drht.datamanage.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.drht.datamanage.model.MinuteData; +import com.drht.datamanage.model.RealTimeData; +import org.apache.ibatis.annotations.Mapper; + + +@Mapper +public interface RealTimeDataDao extends BaseMapper { +} diff --git a/src/main/java/com/drht/datamanage/exception/AnalysisException.java b/src/main/java/com/drht/datamanage/exception/AnalysisException.java new file mode 100644 index 0000000..cbef690 --- /dev/null +++ b/src/main/java/com/drht/datamanage/exception/AnalysisException.java @@ -0,0 +1,30 @@ +package com.drht.datamanage.exception; + +public class AnalysisException extends Exception { + + private String msg; + + private int code; + + public AnalysisException(int code,String msg){ + this.code=code; + this.msg=msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + +} diff --git a/src/main/java/com/drht/datamanage/exception/CommonException.java b/src/main/java/com/drht/datamanage/exception/CommonException.java new file mode 100644 index 0000000..8a24284 --- /dev/null +++ b/src/main/java/com/drht/datamanage/exception/CommonException.java @@ -0,0 +1,56 @@ +package com.drht.datamanage.exception; + + + +/** + * 自定义异常 + * @author chaixueteng + */ +public class CommonException extends RuntimeException { + private int errorCode; + private String msg; + + public CommonException(ResultCode errorCode) { + super(errorCode.getInfo()); + this.errorCode = errorCode.getCode(); + this.msg = errorCode.getInfo(); + } + + public CommonException(ResultCode errorCode, String msg) { + super(msg); + this.errorCode = errorCode.getCode(); + this.msg = msg; + } + + public CommonException(int errorCode, String msg) { + super(msg); + this.errorCode = errorCode; + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + /** + * 重新异常堆栈信息处理,避免遍历堆栈资源浪费,提供性能 + * @return a reference to this {@code Throwable} instance. + * @see Throwable#printStackTrace() + */ + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/src/main/java/com/drht/datamanage/exception/ResultCode.java b/src/main/java/com/drht/datamanage/exception/ResultCode.java new file mode 100644 index 0000000..e4b7f6c --- /dev/null +++ b/src/main/java/com/drht/datamanage/exception/ResultCode.java @@ -0,0 +1,27 @@ +package com.drht.datamanage.exception; + +/** + * 响应码枚举 + */ +public enum ResultCode { + + SUCCESS(0,"成功"), + FAIL(1,"失败"); + + private int code; + private String info; + + ResultCode(int code, String info) { + this.code = code; + this.info = info; + } + + public int getCode() { + return code; + } + + public String getInfo() { + return info; + } + +} diff --git a/src/main/java/com/drht/datamanage/handler/CheckDeviceInChannelHandler.java b/src/main/java/com/drht/datamanage/handler/CheckDeviceInChannelHandler.java new file mode 100644 index 0000000..f599645 --- /dev/null +++ b/src/main/java/com/drht/datamanage/handler/CheckDeviceInChannelHandler.java @@ -0,0 +1,65 @@ +package com.drht.datamanage.handler; + + +import com.drht.datamanage.util.AnalysisUtil; +import com.drht.datamanage.util.SpringContextUtil; +import com.drht.datamanage.dao.HourlyDataDao; +import com.drht.datamanage.exception.AnalysisException; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.timeout.ReadTimeoutException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.ApplicationContext; + +@Slf4j +public class CheckDeviceInChannelHandler extends SimpleChannelInboundHandler { +// @Autowired +// private DeviceMapper deviceMapper; + + // crc校验后调用检查设备是否可用 + @Override + public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { + ApplicationContext context = SpringContextUtil.context; + HourlyDataDao deviceMapper = (HourlyDataDao) context.getBean("hourlyDataDao"); + //解析报文 + String s=(String)msg; + AnalysisUtil.Msg msgo = AnalysisUtil.msgToJsonString(s); + //验证设备 + String mn=msgo.getMN(); +// String status = deviceMapper.queryStatusByMn(mn); +// if (!"0".equals(status)){ +// log.info("验证mn:{}的设备没通过,msg:{}",mn,"设备不在线!"); +// ctx.close(); +// return; +// } + //向下传递 + ctx.fireChannelRead(msgo); + } + + // 数据读取完后被调用 + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用 + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + if (cause instanceof ReadTimeoutException){ + //超时异常 + log.info("关闭了一个90s内没有发送任何数据的链接"); + ctx.close(); + + }else if (cause instanceof AnalysisException){ + AnalysisException e = (AnalysisException) cause; + //解析报文出错的异常 + log.info("解析报文出错:code={},msg={}",e.getCode(),e.getMsg()); + ctx.close(); + // + }else{ + //其他异常向下传递 + ctx.fireExceptionCaught(cause); + } + + } +} diff --git a/src/main/java/com/drht/datamanage/handler/CheckMsgInChannelHandler.java b/src/main/java/com/drht/datamanage/handler/CheckMsgInChannelHandler.java new file mode 100644 index 0000000..8714844 --- /dev/null +++ b/src/main/java/com/drht/datamanage/handler/CheckMsgInChannelHandler.java @@ -0,0 +1,78 @@ +package com.drht.datamanage.handler; + +import com.drht.datamanage.util.HelperUtil; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class CheckMsgInChannelHandler extends SimpleChannelInboundHandler { + + // 检查消息合法否,crc校验 + @Override + public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { + String str=(String)msg; + log.info("原始数据{}",str); + if (!(str.contains("QN") + &&str.contains("PW") + &&str.contains("MN") + &&str.contains("CN") + &&str.contains("CP"))){ +// 不合法的包,关闭通道,记录 + log.info("不合法{},通道关闭",str); + ctx.close(); + return; + } + if (!str.startsWith("##")){ + //包头不是##开头,记录日志关闭通道 + log.info("不合法{},不是##开头,通道关闭",str); + ctx.close(); + return; + } + //获取报文crc + String crc=str.substring(str.length()-4); + //截取掉包头与包未 + str=str.substring(2,str.length()-4); + + //crc校验 + int checkCrc = HelperUtil.getCheckCrc(str.getBytes()); + //转16进制并转成大写 + String scheckCrc = String.format("%04x",checkCrc).toUpperCase(); +// if (!(scheckCrc.equals(crc.toUpperCase()))){ +// //未通过crc校验 +// log.info("不合法{},未通过crc校验,报文crc{},服务端生成的crc{},通道关闭",str,crc,scheckCrc); +// ctx.close(); +// return; +// } + log.info("第一层校验处理后{}",str); + ctx.fireChannelRead(str); + + } + + // 数据读取完后被调用 + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用 + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + //到下一个handler处理 + ctx.fireExceptionCaught(cause); + + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + if (ctx.channel().remoteAddress().toString().startsWith("/100.")) { + ctx.close(); + return; + } + super.channelActive(ctx); + + } + + + +} diff --git a/src/main/java/com/drht/datamanage/handler/ReplyDeviceInChannelHandler.java b/src/main/java/com/drht/datamanage/handler/ReplyDeviceInChannelHandler.java new file mode 100644 index 0000000..2f60976 --- /dev/null +++ b/src/main/java/com/drht/datamanage/handler/ReplyDeviceInChannelHandler.java @@ -0,0 +1,45 @@ +package com.drht.datamanage.handler; + +import com.drht.datamanage.util.AnalysisUtil; +import com.drht.datamanage.cache.CommandInitCache; +import com.drht.datamanage.service.Reply; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; + +import java.io.IOException; + +public class ReplyDeviceInChannelHandler extends SimpleChannelInboundHandler { + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReplyDeviceInChannelHandler.class); + // 检查完设备后,回复命令调用 + @Override + public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { + AnalysisUtil.Msg msgo= (AnalysisUtil.Msg) msg; + //根据cn分别回复 + String cn = msgo.getCN(); + //根据cn获取执行对象 + Reply reply = CommandInitCache.getReplyCache().get(cn); + //执行业务逻辑 + reply.rese(msgo,ctx); +// ctx.fireChannelRead(msg); + } + + // 数据读取完后被调用 + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用 + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + if (cause instanceof IOException){ + logger.error("io异常"); + ctx.close(); + return; + } + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/src/main/java/com/drht/datamanage/handler/SendChannelHandler.java b/src/main/java/com/drht/datamanage/handler/SendChannelHandler.java new file mode 100644 index 0000000..9aec49f --- /dev/null +++ b/src/main/java/com/drht/datamanage/handler/SendChannelHandler.java @@ -0,0 +1,20 @@ +package com.drht.datamanage.handler; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class SendChannelHandler extends ChannelOutboundHandlerAdapter { +//发送消息触发 + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + log.info("发出的报文{}",msg.toString()); + super.write(ctx, msg, promise); + //预留控制发送命令,短时间内不能太多 + } +} diff --git a/src/main/java/com/drht/datamanage/listener/NettyServerListener.java b/src/main/java/com/drht/datamanage/listener/NettyServerListener.java new file mode 100644 index 0000000..9a7b702 --- /dev/null +++ b/src/main/java/com/drht/datamanage/listener/NettyServerListener.java @@ -0,0 +1,27 @@ +package com.drht.datamanage.listener; + +import com.drht.datamanage.App; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +@Component +@Slf4j +public class NettyServerListener implements ApplicationRunner { + /** + * 当一个applicationContext被初始化或被刷新时触发 + */ + @Override + public void run(ApplicationArguments args) throws Exception { + log.info("启动netty组件"); + new Thread(new Runnable() { + @SneakyThrows + @Override + public void run() { + App.run(); + } + }).start(); + } +} diff --git a/src/main/java/com/drht/datamanage/model/HourlyData.java b/src/main/java/com/drht/datamanage/model/HourlyData.java new file mode 100644 index 0000000..350bf0b --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/HourlyData.java @@ -0,0 +1,88 @@ +package com.drht.datamanage.model; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +import java.time.LocalDateTime; + + +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@TableName("t_hourly_data") +@ApiModel(value="小时数据", description="小时数据") +public class HourlyData extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private int id; + + @TableField("f_time") + private String f_time; + + @TableField("f_cod_min") + private String f_cod_min; //w01018-Min + + @TableField("f_cod_avg") + private String f_cod_avg;//w01018-Avg + + @TableField("f_cod_max") + private String f_cod_max;//w01018-Max + + @TableField("f_nitrate_min") + private String f_nitrate_min;//w01018-Min + + + @TableField("f_nitrate_avg") + private String f_nitrate_avg;//w01018-Avg + + + @TableField("f_nitrate_max") + private String f_nitrate_max;//w01018-Max + + @TableField("f_tss_min") + private String f_tss_min;//w01018-Min + + @TableField("f_tss_avg") + private String f_tss_avg;//w01018-Avg + + @TableField("f_tss_max") + private String f_tss_max;//w01018-Max + + @TableField("f_toc_min") + private String f_toc_min;//w01018-Min + + + @TableField("f_toc_avg") + private String f_toc_avg;//w01018-Avg + + @TableField("f_toc_max") + private String f_toc_max;//w01018-Max + + @TableField("f_permanganate_index_min") + private String f_permanganate_index_min;//w01018-Min + + @TableField("f_permanganate_index_avg") + private String f_permanganate_index_avg;//w01018-Avg + + @TableField("f_permanganate_index_max") + private String f_permanganate_index_max;//w01018-Max + + @TableField("f_turbidity_min") + private String f_turbidity_min;//w01018-Min + + @TableField("f_turbidity_avg") + private String f_turbidity_avg;//w01018-Avg + + @TableField("f_turbidity_max") + private String f_turbidity_max;//w01018-Max +} diff --git a/src/main/java/com/drht/datamanage/model/MinuteData.java b/src/main/java/com/drht/datamanage/model/MinuteData.java new file mode 100644 index 0000000..2f25a81 --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/MinuteData.java @@ -0,0 +1,85 @@ +package com.drht.datamanage.model; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import io.swagger.annotations.ApiModel; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + + +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@TableName("t_minute_data") +@ApiModel(value="分钟数据", description="分钟数据") +public class MinuteData extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private int id; + + @TableField("f_time") + private String f_time; + + @TableField("f_cod_min") + private String f_cod_min; //w01018-Min + + @TableField("f_cod_avg") + private String f_cod_avg;//w01018-Avg + + @TableField("f_cod_max") + private String f_cod_max;//w01018-Max + + @TableField("f_nitrate_min") + private String f_nitrate_min;//w01018-Min + + + @TableField("f_nitrate_avg") + private String f_nitrate_avg;//w01018-Avg + + + @TableField("f_nitrate_max") + private String f_nitrate_max;//w01018-Max + + @TableField("f_tss_min") + private String f_tss_min;//w01018-Min + + @TableField("f_tss_avg") + private String f_tss_avg;//w01018-Avg + + @TableField("f_tss_max") + private String f_tss_max;//w01018-Max + + @TableField("f_toc_min") + private String f_toc_min;//w01018-Min + + + @TableField("f_toc_avg") + private String f_toc_avg;//w01018-Avg + + @TableField("f_toc_max") + private String f_toc_max;//w01018-Max + + @TableField("f_permanganate_index_min") + private String f_permanganate_index_min;//w01018-Min + + @TableField("f_permanganate_index_avg") + private String f_permanganate_index_avg;//w01018-Avg + + @TableField("f_permanganate_index_max") + private String f_permanganate_index_max;//w01018-Max + + @TableField("f_turbidity_min") + private String f_turbidity_min;//w01018-Min + + @TableField("f_turbidity_avg") + private String f_turbidity_avg;//w01018-Avg + + @TableField("f_turbidity_max") + private String f_turbidity_max;//w01018-Max +} diff --git a/src/main/java/com/drht/datamanage/model/RealTimeData.java b/src/main/java/com/drht/datamanage/model/RealTimeData.java new file mode 100644 index 0000000..5b64bd9 --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/RealTimeData.java @@ -0,0 +1,50 @@ +package com.drht.datamanage.model; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import io.swagger.annotations.ApiModel; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + + +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@TableName("t_realtime_data") +@ApiModel(value="实时数据", description="实时数据") +public class RealTimeData extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private int id; + + @TableField("f_time") + private String f_time; + + @TableField("f_cod") + private String f_cod;//w01018 + + @TableField("f_nitrate") + private String f_nitrate;//w21007 + + @TableField("f_tss") + private String f_tss;//w01012 + + @TableField("f_toc") + private String f_toc;//w01020 + + + @TableField("f_permanganate_index") + private String f_permanganate_index;//w01019 + + @TableField("f_turbidity") + private String f_turbidity;//w01003 + + @TableField("f_raw_data") + private String f_raw_data; +} diff --git a/src/main/java/com/drht/datamanage/model/msg/CommandMsg.java b/src/main/java/com/drht/datamanage/model/msg/CommandMsg.java new file mode 100644 index 0000000..e193ac6 --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/msg/CommandMsg.java @@ -0,0 +1,36 @@ +package com.drht.datamanage.model.msg; + +import java.util.Map; + +public class CommandMsg { + + private String methodname; + + private String requesid; + + private Map methodparams; + + public String getMethodname() { + return methodname; + } + + public void setMethodname(String methodname) { + this.methodname = methodname; + } + + public String getRequesid() { + return requesid; + } + + public void setRequesid(String requesid) { + this.requesid = requesid; + } + + public Map getMethodparams() { + return methodparams; + } + + public void setMethodparams(Map methodparams) { + this.methodparams = methodparams; + } +} diff --git a/src/main/java/com/drht/datamanage/model/msg/ReplyKafkaMsg.java b/src/main/java/com/drht/datamanage/model/msg/ReplyKafkaMsg.java new file mode 100644 index 0000000..4548fb8 --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/msg/ReplyKafkaMsg.java @@ -0,0 +1,25 @@ +package com.drht.datamanage.model.msg; + +import java.util.Map; + +public class ReplyKafkaMsg { + private boolean isrequest; + + private Map data; + + public boolean isIsrequest() { + return isrequest; + } + + public void setIsrequest(boolean isrequest) { + this.isrequest = isrequest; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } +} diff --git a/src/main/java/com/drht/datamanage/model/msg/SendMsg.java b/src/main/java/com/drht/datamanage/model/msg/SendMsg.java new file mode 100644 index 0000000..f1182d6 --- /dev/null +++ b/src/main/java/com/drht/datamanage/model/msg/SendMsg.java @@ -0,0 +1,80 @@ +package com.drht.datamanage.model.msg; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import com.drht.datamanage.util.QnUtil; + +public class SendMsg { + + + private String QN= QnUtil.getQN(new Date()); + private String PW; + private String MN; + private String CN; + private String Flag; + private String ST; + private List> CP; + + + public String getQN() { + return QN; + } + + public void setQN(String QN) { + this.QN = QN; + } + + public String getPW() { + return PW; + } + + public void setPW(String PW) { + this.PW = PW; + } + + public String getMN() { + return MN; + } + + public void setMN(String MN) { + this.MN = MN; + } + + public String getCN() { + return CN; + } + + public void setCN(String CN) { + this.CN = CN; + } + + public List> getCP() { + return CP; + } + + public void setCP(List> CP) { + this.CP = CP; + } + + public String getFlag() { + return Flag; + } + + public void setFlag(String flag) { + Flag = flag; + } + + public String getST() { + return ST; + } + + public void setST(String ST) { + this.ST = ST; + } + + @Override + public String toString() { + return "QN=" + QN + ";ST=" + ST + ";CN=" + CN + ";PW=" + PW + ";MN=" + MN + ";Flag=" + Flag+";CP=&&"; + } +} diff --git a/src/main/java/com/drht/datamanage/protocols/Cn0001.java b/src/main/java/com/drht/datamanage/protocols/Cn0001.java new file mode 100644 index 0000000..4e40cf5 --- /dev/null +++ b/src/main/java/com/drht/datamanage/protocols/Cn0001.java @@ -0,0 +1,24 @@ +package com.drht.datamanage.protocols; + +import com.drht.datamanage.service.Reply; +import com.drht.datamanage.util.AnalysisUtil; +import io.netty.channel.ChannelHandlerContext; +import org.springframework.stereotype.Service; + +import java.text.ParseException; + +/** + * 设备自动注册报文 + * + * @author chai + */ +@Service("0001") +public class Cn0001 implements Reply { + + + @Override + public void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException { + //编码执行成功报文 回复消息 + ctx.writeAndFlush(AnalysisUtil.exeRtnSuccess(msg)); + } +} diff --git a/src/main/java/com/drht/datamanage/protocols/Cn2011.java b/src/main/java/com/drht/datamanage/protocols/Cn2011.java new file mode 100644 index 0000000..df7754d --- /dev/null +++ b/src/main/java/com/drht/datamanage/protocols/Cn2011.java @@ -0,0 +1,72 @@ +package com.drht.datamanage.protocols; + +import com.drhb.base.result.BaseResult; +import com.drht.datamanage.model.RealTimeData; +import com.drht.datamanage.model.msg.SendMsg; +import com.drht.datamanage.service.RealTimeDataService; +import com.drht.datamanage.service.Reply; +import com.drht.datamanage.util.AnalysisUtil; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.util.*; + +/** + * 实时数据 + */ +@Service +@Slf4j +public class Cn2011 implements Reply { + @Autowired + private RealTimeDataService realTimeDataService; + + @Override + public void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException { + SendMsg sendMsg=new SendMsg(); + sendMsg.setQN(msg.getQN()); + sendMsg.setCN("9014"); + sendMsg.setPW(msg.getPW());//暂时写死 + sendMsg.setMN(msg.getMN()); + sendMsg.setFlag("4"); + sendMsg.setST("91"); + List> CP=new ArrayList<>(); + Map cpMap=new HashMap(); + cpMap.put("QnRtn","1"); + CP.add(cpMap); + sendMsg.setCP(CP); + //编码报文 + String s = AnalysisUtil.KvToMsg(sendMsg,";"); + //回复消息 + ChannelFuture channelFuture = ctx.writeAndFlush(s); + //实时数据入库 + Set set = msg.getCP().keySet(); + RealTimeData realTimeData=new RealTimeData(); + for (Object cpkey:set){ + String ckey=(String)cpkey; + String v = (String) msg.getCP().get(ckey); + if(ckey.startsWith("w21007-Rtd")) + realTimeData.setF_nitrate(v); + else if(ckey.equals("w01012-Rtd")) + realTimeData.setF_tss(v); + else if(ckey.equals("w01018-Rtd")) + realTimeData.setF_cod(v); + else if(ckey.equals("w01020-Rtd")) + realTimeData.setF_toc(v); + else if(ckey.equals("w01019-Rtd")) + realTimeData.setF_permanganate_index(v); + else if(ckey.equals("w01003-Rtd")) + realTimeData.setF_turbidity(v); + else if(ckey.equals("DataTime")) + realTimeData.setF_time(v); + else if(ckey.equals("f_raw_data")) + realTimeData.setF_raw_data(v); + } + BaseResult result=realTimeDataService.insert(realTimeData); + log.info("保存实时数据结果={}",result); + } +} diff --git a/src/main/java/com/drht/datamanage/protocols/Cn2051.java b/src/main/java/com/drht/datamanage/protocols/Cn2051.java new file mode 100644 index 0000000..b6009b7 --- /dev/null +++ b/src/main/java/com/drht/datamanage/protocols/Cn2051.java @@ -0,0 +1,94 @@ +package com.drht.datamanage.protocols; + +import com.drhb.base.result.BaseResult; +import com.drht.datamanage.model.MinuteData; +import com.drht.datamanage.model.RealTimeData; +import com.drht.datamanage.model.msg.SendMsg; +import com.drht.datamanage.service.MinuteDataService; +import com.drht.datamanage.service.Reply; +import com.drht.datamanage.util.AnalysisUtil; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.util.*; + +/** + * 分钟数据 + */ +@Service +@Slf4j +public class Cn2051 implements Reply { + @Autowired + private MinuteDataService minuteDataService; + + @Override + public void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException { + SendMsg sendMsg=new SendMsg(); + sendMsg.setQN(msg.getQN()); + sendMsg.setCN("9014"); + sendMsg.setPW(msg.getPW());//暂时写死 + sendMsg.setMN(msg.getMN()); + sendMsg.setFlag(msg.getFlag()); + sendMsg.setST("91"); + List> CP=new ArrayList<>(); + Map cpMap=new HashMap(); + cpMap.put("ExeRtn","1"); + CP.add(cpMap); + sendMsg.setCP(CP); + //编码报文 + String s = AnalysisUtil.KvToMsg(sendMsg,";"); + //回复消息 + ChannelFuture channelFuture = ctx.writeAndFlush(s); + //分钟数据入库 + Set set = msg.getCP().keySet(); + MinuteData minuteData=new MinuteData(); + for (Object cpkey:set){ + String ckey=(String)cpkey; + String v = (String) msg.getCP().get(ckey); + if(ckey.equals("w21007-Min")) + minuteData.setF_nitrate_min(v); + else if(ckey.equals("w01012-Min")) + minuteData.setF_tss_min(v); + else if(ckey.equals("w01018-Min")) + minuteData.setF_cod_min(v); + else if(ckey.equals("w01020-Min")) + minuteData.setF_toc_min(v); + else if(ckey.equals("w01019-Min")) + minuteData.setF_permanganate_index_min(v); + else if(ckey.equals("w01003-Min")) + minuteData.setF_turbidity_min(v); + else if(ckey.equals("w21007-Avg")) + minuteData.setF_nitrate_avg(v); + else if(ckey.equals("w01012-Avg")) + minuteData.setF_tss_avg(v); + else if(ckey.equals("w01018-Avg")) + minuteData.setF_cod_avg(v); + else if(ckey.equals("w01020-Avg")) + minuteData.setF_toc_avg(v); + else if(ckey.equals("w01019-Avg")) + minuteData.setF_permanganate_index_avg(v); + else if(ckey.equals("w01003-Avg")) + minuteData.setF_turbidity_avg(v); + else if(ckey.equals("w21007-Max")) + minuteData.setF_nitrate_max(v); + else if(ckey.equals("w01012-Max")) + minuteData.setF_tss_max(v); + else if(ckey.equals("w01018-Max")) + minuteData.setF_cod_max(v); + else if(ckey.equals("w01020-Max")) + minuteData.setF_toc_max(v); + else if(ckey.equals("w01019-Max")) + minuteData.setF_permanganate_index_max(v); + else if(ckey.equals("w01003-Max")) + minuteData.setF_turbidity_max(v); + else if(ckey.equals("DataTime")) + minuteData.setF_time(v); + } + BaseResult result=minuteDataService.insert(minuteData); + log.info("保存分钟数据结果={}",result); + } +} diff --git a/src/main/java/com/drht/datamanage/protocols/Cn2601.java b/src/main/java/com/drht/datamanage/protocols/Cn2601.java new file mode 100644 index 0000000..2d9d019 --- /dev/null +++ b/src/main/java/com/drht/datamanage/protocols/Cn2601.java @@ -0,0 +1,95 @@ +package com.drht.datamanage.protocols; + +import com.drhb.base.result.BaseResult; +import com.drht.datamanage.model.HourlyData; +import com.drht.datamanage.model.MinuteData; +import com.drht.datamanage.service.HourlyDataService; +import com.drht.datamanage.util.AnalysisUtil; +import com.drht.datamanage.model.msg.SendMsg; +import com.drht.datamanage.service.Reply; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.util.*; +import java.util.List; + +/** + * 小时数据 + */ +@Service +@Slf4j +public class Cn2601 implements Reply { + @Autowired + private HourlyDataService hourlyDataService; + + @Override + public void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException { + SendMsg sendMsg=new SendMsg(); + sendMsg.setQN(msg.getQN()); + sendMsg.setCN("9014"); + sendMsg.setPW(msg.getPW());//暂时写死 + sendMsg.setMN(msg.getMN()); + sendMsg.setFlag("8"); + sendMsg.setST("91"); + List> CP=new ArrayList<>(); + Map cpMap=new HashMap(); + cpMap.put("QnRtn","1"); + CP.add(cpMap); + sendMsg.setCP(CP); + //编码报文 + String s = AnalysisUtil.KvToMsg(sendMsg,";"); + //回复消息 + ChannelFuture channelFuture = ctx.writeAndFlush(s); + //小时数据入库 + Set set = msg.getCP().keySet(); + HourlyData hourlyData=new HourlyData(); + for (Object cpkey:set){ + String ckey=(String)cpkey; + String v = (String) msg.getCP().get(ckey); + if(ckey.equals("w21007-Min")) + hourlyData.setF_nitrate_min(v); + else if(ckey.equals("w01012-Min")) + hourlyData.setF_tss_min(v); + else if(ckey.equals("w01018-Min")) + hourlyData.setF_cod_min(v); + else if(ckey.equals("w01020-Min")) + hourlyData.setF_toc_min(v); + else if(ckey.equals("w01019-Min")) + hourlyData.setF_permanganate_index_min(v); + else if(ckey.equals("w01003-Min")) + hourlyData.setF_turbidity_min(v); + else if(ckey.equals("w21007-Avg")) + hourlyData.setF_nitrate_avg(v); + else if(ckey.equals("w01012-Avg")) + hourlyData.setF_tss_avg(v); + else if(ckey.equals("w01018-Avg")) + hourlyData.setF_cod_avg(v); + else if(ckey.equals("w01020-Avg")) + hourlyData.setF_toc_avg(v); + else if(ckey.equals("w01019-Avg")) + hourlyData.setF_permanganate_index_avg(v); + else if(ckey.equals("w01003-Avg")) + hourlyData.setF_turbidity_avg(v); + else if(ckey.equals("w21007-Max")) + hourlyData.setF_nitrate_max(v); + else if(ckey.equals("w01012-Max")) + hourlyData.setF_tss_max(v); + else if(ckey.equals("w01018-Max")) + hourlyData.setF_cod_max(v); + else if(ckey.equals("w01020-Max")) + hourlyData.setF_toc_max(v); + else if(ckey.equals("w01019-Max")) + hourlyData.setF_permanganate_index_max(v); + else if(ckey.equals("w01003-Max")) + hourlyData.setF_turbidity_max(v); + else if(ckey.equals("DataTime")) + hourlyData.setF_time(v); + } + BaseResult result=hourlyDataService.insert(hourlyData); + log.info("保存小时数据结果={}",result); + } +} diff --git a/src/main/java/com/drht/datamanage/protocols/Cn9015.java b/src/main/java/com/drht/datamanage/protocols/Cn9015.java new file mode 100644 index 0000000..04e20ac --- /dev/null +++ b/src/main/java/com/drht/datamanage/protocols/Cn9015.java @@ -0,0 +1,40 @@ +package com.drht.datamanage.protocols; + +import com.drht.datamanage.model.msg.SendMsg; +import com.drht.datamanage.service.Reply; +import com.drht.datamanage.util.AnalysisUtil; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.util.*; + +/** + * 心跳 + */ +@Service +@Slf4j +public class Cn9015 implements Reply { + @Override + public void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException { + SendMsg sendMsg=new SendMsg(); + sendMsg.setQN(msg.getQN()); + sendMsg.setCN("9014"); + sendMsg.setPW(msg.getPW());//暂时写死 + sendMsg.setMN(msg.getMN()); + sendMsg.setFlag("0"); + sendMsg.setST("91"); + List> CP=new ArrayList<>(); + Map cpMap=new HashMap(); + cpMap.put("QnRtn","1"); + CP.add(cpMap); + sendMsg.setCP(CP); + //编码报文 + String s = AnalysisUtil.KvToMsg(sendMsg,";"); + //回复消息 + ChannelFuture channelFuture = ctx.writeAndFlush(s); + log.info("回复消息成功={}",s); + } +} diff --git a/src/main/java/com/drht/datamanage/service/HourlyDataService.java b/src/main/java/com/drht/datamanage/service/HourlyDataService.java new file mode 100644 index 0000000..3ba8e65 --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/HourlyDataService.java @@ -0,0 +1,12 @@ +package com.drht.datamanage.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.drhb.base.result.BaseListVO; +import com.drhb.base.result.BaseResult; +import com.drhb.common.form.IdsForm; +import com.drht.datamanage.model.*; + +public interface HourlyDataService extends IService { + + BaseResult insert(HourlyData deviceVO); +} diff --git a/src/main/java/com/drht/datamanage/service/Impl/HourlyDataServiceImpl.java b/src/main/java/com/drht/datamanage/service/Impl/HourlyDataServiceImpl.java new file mode 100644 index 0000000..0729b23 --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/Impl/HourlyDataServiceImpl.java @@ -0,0 +1,22 @@ +package com.drht.datamanage.service.Impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.drhb.base.result.BaseResult; +import com.drhb.base.result.BaseResultGenerator; +import com.drht.datamanage.dao.HourlyDataDao; +import com.drht.datamanage.model.*; +import com.drht.datamanage.service.HourlyDataService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class HourlyDataServiceImpl extends ServiceImpl implements HourlyDataService { + + @Override + public BaseResult insert(HourlyData deviceVO) { + save(deviceVO); + return BaseResultGenerator.genSuccessResult(); + } +} diff --git a/src/main/java/com/drht/datamanage/service/Impl/MinuteDataServiceImpl.java b/src/main/java/com/drht/datamanage/service/Impl/MinuteDataServiceImpl.java new file mode 100644 index 0000000..43efba1 --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/Impl/MinuteDataServiceImpl.java @@ -0,0 +1,23 @@ +package com.drht.datamanage.service.Impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.drhb.base.result.BaseResult; +import com.drhb.base.result.BaseResultGenerator; +import com.drht.datamanage.dao.MinuteDataDao; +import com.drht.datamanage.model.MinuteData; +import com.drht.datamanage.service.MinuteDataService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class MinuteDataServiceImpl extends ServiceImpl implements MinuteDataService { + + + @Override + public BaseResult insert(MinuteData deviceTypeVO) { + save(deviceTypeVO); + return BaseResultGenerator.genSuccessResult(); + } +} diff --git a/src/main/java/com/drht/datamanage/service/Impl/RealTimeDataServiceImpl.java b/src/main/java/com/drht/datamanage/service/Impl/RealTimeDataServiceImpl.java new file mode 100644 index 0000000..d0cd8fc --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/Impl/RealTimeDataServiceImpl.java @@ -0,0 +1,26 @@ +package com.drht.datamanage.service.Impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.drhb.base.result.BaseResult; +import com.drhb.base.result.BaseResultGenerator; +import com.drht.datamanage.dao.MinuteDataDao; +import com.drht.datamanage.dao.RealTimeDataDao; +import com.drht.datamanage.model.MinuteData; +import com.drht.datamanage.model.RealTimeData; +import com.drht.datamanage.service.MinuteDataService; +import com.drht.datamanage.service.RealTimeDataService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class RealTimeDataServiceImpl extends ServiceImpl implements RealTimeDataService { + + + @Override + public BaseResult insert(RealTimeData deviceTypeVO) { + save(deviceTypeVO); + return BaseResultGenerator.genSuccessResult(); + } +} diff --git a/src/main/java/com/drht/datamanage/service/MinuteDataService.java b/src/main/java/com/drht/datamanage/service/MinuteDataService.java new file mode 100644 index 0000000..3138de3 --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/MinuteDataService.java @@ -0,0 +1,10 @@ +package com.drht.datamanage.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.drhb.base.result.BaseResult; +import com.drht.datamanage.model.MinuteData; + +public interface MinuteDataService extends IService { + + BaseResult insert(MinuteData deviceTypeVO); +} diff --git a/src/main/java/com/drht/datamanage/service/RealTimeDataService.java b/src/main/java/com/drht/datamanage/service/RealTimeDataService.java new file mode 100644 index 0000000..0150a8c --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/RealTimeDataService.java @@ -0,0 +1,11 @@ +package com.drht.datamanage.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.drhb.base.result.BaseResult; +import com.drht.datamanage.model.HourlyData; +import com.drht.datamanage.model.RealTimeData; + +public interface RealTimeDataService extends IService { + + BaseResult insert(RealTimeData deviceVO); +} diff --git a/src/main/java/com/drht/datamanage/service/Reply.java b/src/main/java/com/drht/datamanage/service/Reply.java new file mode 100644 index 0000000..2a52658 --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/Reply.java @@ -0,0 +1,11 @@ +package com.drht.datamanage.service; + +import com.drht.datamanage.util.AnalysisUtil; +import io.netty.channel.ChannelHandlerContext; + +import java.text.ParseException; + +public interface Reply { + + void rese(AnalysisUtil.Msg msg, ChannelHandlerContext ctx) throws ParseException; +} diff --git a/src/main/java/com/drht/datamanage/service/Send.java b/src/main/java/com/drht/datamanage/service/Send.java new file mode 100644 index 0000000..5904f6a --- /dev/null +++ b/src/main/java/com/drht/datamanage/service/Send.java @@ -0,0 +1,10 @@ +package com.drht.datamanage.service; + +import com.drht.datamanage.model.msg.CommandMsg; + +public interface Send { + + public void send(CommandMsg msg); + + +} diff --git a/src/main/java/com/drht/datamanage/test/Test.java b/src/main/java/com/drht/datamanage/test/Test.java new file mode 100644 index 0000000..81b4bf7 --- /dev/null +++ b/src/main/java/com/drht/datamanage/test/Test.java @@ -0,0 +1,116 @@ +package com.drht.datamanage.test; + +import com.drht.datamanage.util.AnalysisUtil; +import com.drht.datamanage.model.msg.SendMsg; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +import java.io.*; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +@Slf4j +public class Test { + public static void main(String[] args) throws IOException, InterruptedException { +// Socket socket=new Socket("27.185.43.173",7007); + Socket socket=new Socket("127.0.0.1",7001); + OutputStream outputStream = socket.getOutputStream(); + BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream)); +// String a ="##0094QN=20000101000000000;ST=21;CN=0001;PW=123456;MN=60288888000103;Flag=1;CP=&&model=DR-103K;FN=&&47C0\r\n"; +// String a="##0077QN=20000101000000000;ST=21;CN=9900;PW=123456;MN=60288888000103;Flag=1;CP=&&&&9B81\r\n"; +// String a="##1234QN=20180210154956000;ST=21;CN=2701;PW=123456;" + +// "MN=60288888000014;Flag=0;CP=&&DataTime=20230925002155;" + +// "w01019-Rtd=8.1,w01019-Flag=N;w01018-Rtd=8.1," + +// "w01018-ADC=65535;w01020-Rtd=100.2;Version=2022030401&&53C0\r\n"; + List strList = new ArrayList<>(); + BufferedReader reader; + try { + reader = new BufferedReader(new FileReader("d:\\667.txt")); + String line = reader.readLine(); + while (line != null) { + strList.add(line); + line = reader.readLine();// 继续读取下一行 + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + System.out.println("文件不存在"); + } + System.out.println(strList); + String a="##1234QN=20180210154956000;ST=21;CN=2011;PW=123456;MN=60288888000103;" + + "Flag=0;CP=&&DataTime=20231129111455;" + + "w21007-Rtd=7.1;" + + "w01012-Rtd=7.5;" + + "w01018-Rtd=7.9;" + + "w01020-Rtd=9.22;" + + "w01019-Rtd=7.1;" + + "w01003-Rtd=7.5;" + + "f_raw_data="+ StringUtils.join(strList,"") +"&&1234\r\n"; +// String a="##1234QN=20180210154956000;ST=21;CN=2601;PW=123456;MN=60288888000103;" + +// "Flag=0;CP=&&DataTime=20231129111455;" + +// "w21007-Min=7.1,w01012-Avg=7.5,w21007-Max=7.1;" + +// "w01012-Min=7.1,w01012-Avg=7.5,w01012-Max=7.1;" + +// "w01018-Min=7.1,w01018-Avg=7.5,w01018-Max=7.1;" + +// "w01020-Min=7.1,w01020-Avg=7.5,w01020-Max=7.1;" + +// "w01019-Min=7.1,w01019-Avg=7.5,w01019-Max=7.1;" + +// "w01003-Min=7.1,w01003-Avg=7.5,w01003-Max=7.1" + +// "&&1234\r\n"; +// String a="##1234QN=20180210154956000;ST=21;CN=2051;PW=123456;MN=60288888000103;" + +// "Flag=0;CP=&&DataTime=20231129111455;" + +// "w21007-Min=7.1,w01012-Avg=7.5,w21007-Max=7.1;" + +// "w01012-Min=7.1,w01012-Avg=7.5,w01012-Max=7.1;" + +// "w01018-Min=7.1,w01018-Avg=7.5,w01018-Max=7.1;" + +// "w01020-Min=7.1,w01020-Avg=7.5,w01020-Max=7.1;" + +// "w01019-Min=7.1,w01019-Avg=7.5,w01019-Max=7.1;" + +// "w01003-Min=7.1,w01003-Avg=7.5,w01003-Max=7.1" + +// "&&1234\r\n"; +// String a="##FL=0090;QN=201450800121333000;CN=1001;PW=123456;MN=10488888812345;CP=&&Status=1111&&7EC0\r\n"; +// String b="##FL=0072;QN=20200817165008655;CN=1003;PW=123456;MN=test2020081601;CP=&&ExeRtn=0&&3480\r\n"; + BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); + bufferedWriter.write(a); + bufferedWriter.flush(); + System.out.println(); + String msg=""; + while ((msg=bufferedReader.readLine())!=null){ + log.info("服务器回复->{}",msg); +// if (msg!=null){ +//// String substring = msg.substring(msg.indexOf("DealCode=")+9, msg.indexOf("DealCode=") + 29); +//// bufferedWriter.write(b); +//// bufferedWriter.flush(); +//// System.out.println("2->"+b); +// Thread.sleep(3000); +//// String sss = sss(substring); +//// System.out.println("substring"+substring); +//// System.out.println("3->"+sss); +//// bufferedWriter.write(sss); +//// bufferedWriter.flush(); +//// Thread.sleep(5000); +// bufferedWriter.write(a); +// bufferedWriter.flush(); +// +// } + + } + } + public static String sss(String args) { + SendMsg sendMsg=new SendMsg(); + sendMsg.setCN("1004"); + sendMsg.setPW("123456");//暂时写死 + sendMsg.setMN("12345678"); + List> CP=new ArrayList<>(); + Map methodparams=new HashMap<>(); + methodparams.put("WaterL","0000"); + methodparams.put("DealCode",args); + CP.add(methodparams); + sendMsg.setCP(CP); + //编码报文 + // String a="##FL=0090;QN=201450800121333000;CN=1001;PW=123456;MN=10488888812345;CP=&&Status=1111&&7EC0\r\n"; + + String s = AnalysisUtil.KvToMsg(sendMsg,";");//第二参数规定报文编码时cp段以什么分隔 + System.out.println(s); + return s; + } +} diff --git a/src/main/java/com/drht/datamanage/util/AnalysisUtil.java b/src/main/java/com/drht/datamanage/util/AnalysisUtil.java new file mode 100644 index 0000000..94d58b1 --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/AnalysisUtil.java @@ -0,0 +1,242 @@ +package com.drht.datamanage.util; + +import cn.hutool.core.map.MapUtil; +import com.alibaba.fastjson.annotation.JSONField; +import com.drht.datamanage.exception.AnalysisException; +import com.drht.datamanage.model.msg.SendMsg; +import com.google.common.collect.Lists; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; +import org.apache.commons.lang3.StringUtils; + +import java.util.*; + +public class AnalysisUtil { + private static final InternalLogger logger = InternalLoggerFactory.getInstance(AnalysisUtil.class); + + public static AnalysisUtil.Msg msgToJsonString(String msg) throws AnalysisException { + //报文对象 + Msg m=new Msg(); + //cp对象 + Map cpMap=new HashMap(); + //验证cp段合法性 + //判断截取开始位置 + int start=msg.indexOf("CP=&&"); + if (start==-1){ + //报文不包含CP=&& + throw new AnalysisException(1000,"解析报文出错,报文不包含CP=&&字符"); + } + if (!msg.endsWith("&&")){ + //报文cp段不是以&&结尾 + throw new AnalysisException(1001,"解析报文出错,报文cp段不是以&&结尾"); + } + //判断结束位置 + int end=msg.lastIndexOf("&&"); + if (end<(start+5)){ + //报文cp段不是以&&包围 + throw new AnalysisException(2701,"解析报文出错,报文cp段不是以&&包围"); + } + //截取CP + + String cp=msg.substring(start+5,end); + if ("".equals(cp)){ + //cp无值 + m.setCP(cpMap); + }else{ + //解析cp + Map map = msgToKV(cp); + m.setCP(map); + + } + //解析除cp段的其他值 + msg=msg.substring(0,start); + Map map = msgToKV(msg); + // + m.setCN(map.get("CN")); + m.setMN(map.get("MN")); + m.setPW(map.get("PW")); + m.setQN(map.get("QN")); + //添加flag + m.setFlag(map.get("Flag")); + //添加ST + m.setST(map.get("ST")); + + //以分号分隔 + return m; + } + public static String exeRtnSuccess(Msg msg) { + SendMsg sendMsg = new SendMsg(); + sendMsg.setCN(msg.getCN()); + sendMsg.setFlag("0"); + sendMsg.setPW(msg.getPW()); + sendMsg.setMN(msg.getMN()); + sendMsg.setCP(Lists.newArrayList(MapUtil.of("ExeRtn", "1"))); + return KvToMsg(sendMsg, ";"); + } + + public static Map msgToKV(String s) throws AnalysisException { + Map resultMap=new HashMap(); + //以;分隔截取成数组 + String[] cpArry = s.split(";"); + for (String ss:cpArry){ + //以逗号分隔 + String[] c = ss.split(","); + for (String s1:c){ + //此处已经是单值 xxx=xxx + String[] split = s1.split("="); + String key=""; + String value=""; + key=split[0]; + if (split.length==2){ + //不是key=value的格式 +// throw new AnalysisException(2701,"解析报文出错,报文cp段的值不是key=value形式"); + value=split[1]; + } + //特殊处理 ##1234QN=20180210154956000 + if(key.endsWith("QN")&&!"QN".equals(key.split("QN")[0])) + key="QN"; + resultMap.put(key,value); + } + } + return resultMap; + } + + public static String KvToMsg(SendMsg sendMsg, String t) { + //sendmsg的tostring方法被重写返回除去cp段的字符串 + String s = sendMsg.toString(); + List> cp = sendMsg.getCP(); + if (cp==null||cp.size()==0){ + s+="&&"; + }else{ + for (Map m:cp){ + String maptomsg = maptomsg(m,t); + s+=maptomsg; + } + s=s.substring(0,s.length()-1); + s+="&&"; + } + + //获取数据段长度 + int length = s.length()+14; + //前面补0共计4位 + + String format = String.format("%04d", length); + //获取crc校验 + s=format+s; + int checkCrc = HelperUtil.getCheckCrc(s.getBytes()); + String crc = String.format("%04x",checkCrc).toUpperCase(); + return "##"+s+crc+"\r\n"; + } + + public static String maptomsg(Map map,String t){ + String s=""; + Set set = map.keySet(); + for (Object k:set){ + String kk=(String)k; + if (kk=="mn"||"mn".equals(kk)){ + continue; + } + String v = (String) map.get(k); + + s+=kk+"="+v+t; + } + if (StringUtils.isNotEmpty(s)){ + return s.substring(0,s.length()-1)+";"; + } + //随便多拼一个字符,防止substring丢失一个字符 + return ";"; + + } + + public static void main(String[] args) { + SendMsg sendMsg=new SendMsg(); + sendMsg.setCN("1003"); + sendMsg.setPW("123456");//暂时写死 + sendMsg.setMN("10488888812345"); + List> CP=new ArrayList<>(); + Map methodparams=new HashMap<>(); + methodparams.put("mn","10488888812345"); + methodparams.put("aaa","2"); + CP.add(methodparams); + sendMsg.setCP(CP); + //编码报文 + String s = AnalysisUtil.KvToMsg(sendMsg,";");//第二参数规定报文编码时cp段以什么分隔 + System.out.println(s); + //String a="##FL=0090;QN=201450800121333000;CN=1001;PW=123456;MN=10488888812345;CP=&&Status=1111&&7EC0\r\n"; + +// String a="##FL=0078;QN=20200818155859920;CN=1003;PW=123456;MN=test2020081601;CP=&&ExeRtn=0&&9AC1"; +// System.out.println(a.length()); + } + public static class Msg{ + @JSONField(name = "QN") + private String QN; + @JSONField(name = "ST") + private String ST; + @JSONField(name = "PW") + private String PW; + @JSONField(name = "PW") + private String MN; + @JSONField(name = "Flag") + private String Flag; + @JSONField(name = "CN") + private String CN; + @JSONField(name = "CP") + private Map CP; + + public String getQN() { + return QN; + } + + public void setQN(String QN) { + this.QN = QN; + } + + public String getST() { + return ST; + } + + public void setST(String ST) { + this.ST = ST; + } + + public String getPW() { + return PW; + } + + public void setPW(String PW) { + this.PW = PW; + } + + public String getMN() { + return MN; + } + + public void setMN(String MN) { + this.MN = MN; + } + + public String getFlag() { + return Flag; + } + + public void setFlag(String flag) { + Flag = flag; + } + + public String getCN() { + return CN; + } + + public void setCN(String CN) { + this.CN = CN; + } + + public Map getCP() { + return CP; + } + + public void setCP(Map CP) { + this.CP = CP; + } + } +} diff --git a/src/main/java/com/drht/datamanage/util/CommonUtil.java b/src/main/java/com/drht/datamanage/util/CommonUtil.java new file mode 100644 index 0000000..28f833a --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/CommonUtil.java @@ -0,0 +1,34 @@ +package com.drht.datamanage.util; + +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.StrUtil; +import com.google.common.collect.Lists; +import lombok.extern.slf4j.Slf4j; +//import org.apache.logging.log4j.util.Strings; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 公用工具类 + * + * @author chai + */ +@Slf4j +public class CommonUtil { + + private CommonUtil() { + } + /** + * db + * */ + public volatile static Map deviceTypeChe = new ConcurrentHashMap(); + +} diff --git a/src/main/java/com/drht/datamanage/util/DateUtils.java b/src/main/java/com/drht/datamanage/util/DateUtils.java new file mode 100644 index 0000000..22524cd --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/DateUtils.java @@ -0,0 +1,683 @@ +package com.drht.datamanage.util; + +import cn.hutool.core.date.DateException; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ReUtil; +import cn.hutool.core.util.StrUtil; + +import com.drht.datamanage.exception.CommonException; +import com.drht.datamanage.exception.ResultCode; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateFormatUtils; + +import java.io.IOException; +import java.math.BigDecimal; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; + +/** + * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类 + */ +@Slf4j +public class DateUtils extends org.apache.commons.lang3.time.DateUtils { + //7天换算秒 + public static final BigDecimal SECOND = new BigDecimal(60*60*24*7); + //30天换算分钟 + public static final BigDecimal MINUTE = new BigDecimal(60*24*30); + //一年换算小时 + public static final BigDecimal HOUR = new BigDecimal(24*30*12); + + /** + * 日期yyyy-MM-dd 格式匹配 + */ + private static final String DATE_PATTERN = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))$"; + + private static String[] parsePatterns = { + "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy", "yyyy-MM-dd HH", + "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", + "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyy-MM-dd'T'HH:mm:ss.SSS Z", "yyyy-MM-dd'T'HH:mm:ss", + "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSS+Z","yyyy-MM-dd'T'HH:mm:ss.S'Z'", "yyyy-MM-dd'T'HH:mm:ss'Z'" + }; + + /** + * 得到当前日期字符串 格式(yyyy-MM-dd) + */ + public static String getDate() { + return getDate("yyyy-MM-dd"); + } + + /** + * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" + */ + public static String getDate(String pattern) { + return DateFormatUtils.format(new Date(), pattern); + } + + /** + * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" + */ + public static String formatDate(Date date, Object... pattern) { + String formatDate = null; + if (pattern != null && pattern.length > 0) { + formatDate = DateFormatUtils.format(date, pattern[0].toString()); + } else { + formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); + } + return formatDate; + } + + /** + * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss) + */ + public static String formatDateTime(Date date) { + return formatDate(date, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 得到当前时间字符串 格式(HH:mm:ss) + */ + public static String getTime() { + return formatDate(new Date(), "HH:mm:ss"); + } + + /** + * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss) + */ + public static String getDateTime() { + return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 得到当前年份字符串 格式(yyyy) + */ + public static String getYear() { + return formatDate(new Date(), "yyyy"); + } + + /** + * 得到当前月份字符串 格式(MM) + */ + public static String getMonth() { + return formatDate(new Date(), "MM"); + } + + /** + * 得到当天字符串 格式(dd) + */ + public static String getDay() { + return formatDate(new Date(), "dd"); + } + + /** + * 得到当前星期字符串 格式(E)星期几 + */ + public static String getWeek() { + return formatDate(new Date(), "E"); + } + + /** + * 日期型字符串转化为日期 格式 + * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", + * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", + * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" } + */ + public static Date parseDate(Object str) { + if (str == null) { + return null; + } + try { + return parseDate(str.toString(), parsePatterns); + } catch (ParseException e) { + return null; + } + } + + public static Date strToDate(String strDate, String pattern) { + SimpleDateFormat formatter = new SimpleDateFormat(pattern); + ParsePosition pos = new ParsePosition(0); + Date strtodate = formatter.parse(strDate, pos); + return strtodate; + } + + /** + * 获取过去的天数 + * + * @param date + * @return + */ + public static long pastDays(Date date) { + long t = System.currentTimeMillis() - date.getTime(); + return t / (24 * 60 * 60 * 1000); + } + + /** + * 获取过去的小时 + * + * @param date + * @return + */ + public static long pastHour(Date date) { + long t = System.currentTimeMillis() - date.getTime(); + return t / (60 * 60 * 1000); + } + + /** + * 获取过去的分钟 + * + * @param date + * @return + */ + public static long pastMinutes(Date date) { + long t = System.currentTimeMillis() - date.getTime(); + return t / (60 * 1000); + } + + /** + * 转换为时间(天,时:分:秒.毫秒) + * + * @param timeMillis + * @return + */ + public static String formatDateTime(long timeMillis) { + long day = timeMillis / (24 * 60 * 60 * 1000); + long hour = (timeMillis / (60 * 60 * 1000) - day * 24); + long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60); + long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); + long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000); + return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss; + } + + /** + * 获取两个日期之间的天数 + * + * @param before + * @param after + * @return + */ + public static double getDistanceOfTwoDate(Date before, Date after) { + long beforeTime = before.getTime(); + long afterTime = after.getTime(); + return (double) (afterTime - beforeTime) / (1000 * 60 * 60 * 24); + } + + /** + * String类型时区格式字符串转Date + */ + public static Date StringToDate(String timeStr) { + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //yyyy-MM-dd'T'HH:mm:ss.SSSZ + Date date = null; + try { + date = df.parse(timeStr); + + } catch (ParseException e) { + e.printStackTrace(); + } + return date; + } + + /** + * 获取网络时间 + * + * @return + */ + public static String getWebsiteDatetime(String pattern) { + String webUrl = "http://www.baidu.com";//百度 + //String webUrl = "http://www.taobao.com";//淘宝 + //String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心 + //String webUrl = "http://www.360.cn";//360 + //String webUrl = "http://www.beijing-time.org";//beijing-time + try { + URL url = new URL(webUrl);// 取得资源对象 + URLConnection uc = url.openConnection();// 生成连接对象 + uc.connect();// 发出连接 + long ld = uc.getDate();// 读取网站日期时间 + Date date = new Date(ld);// 转换为标准时间对象 + SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.CHINA);// 输出北京时间 + return sdf.format(date); + } catch (MalformedURLException e) { + log.error("读取网络时间错误", e); + } catch (IOException e) { + log.error("传输数据错误", e); + } + return null; + } + + /** + * 获取过去一天的时间 + * + * @return + */ + public static String getLostDayLater() { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance();//日历对象 + calendar.setTime(new Date());//设置当前日期 + calendar.add(Calendar.DAY_OF_MONTH, -1);//天数-1 + return format.format(calendar.getTime()); + } + + /** + * 根据类别获取开始日期 + * + * @param type + * @return + */ + public static String getStartDateByType(String type) { + SimpleDateFormat format = null; + Calendar calendar = Calendar.getInstance(); //日历对象 + String startDate = ""; + switch (type) { + case "0": + //;日统计 本月初 + format = new SimpleDateFormat("yyyy-MM-dd"); + + calendar.add(Calendar.MONTH, 0); + calendar.set(Calendar.DAY_OF_MONTH, 1); + startDate = format.format(calendar.getTime()); + break; + case "1": + //月统计 本年 + int year = calendar.get(Calendar.YEAR); + startDate = year + "-01"; + break; + default: + } + return startDate; + } + + /** + * 根据类别获取结束日期 + * + * @param type + * @return + */ + public static String getEndDateByType(String type) { + SimpleDateFormat format = null; + Calendar calendar = Calendar.getInstance();//日历对象 + String endDate = ""; + switch (type) { + case "0": + //;日统计 本月末 + format = new SimpleDateFormat("yyyy-MM-dd"); + calendar.add(Calendar.MONTH, 1); + calendar.set(Calendar.DAY_OF_MONTH, 0); + endDate = format.format(calendar.getTime()); + break; + case "1": + //月统计 本年 + int year = calendar.get(Calendar.YEAR); + endDate = year + "-12"; + break; + default: + } + return endDate; + } + + /** + * @description: 根据日期改为今天昨天 + * @author chaixueteng + * @date 2019-09-12 15:12 + */ + public static String JudgmentDay(Date date) { + Calendar pre = Calendar.getInstance(); + Date predate = new Date(System.currentTimeMillis()); + pre.setTime(predate); + + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + + if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) { + int diffDay = cal.get(Calendar.DAY_OF_YEAR) + - pre.get(Calendar.DAY_OF_YEAR); + switch (diffDay) { + case -1: { + return "昨天 " + formatDate(date, "HH:mm"); + } + case 0: { + return "今天 " + formatDate(date, "HH:mm"); + } + default: + } + } + return formatDate(date, "yyyy-MM-dd HH:mm"); + } + + public static String getStringDateFormatter(Date date, String format) { + SimpleDateFormat formatter = new SimpleDateFormat(format); + String dateString = formatter.format(date); + return dateString; + } + + /** + * 时间格式转换 + */ + public static String getStringDateFormatter(String date, String oldFormat, String newFormat) { + if (StrUtil.isBlank(date)){ + return date; + } + SimpleDateFormat oldformatter = new SimpleDateFormat(oldFormat); + SimpleDateFormat newformatter = new SimpleDateFormat(newFormat); + Date parse = null; + try { + parse = oldformatter.parse(date); + } catch (ParseException e) { + log.error("时间转换错误", e); + } + return newformatter.format(parse); + } + + /** + * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" + */ + public static long getTimeMillis() { + return System.currentTimeMillis() / 1000; + } + + public static long strToTimeMillis(String strDate, String pattern) { + SimpleDateFormat formatter = new SimpleDateFormat(pattern); + ParsePosition pos = new ParsePosition(0); + Date strtodate = formatter.parse(strDate, pos); + return strtodate.getTime() / 1000; + } + + /** + * unix 时间戳转日期字符串 秒 + */ + public static String TimeStampDate(Long timestamp, String formats) { + if (StringUtils.isEmpty(formats)) { + formats = "yyyy-MM-dd HH:mm:ss"; + } + if (null == timestamp){ + return ""; + } + String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp * 1000)); + return date; + } + + /** + * unix 时间戳转日期字符串 毫秒 + */ + public static String timeMsStampDate(long timestamp, String formats) { + if (StringUtils.isEmpty(formats)) { + formats = "yyyy-MM-dd HH:mm:ss"; + } + String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp)); + return date; + } + + /** + * unix 时间戳转日期字符串 + */ + public static Long stringToUnix(String date) { + if (StringUtils.isBlank(date)) { + return null; + } + Date date1 = parseDate(date); + if (null == date1){ + return null; + } + return date1.getTime() / 1000; + } + + /** + * 转换influxdb 时间 + */ + public static String paseInfluxdbTime(String timeStr, String formats) { + if (StringUtils.isEmpty(formats)) { + formats = "yyyy-MM-dd HH:mm:ss"; + } + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //yyyy-MM-dd'T'HH:mm:ss.SSSZ + Date date = null; + try { + date = df.parse(timeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + SimpleDateFormat Time3 = new SimpleDateFormat(formats); + return Time3.format(date); + } + + public static Map getDatePoor(Date endDate, Date nowDate) { + long nd = 1000 * 24 * 60 * 60; + long nh = 1000 * 60 * 60; + long nm = 1000 * 60; + long ns = 1000; + // 获得两个时间的毫秒时间差异 + BigDecimal time = new BigDecimal(endDate.getTime()).subtract(new BigDecimal(nowDate.getTime())); + //换算成秒 + BigDecimal sec = time.divide(new BigDecimal(ns)); + //换算成分钟 + BigDecimal min = time.divide(new BigDecimal(nm)); + //换算成小时 + BigDecimal hour = time.divide(new BigDecimal(nh)); + //换算成天 + BigDecimal day = time.divide(new BigDecimal(nd)); + Map map = new HashMap<>(); + map.put("sec",sec); + map.put("min",min); + map.put("hour",hour); + map.put("day",day); + return map; + } + + /** + * @param timeStr + * @return java.lang.String + * @Description 转换influxdb 查询时间减八小时 + * @Date 2020/3/20 19:11 + **/ + public static String paseInfluxdbDate(String timeStr) { + if (StringUtils.isBlank(timeStr)) { + return timeStr; + } + Date date = parseDate(timeStr); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.HOUR_OF_DAY, -8); + Date calTime = cal.getTime(); + return formatDate(calTime, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 获取时间小时值 + */ + public static int getHour(String timeStr) { + Date influxdbDate = null; + try { + influxdbDate = parseDate(timeStr, "yyyy-MM-dd HH:mm:ss"); + } catch (ParseException e) { + log.error("转换时间错误:{} - {}", timeStr, e.toString()); + } + Calendar cal = Calendar.getInstance(); + cal.setTime(influxdbDate); + return cal.get(Calendar.HOUR_OF_DAY); + } + + /** + * 获取时间小时值 + */ + public static int getInfluxdbHour(String timeStr) { + Calendar influxdbDate = getInfluxdbDate(timeStr); + return influxdbDate.get(Calendar.HOUR_OF_DAY); + } + + /** + * 获取时间天 + */ + public static int getInfluxdbDay(String timeStr) { + Calendar influxdbDate = getInfluxdbDate(timeStr); + return influxdbDate.get(Calendar.DATE) + 1; + } + + /** + * 获取时间月 + */ + public static int getInfluxdbMonth(String timeStr) { + Calendar influxdbDate = getInfluxdbDate(timeStr); + return influxdbDate.get(Calendar.MONTH); + } + + /** + * 获取时间月 + */ + public static long getInfluxdbUnix(String timeStr) { + Calendar influxdbDate = getInfluxdbDate(timeStr); + return influxdbDate.getTime().getTime() / 1000; + } + + /** + * 获取时间 + */ + public static Calendar getInfluxdbDate(String timeStr) { + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //yyyy-MM-dd'T'HH:mm:ss.SSSZ + Date date = null; + try { + date = df.parse(timeStr); + } catch (ParseException e) { + log.error("转换influxdb时间错误:{} - {}", timeStr, e.toString()); + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal; + } + + public static String getStartDateByQueryType(Integer queryType, String queryDate) { + Date date = strToDate(queryDate, "yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + //日设置起止时间 + cal.set(Calendar.HOUR_OF_DAY, 00); + cal.set(Calendar.MINUTE, 00); + cal.set(Calendar.SECOND, 00); + //月设置起止时间 2020-04-01 + if (queryType != null && queryType.intValue() == 1) { + cal.set(Calendar.DAY_OF_MONTH, 1); + } + //年设置起止时间 + if (queryType != null && queryType.intValue() == 2) { + cal.set(Calendar.MONTH, 0);//从0开始,0表是1月,1表示知2月依次类推道 + cal.set(Calendar.DAY_OF_MONTH, 1); + } + return formatDate(cal.getTime(), "yyyy-MM-dd HH:mm:ss"); + } + + public static String getEndDateByQueryType(Integer queryType, String queryDate) { + Date date = strToDate(queryDate, "yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + //日设置起止时间 + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + //月设置起止时间 2020-04-01 + if (queryType != null && queryType.intValue() == 1) { + cal.set(Calendar.DAY_OF_MONTH, 1); + cal.add(Calendar.MONTH, 1);/*将本月+1,变成2017年7月1日10:31:28*/ + cal.add(Calendar.DAY_OF_MONTH, -1); + + } + //年设置起止时间 + if (queryType != null && queryType.intValue() == 2) { + cal.set(Calendar.MONTH, 11);//从0开始,0表是1月,1表示知2月依次类推道 + cal.set(Calendar.DAY_OF_MONTH, 31); + } + return formatDate(cal.getTime(), "yyyy-MM-dd HH:mm:ss"); + } + + public static String setDateHour(Integer hour, String strDate) { + Date date = strToDate(strDate, "yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + //日设置起止时间 + cal.set(Calendar.HOUR_OF_DAY, hour); + cal.set(Calendar.MINUTE, 00); + cal.set(Calendar.SECOND, 00); + return formatDate(cal.getTime(), "yyyy-MM-dd'T'HH:mm:ss"); + } + + /** + * @param + * @return java.lang.String + * @Description 获取昨天日期 + * @Date 2020/4/26 16:11 + **/ + public static String yesterday() { + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.HOUR_OF_DAY, -24); + String yesterdayDate = dateFormat.format(calendar.getTime()); + return yesterdayDate; + } + + /** + * 获取过去第几天的日期 + * + * @param past + * @return + */ + public static Date getPastDate(int past) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past); + calendar.set(Calendar.HOUR_OF_DAY, 00); + calendar.set(Calendar.MINUTE, 00); + calendar.set(Calendar.SECOND, 00); + Date today = calendar.getTime(); + return today; + } + + /** + * 根据时间字符串返回系统处理后的字符串 容错机制,带时分秒未转换成功则只转换日期 + * + * @param startTime 时间,带时分秒则不做处理 不带的则默认为 00:00:00 + * @param begin true 则获取开始时间 false则获取结束时间 + * @return + */ + public static String strOfDay(String startTime,boolean begin) { + if(StrUtil.isBlank(startTime)){ + return ""; + } + boolean flag = false; + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); + DateUtil.parse(startTime, formatter); + } catch (DateTimeParseException e) { + flag = true; + } + if (flag) { + //判断日期是否符合yyyy-MM-dd + boolean match = ReUtil.isMatch(DATE_PATTERN, startTime); + if (!match) { + throw new CommonException(ResultCode.FAIL, "时间格式不正确!"); + } + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()); + LocalDate localDate = LocalDate.parse(startTime,formatter); + Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); + Date date = Date.from(instant); + Date ofDay; + if(begin){ + ofDay = DateUtil.beginOfDay(date); + }else{ + ofDay = DateUtil.endOfDay(date); + } + startTime = DateUtil.format(ofDay, "yyyy-MM-dd HH:mm:ss"); + } catch (DateTimeParseException e) { + throw new CommonException(ResultCode.FAIL, "时间格式不正确!"); + } catch (DateException e){ + throw new CommonException(ResultCode.FAIL, "时间格式不正确!"); + } + } + return startTime; + } +} diff --git a/src/main/java/com/drht/datamanage/util/HelperUtil.java b/src/main/java/com/drht/datamanage/util/HelperUtil.java new file mode 100644 index 0000000..d977a68 --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/HelperUtil.java @@ -0,0 +1,90 @@ +package com.drht.datamanage.util; + +import java.util.UUID; + +/** + * 帮助操作类 + */ +public class HelperUtil { + /** + * @param bytes 字节数组 + * @return 获取crc校验结果 + */ + public static int getCheckCrc(byte[] bytes){ + int CRC = 0xFFFF; + int num = 0xA001; + int inum = 0; + for(int j = 0; j < bytes.length; j ++) { + inum = bytes[j]; + CRC = (CRC >> 8) & 0x00FF; + CRC ^= inum; + for(int k = 0; k < 8; k++) { + int flag = CRC % 2; + CRC = CRC >> 1; + + if(flag == 1) { + CRC = CRC ^ num; + } + } + } + return CRC; + } + + /** + * 字节数组转16进制 + * @param bytes 需要转换的byte数组 + * @return 转换后的Hex字符串 + */ + public static String bytesToHex(byte[] bytes) { + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(bytes[i] & 0xFF); + if(hex.length() < 2){ + sb.append(0); + } + sb.append(hex); + } + return sb.toString(); + } + + + /** + * 从一个byte[]数组中截取一部分 + * @param src + * @param begin + * @param count + * @return + */ + public static byte[] subBytes(byte[] src, int begin, int count) { + byte[] bs = new byte[count]; + for (int i=begin;i executeLinuxCmd(String cmd) { + Runtime run = Runtime.getRuntime(); + try { + Process process = run.exec(new String[]{"/bin/sh", "-c", cmd}); + InputStream in = process.getInputStream(); + BufferedReader bs = new BufferedReader(new InputStreamReader(in)); + List list = new ArrayList(); + String result = null; + while ((result = bs.readLine()) != null) { + //logger.debug(".................执行命令:"+result); + list.add(result); + } + in.close(); + // process.waitFor(); + process.destroy(); + return list; + } catch (IOException e) { + logger.error("执行命令出错", e); + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/com/drht/datamanage/util/QnUtil.java b/src/main/java/com/drht/datamanage/util/QnUtil.java new file mode 100644 index 0000000..b08617a --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/QnUtil.java @@ -0,0 +1,12 @@ +package com.drht.datamanage.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class QnUtil { + public static SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS" ); + + public static String getQN( Date date) { + return sdf.format(date); + } +} diff --git a/src/main/java/com/drht/datamanage/util/SpringContextUtil.java b/src/main/java/com/drht/datamanage/util/SpringContextUtil.java new file mode 100644 index 0000000..f69ba02 --- /dev/null +++ b/src/main/java/com/drht/datamanage/util/SpringContextUtil.java @@ -0,0 +1,31 @@ +package com.drht.datamanage.util; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * 上下文Context 工具类 + */ +@Component +@Order(0) +public class SpringContextUtil implements ApplicationContextAware { + public static ApplicationContext context = null; + /* (non Javadoc) + * @Title: setApplicationContext + * @Description: spring获取bean工具类 + * @param applicationContext + * @throws BeansException + * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + this.context = applicationContext; + } + /// 获取当前环境 + public static String getActiveProfile() { + return context.getEnvironment().getActiveProfiles()[0]; + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..554e7b1 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,13 @@ +spring.application.name=devicecenter +server.port=8019 +#server.servlet.context-path=/dataManage-1.0-SNAPSHOT + +#============== mybatis =================== +mybatis-plus.mapper-locations=classpath:mapping/*.xml +mybatis-plus.type-aliases-package= com.drht.datamanage.model +mybatis-plus.configuration.log-impl= org.apache.ibatis.logging.stdout.StdOutImpl +#============== mybatis end=================== +spring.datasource.url=jdbc:mysql://120.46.194.248:13306/full_spectrum_broker?characterEncoding=utf-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai&allowMultiQueries=true +spring.datasource.username=quanguangpu_user +spring.datasource.password=x$u##5DKa%qD +spring.datasource.driverClassName=com.mysql.jdbc.Driver diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..f28577b --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,54 @@ + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + ${LOG_HOME}/manage.log-%d{yyyy-MM-dd}.%i.log + + 30 + 2GB + + 50MB + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapping/HourlyDataMapper.xml b/src/main/resources/mapping/HourlyDataMapper.xml new file mode 100644 index 0000000..3d4a22b --- /dev/null +++ b/src/main/resources/mapping/HourlyDataMapper.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/src/main/resources/mapping/MinuteDataMapper.xml b/src/main/resources/mapping/MinuteDataMapper.xml new file mode 100644 index 0000000..9702139 --- /dev/null +++ b/src/main/resources/mapping/MinuteDataMapper.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/src/main/resources/mapping/RealTimeDataMapper.xml b/src/main/resources/mapping/RealTimeDataMapper.xml new file mode 100644 index 0000000..6f38ed0 --- /dev/null +++ b/src/main/resources/mapping/RealTimeDataMapper.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file