Compare commits

...

4 Commits

Author SHA1 Message Date
tiger_zhou
3a79ff3942 用户权限调整,及用户token刷新,日志记录
Some checks failed
local-test分支构建docker并发布运行 / Docker-Build (push) Failing after 1m15s
2024-10-18 10:59:37 +08:00
tiger_zhou
615b83a681 用户权限调整,及用户token刷新,日志记录 2024-10-18 10:46:39 +08:00
tiger_zhou
11ae9ea755 结构调整 2024-10-12 17:41:56 +08:00
tiger_zhou
dfdc33b313 操作日志收集 2024-09-29 18:20:10 +08:00
91 changed files with 1093 additions and 312 deletions

View File

@ -44,7 +44,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>

View File

@ -5,6 +5,7 @@ import java.util.Optional;
public class AlertUtil {
public static Optional<AlertLocation> findLocationByRtuCode(String rtuCode) {
switch (rtuCode) {
case "1" -> {

View File

@ -0,0 +1,106 @@
package club.joylink.xiannccda.aop;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.constants.SystemContext;
import club.joylink.xiannccda.event.OperateEvent;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriTemplate;
@Aspect
@Slf4j
@Component
public class SystemEventAspect {
@Autowired
private JwtDecoder jwtDecoder;
@AfterReturning(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", returning = "returnObj")
public void watchRequest(JoinPoint joinPoint, Object returnObj) {
OperateEvent obj = this.parseRequestParameter(joinPoint);
if (Objects.nonNull(obj)) {
obj.setRequestSuccess(1);
if (obj.getType() == CommonLogTypeEnum.LOGIN && obj.getSubType() == SubEventType.LOGIN) {
Jwt jwt = jwtDecoder.decode(returnObj.toString());
String userId = jwt.getClaimAsString("sub");
obj.setUserId(Long.parseLong(userId));
SystemContext.publishEvent(obj);
}
}
}
@AfterThrowing(value = "execution(public * club.joylink.xiannccda.controller..*.*(..))", throwing = "e")
public void watchRequest(JoinPoint joinPoint, Exception e) {
OperateEvent oe = this.parseRequestParameter(joinPoint);
if (Objects.nonNull(oe)) {
oe.setRequestSuccess(0);
SystemContext.publishEvent(oe);
}
}
private OperateEvent parseRequestParameter(JoinPoint joinPoint) {
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
CommonLogAnno commonLogAnno = ms.getMethod().getDeclaredAnnotation(CommonLogAnno.class);
if (Objects.nonNull(commonLogAnno)) {
GetMapping getMapping = ms.getMethod().getDeclaredAnnotation(GetMapping.class);
PostMapping postMapping = ms.getMethod().getDeclaredAnnotation(PostMapping.class);
Map<String, Object> params = null;
if (Objects.nonNull(getMapping)) {
params = getRequestParam(getMapping.value(), joinPoint.getArgs());
} else if (Objects.nonNull(postMapping)) {
params = getRequestParam(postMapping.value(), joinPoint.getArgs());
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long userId = null;
if (commonLogAnno.logType() != CommonLogTypeEnum.LOGIN) {
userId = Long.valueOf(authentication.getName());
}
return new OperateEvent(commonLogAnno.name(), commonLogAnno.logType(), commonLogAnno.subLogType(), uri, method, params, userId);
}
return null;
}
private Map<String, Object> getRequestParam(String[] mappingUri, Object[] args) {
Map<String, Object> params = new HashMap<>();
int argsIndex = 0;
if (ArrayUtils.isNotEmpty(mappingUri)) {
Map<String, Object> uriParamMap = new HashMap<>();
UriTemplate ut = new UriTemplate(mappingUri[0]);
for (String vn : ut.getVariableNames()) {
uriParamMap.put(vn, args[argsIndex]);
argsIndex++;
}
params.put("uriParam", uriParamMap);
}
for (; argsIndex < args.length; argsIndex++) {
params.put("param", args[argsIndex]);
}
return params;
}
}

View File

@ -1,6 +1,7 @@
package club.joylink.xiannccda.ats.cache;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.collect.DeviceDataRepository;
import club.joylink.xiannccda.ats.message.collect.DeviceDataRepository.DataTypeEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
@ -195,7 +196,7 @@ public class LineGraphicDataRepository {
statusChange.setType(dt);
statusChange.setDeviceStatus(0);
statusChange.setRtuId(rtuId);
return statusChange.generateProto();
return statusChange.generateProto(DeviceNameChangerManage.findNameChanger(lineId));
}
public static Integer getStationCenterById(Integer lineId, String deviceId) {

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
import com.alibaba.fastjson2.annotation.JSONField;
import com.google.common.collect.Lists;
@ -92,7 +93,7 @@ public abstract class MessageData {
*/
public abstract void decode2(ByteBuf buf) throws Exception;
public abstract List<GeneratedMessageV3.Builder> generateProto();
public abstract List<GeneratedMessageV3.Builder> generateProto(NameChangerEnum nameChanger);
public void encode(ByteBuf buf) {

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import com.google.protobuf.GeneratedMessageV3.Builder;
import io.netty.buffer.ByteBuf;
import java.util.List;
@ -18,7 +19,7 @@ public abstract class MessageRequest extends MessageData {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
return null;
}
}

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import com.google.protobuf.GeneratedMessageV3.Builder;
import io.netty.buffer.ByteBuf;
import java.util.Collections;
@ -13,8 +14,9 @@ public abstract class MessageResponse extends MessageData {
public abstract Short getLineId();
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
return Collections.emptyList();
}

View File

@ -40,7 +40,7 @@ public class OccMessageHandler extends SimpleChannelInboundHandler<List<MessageD
DeviceStatusConvertorManager.addStatusConvertor(new TrainInitConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new TrainRecordConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new TrainRemoveConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new TrainRecordConvertor());
// DeviceStatusConvertorManager.addStatusConvertor(new TrainRecordConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new TrainUpdateConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new PlanScheduleConvertor());
DeviceStatusConvertorManager.addStatusConvertor(new InterLockDeviceBitMapConvertor());
@ -67,7 +67,7 @@ public class OccMessageHandler extends SimpleChannelInboundHandler<List<MessageD
if (this.collectorData) {
MockAppContext.publish(msg);
}
DeviceStatusConvertorManager.doConvertor(msg);
DeviceStatusConvertorManager.doConvertor(this.connection.getNameChanger(), msg);
}
}

View File

@ -1,43 +1,31 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import com.google.common.collect.Maps;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import oshi.SystemInfo;
import oshi.software.os.OSProcess;
/**
* OCC客户端管理
*/
@Component
@Slf4j
@Component
@Setter
@ConfigurationProperties(prefix = "occ-client")
public class OccMessageManage implements ApplicationRunner {
@Value("${occ.host}")
private String serverHost;
@Value("${occ.realPort}")
private Integer realPort;
@Value("${occ.unRealPort}")
private Integer unRealPort;
@Value("${occ.lineId}")
private Integer lineId;
@Value("${occ.collectorData:false}")
private Boolean collectorData;
@Value("${receive-msg-timeout:6}")
private Integer receiveMsgTimeout;
@Value("${monitor-handware-change:false}")
private boolean monitorHandwareChange;
private Map<Integer, OccClientMessage> clientInfoMap;
Map<Integer, XianOccMessagingClient> clientMap = new HashMap<>();
public void sendMsg(Integer lineId, MessageData md, boolean isRealTime) {
@ -48,6 +36,20 @@ public class OccMessageManage implements ApplicationRunner {
client.send(md, isRealTime);
}
public boolean notMatchHandle(Integer lineId, Integer rtuId) {
OccClientMessage clientMessage = this.clientInfoMap.get(lineId);
if (Objects.isNull(clientMessage)) {
return true;
}
if (CollectionUtils.isEmpty(clientMessage.filterRtuIds)) {
return true;
}
if (clientMessage.filterRtuIds.contains(rtuId)) {
return false;
}
return true;
}
public void registerClient(XianOccMessagingClient client) {
clientMap.put(client.lineId, client);
@ -61,13 +63,36 @@ public class OccMessageManage implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("初始化 occ tcp连接.... 是否监控cpu内存信息:{}", this.monitorHandwareChange);
DeviceNameChangerManage.init();
// 读取数据配置创建客户端
this.registerClient(new XianOccMessagingClient(this.lineId, this.realPort, this.unRealPort, this.serverHost, this.collectorData, receiveMsgTimeout));
for (XianOccMessagingClient client : this.clientMap.values()) {
client.connect(this.monitorHandwareChange);
}
this.clientInfoMap.forEach((k, v) -> {
log.info("初始化 occ tcp连接.... 是否监控cpulineId:{} 内存信息:{}", k, v.monitorHandwareChange);
DeviceNameChangerManage.initLineIdNameCHanger(k, v.getNameChanger());
XianOccMessagingClient client = new XianOccMessagingClient(k, v);
this.registerClient(client);
client.connect(v.monitorHandwareChange);
});
}
@Data
public static class OccClientMessage {
private String serverHost;
private Integer realPort;
private Integer unRealPort;
private Boolean collectorData;
private Integer receiveMsgTimeout;
private boolean monitorHandwareChange;
private List<Integer> filterRtuIds;
private NameChangerEnum nameChanger;
}
}

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.constants.SystemContext;
import club.joylink.xiannccda.ws.msg.SystemWarnEvent;
import club.joylink.xiannccda.ws.msg.SystemWarnEvent.SystemWarnConnStateEvent;
@ -54,13 +55,16 @@ public class OccTcpClientConnection {
@Getter
final boolean isRealPort;
@Getter
final NameChangerEnum nameChanger;
public void write(MessageData messageData) {
if (Objects.nonNull(this.channel)) {
this.channel.writeAndFlush(List.of(messageData));
}
}
public OccTcpClientConnection(XianOccMessagingClient client, String host, int port, boolean collectorData, boolean isRealPort) {
public OccTcpClientConnection(XianOccMessagingClient client, String host, int port, boolean collectorData, boolean isRealPort, NameChangerEnum nameChanger) {
this.client = client;
this.host = host;
@ -68,6 +72,7 @@ public class OccTcpClientConnection {
this.group = new NioEventLoopGroup(1);
this.bootstrap = new Bootstrap();
this.isRealPort = isRealPort;
this.nameChanger = nameChanger;
OccTcpClientConnection self = this;
bootstrap.group(group)
.channel(NioSocketChannel.class)
@ -117,7 +122,6 @@ public class OccTcpClientConnection {
this.connected = false;
this.channel = null;
this.client.resetRequestBaseDataFlag();
}
SystemContext.publishEvent(new SystemWarnConnStateEvent(this.client.getLineId(), this));
this.reconnectState.resetState();

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message;
import club.joylink.xiannccda.ats.message.OccMessageManage.OccClientMessage;
import club.joylink.xiannccda.ats.message.line3.req.LoadHistoryTGDataRequest;
import club.joylink.xiannccda.ats.message.line3.req.LoadHistoryTGDataRequest.ApplyTypeEnum;
import java.time.LocalDateTime;
@ -21,8 +22,6 @@ import oshi.hardware.GlobalMemory;
@Slf4j
public class XianOccMessagingClient {
// final int realTimePortBase = 2600;
// final int nonRealTimePortBase = 2700;
/**
* 线路号 实时信息的侦听端口号为2600+line_id非实时信息的侦听端口号为2700+line_id (如对于地铁1号线来说实时信息的侦听端口号为2601非实时信息的侦听端口号为2701)
*/
@ -58,7 +57,7 @@ public class XianOccMessagingClient {
}
public XianOccMessagingClient(int lineId, Integer realPort, Integer unRealPort, String host, boolean collectorData, Integer receiveMsgTimeout) {
/* public XianOccMessagingClient(int lineId, Integer realPort, Integer unRealPort, String host, boolean collectorData, Integer receiveMsgTimeout) {
this.host = host;
this.lineId = lineId;
this.requestBaseTime = TimeUnit.HOURS.toMillis(receiveMsgTimeout);
@ -67,6 +66,17 @@ public class XianOccMessagingClient {
this.nrtConnection = new OccTcpClientConnection(this, host, unRealPort, false, false);
this.timeOutHandler.addConnection(this.rtConnection);
this.timeOutHandler.addConnection(this.nrtConnection);
}*/
public XianOccMessagingClient(Integer lineId, OccClientMessage clientMessage) {
this.host = clientMessage.getServerHost();
this.lineId = lineId;
this.requestBaseTime = TimeUnit.HOURS.toMillis(clientMessage.getReceiveMsgTimeout());
// 创建实时和非实时消息连接
this.rtConnection = new OccTcpClientConnection(this, host, clientMessage.getRealPort(), clientMessage.getCollectorData(), true, clientMessage.getNameChanger());
this.nrtConnection = new OccTcpClientConnection(this, host, clientMessage.getUnRealPort(), false, false, clientMessage.getNameChanger());
this.timeOutHandler.addConnection(this.rtConnection);
this.timeOutHandler.addConnection(this.nrtConnection);
}
@ -164,20 +174,6 @@ public class XianOccMessagingClient {
}
return null;
/* GlobalMemory memory = systemInfo.getHardware().getMemory();
long totalMemory = memory.getTotal();
long availableMemory = memory.getAvailable();
long usedMemory = totalMemory - availableMemory;
if (Objects.isNull(this.osProcess)) {
return String.format("内存总内存:%s(MB) 使用:%s(MB) 可用:%s(MB)", (totalMemory / 1024 / 1024), (usedMemory / 1024 / 1024),
(availableMemory / 1024 / 1024));
} else {
OSProcess osp = this.systemInfo.getOperatingSystem().getProcess(this.processId);
double d2 = this.osProcess.getProcessCpuLoadBetweenTicks(osp);
return String.format("当前CPU使用:%d%% 内存总内存:%s(MB) 使用:%s(MB) 可用:%s(MB)", Math.round(d2 * 100), (totalMemory / 1024 / 1024), (usedMemory / 1024 / 1024),
(availableMemory / 1024 / 1024));
}*/
}
public void start() {

View File

@ -1,8 +1,9 @@
package club.joylink.xiannccda.ats.message.line3.changer;
package club.joylink.xiannccda.ats.message.changer;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import java.util.ArrayList;
import java.util.Collections;
@ -24,10 +25,11 @@ import org.springframework.util.CollectionUtils;
@Slf4j
public class DeviceNameChangerManage {
final static Table<Integer, DeviceType, List<NameChangerFilter>> CHANGER_TABLE = HashBasedTable.create();
private final static Integer TMP_DEFAULT_LINEID = 3;
final static Table<NameChangerEnum, DeviceType, List<NameChangerFilter>> CHANGER_TABLE2 = HashBasedTable.create();
final static Map<Integer, NameChangerEnum> LINEID_NAMECHANGER_MAP = Maps.newHashMap();
public static String findMatch(DeviceType deviceType, String occName) {
public static String findMatch(NameChangerEnum nameChanger, DeviceType deviceType, String occName) {
if (Objects.isNull(deviceType)) {
log.debug("错误的设备类型 type[{}]", deviceType);
return occName;
@ -36,7 +38,7 @@ public class DeviceNameChangerManage {
log.debug("错误的设备名称 occName[{}]", occName);
return occName;
}
List<NameChangerFilter> filters = CHANGER_TABLE.get(TMP_DEFAULT_LINEID, deviceType);
List<NameChangerFilter> filters = CHANGER_TABLE2.get(nameChanger, deviceType);
if (CollectionUtils.isEmpty(filters)) {
log.debug("未找到对应的转换的occName:[{}] deviceType[{}]", occName, deviceType);
return occName;
@ -51,8 +53,41 @@ public class DeviceNameChangerManage {
return occName;
}
public static NameChangerEnum findNameChanger(Integer lineId) {
NameChangerEnum nameChanger = LINEID_NAMECHANGER_MAP.get(lineId);
if (Objects.isNull(nameChanger)) {
return NameChangerEnum.UNIVERSAL;
}
return nameChanger;
}
public static String findMatch(Integer lineId, DeviceType deviceType, String occName) {
NameChangerEnum nameChanger = LINEID_NAMECHANGER_MAP.get(lineId);
if (Objects.isNull(nameChanger)) {
log.debug("错误的设备类型 type[{}]", deviceType);
return occName;
}
List<NameChangerFilter> filters = CHANGER_TABLE2.get(nameChanger, deviceType);
if (CollectionUtils.isEmpty(filters)) {
log.debug("未找到对应的转换的occName:[{}] deviceType[{}]", occName, deviceType);
return occName;
}
for (NameChangerFilter filter : filters) {
String newName = filter.changeDeviceName(occName);
if (Objects.nonNull(newName)) {
return newName;
}
}
log.debug("不能转换的occName:[{}] deviceType[{}]", occName, deviceType);
return occName;
}
public static void init() throws Exception {
List<Class> classes = getClassFQName("club.joylink.xiannccda.ats.message.line3.changer", NameChangerFilter.class);
List<Class> classes = getClassFQName("club.joylink.xiannccda.ats.message.changer.universal", NameChangerFilter.class);
List<NameChangerFilter> filters = Lists.newArrayList();
for (Class clazz : classes) {
Object obj = clazz.getDeclaredConstructor().newInstance();
@ -61,10 +96,14 @@ public class DeviceNameChangerManage {
Map<DeviceType, List<NameChangerFilter>> filteMaper = filters.stream().collect(Collectors.groupingBy(NameChangerFilter::deviceType));
filteMaper.forEach((k, v) -> {
Collections.sort(v, Comparator.comparingInt(NameChangerFilter::filterIndex));
CHANGER_TABLE.put(TMP_DEFAULT_LINEID, k, v);
CHANGER_TABLE2.put(NameChangerEnum.UNIVERSAL, k, v);
});
}
public static void initLineIdNameCHanger(Integer lineId, NameChangerEnum nameChanger) {
LINEID_NAMECHANGER_MAP.put(lineId, nameChanger);
}
private static List<Class> getClassFQName(String packgeName, Class clz) {
// final String BASE_PACKAGE = packgeName;
final String RESOURCE_PATTERN = "/**/*.class";
@ -101,18 +140,18 @@ public class DeviceNameChangerManage {
public static void main(String[] args) throws Exception {
DeviceNameChangerManage.init();
String d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, "T13301C");
String d = DeviceNameChangerManage.findMatch(NameChangerEnum.UNIVERSAL, DeviceType.DEVICE_TYPE_TRACK, "T13301C");
System.out.println(d);
d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, "T06301C");
d = DeviceNameChangerManage.findMatch(NameChangerEnum.UNIVERSAL, DeviceType.DEVICE_TYPE_TRACK, "T06301C");
System.out.println(d);
d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, "T04325G");
d = DeviceNameChangerManage.findMatch(NameChangerEnum.UNIVERSAL, DeviceType.DEVICE_TYPE_TRACK, "T04325G");
System.out.println(d);
/*d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, "TD_2DG");
System.out.println(d);
d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_SWITCH, "P02309");
System.out.println(d);*/
d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_SIGNAL, "S03305");
d = DeviceNameChangerManage.findMatch(NameChangerEnum.UNIVERSAL, DeviceType.DEVICE_TYPE_SIGNAL, "S03305");
System.out.println(d);
/* d = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_SIGNAL, "XR");
System.out.println(d);

View File

@ -0,0 +1,7 @@
package club.joylink.xiannccda.ats.message.changer;
public enum NameChangerEnum {
//通用
UNIVERSAL,
;
}

View File

@ -1,4 +1,4 @@
package club.joylink.xiannccda.ats.message.line3.changer;
package club.joylink.xiannccda.ats.message.changer;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message.line3.changer;
package club.joylink.xiannccda.ats.message.changer.universal;
import club.joylink.xiannccda.ats.message.changer.NameChangerFilter;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message.line3.changer;
package club.joylink.xiannccda.ats.message.changer.universal;
import club.joylink.xiannccda.ats.message.changer.NameChangerFilter;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

View File

@ -1,5 +1,6 @@
package club.joylink.xiannccda.ats.message.line3.changer;
package club.joylink.xiannccda.ats.message.changer.universal;
import club.joylink.xiannccda.ats.message.changer.NameChangerFilter;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

View File

@ -2,9 +2,13 @@ package club.joylink.xiannccda.ats.message.collect;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.changer.NameChangerFilter;
import java.util.List;
/** 消息数据额外转换时间,比如:线路的数据转换为线网数据 */
/**
* 消息数据额外转换时间比如线路的数据转换为线网数据
*/
public abstract class DeviceStatusConvertor {
/**
@ -14,6 +18,8 @@ public abstract class DeviceStatusConvertor {
*/
public abstract MessageId getMessageId();
/** 任务执行逻辑 */
public abstract void run(List<MessageData> messageDataList);
/**
* 任务执行逻辑
*/
public abstract void run(NameChangerEnum nameChanger, List<MessageData> messageDataList);
}

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.collect;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@ -48,14 +49,14 @@ public class DeviceStatusConvertorManager {
*
* @param dataList 消息数据列表
*/
public static void doConvertor(List<MessageData> dataList) {
public static void doConvertor(NameChangerEnum nameChanger, List<MessageData> dataList) {
dataList.stream()
.filter(m -> CONVERTOR_MAP.containsKey(m.getMsgId()))
.collect(Collectors.groupingBy(MessageData::getMsgId))
.forEach((k, v) -> CONVERTOR_MAP.get(k).values().forEach(c -> c.run(v)));
.forEach((k, v) -> CONVERTOR_MAP.get(k).values().forEach(c -> c.run(nameChanger, v)));
}
public static void doConvertor(MessageData md) {
doConvertor(Collections.singletonList(md));
public static void doConvertor(NameChangerEnum nameChanger, MessageData md) {
doConvertor(nameChanger, Collections.singletonList(md));
}
}

View File

@ -60,11 +60,9 @@ public abstract class DeviceStatusDataOperate {
.forEach(
(k, v) -> {
// 当前的设备状态
Map<String, Builder> deviceStatusMap =
allDeviceMap.computeIfAbsent(k, key -> new ConcurrentHashMap<>(v.size()));
Map<String, Builder> deviceStatusMap = allDeviceMap.computeIfAbsent(k, key -> new ConcurrentHashMap<>(v.size()));
// 新的设备状态
Map<String, Builder> newDeviceMap =
v.stream().collect(Collectors.toMap(DeviceStatusDataOperate::getIdVal, b -> b, (v1, v2) -> {
Map<String, Builder> newDeviceMap = v.stream().collect(Collectors.toMap(DeviceStatusDataOperate::getIdVal, b -> b, (v1, v2) -> {
Long curTime = DeviceStatusDataOperate.findFieldVal(v1, "timestamp", Long.class);
Long collTime = DeviceStatusDataOperate.findFieldVal(v2, "timestamp", Long.class);
if (Objects.nonNull(curTime) && Objects.nonNull(collTime)) {

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceDataRepository;
import club.joylink.xiannccda.ats.message.collect.DeviceDataRepository.DataTypeEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertor;
@ -46,10 +47,10 @@ public abstract class DefaultConvertor extends DeviceStatusConvertor {
}
@Override
public void run(List<MessageData> messageDataList) {
public void run(NameChangerEnum nameChanger, List<MessageData> messageDataList) {
Map<Short, List<MessageResponse>> lineMapper = this.groupByLineId(messageDataList);
lineMapper.forEach((k, v) -> {
List<GeneratedMessageV3.Builder> builders = v.stream().map(MessageResponse::generateProto)
List<GeneratedMessageV3.Builder> builders = v.stream().map(d -> d.generateProto(nameChanger))
.flatMap(Collection::stream).filter(d -> {
Integer lineId = DeviceStatusDataOperate.findFieldVal(d, "lineId", Integer.class);
Integer rtuId = DeviceStatusDataOperate.findFieldVal(d, "rtuId", Integer.class);

View File

@ -1,10 +1,11 @@
package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.cache.LineGraphicDataRepository;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataRepository;
import club.joylink.xiannccda.ats.message.collect.datasource.DeviceStatusData;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceInfoProto;
import club.joylink.xiannccda.dto.protos.DeviceInfoProto.DeviceKilometer;
@ -56,10 +57,10 @@ public abstract class LineNetTrainComMethod {
* @param type 所在设备类型
* @param deviceName 设备名称
*/
public static void setUpKilometerCode(
public static void setUpKilometerCode(NameChangerEnum nameChanger,
WsMessageProto.WsLineNetTrainOffsetMessage.Builder obj, DeviceType type, String deviceName) {
// 获取到当前区段公里标
DeviceKilometer.Builder km = getDeviceKM(obj.getLineId(), type, deviceName);
DeviceKilometer.Builder km = getDeviceKM(nameChanger, obj.getLineId(), type, deviceName);
if (km != null) {
obj.setKilometerCode(selectDeviceKilometerCode(obj.getDir(), km));
} else {
@ -76,14 +77,14 @@ public abstract class LineNetTrainComMethod {
* @param type 设备类型
* @param name 设备名称
*/
public static void setTrainDirectionAndKilometerCode(
public static void setTrainDirectionAndKilometerCode(NameChangerEnum nameChanger,
WsMessageProto.WsLineNetTrainOffsetMessage.Builder obj,
String globalId,
String destinationCode,
DeviceType type,
String name) {
TrainRunDirection direction = null;
DeviceKilometer.Builder deviceKm = getDeviceKM(obj.getLineId(), type, name);
DeviceKilometer.Builder deviceKm = getDeviceKM(nameChanger, obj.getLineId(), type, name);
if (deviceKm != null && StringUtils.isNoneEmpty(destinationCode)) {
DeviceKilometer.Builder destinationKm = getDirectionCodeKM(obj.getLineId(), destinationCode);
// 目的地最大公里标大于设备最大公里标上行
@ -120,13 +121,13 @@ public abstract class LineNetTrainComMethod {
* @param name 设备名称
* @return 公里标列表
*/
private static DeviceKilometer.Builder getDeviceKM(int lineId, DeviceType type, String name) {
private static DeviceKilometer.Builder getDeviceKM(NameChangerEnum nameChanger, int lineId, DeviceType type, String name) {
// 非区段道岔直接返回
if (!DeviceType.DEVICE_TYPE_TRACK.equals(type) && !DeviceType.DEVICE_TYPE_SWITCH.equals(type)) {
return null;
}
// 转换成程序中的名称
String convertName = DeviceNameChangerManage.findMatch(type, name);
String convertName = DeviceNameChangerManage.findMatch(nameChanger, type, name);
// 获取到当前区段公里标
return LineGraphicDataRepository.getKilometerCodeList(lineId, convertName);
}

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
import club.joylink.xiannccda.ats.message.line3.rep.TrainIndicationInitResponse;
@ -13,16 +14,19 @@ import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
/** 接收列车初始化消息,就收转换线网的列车数据 */
/**
* 接收列车初始化消息就收转换线网的列车数据
*/
@Slf4j
public class LineNetTrainInitConvertor extends DeviceStatusConvertor {
@Override
public MessageId getMessageId() {
return MessageId.TRAIN_INDICATION_INIT;
}
@Override
public void run(List<MessageData> messageDataList) {
public void run(NameChangerEnum nameChanger, List<MessageData> messageDataList) {
List<Builder> buildList = Lists.newArrayList();
try {
for (MessageData data : messageDataList) {
@ -35,7 +39,7 @@ public class LineNetTrainInitConvertor extends DeviceStatusConvertor {
offset.setLineId(response.getLineId()); // 线路id
offset.setTrainIndex(trainCell.getTrainIndex()); // 列车标示号全线唯一
offset.setGroupId(trainCell.getGroupId()); // 车组号
LineNetTrainComMethod.setTrainDirectionAndKilometerCode(
LineNetTrainComMethod.setTrainDirectionAndKilometerCode(nameChanger,
offset,
trainCell.getGlobalId(),
trainCell.getDestinationId(),

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
@ -23,7 +24,7 @@ public class LineNetTrainRecordConvertor extends DeviceStatusConvertor {
}
@Override
public void run(List<MessageData> messageDataList) {
public void run(NameChangerEnum nameChanger, List<MessageData> messageDataList) {
try {
List<Builder> buildList = Lists.newArrayList();
// 已存在的设备信息
@ -37,7 +38,7 @@ public class LineNetTrainRecordConvertor extends DeviceStatusConvertor {
LineNetTrainComMethod.getDeviceStatusById(offset); // 合并老旧数据
offset.setDir(response.getDirection().getValue()); // 初始设置无运行方向
// 设置公里标信息
LineNetTrainComMethod.setUpKilometerCode(
LineNetTrainComMethod.setUpKilometerCode(nameChanger,
offset, DeviceType.DEVICE_TYPE_TRACK, response.getTrackName());
offset.setShow(offset.getKilometerCode() != 0);
buildList.add(offset);

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.cache.LineGraphicDataRepository;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
@ -17,7 +18,9 @@ import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
/** 列车信息移除时,线网信息处理 */
/**
* 列车信息移除时线网信息处理
*/
@Slf4j
public class LineNetTrainRemoveConvertor extends DeviceStatusConvertor {
@ -27,7 +30,7 @@ public class LineNetTrainRemoveConvertor extends DeviceStatusConvertor {
}
@Override
public void run(List<MessageData> messageDataList) {
public void run(NameChangerEnum nameChanger, List<MessageData> messageDataList) {
try {
List<Builder> buildList = Lists.newArrayList();
for (MessageData data : messageDataList) {
@ -39,7 +42,7 @@ public class LineNetTrainRemoveConvertor extends DeviceStatusConvertor {
offset.setGroupId(response.getGroupId());
offset.setTrainIndex(response.getTrainIndex());
LineNetTrainComMethod.getDeviceStatusById(offset); // 合并老旧数据
LineNetTrainComMethod.setUpKilometerCode(
LineNetTrainComMethod.setUpKilometerCode(nameChanger,
offset, response.getDevType(), response.getDevName());
offset.setShow(false);
buildList.add(offset);

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.collect.convertor;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
import club.joylink.xiannccda.ats.message.line3.rep.TrainIndicationUpdateResponse;
@ -12,7 +13,9 @@ import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
/** 列车信息更新时,信息转换 */
/**
* 列车信息更新时信息转换
*/
@Slf4j
public class LineNetTrainUpdateConvertor extends DeviceStatusConvertor {
@ -22,7 +25,7 @@ public class LineNetTrainUpdateConvertor extends DeviceStatusConvertor {
}
@Override
public void run(List<MessageData> messageDataList) {
public void run(NameChangerEnum nameChanger, List<MessageData> messageDataList) {
try {
List<Builder> buildList = Lists.newArrayList();
for (MessageData data : messageDataList) {
@ -34,7 +37,7 @@ public class LineNetTrainUpdateConvertor extends DeviceStatusConvertor {
offset.setTrainIndex(response.getTrainIndex()); // 列车标示号全线唯一
offset.setGroupId(response.getGroupId()); // 车组号
LineNetTrainComMethod.getDeviceStatusById(offset); // 合并老旧数据
LineNetTrainComMethod.setTrainDirectionAndKilometerCode(
LineNetTrainComMethod.setTrainDirectionAndKilometerCode(nameChanger,
offset,
response.getGlobalId(),
response.getDestinationId(),

View File

@ -39,6 +39,12 @@ public class TrainDataSource extends AbstractData {
/**
* 增量的设备更新信息
* <p>
* k1 数据类型
* <p>
* k2 车组号
* <p>
* v 列车数据
*/
private Table<String, String, Message> trainUpdate = Tables.synchronizedTable(HashBasedTable.create());

View File

@ -2,6 +2,7 @@ package club.joylink.xiannccda.ats.message.line3;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import com.google.protobuf.GeneratedMessageV3.Builder;
import io.netty.buffer.ByteBuf;
import java.util.List;
@ -18,7 +19,7 @@ public class HeartBeatMsg extends MessageData {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
return null;
}

View File

@ -2,8 +2,9 @@ package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.ats.message.line3.rep.EntityParseUtil.ReadData;
@ -69,14 +70,14 @@ public class DeviceStatusBitmapResponse extends MessageResponse {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
List<GeneratedMessageV3.Builder> msgBuildList = Lists.newArrayList();
for (DeviceTypeEntity deviceTypeEntity : this.entityList) {
DeviceType dt = deviceTypeEntity.getType();
for (DeviceEntity deviceEntity : deviceTypeEntity.deviceList) {
GeneratedMessageV3.Builder builder = DeviceStatusConvertor.convert(dt, deviceEntity.status);
// DeviceStatusConvertor.fillField(builder, "id", deviceEntity.devName);
String newOccName = DeviceNameChangerManage.findMatch(dt, deviceEntity.devName);
String newOccName = DeviceNameChangerManage.findMatch(nameChanger, dt, deviceEntity.devName);
DeviceStatusConvertor.fillField(builder, "id", newOccName);
DeviceStatusConvertor.fillField(builder, "rtuId", this.rtuId);
DeviceStatusConvertor.fillField(builder, "timestamp", this.getTime());

View File

@ -2,25 +2,21 @@ package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.GeneratedMessageV3.Builder;
import io.netty.buffer.ByteBuf;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
/**
* 2.7.5 设备状态变化消息
@ -91,12 +87,12 @@ public class DeviceStatusChangeResponse extends MessageResponse {
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
if (Objects.isNull(this.type)) {
log.error("设备变更状态类型为空:{}", JSON.toJSONString(this));
return Collections.emptyList();
}
String occName = DeviceNameChangerManage.findMatch(this.type, this.devName);
String occName = DeviceNameChangerManage.findMatch(nameChanger, this.type, this.devName);
// if (this.type == DeviceType.DEVICE_TYPE_SWITCH && StringUtils.startsWith(occName, "DG")) {
// this.type = DeviceType.DEVICE_TYPE_TRACK;
// }

View File

@ -1,6 +1,7 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.line3.DateTimeUtil;
import club.joylink.xiannccda.ats.message.line3.device.ScheduleSubIdType;
import club.joylink.xiannccda.ats.message.line3.rep.EntityParseUtil.ReadData;
@ -83,7 +84,7 @@ public class InusedScheduleResponse extends MessageResponse {
}
@Override
public List<GeneratedMessageV3.Builder> generateProto() {
public List<GeneratedMessageV3.Builder> generateProto(NameChangerEnum nameChanger) {
List<GeneratedMessageV3.Builder> planBuilds = Lists.newArrayList();
if (CollectionUtils.isEmpty(this.entityList)) {
Plan.Builder planBuild = Plan.newBuilder();

View File

@ -1,6 +1,7 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.line3.MessageCons;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
@ -48,7 +49,7 @@ public class TrainBlockInfoResponse extends MessageResponse {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
List<GeneratedMessageV3.Builder> builders = Lists.newArrayList();
for (TrainCell train : this.trains) {
TrainBlock.Builder builder = TrainBlock.newBuilder();

View File

@ -1,10 +1,11 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.line3.DateTimeUtil;
import club.joylink.xiannccda.ats.message.line3.MessageCons;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
@ -54,7 +55,7 @@ public class TrainIndicationInitResponse extends MessageResponse {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
List<Builder> msgBuildList = Lists.newArrayList();
for (TrainCell trainCell : this.trains) {
TrainInfo.Builder builder = TrainInfo.newBuilder();
@ -75,7 +76,7 @@ public class TrainIndicationInitResponse extends MessageResponse {
}
// builder.setDevName(StringUtils.defaultString(trainCell.getDevName(), ""));
String occName = DeviceNameChangerManage.findMatch(trainCell.getDevType(), trainCell.getDevName());
String occName = DeviceNameChangerManage.findMatch(nameChanger, trainCell.getDevType(), trainCell.getDevName());
builder.setDevName(occName);
if (trainCell.devType == DeviceType.DEVICE_TYPE_SWITCH) {
//车辆在道岔时转换对应的设备类型

View File

@ -1,8 +1,9 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.line3.MessageCons;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
import club.joylink.xiannccda.dto.protos.TrainProto.NccWindow;
@ -79,7 +80,7 @@ public class TrainIndicationRemoveResponse extends MessageResponse {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
TrainRemove.Builder trainRemove = TrainRemove.newBuilder();
trainRemove.setReceiveTime(System.currentTimeMillis());
if (Objects.nonNull(this.lineId)) {
@ -100,7 +101,7 @@ public class TrainIndicationRemoveResponse extends MessageResponse {
trainRemove.setDeviceType(DeviceStatusProto.DeviceType.forNumber(this.devType.getVal()));
}
// trainRemove.setDevName(StringUtils.defaultString(this.devName, ""));
String occName = DeviceNameChangerManage.findMatch(this.devType, this.devName);
String occName = DeviceNameChangerManage.findMatch(nameChanger, this.devType, this.devName);
trainRemove.setDevName(occName);
if (this.devType == DeviceType.DEVICE_TYPE_SWITCH) {
//车辆在道岔时转换对应的设备类型

View File

@ -1,10 +1,11 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.line3.DateTimeUtil;
import club.joylink.xiannccda.ats.message.line3.MessageCons;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
@ -20,7 +21,6 @@ import java.util.List;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
/**
@ -127,7 +127,7 @@ public class TrainIndicationUpdateResponse extends MessageResponse {
}
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
TrainProto.TrainInfo.Builder train = TrainInfo.newBuilder();
train.setReceiveTime(System.currentTimeMillis());
@ -148,7 +148,7 @@ public class TrainIndicationUpdateResponse extends MessageResponse {
}
// train.setDevName(StringUtils.defaultString(this.devName, ""));
String occName = DeviceNameChangerManage.findMatch(this.devType, this.devName);
String occName = DeviceNameChangerManage.findMatch(nameChanger, this.devType, this.devName);
train.setDevName(occName);
if (this.devType == DeviceType.DEVICE_TYPE_SWITCH) {
//车辆在道岔时转换对应的设备类型

View File

@ -1,16 +1,13 @@
package club.joylink.xiannccda.ats.message.line3.rep;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.line3.DateTimeUtil;
import club.joylink.xiannccda.ats.message.line3.MessageCons;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import club.joylink.xiannccda.ats.message.line3.rep.TrainIndicationInitResponse.TrainCell;
import club.joylink.xiannccda.dto.protos.DeviceStatusProto;
import club.joylink.xiannccda.dto.protos.TrainProto.TrainInfo;
import club.joylink.xiannccda.dto.protos.TrainProto.TrainRecord;
import com.google.common.collect.Lists;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.GeneratedMessageV3.Builder;
import io.netty.buffer.ByteBuf;
import java.time.ZoneOffset;
@ -133,7 +130,7 @@ public class TrainRecordResponse extends MessageResponse {
@Override
public List<Builder> generateProto() {
public List<Builder> generateProto(NameChangerEnum nameChanger) {
TrainRecord.Builder builder = TrainRecord.newBuilder();
builder.setReceiveTime(System.currentTimeMillis());
@ -164,7 +161,7 @@ public class TrainRecordResponse extends MessageResponse {
builder.setSideId(this.getSideId());
}
builder.setTrackName(StringUtils.defaultString(this.trackName, ""));
String deviceName = DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, builder.getTrackName());
String deviceName = DeviceNameChangerManage.findMatch(nameChanger, DeviceType.DEVICE_TYPE_TRACK, builder.getTrackName());
builder.setTrackName(deviceName);
if (this.getRecordType() != null) {
builder.setRecordType(this.getRecordType());

View File

@ -4,7 +4,7 @@ import club.joylink.xiannccda.alert.core.AlertSourceEventListener;
import club.joylink.xiannccda.ats.message.line3.rep.TrainRecordResponse.DirectionEnum;
import club.joylink.xiannccda.ats.warn.DeviceAlertEvent;
import club.joylink.xiannccda.ats.warn.platform.TrainReacrdAlertListener.TrainRecordAlertEvent;
import club.joylink.xiannccda.configuration.pros.OccNotHandlePros;
import club.joylink.xiannccda.dto.protos.TrainProto.TrainRecord;
import club.joylink.xiannccda.dto.protos.TrainProto.TrainRecord.Builder;
import lombok.extern.slf4j.Slf4j;
@ -17,8 +17,7 @@ import org.springframework.stereotype.Component;
public class TrainReacrdAlertListener implements AlertSourceEventListener<TrainRecordAlertEvent> {
private final PlatformAlertMonitoringTask platformAlertMonitoringTask;
@Autowired
private OccNotHandlePros notHandlePros;
public TrainReacrdAlertListener(PlatformAlertMonitoringTask platformAlertMonitoringTask) {
this.platformAlertMonitoringTask = platformAlertMonitoringTask;

View File

@ -0,0 +1,61 @@
package club.joylink.xiannccda.configuration;
import club.joylink.xiannccda.constants.common.LoginUserAttr;
import club.joylink.xiannccda.dto.auth.ApiPathCacheDTO;
import club.joylink.xiannccda.service.AuthService;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
//@Component
@Slf4j
public class AuthFilter implements Filter {
@Autowired
private AuthService authService;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
HttpServletRequest req = (HttpServletRequest) request;
var finder = true;
if (Objects.nonNull(authentication) && authentication.isAuthenticated() && (authentication.getPrincipal() instanceof Jwt jwt)) {
if (Objects.isNull(jwt.getClaim(LoginUserAttr.DEFAULTS))) {
finder = false;
Object roleObj = jwt.getClaim(LoginUserAttr.ROLES);
var roleList = (List<Long>) roleObj;
for (Long roleId : roleList) {
var cacheList = this.authService.findByRoleId(roleId);
for (ApiPathCacheDTO cache : cacheList) {
AntPathRequestMatcher matcher = new AntPathRequestMatcher(cache.getUri());
if (matcher.matcher(req).isMatch() && cache.getMethods().contains(req.getMethod().toUpperCase())) {
finder = true;
}
}
}
}
}
if (finder) {
chain.doFilter(request, response);
} else {
throw new AccessDeniedException("无权限");
}
}
}

View File

@ -19,8 +19,6 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@ -31,6 +29,7 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtGra
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.cors.CorsConfigurationSource;
@ -52,7 +51,8 @@ public class SpringSecurityConfiguration {
@Autowired
CorsConfigurationSource corsConfigurationSource;
/*@Autowired
private AuthFilter authFilter;*/
static List<RequestMatcher> AuthWhiteList = new ArrayList<>();
static {
@ -68,6 +68,7 @@ public class SpringSecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> {
// authorize.requestMatchers("/favicon.ico", "/js2/**",
@ -79,10 +80,14 @@ public class SpringSecurityConfiguration {
authorize.anyRequest().authenticated();
}
)
// BearerTokenAuthenticationFilter
.cors(corsConfig -> corsConfig.configurationSource(corsConfigurationSource))
.csrf((csrf) -> csrf.disable())
// .httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(this.jwtDecoder())))
// .addFilterAfter(authFilter,FilterSecurityInterceptor.class)
.sessionManagement(
(session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling((exceptions) -> exceptions

View File

@ -0,0 +1,26 @@
package club.joylink.xiannccda.configuration;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class SystemSynTaskConfig {
@Bean("nsExecutor")
public TaskExecutor nsExecutor(Environment env) {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setThreadNamePrefix("ns-executor-");
taskExecutor.setCorePoolSize(2);
taskExecutor.setMaxPoolSize(2);
taskExecutor.setQueueCapacity(100);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}

View File

@ -1,33 +0,0 @@
package club.joylink.xiannccda.configuration.pros;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "occ-not-handle")
public class OccNotHandlePros {
private Integer lineId;
private List<Integer> filterRtuIds;
private Map<Integer, List<String>> trainRecordStation;
public boolean notMatchHandle(Integer lineId, Integer rtuId) {
if (Objects.isNull(lineId) || Objects.isNull(rtuId)) {
return true;
}
if (CollectionUtils.isEmpty(this.filterRtuIds)) {
return true;
}
if (this.filterRtuIds.contains(rtuId)) {
return false;
}
return true;
}
}

View File

@ -1,14 +0,0 @@
package club.joylink.xiannccda.constants;
import club.joylink.xiannccda.ats.message.line3.device.ScheduleSubIdType;
import java.util.Arrays;
public enum EventLogType {
//登录
LOGIN,
//登出
LOGOUT,
;
}

View File

@ -1,6 +1,6 @@
package club.joylink.xiannccda.constants;
import club.joylink.xiannccda.configuration.pros.OccNotHandlePros;
import club.joylink.xiannccda.ats.message.OccMessageManage;
import club.joylink.xiannccda.ws.msg.SystemWarnEvent;
import lombok.Getter;
import org.springframework.beans.BeansException;
@ -26,7 +26,7 @@ public class SystemContext implements ApplicationContextAware {
}
public static boolean notMatchRtu(Integer lineId, Integer rtuId) {
OccNotHandlePros cu = SystemContext.getAppContext().getBean(OccNotHandlePros.class);
OccMessageManage cu = SystemContext.getAppContext().getBean(OccMessageManage.class);
return cu.notMatchHandle(lineId, rtuId);
}

View File

@ -0,0 +1,22 @@
package club.joylink.xiannccda.constants.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Indexed;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface CommonLogAnno {
String name() default "";
CommonLogTypeEnum logType();
CommonLogTypeEnum.SubEventType subLogType();
}

View File

@ -0,0 +1,13 @@
package club.joylink.xiannccda.constants.common;
public enum CommonLogTypeEnum {
//登录
LOGIN,
OPERATE,
WARN,
;
public enum SubEventType {
LOGIN, LOGOUT, QUERY, SAVE_OR_UPDATE, DELETE, WARN, NONE
}
}

View File

@ -0,0 +1,5 @@
package club.joylink.xiannccda.constants.common;
public enum LineTypeEnum {
NCC, OCC;
}

View File

@ -0,0 +1,13 @@
package club.joylink.xiannccda.constants.common;
public class LoginUserAttr {
public static final String DEFAULTS = "default";
public static final String ROLES = "roles";
public enum DefaultUserRuleEnum {
ADMIN, USER
}
}

View File

@ -2,6 +2,9 @@ package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.alert.NccAlertInfo;
import club.joylink.xiannccda.alert.NccAlertInfo.AlertStatus;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.record.AlertRecordQueryDTO;
import club.joylink.xiannccda.dto.record.AlertRecordReportDTO;
import club.joylink.xiannccda.dto.record.AlertRecordReportResponseDTO;
@ -15,7 +18,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@ -48,6 +50,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "报警信息确认")
@ApiResponse(description = "报警信息确认")
@CommonLogAnno(name = "报警信息确认", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public AlertTip confirm(@PathVariable("recordId") Long recordId, @PathVariable("tipType") String tipType, @RequestParam(value = "alertLocationId", required = false) Long locationId) {
return this.alertRecordService.confirm(recordId, tipType, locationId);
}
@ -56,6 +59,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "错误报警")
@ApiResponse(description = "错误报警")
@CommonLogAnno(name = "报警信息-人工确认", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void batchAlarmWarn(@RequestBody List<Long> recordId) {
this.alertRecordService.failAlarm(recordId, AlertStatus.PERSON_WARN_DO);
}
@ -64,6 +68,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "错误报警")
@ApiResponse(description = "错误报警")
@CommonLogAnno(name = "报警信息-误报", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void failAlarm(@PathVariable("recordId") Long recordId) {
this.alertRecordService.failAlarm(List.of(recordId), AlertStatus.FAIL_DO);
}
@ -72,14 +77,17 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "分页查询报警记录")
@ApiResponse(description = "报警记录")
@CommonLogAnno(name = "报警信息-列表数据", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<AlertRecord> pageQuery(@RequestBody AlertRecordQueryDTO queryDTO) {
return alertRecordRepository.page(queryDTO);
}
@PostMapping("/page/detail")
@SecurityRequirement(name = "jwt")
@Operation(summary = "分页查询报警记录详情")
@ApiResponse(description = "报警记录详情")
@CommonLogAnno(name = "报警信息-列表数据2", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<NccAlertInfo> pageQueryAlertDetail(@RequestBody AlertRecordQueryDTO queryDTO) {
return alertRecordService.pageQueryAlertDetail(queryDTO);
}
@ -89,6 +97,7 @@ public class AlertRecordController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "报警统计")
@ApiResponse(description = "报警统计")
@CommonLogAnno(name = "报警信息-统计", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public List<AlertRecordReportResponseDTO> reportStatistics(@PathVariable("lineId") Integer lineId, @RequestBody AlertRecordReportDTO reportDTO) {
return this.alertRecordRepository.report(lineId, reportDTO);
}

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.alertTip.AlertTipInfoDto;
import club.joylink.xiannccda.dto.alertTip.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipSaveDTO;
@ -9,8 +12,6 @@ import club.joylink.xiannccda.service.AlertTipService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService.AreaFinder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -21,14 +22,13 @@ import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 报警时的提示信息 前端控制器
* 决策信息
* </p>
*
* @author walker-sheng
@ -52,6 +52,7 @@ public class AlertTipController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "插入报警提示信息")
@PostMapping()
@CommonLogAnno(name = "决策信息-保存修改", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void save(@RequestBody @Validated AlertTipSaveDTO saveDTO) {
alertTipService.save(saveDTO);
}
@ -60,6 +61,7 @@ public class AlertTipController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "根据id查询数据")
@GetMapping("/id/{id}")
@CommonLogAnno(name = "决策信息-查看", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public AlertTip getById(@PathVariable int id) {
return alertTipRepository.getById(id);
}
@ -68,6 +70,7 @@ public class AlertTipController {
@Operation(summary = "分页查询报警提示信息")
@ApiResponse(description = "报警提示信息分页")
@GetMapping("/page")
@CommonLogAnno(name = "决策信息-分页列表", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public IPage<AlertTipInfoDto> pageAlertTips(AlertTipQueryDTO alertTipQueryDTO) {
return this.alertTipService.page(alertTipQueryDTO);
}
@ -77,13 +80,15 @@ public class AlertTipController {
@Operation(summary = "根据id删除数据")
@ApiResponse(description = "是否确实删除掉了一条数据")
@DeleteMapping("/id/{id}")
@CommonLogAnno(name = "决策信息-删除", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.DELETE)
public boolean deleteById(@PathVariable int id) {
return this.alertTipRepository.removeById(id);
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/find/type/{lineId}/{alertType}")
@PostMapping(value = "/find/type/{lineId}/{alertType}")
@CommonLogAnno(name = "决策信息-类型绑定查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public List<AreaFinder> findAlertType(@PathVariable("lineId") Integer lineId, @PathVariable("alertType") String alertType) {
return this.areaConfigService.findAlertType(lineId, alertType);

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.alertTip.AlertTipTimeQueryDTO;
import club.joylink.xiannccda.entity.AlertTipTimeConfig;
import club.joylink.xiannccda.repository.impl.AlertTipTimeConfigRepository;
@ -8,6 +11,10 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import java.security.Principal;
import java.time.Instant;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -15,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* 决策信息时间类型配置
* </p>
*
* @author walker-sheng
@ -36,6 +43,7 @@ public class AlertTipTimeConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("")
@CommonLogAnno(name = "决策信息时间-类型保存", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public void save(@RequestBody AlertTipTimeConfig dto) {
this.timeConfigService.saveOrUpdate(dto);
}
@ -43,8 +51,16 @@ public class AlertTipTimeConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("page")
public IPage<AlertTipTimeConfig> page(AlertTipTimeQueryDTO dto) {
@CommonLogAnno(name = "决策信息时间-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public IPage<AlertTipTimeConfig> page(Principal user, AlertTipTimeQueryDTO dto) {
JwtAuthenticationToken authToken = (JwtAuthenticationToken) user;
System.out.println(authToken.getPrincipal());
System.out.println(authToken.getTokenAttributes());
Object exp = authToken.getTokenAttributes().get(JwtClaimNames.EXP);
Instant time = (Instant) exp;
System.out.println(time.getEpochSecond());
System.out.println(authToken.getCredentials());
System.out.println(authToken.getAuthorities());
return this.configRepository.page(dto, Wrappers.lambdaQuery(AlertTipTimeConfig.class).eq(AlertTipTimeConfig::getListShower, 1));
}

View File

@ -1,15 +1,12 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigDto;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigPageDto;
import club.joylink.xiannccda.dto.config.DeviceAreaConfigQueryDto;
import club.joylink.xiannccda.entity.DeviceAreaConfig;
import club.joylink.xiannccda.repository.impl.DeviceAreaConfigRepository;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService;
import club.joylink.xiannccda.service.config.DeviceAreaConfigService.AreaFinder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -25,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* 设备区域配置
* </p>
*
* @author walker-sheng
@ -45,6 +42,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("/save")
@CommonLogAnno(name = "决策信息设备区域配置-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String save(@RequestBody DeviceAreaConfigDto dto) {
this.areaConfigService.saveOrUpdate(dto);
return "ok";
@ -53,23 +51,17 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/bind/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-信息绑定", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String bindAlertType(@PathVariable("id") Long id, @RequestBody List<String> alertTypes) {
this.areaConfigService.bindAlertType(id, alertTypes);
return "ok";
}
/* @SecurityRequirement(name = "jwt")
@Operation(summary = "绑定对应的错误类型")
@PostMapping("/find/type/{lineId}/{alertType}")
public List<AreaFinder> findAlertType(@PathVariable("lineId") Integer lineId, @PathVariable("alertType") String alertType) {
return this.areaConfigService.findAlertType(lineId, alertType);
}*/
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@GetMapping("/page/{lineId}")
@CommonLogAnno(name = "决策信息设备区域配置-分页查询", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public Page<DeviceAreaConfigPageDto> page(@PathVariable("lineId") Integer lineId, DeviceAreaConfigQueryDto queryDto) {
return this.areaConfigService.page(queryDto, lineId);
}
@ -77,6 +69,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@GetMapping("/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public DeviceAreaConfigDto findById(@PathVariable("id") Long id) {
return this.areaConfigService.findInfo(id);
}
@ -84,6 +77,7 @@ public class DeviceAreaConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "获取详情数据")
@DeleteMapping("/{id}")
@CommonLogAnno(name = "决策信息设备区域配置-删除", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.DELETE)
public String delete(@PathVariable("id") Long id) {
this.areaConfigService.delete(id);
return "ok";

View File

@ -1,5 +1,8 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.entity.DeviceGuardConfig;
import club.joylink.xiannccda.repository.IDeviceGuardConfigRepository;
import club.joylink.xiannccda.service.config.DeviceGuardConfigService;
@ -8,7 +11,6 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -17,7 +19,10 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "设备保护配置接口")
/**
* 决策信息阈值管理
*/
@Tag(name = "决策信息阈值管理")
@RestController
@RequestMapping("/api/config/device")
public class DeviceGuardConfigController {
@ -32,6 +37,7 @@ public class DeviceGuardConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "initData")
@GetMapping("/initData/{lineId}")
@CommonLogAnno(name = "决策信息阈值管理-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.QUERY)
public DeviceGuardConfig initData(@PathVariable("lineId") Integer lineId) {
LambdaQueryWrapper<DeviceGuardConfig> qw = Wrappers.lambdaQuery(DeviceGuardConfig.class);
qw.eq(DeviceGuardConfig::getLineId, lineId);
@ -41,6 +47,7 @@ public class DeviceGuardConfigController {
@SecurityRequirement(name = "jwt")
@Operation(summary = "保存修改")
@PostMapping("/save")
@CommonLogAnno(name = "决策信息阈值管理-数据详情", logType = CommonLogTypeEnum.OPERATE, subLogType = SubEventType.SAVE_OR_UPDATE)
public String saveOrUpdate(@RequestBody DeviceGuardConfig dto) {
this.configService.saveOrUpdate(dto);
return "ok";

View File

@ -21,7 +21,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -63,13 +65,19 @@ public class RoleAuthController {
this.authPathRepository.saveOrUpdate(apiPath);
}
@DeleteMapping("/res/{id}")
@Operation(summary = "保存编辑资源")
@ApiResponse(description = "保存编辑资源")
public void deleteRes(@PathVariable("id") Long id) {
this.authPathRepository.removeById(id);
}
@GetMapping("/role/page")
@SecurityRequirement(name = "jwt")
@Operation(summary = "角色分页")
@ApiResponse(description = "角色分页")
public Page<AuthRoleDTO> rulePage(AuthRoleQueryDTO queryDTO) {
return this.authRoleRepository.roleApiPage(queryDTO);
}
@PostMapping("/role/saveOrUpdate")

View File

@ -1,9 +1,14 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.constants.common.CommonLogAnno;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum.SubEventType;
import club.joylink.xiannccda.dto.LoginInfoDTO;
import club.joylink.xiannccda.dto.user.UserDetailDTO;
import club.joylink.xiannccda.dto.user.UserEditDTO;
import club.joylink.xiannccda.dto.user.UserInfoAuthDTO;
import club.joylink.xiannccda.dto.user.UserQueryDTO;
import club.joylink.xiannccda.dto.user.UserTokenDTO;
import club.joylink.xiannccda.entity.User;
import club.joylink.xiannccda.entity.User.Register;
import club.joylink.xiannccda.repository.IUserRepository;
@ -13,6 +18,8 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.Principal;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@ -39,23 +46,47 @@ public class UserController {
this.userRepository = userRepository;
}
@PostMapping("/register")
/* @PostMapping("/register")
@Operation(summary = "用户注册")
@ApiResponse(description = "用户注册结果")
public String register(@RequestBody @Validated(Register.class) User user) {
return this.userService.register(user);
}*/
@PostMapping("/info")
@Operation(summary = "用户信息")
@ApiResponse(description = "用户信息")
public UserInfoAuthDTO userInfo(Principal user) {
return this.userService.userInfo((JwtAuthenticationToken) user);
}
@PostMapping("/login")
@Operation(summary = "用户登录")
@ApiResponse(description = "授权的jwt")
@CommonLogAnno(name = "用户登录", logType = CommonLogTypeEnum.LOGIN, subLogType = SubEventType.LOGIN)
public String login(@RequestBody LoginInfoDTO loginInfo) {
return this.userService.login(loginInfo);
}
@PostMapping("/logout")
@Operation(summary = "用户登出")
@ApiResponse(description = "授权的jwt")
@CommonLogAnno(name = "用户登出", logType = CommonLogTypeEnum.LOGIN, subLogType = SubEventType.LOGOUT)
public String logout() {
return "";
}
@PostMapping("/refresh/token")
@SecurityRequirement(name = "jwt")
@Operation(summary = "用户刷新token")
@ApiResponse(description = "刷新jwt")
public UserTokenDTO refreshToken(Principal user) {
return this.userService.refreshToken((JwtAuthenticationToken) user);
}
@PostMapping("/edit")
@Operation(summary = "用户修改")
@SecurityRequirement(name = "jwt")
@ApiResponse(description = "用户修改")
public void editUser(@RequestBody UserEditDTO dto) {
this.userService.editUser(dto);

View File

@ -0,0 +1,13 @@
package club.joylink.xiannccda.dto.auth;
import java.util.List;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class ApiPathCacheDTO {
private String uri;
private List<String> methods;
}

View File

@ -1,6 +1,8 @@
package club.joylink.xiannccda.dto.event;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.Data;
@ -8,9 +10,26 @@ import lombok.Data;
public class EventLogPageDTO {
private Long id;
private EventLogType eventType;
@Schema(name = "接口名称")
private String faceName;
@Schema(name = "接口请求大类")
private CommonLogTypeEnum eventType;
@Schema(name = "接口请求类别")
private CommonLogTypeEnum.SubEventType subEventType;
@Schema(name = "接口uri")
private String uri;
@Schema(name = "接口uri method")
private String method;
@Schema(name = "接口请求参数")
private String parameters;
@Schema(name = "接口执行结果0=失败,1=成功")
private Integer requestSuccess;
@Schema(name = "操作人姓名")
private String userName;
@Schema(name = "操作人id")
private Long fromUserId;
@Schema(name = "操作人电话")
private String mobile;
@Schema(name = "操作时间")
private LocalDateTime createDateTime;
}

View File

@ -1,12 +1,14 @@
package club.joylink.xiannccda.dto.user;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDateTime;
import java.util.List;
import lombok.Data;
import lombok.experimental.Accessors;
@Deprecated
@Data
public class UserDetailDTO {
private Long id;
@ -14,7 +16,8 @@ public class UserDetailDTO {
private String mobile;
private LocalDateTime registerTime;
private List<UserRoleDetail> roleList;
@JsonIgnore
private DefaultUserRuleEnum defaultRole;
@JsonIgnore
private String userRoles;

View File

@ -0,0 +1,24 @@
package club.joylink.xiannccda.dto.user;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import club.joylink.xiannccda.entity.AuthRole;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.Data;
@Data
public class UserInfoAuthDTO {
@Schema(name = "token剩余时间 (秒)")
private Long remainingSecond;
@Schema(name = "用户角色")
private List<AuthRole> roles;
@Schema(name = "用户默认角色")
private DefaultUserRuleEnum defaultRole;
public UserInfoAuthDTO(Long remainingSecond, List<AuthRole> roles, DefaultUserRuleEnum defaultRole) {
this.remainingSecond = remainingSecond;
this.roles = roles;
this.defaultRole = defaultRole;
}
}

View File

@ -4,9 +4,18 @@ import club.joylink.xiannccda.dto.protos.AlertConstProto.AlertType;
import club.joylink.xiannccda.entity.AlertRecord;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Builder
public class UserQueryDTO extends PageDTO<UserQueryDTO> {
private String mobile;
private String password;
}

View File

@ -0,0 +1,12 @@
package club.joylink.xiannccda.dto.user;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class UserTokenDTO {
private String token;
private long remainingSecond;
}

View File

@ -1,17 +1,23 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.constants.common.LineTypeEnum;
import club.joylink.xiannccda.entity.AuthApiPath.AuthApi;
import com.alibaba.fastjson2.JSON;
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.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
@Data
@Setter
@Getter
@Accessors(chain = true)
@TableName("auth_role")
@Schema(name = "authRole", description = "用户角色")
@ -24,7 +30,31 @@ public class AuthRole {
@NotBlank(message = "名字不能为空", groups = {AuthApi.class})
private String name;
@Schema(description = "角色配置")
@JsonIgnore
private String roleConfigStr;
@Schema(description = "角色配置")
@TableField(exist = false)
private RoleConfig roleConfig;
public RoleConfig getRoleConfig() {
if (StringUtils.isNotEmpty(this.roleConfigStr)) {
return JSON.parseObject(this.roleConfigStr, RoleConfig.class);
}
return null;
}
public static final String ID = "id";
public static final String NAME = "name";
@Data
public static class RoleConfig {
private Integer lineId;
private LineTypeEnum lineType;
}
}

View File

@ -1,7 +1,6 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.alert.core.AlertDeviceType;
import club.joylink.xiannccda.constants.EventLogType;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@ -30,14 +29,18 @@ public class EventLog {
private Long id;
@Schema(description = "设备类型")
private EventLogType eventType;
private CommonLogTypeEnum eventType;
private CommonLogTypeEnum.SubEventType subEventType;
private String faceName;
private String uri;
private String method;
private String parameters;
@Schema(description = "设备告警")
private Long fromUserId;
@Schema(description = "开始时间(小时)")
private LocalDateTime createDateTime;
private Integer requestSuccess;
public static final String ID = "id";
public static final String EVENT_TYPE = "event_Type";
public static final String FROM_USER_ID = "from_User_Id";

View File

@ -1,8 +1,9 @@
package club.joylink.xiannccda.entity;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema.RequiredMode;
import jakarta.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import io.swagger.v3.oas.annotations.media.Schema;
@ -42,6 +43,9 @@ public class User {
@Schema(description = "注册时间")
private LocalDateTime registerTime;
@Schema(description = "用户默认角色")
private DefaultUserRuleEnum defaultRole;
public static final String ID = "id";
public static final String NAME = "name";
@ -51,6 +55,7 @@ public class User {
public static final String PASSWORD = "password";
public static final String REGISTER_TIME = "register_time";
public static final String DEFAULT_ROLE = "default_role";
public interface Register {

View File

@ -0,0 +1,39 @@
package club.joylink.xiannccda.event;
import club.joylink.xiannccda.constants.common.CommonLogTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.context.ApplicationEvent;
@Getter
@Setter
@Accessors(chain = true)
public class OperateEvent extends ApplicationEvent {
private String faceName;
private CommonLogTypeEnum type;
private CommonLogTypeEnum.SubEventType subType;
private String uri;
private String method;
private Long userId;
private Integer requestSuccess;
public OperateEvent(String faceName, CommonLogTypeEnum type, CommonLogTypeEnum.SubEventType subType, String uri, String method, Object source, Long userId) {
super(source);
this.faceName = faceName;
this.type = type;
this.subType = subType;
this.uri = uri;
this.method = method;
this.userId = userId;
}
public Object getSource() {
return this.source;
}
}

View File

@ -0,0 +1,29 @@
package club.joylink.xiannccda.event;
import club.joylink.xiannccda.entity.EventLog;
import club.joylink.xiannccda.repository.IEventLogRepository;
import com.alibaba.fastjson2.JSON;
import java.time.LocalDateTime;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class OperateEventHandle {
private final IEventLogRepository eventLogRepository;
public OperateEventHandle(IEventLogRepository eventLogRepository) {
this.eventLogRepository = eventLogRepository;
}
@Async("nsExecutor")
@EventListener
public void eventHandle(OperateEvent event) {
EventLog eventLog = new EventLog();
eventLog.setFaceName(event.getFaceName()).setEventType(event.getType()).setSubEventType(event.getSubType()).setUri(event.getUri()).setMethod(event.getMethod())
.setRequestSuccess(event.getRequestSuccess())
.setFromUserId(event.getUserId()).setParameters(JSON.toJSONString(event.getSource())).setCreateDateTime(LocalDateTime.now());
eventLogRepository.save(eventLog);
}
}

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.mapper;
import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.RelieveTimeShere;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
/**
@ -16,4 +17,5 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AuthApiPathMapper extends BaseMapper<AuthApiPath> {
List<AuthApiPath> findByApiPathByRoleId(Long roleId);
}

View File

@ -4,9 +4,12 @@ import club.joylink.xiannccda.dto.auth.AuthRoleDTO;
import club.joylink.xiannccda.dto.auth.AuthRoleQueryDTO;
import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.AuthRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -20,4 +23,6 @@ import org.apache.ibatis.annotations.Mapper;
public interface AuthRoleMapper extends BaseMapper<AuthRole> {
Page<AuthRoleDTO> queryRole(AuthRoleQueryDTO dto);
List<AuthRole> getAuthRoleByUserId(@Param("userId") String userId);
}

View File

@ -2,8 +2,11 @@ package club.joylink.xiannccda.mapper;
import club.joylink.xiannccda.entity.AuthRoleApiPathRef;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -16,4 +19,5 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AuthRoleUserRefMapper extends BaseMapper<AuthRoleUserRef> {
}

View File

@ -6,6 +6,7 @@ import club.joylink.xiannccda.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -18,5 +19,6 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
Page<UserDetailDTO> detailQuery(UserQueryDTO dto);
Page<UserDetailDTO> detailQuery(@Param("dto") UserQueryDTO dto);
}

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.mock.message;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusConvertorManager;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@ -64,7 +65,7 @@ public class MockLoadData implements ApplicationRunner {
// .ne(NccMockData::getIsDelete, 1)
.orderBy(true, true, NccMockData::getId);
List<MessageResponse> dataList = this.nccMockDataService.loadALLData(wrapper);
DeviceStatusConvertorManager.doConvertor(dataList.stream().map(d -> (MessageData) d).collect(Collectors.toList()));
DeviceStatusConvertorManager.doConvertor(NameChangerEnum.UNIVERSAL, dataList.stream().map(d -> (MessageData) d).collect(Collectors.toList()));
} catch (Exception e) {
log.error(e.getMessage(), e);

View File

@ -5,6 +5,7 @@ import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.User;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
@ -18,4 +19,7 @@ public interface IAuthApiPathRepository extends IService<AuthApiPath> {
Page<AuthApiPath> page(AuthApiPathQueryDTO dto);
List<AuthApiPath> findByRoleId(Long roleId);
}

View File

@ -7,6 +7,7 @@ import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.AuthRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
@ -19,4 +20,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
public interface IAuthRoleRepository extends IService<AuthRole> {
Page<AuthRoleDTO> roleApiPage(AuthRoleQueryDTO role);
List<AuthRole> getAuthRoleByUserId(String userId);
}

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.repository;
import club.joylink.xiannccda.entity.AuthRoleApiPathRef;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>

View File

@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
/**
@ -27,4 +28,9 @@ public class AuthApiPathRepository extends ServiceImpl<AuthApiPathMapper, AuthAp
LambdaQueryWrapper<AuthApiPath> queryWrapper = Wrappers.lambdaQuery(AuthApiPath.class);
return this.page(dto, queryWrapper);
}
@Override
public List<AuthApiPath> findByRoleId(Long roleId) {
return this.getBaseMapper().findByApiPathByRoleId(roleId);
}
}

View File

@ -35,4 +35,9 @@ public class AuthRoleRepository extends ServiceImpl<AuthRoleMapper, AuthRole> im
});
return page;
}
@Override
public List<AuthRole> getAuthRoleByUserId(String userId) {
return this.baseMapper.getAuthRoleByUserId(userId);
}
}

View File

@ -7,6 +7,7 @@ import club.joylink.xiannccda.mapper.AuthRoleUserRefMapper;
import club.joylink.xiannccda.repository.IAuthRoleApiRefRepository;
import club.joylink.xiannccda.repository.IAuthRoleUserRefRepository;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
/**
@ -20,4 +21,5 @@ import org.springframework.stereotype.Service;
@Service
public class AuthRoleUserRefRepository extends ServiceImpl<AuthRoleUserRefMapper, AuthRoleUserRef> implements IAuthRoleUserRefRepository {
}

View File

@ -11,6 +11,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@ -30,11 +31,14 @@ public class UserRepository extends ServiceImpl<UserMapper, User> implements IUs
Page<UserDetailDTO> page = this.baseMapper.detailQuery(dto);
for (UserDetailDTO record : page.getRecords()) {
List<UserRoleDetail> userRoleList = Lists.newArrayList();
if (StringUtils.isNotEmpty(record.getUserRoles())) {
Arrays.stream(StringUtils.split(record.getUserRoles(), ',')).forEach(d -> {
String[] idName = StringUtils.split(d, '|');
userRoleList.add(new UserRoleDetail(Long.valueOf(idName[0]), idName[1]));
});
record.setRoleList(userRoleList);
}
record.setUserRoles(null);
}
return page;

View File

@ -1,7 +1,9 @@
package club.joylink.xiannccda.service;
import club.joylink.xiannccda.dto.LoginInfoDTO;
import club.joylink.xiannccda.dto.auth.ApiPathCacheDTO;
import club.joylink.xiannccda.dto.auth.AuthRoleDTO;
import club.joylink.xiannccda.entity.AuthApiPath;
import club.joylink.xiannccda.entity.AuthRole;
import club.joylink.xiannccda.entity.AuthRoleApiPathRef;
import club.joylink.xiannccda.entity.User;
@ -15,11 +17,19 @@ import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
@ -27,14 +37,46 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Slf4j
public class AuthService {
IAuthRoleRepository authRoleRepository;
IAuthRoleApiRefRepository authRoleApiRefRepository;
IAuthApiPathRepository authApiPathRepository;
private final static Lock cacheLock = new ReentrantLock();
private final static Cache<Long, List<ApiPathCacheDTO>> CACHE = CacheBuilder.newBuilder().build();
public AuthService(IAuthRoleRepository authRoleRepository, IAuthRoleApiRefRepository authRoleApiRefRepository) {
public AuthService(IAuthRoleRepository authRoleRepository, IAuthRoleApiRefRepository authRoleApiRefRepository, IAuthApiPathRepository authApiPathRepository) {
this.authRoleRepository = authRoleRepository;
this.authRoleApiRefRepository = authRoleApiRefRepository;
this.authApiPathRepository = authApiPathRepository;
}
public void removeByRoleId(Long roleId) {
CACHE.invalidate(roleId);
}
public List<ApiPathCacheDTO> findByRoleId(Long roleId) {
try {
cacheLock.lock();
return CACHE.get(roleId, () -> {
List<AuthApiPath> apiPathList = this.authApiPathRepository.findByRoleId(roleId);
List<ApiPathCacheDTO> cacheDTOList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(apiPathList)) {
for (AuthApiPath apiPath : apiPathList) {
List<String> methodList = Splitter.on(",").trimResults().splitToList(apiPath.getMethod());
ApiPathCacheDTO dto = ApiPathCacheDTO.builder().uri(apiPath.getPath()).methods(methodList).build();
cacheDTOList.add(dto);
}
}
return cacheDTOList;
});
} catch (Exception e) {
log.error("");
return null;
} finally {
cacheLock.unlock();
}
}
@Transactional
@ -42,7 +84,6 @@ public class AuthService {
if (Objects.isNull(dto.getId())) {
AuthRole r = new AuthRole();
r.setName(dto.getName());
this.authRoleRepository.save(r);
this.batchSave(dto.getResList(), r.getId());
} else {
@ -51,6 +92,7 @@ public class AuthService {
r.setName(dto.getName());
this.authRoleRepository.updateById(r);
this.batchSave(dto.getResList(), dto.getId());
this.removeByRoleId(dto.getId());
}
}

View File

@ -1,25 +1,31 @@
package club.joylink.xiannccda.service;
import club.joylink.xiannccda.constants.common.LoginUserAttr.DefaultUserRuleEnum;
import club.joylink.xiannccda.constants.common.LoginUserAttr;
import club.joylink.xiannccda.dto.LoginInfoDTO;
import club.joylink.xiannccda.dto.user.UserEditDTO;
import club.joylink.xiannccda.dto.user.UserQueryDTO;
import club.joylink.xiannccda.dto.user.UserInfoAuthDTO;
import club.joylink.xiannccda.dto.user.UserTokenDTO;
import club.joylink.xiannccda.entity.AuthRole;
import club.joylink.xiannccda.entity.AuthRoleUserRef;
import club.joylink.xiannccda.entity.User;
import club.joylink.xiannccda.exception.BusinessExceptionAssertEnum;
import club.joylink.xiannccda.repository.IAuthRoleRepository;
import club.joylink.xiannccda.repository.IAuthRoleUserRefRepository;
import club.joylink.xiannccda.repository.IUserRepository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -29,11 +35,14 @@ public class UserService {
final IUserRepository userRepository;
final JwtEncoder jwtEncoder;
final IAuthRoleUserRefRepository authRoleUserRefRepository;
final IAuthRoleRepository authRoleRepository;
private final static long EXPIRY = 3 * 24 * 60 * 60;//3天过期时间
public UserService(IUserRepository userRepository, JwtEncoder jwtEncoder, IAuthRoleUserRefRepository authRoleUserRefRepository) {
public UserService(IUserRepository userRepository, JwtEncoder jwtEncoder, IAuthRoleUserRefRepository authRoleUserRefRepository, IAuthRoleRepository authRoleRepository) {
this.userRepository = userRepository;
this.jwtEncoder = jwtEncoder;
this.authRoleUserRefRepository = authRoleUserRefRepository;
this.authRoleRepository = authRoleRepository;
}
public String register(User user) {
@ -48,22 +57,44 @@ public class UserService {
}
public String login(LoginInfoDTO loginInfo) {
/* UserQueryDTO dto = UserQueryDTO.builder().mobile(loginInfo.getAccount()).password(loginInfo.getPassword()).build();
dto.setCurrent(0);
dto.setSize(1);
Page<UserDetailDTO> page = this.userRepository.userRolePage(dto);
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(CollectionUtils.isNotEmpty(page.getRecords()), "账号或密码错误");*/
// UserDetailDTO dd = page.getRecords().get(0);
// List<Long> ruleList = dd.getRoleList().stream().map(UserRoleDetail::getRoleId).collect(Collectors.toList());
User user = this.userRepository.getOne(
Wrappers.<User>lambdaQuery().eq(User::getMobile, loginInfo.getAccount())
.eq(User::getPassword, loginInfo.getPassword()));
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(user, "账号或密码错误");
long expiry = 3 * 24 * 60 * 60;
// 使用默认的RS256生成jwt
Instant now = Instant.now();
Instant end = now.plusSeconds(EXPIRY);
return this.createToken(List.of(), user.getDefaultRole(), String.valueOf(user.getId()), now, end);
}
private String createToken(List<Long> ruleList, DefaultUserRuleEnum userDefaultRule, String userId, Instant start, Instant end) {
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plusSeconds(expiry))
.subject(user.getId() + "")//此处实际为用户id(数据库记录id)
// .claim("scope", scope)
.issuedAt(start)
.expiresAt(end)
.claims((d) -> {
d.put(LoginUserAttr.ROLES, ruleList);
if (userDefaultRule == DefaultUserRuleEnum.ADMIN) {
d.put(LoginUserAttr.DEFAULTS, "admin");
}
})
.subject(userId)//此处实际为用户id(数据库记录id)
.build();
// 使用默认的RS256生成jwt
final String token = this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
return token;
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
@Transactional
@ -78,4 +109,30 @@ public class UserService {
this.authRoleUserRefRepository.saveBatch(refList);
}
}
public UserInfoAuthDTO userInfo(JwtAuthenticationToken authToken) {
Object iat = authToken.getTokenAttributes().get(JwtClaimNames.IAT);
Object exp = authToken.getTokenAttributes().get(JwtClaimNames.EXP);
Object defulatRole = authToken.getTokenAttributes().get(LoginUserAttr.DEFAULTS);
DefaultUserRuleEnum userDefulatRole = Objects.nonNull(defulatRole) ? DefaultUserRuleEnum.ADMIN : DefaultUserRuleEnum.USER;
long remainingSecond = 0;
List<AuthRole> roleList = null;
if (Objects.nonNull(iat) && !Objects.nonNull(exp)) {
Instant iatInstant = (Instant) iat;
Instant expInstant = (Instant) exp;
remainingSecond = expInstant.getEpochSecond() - iatInstant.getEpochSecond();
roleList = this.authRoleRepository.getAuthRoleByUserId(authToken.getName());
}
return new UserInfoAuthDTO(remainingSecond, roleList, userDefulatRole);
}
public UserTokenDTO refreshToken(JwtAuthenticationToken authToken) {
Object defulatRole = authToken.getTokenAttributes().get(LoginUserAttr.DEFAULTS);
DefaultUserRuleEnum userDefulatRole = Objects.nonNull(defulatRole) ? DefaultUserRuleEnum.ADMIN : DefaultUserRuleEnum.USER;
Instant now = Instant.now();
Instant end = now.plusSeconds(EXPIRY);
String token = this.createToken(List.of(), userDefulatRole, authToken.getName(), now, end);
return new UserTokenDTO(token, end.getEpochSecond() - now.getEpochSecond());
}
}

View File

@ -1,10 +1,12 @@
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.3.233:3306/xian-ncc-da?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
# url: jdbc:mysql://192.168.3.233:3306/xian-ncc-da?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
# username: root
# password: joylink0503
url: jdbc:mysql://127.0.0.1:3306/xian-ncc-da?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: root
password: joylink0503
password: root
logging:
level:
root: info
@ -12,14 +14,24 @@ logging:
com.zaxxer.hikari: debug
file:
path: /usr/local/joylink/logs/xianncc
occ:
host: localhost
realPort: 2603
unRealPort: 123
lineId: 3
collectorData: false
occ-client:
clientInfoMap:
3:
server-host: 127.0.0.1
real-port: 2603
un-real-port: 5703
line-id: 3
collector-data: false
monitor-handware-change: false
receiveMsgTimeout: 6
filterRtuIds:
- 81
- 82
nameChanger: UNIVERSAL
#故障测试
mock-alert-test: true
mock-alert-test: false
#加载历史模拟数据
load-mock-history-data: false
#延时加载告警处理

View File

@ -13,11 +13,19 @@ logging:
file:
path: /usr/local/joylink/logs/xianncc
occ:
host: localhost
realPort: 2603
unRealPort: 123
lineId: 3
collectorData: false
clientInfoMap:
3:
nameChanger: UNIVERSAL
server-host: 127.0.0.1
real-port: 2603
un-real-port: 5703
line-id: 3
collector-data: false
monitor-handware-change: false
receiveMsgTimeout: 6
filterRtuIds:
- 81
- 82
#故障测试
mock-alert-test: true
#加载历史模拟数据

View File

@ -15,14 +15,22 @@ logging:
path: /usr/xianncc
max-size: 40MB
occ:
host: 127.0.0.1
realPort: 2603
# host: 10.255.11.15
# realPort: 5603
unRealPort: 5703
lineId: 3
collectorData: false
occ-client:
clientInfoMap:
3:
server-host: 127.0.0.1
real-port: 2603
un-real-port: 5703
line-id: 3
collector-data: false
monitor-handware-change: false
receiveMsgTimeout: 6
filterRtuIds:
- 81
- 82
nameChanger: UNIVERSAL
mock-alert-test: true
load-mock-history-data: false
#延时加载告警处理

View File

@ -19,12 +19,20 @@ logging:
club.joylink.xiannccda.ats.message.line3.rep: debug
club.joylink.xiannccda.mapper: debug
com.zaxxer.hikari: debug
occ:
host: 10.255.11.15
realPort: 5603
unRealPort: 5703
lineId: 3
collectorData: false
occ-client:
clientInfoMap:
3:
nameChanger: UNIVERSAL
server-host: 10.255.11.15
real-port: 5603
un-real-port: 5703
collector-data: false
monitor-handware-change: false
receiveMsgTimeout: 6
filterRtuIds:
- 81
- 82
mock-alert-test: false
load-mock-history-data: false
#延时加载告警处理

View File

@ -16,12 +16,20 @@ logging:
level:
root: "info"
occ:
host: 10.255.11.15
realPort: 5603
unRealPort: 5703
lineId: 3
collectorData: false
occ-client:
clientInfoMap:
3:
nameChanger: UNIVERSAL
server-host: 10.255.11.15
real-port: 5603
un-real-port: 5703
collector-data: false
monitor-handware-change: false
receiveMsgTimeout: 6
filterRtuIds:
- 81
- 82
mock-alert-test: false
load-mock-history-data: false
#延时加载告警处理

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="club.joylink.xiannccda.mapper.AuthApiPathMapper">
<select id="findByApiPathByRoleId" parameterType="long" resultType="club.joylink.xiannccda.entity.AuthApiPath">
select *
from auth_api_path
where id in (select api_id from auth_role_api_ref where role_id = #{roleId})
</select>
</mapper>

View File

@ -19,4 +19,13 @@
on A.id = B.role_id
where 1 = 1
</select>
<select id="getAuthRoleByUserId" resultType="club.joylink.xiannccda.entity.AuthRole">
select A.*
from auth_role A
left join auth_role_user_ref B on A.id = B.role_id
where 1 = 1
and B.user_id = ${userId}
</select>
</mapper>

View File

@ -2,7 +2,18 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="club.joylink.xiannccda.mapper.EventLogMapper">
<select id="detailPage" resultType="club.joylink.xiannccda.dto.event.EventLogPageDTO">
select A.id, A.event_type, A.create_date_time, A.from_user_id, B.`name` as user_name, B.mobile
select A.id,
A.face_name,
A.event_type,
A.sub_event_type,
A.uri,
A.method,
A.parameters,
A.create_date_time,
A.from_user_id,
A.request_success,
B.`name` as user_name,
B.mobile
from event_log A
left join user B on A.from_user_id = B.id
where 1 = 1

View File

@ -13,11 +13,10 @@
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id
, name, mobile, password, register_time
id, name, mobile, password, register_time
</sql>
<select id="detailQuery" resultType="club.joylink.xiannccda.dto.user.UserDetailDTO">
select A.id, A.name, A.mobile, A.register_time, B.user_roles
<select id="detailQuery" resultType="club.joylink.xiannccda.dto.user.UserDetailDTO" parameterType="club.joylink.xiannccda.dto.user.UserQueryDTO">
select A.id, A.name, A.mobile, A.register_time, B.user_roles,A.default_role
from user A
left join (select A.user_id, GROUP_CONCAT(A.role_id, '|', B.`name`) as user_roles
from auth_role_user_ref A
@ -25,5 +24,11 @@
GROUP BY user_id) B
on A.id = B.user_id
where 1 = 1
<if test="dto.mobile != null">
and A.mobile = #{dto.mobile}
</if>
<if test="dto.password != null">
and A.password = #{dto.password}
</if>
</select>
</mapper>

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.device;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataOperate;
import club.joylink.xiannccda.ats.message.collect.DeviceStatusDataRepository;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
@ -136,7 +137,7 @@ public class DeviceStatusTest {
Set<Integer> rtuSet = new HashSet<>();
for (MessageResponse messageDatum : messageData) {
List<? extends GeneratedMessageV3.Builder> msgs = messageDatum.generateProto();
List<? extends GeneratedMessageV3.Builder> msgs = messageDatum.generateProto(NameChangerEnum.UNIVERSAL);
for (Builder msg : msgs) {
Integer rtuId = DeviceStatusDataOperate.findFieldVal(msg, "rtuId", Integer.class);
rtuSet.add(rtuId);

View File

@ -3,6 +3,7 @@ package club.joylink.xiannccda.device;
import club.joylink.xiannccda.ats.message.MessageData;
import club.joylink.xiannccda.ats.message.MessageId;
import club.joylink.xiannccda.ats.message.MessageResponse;
import club.joylink.xiannccda.ats.message.changer.NameChangerEnum;
import club.joylink.xiannccda.ats.message.convertor.DeviceStatusConvertor;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus;
import club.joylink.xiannccda.ats.message.line3.device.DeviceStatus.PLATFORM;
@ -205,9 +206,9 @@ public class TrainDataTest {
List<MessageResponse> messageData = this.dataService.loadALLData(wrapper);
for (MessageResponse messageDatum : messageData) {
List<? extends GeneratedMessageV3.Builder> msgs = messageDatum.generateProto();
List<? extends GeneratedMessageV3.Builder> msgs = messageDatum.generateProto(NameChangerEnum.UNIVERSAL);
System.out.println(messageDatum);
System.out.println(messageDatum.generateProto());
System.out.println(messageDatum.generateProto(NameChangerEnum.UNIVERSAL));
}
}

View File

@ -1,6 +1,6 @@
package club.joylink.xiannccda.util;
import club.joylink.xiannccda.ats.message.line3.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.changer.DeviceNameChangerManage;
import club.joylink.xiannccda.ats.message.line3.device.DeviceType;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
@ -86,7 +86,7 @@ public abstract class Device {
@Override
public String changeDeviceName(String nccDeviceName) {
return DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_SWITCH, nccDeviceName);
return DeviceNameChangerManage.findMatch(3, DeviceType.DEVICE_TYPE_SWITCH, nccDeviceName);
}
}
@ -114,10 +114,8 @@ public abstract class Device {
@Override
String changeDeviceName(String nccDeviceName) {
if (StringUtils.equals(nccDeviceName, "T13301C")) {
System.out.println("aaaaaaaaaaaaaa");
}
return DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_TRACK, nccDeviceName);
return DeviceNameChangerManage.findMatch(3, DeviceType.DEVICE_TYPE_TRACK, nccDeviceName);
}
}
@ -131,7 +129,7 @@ public abstract class Device {
@Override
String changeDeviceName(String nccDeviceName) {
return DeviceNameChangerManage.findMatch(DeviceType.DEVICE_TYPE_SIGNAL, nccDeviceName);
return DeviceNameChangerManage.findMatch(3, DeviceType.DEVICE_TYPE_SIGNAL, nccDeviceName);
}
}