审计日志入库完成

This commit is contained in:
2022-07-14 19:27:23 +08:00
parent f58dda8534
commit e93a3c1e08
6 changed files with 120 additions and 73 deletions

View File

@@ -54,10 +54,10 @@ public class UserTokenService {
* @param oAuth2AccessToken 认证后的最新token信息 * @param oAuth2AccessToken 认证后的最新token信息
*/ */
@Async("asyncExecutor") @Async("asyncExecutor")
public void recordUserInfo(OAuth2AccessToken oAuth2AccessToken,String ip) { public void recordUserInfo(OAuth2AccessToken oAuth2AccessToken, String ip) {
UserTokenInfo userTokenInfo = new UserTokenInfo(); UserTokenInfo userTokenInfo = new UserTokenInfo();
String accessTokenValue = oAuth2AccessToken.getValue(); String accessTokenValue = oAuth2AccessToken.getValue();
JWSObject accessJwsObject ; JWSObject accessJwsObject;
try { try {
accessJwsObject = JWSObject.parse(accessTokenValue); accessJwsObject = JWSObject.parse(accessTokenValue);
} catch (ParseException e) { } catch (ParseException e) {
@@ -66,6 +66,7 @@ public class UserTokenService {
JSONObject accessJson = JSONUtil.parseObj(accessJwsObject.getPayload().toString()); JSONObject accessJson = JSONUtil.parseObj(accessJwsObject.getPayload().toString());
String userIndex = accessJson.getStr(SecurityConstants.USER_INDEX_KEY); String userIndex = accessJson.getStr(SecurityConstants.USER_INDEX_KEY);
String nickName = accessJson.getStr(SecurityConstants.USER_NICKNAME_KEY); String nickName = accessJson.getStr(SecurityConstants.USER_NICKNAME_KEY);
String loginName = accessJson.getStr(SecurityConstants.USER_NAME_KEY);
//查询是否有在线的当前用户 //查询是否有在线的当前用户
String onlineUserKey = SecurityConstants.TOKEN_ONLINE_PREFIX + userIndex; String onlineUserKey = SecurityConstants.TOKEN_ONLINE_PREFIX + userIndex;
Object onlineTokenInfoOld = redisUtil.getObjectByKey(onlineUserKey); Object onlineTokenInfoOld = redisUtil.getObjectByKey(onlineUserKey);
@@ -86,7 +87,7 @@ public class UserTokenService {
} }
String accessJti = accessJson.getStr(SecurityConstants.JWT_JTI); String accessJti = accessJson.getStr(SecurityConstants.JWT_JTI);
OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken(); OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
JWSObject refreshJwsObject ; JWSObject refreshJwsObject;
try { try {
refreshJwsObject = JWSObject.parse(refreshToken.getValue()); refreshJwsObject = JWSObject.parse(refreshToken.getValue());
} catch (ParseException e) { } catch (ParseException e) {
@@ -97,13 +98,13 @@ public class UserTokenService {
Long refreshExpireTime = refreshJson.getLong(SecurityConstants.JWT_EXP); Long refreshExpireTime = refreshJson.getLong(SecurityConstants.JWT_EXP);
userTokenInfo.setAccessTokenJti(accessJti); userTokenInfo.setAccessTokenJti(accessJti);
userTokenInfo.setRefreshToken(refreshToken.getValue()); userTokenInfo.setRefreshToken(refreshToken.getValue());
LocalDateTime refreshLifeTime =LocalDateTime.ofEpochSecond(refreshExpireTime,0,ZoneOffset.of("+8")); LocalDateTime refreshLifeTime = LocalDateTime.ofEpochSecond(refreshExpireTime, 0, ZoneOffset.of("+8"));
userTokenInfo.setRefreshTokenExpire(refreshLifeTime); userTokenInfo.setRefreshTokenExpire(refreshLifeTime);
//生命周期在refreshToken的基础上延迟5分钟 //生命周期在refreshToken的基础上延迟5分钟
redisUtil.saveByKeyWithExpire(onlineUserKey, userTokenInfo, refreshLifeTime.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); redisUtil.saveByKeyWithExpire(onlineUserKey, userTokenInfo, refreshLifeTime.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
//记录成功登录后的信息 //记录成功登录后的信息
LogInfoDTO logInfoDTO = new LogInfoDTO(nickName, ip, "登录认证", OperateType.AUTHENTICATE, 1, "",0, 1, generalInfo.getMicroServiceName(), userIndex); LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, nickName, ip, "登录认证", OperateType.AUTHENTICATE, 1, "", 0, 1, generalInfo.getMicroServiceName(), userIndex);
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false); publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false);
} }
@@ -126,7 +127,7 @@ public class UserTokenService {
if (CollectionUtils.isNotEmpty(blackUsers)) { if (CollectionUtils.isNotEmpty(blackUsers)) {
blackUsers.forEach(temp -> { blackUsers.forEach(temp -> {
//存在当前的刷新token则抛出业务异常 //存在当前的刷新token则抛出业务异常
if(temp.getRefreshToken().equalsIgnoreCase(refreshToken)){ if (temp.getRefreshToken().equalsIgnoreCase(refreshToken)) {
throw new BusinessException(CommonResponseEnum.TOKEN_EXPIRE_JWT); throw new BusinessException(CommonResponseEnum.TOKEN_EXPIRE_JWT);
} }
}); });

View File

@@ -21,8 +21,14 @@ public class LogInfoDTO implements Serializable {
/** /**
* 登录名 * 登录名
*/ */
private String loginName;
/**
* 用户已登录:用户名
*/
private String userName; private String userName;
private String ip; private String ip;
private String operate; private String operate;

View File

@@ -57,14 +57,17 @@ public class LogServiceImpl implements ILogService {
@Async("asyncExecutor") @Async("asyncExecutor")
public void recodeAdviceLog(ServerHttpRequest request, MethodParameter returnType, HttpResult httpResult, String methodDescribe) { public void recodeAdviceLog(ServerHttpRequest request, MethodParameter returnType, HttpResult httpResult, String methodDescribe) {
//处理审计日志 //处理审计日志
String loginName;
String userName; String userName;
String userIndex ; String userIndex;
HttpServletRequest httpServletRequest = RequestUtil.getRequest(request); HttpServletRequest httpServletRequest = RequestUtil.getRequest(request);
if (UN_LOGIN_METHOD.contains(methodDescribe)) { if (UN_LOGIN_METHOD.contains(methodDescribe)) {
userName = RequestUtil.getLoginName(httpServletRequest); loginName = RequestUtil.getLoginName(httpServletRequest);
userName = "";
userIndex = userName; userIndex = userName;
} else { } else {
userName = RequestUtil.getLoginName(request); loginName = RequestUtil.getLoginNameByPayload(request);
userName = RequestUtil.getUserNickname(request);
userIndex = RequestUtil.getUserIndex(request); userIndex = RequestUtil.getUserIndex(request);
} }
String result = httpResult.getCode().equalsIgnoreCase(CommonResponseEnum.FAIL.getCode()) ? CommonResponseEnum.FAIL.getMessage() : CommonResponseEnum.SUCCESS.getMessage(); String result = httpResult.getCode().equalsIgnoreCase(CommonResponseEnum.FAIL.getCode()) ? CommonResponseEnum.FAIL.getMessage() : CommonResponseEnum.SUCCESS.getMessage();
@@ -72,7 +75,7 @@ public class LogServiceImpl implements ILogService {
String type = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateType(); String type = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateLevel(); String level = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(returnType.getMethod()); String operateType = ReflectCommonUtil.getOperateTypeByMethod(returnType.getMethod());
LogInfoDTO logInfoDTO = new LogInfoDTO(userName, ip, methodDescribe, operateType, result.equalsIgnoreCase("失败") ? 0 : 1, "",levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex); LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, userName, ip, methodDescribe, operateType, result.equalsIgnoreCase("失败") ? 0 : 1, "", levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex);
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false); publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false);
} }
@@ -90,10 +93,11 @@ public class LogServiceImpl implements ILogService {
LogInfoDTO tempLogInfo = RequestUtil.initLogInfo(request); LogInfoDTO tempLogInfo = RequestUtil.initLogInfo(request);
//认证前,获取用户信息 //认证前,获取用户信息
String userIndex; String userIndex;
if (Objects.equals(tempLogInfo.getUserName(), LogInfo.UNKNOWN_USER)) { if (Objects.equals(tempLogInfo.getLoginName(), LogInfo.UNKNOWN_USER)) {
tempLogInfo.setUserName(RequestUtil.getLoginName(request)); tempLogInfo.setLoginName(RequestUtil.getLoginName(request));
userIndex = tempLogInfo.getUserName(); tempLogInfo.setUserName("");
}else{ userIndex = tempLogInfo.getLoginName();
} else {
userIndex = RequestUtil.getUserIndex(request); userIndex = RequestUtil.getUserIndex(request);
} }
//根据异常获取method方法 //根据异常获取method方法
@@ -106,7 +110,7 @@ public class LogServiceImpl implements ILogService {
String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType(); String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel(); String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method); String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
LogInfoDTO logInfoDTO = new LogInfoDTO(tempLogInfo.getUserName(), tempLogInfo.getIp(), ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1,message, levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex); LogInfoDTO logInfoDTO = new LogInfoDTO(tempLogInfo.getLoginName(), tempLogInfo.getUserName(), tempLogInfo.getIp(), ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1, message, levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex);
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false); publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
} }
@@ -116,11 +120,11 @@ public class LogServiceImpl implements ILogService {
* @param exception 异常数据 * @param exception 异常数据
* @param request 请求信息 * @param request 请求信息
* @param message 信息 * @param message 信息
* @param userName 用户 * @param loginName 登录
*/ */
@Override @Override
@Async("asyncExecutor") @Async("asyncExecutor")
public void recodeAuthExceptionLog(Exception exception, HttpServletRequest request, String message, String userName) { public void recodeAuthExceptionLog(Exception exception, HttpServletRequest request, String message, String loginName) {
//根据异常获取method方法 //根据异常获取method方法
Method method = ReflectCommonUtil.getMethod(exception); Method method = ReflectCommonUtil.getMethod(exception);
if (exception instanceof MethodArgumentNotValidException) { if (exception instanceof MethodArgumentNotValidException) {
@@ -132,7 +136,7 @@ public class LogServiceImpl implements ILogService {
String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType(); String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel(); String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method); String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
LogInfoDTO logInfoDTO = new LogInfoDTO(userName, ip, ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1,message, levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userName); LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, "", ip, ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1, message, levelStringToNumber(level), type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), loginName);
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false); publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
} }

View File

@@ -331,6 +331,19 @@ public class RequestUtil {
return StrUtil.isBlank(loginName) ? LogInfo.UNKNOWN_USER : loginName; return StrUtil.isBlank(loginName) ? LogInfo.UNKNOWN_USER : loginName;
} }
/**
* ServerHttpRequest获取在网关中存储的用户昵称
*/
public static String getLoginNameByPayload(ServerHttpRequest request) {
String loginName = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String loginNameTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
loginName = StrUtil.isBlank(loginNameTemp) ? LogInfo.UNKNOWN_USER : loginNameTemp;
}
return loginName;
}
/** /**
* ServerHttpRequest获取用户登录名 * ServerHttpRequest获取用户登录名
*/ */
@@ -376,11 +389,15 @@ public class RequestUtil {
LogInfoDTO temp = new LogInfoDTO(); LogInfoDTO temp = new LogInfoDTO();
temp.setIp(StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip); temp.setIp(StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip);
String username = LogInfo.UNKNOWN_USER; String username = LogInfo.UNKNOWN_USER;
String loginName = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request); JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) { if (Objects.nonNull(jwtPayload)) {
String userSignTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY); String loginNameTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
username = StrUtil.isBlank(userSignTemp) ? LogInfo.UNKNOWN_USER : userSignTemp; loginName = StrUtil.isBlank(loginNameTemp) ? LogInfo.UNKNOWN_USER : loginNameTemp;
String userNameTemp = jwtPayload.getString(SecurityConstants.USER_NICKNAME_KEY);
username = StrUtil.isBlank(userNameTemp) ? LogInfo.UNKNOWN_USER : userNameTemp;
} }
temp.setLoginName(loginName);
temp.setUserName(username); temp.setUserName(username);
return temp; return temp;
} }

View File

@@ -68,9 +68,9 @@ public class TransientServiceImpl implements TransientService {
if (!CollectionUtils.isEmpty(deviceList)) { if (!CollectionUtils.isEmpty(deviceList)) {
List<List<String>> lists = deviceList.stream().map(GeneralDeviceDTO::getLineIndexes).collect(Collectors.toList()); List<List<String>> lists = deviceList.stream().map(GeneralDeviceDTO::getLineIndexes).collect(Collectors.toList());
List<String> lineList = new ArrayList<>(); List<String> lineList = new ArrayList<>();
for (int i = 0; i<lists.size(); i++) { for (int i = 0; i < lists.size(); i++) {
List<String> strings1 = lists.get(i); List<String> strings1 = lists.get(i);
for (int a = 0; a<strings1.size(); a++) { for (int a = 0; a < strings1.size(); a++) {
lineList.add(strings1.get(a)); lineList.add(strings1.get(a));
} }
} }
@@ -79,10 +79,10 @@ public class TransientServiceImpl implements TransientService {
List<EventDetail> data = eventDetailService.getEventDetail(lineList, transientParam.getSearchBeginTime(), transientParam.getSearchEndTime()); List<EventDetail> data = eventDetailService.getEventDetail(lineList, transientParam.getSearchBeginTime(), transientParam.getSearchEndTime());
page.setTotal(data.size()); page.setTotal(data.size());
//分页总页数 //分页总页数
int pages = (int)Math.ceil(data.size()*1.0/transientParam.getPageSize()); int pages = (int) Math.ceil(data.size() * 1.0 / transientParam.getPageSize());
page.setPages(pages); page.setPages(pages);
//influxDB分页查询 //influxDB分页查询
List<EventDetail> eventDetailData = eventDetailService.getEventDetailLimit(lineList, transientParam.getSearchBeginTime(), transientParam.getSearchEndTime(), transientParam.getPageSize(), transientParam.getPageNum()); List<EventDetail> eventDetailData = eventDetailService.getEventDetailLimit(lineList, transientParam.getSearchBeginTime(), transientParam.getSearchEndTime(), transientParam.getPageSize(), transientParam.getPageNum());
// List<List<EventDetail>> partition = Lists.partition(eventDetailData, transientParam.getPageSize()); // List<List<EventDetail>> partition = Lists.partition(eventDetailData, transientParam.getPageSize());
// List<EventDetail> detailList = partition.get(transientParam.getPageNum() - 1); // List<EventDetail> detailList = partition.get(transientParam.getPageNum() - 1);
if (!CollectionUtils.isEmpty(eventDetailData)) { if (!CollectionUtils.isEmpty(eventDetailData)) {
@@ -90,7 +90,7 @@ public class TransientServiceImpl implements TransientService {
collect = collect.stream().distinct().collect(Collectors.toList()); collect = collect.stream().distinct().collect(Collectors.toList());
List<TransientVO> transientData = transientMapper.getTransientData(collect); List<TransientVO> transientData = transientMapper.getTransientData(collect);
int i = 1; int i = 1;
for (EventDetail eventDetail: eventDetailData) { for (EventDetail eventDetail : eventDetailData) {
if (!Objects.isNull(eventDetail)) { if (!Objects.isNull(eventDetail)) {
TransientVO transientVO = new TransientVO(); TransientVO transientVO = new TransientVO();
transientVO.setId(eventDetail.getLineId()); transientVO.setId(eventDetail.getLineId());
@@ -127,9 +127,9 @@ public class TransientServiceImpl implements TransientService {
break; break;
} }
Double value = new BigDecimal(eventDetail.getEventValue()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue(); Double value = new BigDecimal(eventDetail.getEventValue()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
transientVO.setEventValue(new BigDecimal(value*100).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue()); transientVO.setEventValue(new BigDecimal(value * 100).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
transientVO.setEventValues(100-transientVO.getEventValue()); transientVO.setEventValues(100 - transientVO.getEventValue());
transientVO.setPersistTime((Float.parseFloat(eventDetail.getPersistTime().toString()))/1000); transientVO.setPersistTime((Float.parseFloat(eventDetail.getPersistTime().toString())) / 1000);
Float eventValue = Float.parseFloat(eventDetail.getEventValue().toString()); Float eventValue = Float.parseFloat(eventDetail.getEventValue().toString());
Float persistTime = Float.parseFloat(eventDetail.getPersistTime().toString()); Float persistTime = Float.parseFloat(eventDetail.getPersistTime().toString());
@@ -174,7 +174,7 @@ public class TransientServiceImpl implements TransientService {
// waveDataVO.setName("变电站名称: "+ substation +" 监测点名称: "+ name +" 发生时刻: "+ timeId +" 暂降幅值: "+ v +"% 持续时间: "+ persistTime +"s"); // waveDataVO.setName("变电站名称: "+ substation +" 监测点名称: "+ name +" 发生时刻: "+ timeId +" 暂降幅值: "+ v +"% 持续时间: "+ persistTime +"s");
// waveDataVO.setTargetName("相电压有效值"); // waveDataVO.setTargetName("相电压有效值");
AnalyWave analyWave = new AnalyWave(); AnalyWave analyWave = new AnalyWave();
WaveDataDTO comtrade = analyWave.getComtrade(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".CFG", 1); WaveDataDTO comtrade = analyWave.getComtrade(eventBaseConfig.getWavePath() + File.separator + ip + File.separator + waveName + ".CFG", 1);
if (Objects.isNull(comtrade.getComtradeCfgDTO())) { if (Objects.isNull(comtrade.getComtradeCfgDTO())) {
throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND); throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND);
} }
@@ -185,8 +185,8 @@ public class TransientServiceImpl implements TransientService {
double pt2 = Double.parseDouble(lineDetailData.getPt().split("/")[1]); double pt2 = Double.parseDouble(lineDetailData.getPt().split("/")[1]);
double ct1 = Double.parseDouble(lineDetailData.getCt().split("/")[0]); double ct1 = Double.parseDouble(lineDetailData.getCt().split("/")[0]);
double ct2 = Double.parseDouble(lineDetailData.getCt().split("/")[1]); double ct2 = Double.parseDouble(lineDetailData.getCt().split("/")[1]);
waveDataDTO.setPt(pt1/pt2); waveDataDTO.setPt(pt1 / pt2);
waveDataDTO.setCt(ct1/ct2); waveDataDTO.setCt(ct1 / ct2);
return waveDataDTO; return waveDataDTO;
} }
@@ -195,7 +195,7 @@ public class TransientServiceImpl implements TransientService {
public HttpServletResponse downloadWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception { public HttpServletResponse downloadWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception {
List<String> lineId = waveFileParam.getLineId(); List<String> lineId = waveFileParam.getLineId();
List<String> timeId = waveFileParam.getTimeId(); List<String> timeId = waveFileParam.getTimeId();
copyTempData(timeId,lineId); copyTempData(timeId, lineId);
zipCompress(new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade")); zipCompress(new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade"));
String zipPath = "C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade.zip"; String zipPath = "C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade.zip";
@@ -229,9 +229,11 @@ public class TransientServiceImpl implements TransientService {
return response; return response;
} }
/**复制保存文件 */ /**
* 复制保存文件
*/
public void copyTempData(List<String> timeId, List<String> lineId) throws IOException { public void copyTempData(List<String> timeId, List<String> lineId) throws IOException {
for (int i=0; i<timeId.size(); i++) { for (int i = 0; i < timeId.size(); i++) {
//根据监测点id获取监测点详情 //根据监测点id获取监测点详情
LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId.get(i)).getData(); LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId.get(i)).getData();
EventDetail eventDetailByTime = eventDetailService.getEventDetailByTime(lineId.get(i), timeId.get(i)); EventDetail eventDetailByTime = eventDetailService.getEventDetailByTime(lineId.get(i), timeId.get(i));
@@ -240,29 +242,30 @@ public class TransientServiceImpl implements TransientService {
} }
String ip = lineDetailData.getIp(); String ip = lineDetailData.getIp();
String waveName = eventDetailByTime.getWaveName(); String waveName = eventDetailByTime.getWaveName();
File srcCFGFile = new File(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".CFG"); File srcCFGFile = new File(eventBaseConfig.getWavePath() + "\\" + ip + "\\" + waveName + ".CFG");
File srcDATFile = new File(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".DAT"); File srcDATFile = new File(eventBaseConfig.getWavePath() + "\\" + ip + "\\" + waveName + ".DAT");
if (!srcCFGFile.exists() && !srcDATFile.exists()) { if (!srcCFGFile.exists() && !srcDATFile.exists()) {
throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND); throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND);
} }
File temp = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip); File temp = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\" + ip);
temp.mkdirs(); temp.mkdirs();
// File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcCFGFile.getName()); // File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcCFGFile.getName());
// File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcDATFile.getName()); // File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcDATFile.getName());
File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip+"\\"+srcCFGFile.getName()); File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\" + ip + "\\" + srcCFGFile.getName());
File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip+"\\"+srcDATFile.getName()); File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\" + ip + "\\" + srcDATFile.getName());
writeFile(srcCFGFile,cfg); writeFile(srcCFGFile, cfg);
writeFile(srcDATFile,dat); writeFile(srcDATFile, dat);
} }
} }
//读写文件 //读写文件
public static void writeFile(File wave, File temp) throws IOException { public static void writeFile(File wave, File temp) throws IOException {
FileInputStream fis=new FileInputStream(wave); FileInputStream fis = new FileInputStream(wave);
FileOutputStream fos=new FileOutputStream(temp); FileOutputStream fos = new FileOutputStream(temp);
int len; int len;
byte[] bys=new byte[1024]; byte[] bys = new byte[1024];
while((len=fis.read(bys))!=-1){ while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len); fos.write(bys, 0, len);
fos.flush(); fos.flush();
} }
@@ -276,72 +279,75 @@ public class TransientServiceImpl implements TransientService {
/** /**
* 将文件夹及文件夹包含的内容压缩成zip文件 * 将文件夹及文件夹包含的内容压缩成zip文件
* (为了解决中文乱码的问题ZipOutputStream用org.apache.tools.zip.*) * (为了解决中文乱码的问题ZipOutputStream用org.apache.tools.zip.*)
*
* @param inputFile 源文件(夹) * @param inputFile 源文件(夹)
* @return File 压缩后的文件(路径在源文件的文件夹路径下) * @return File 压缩后的文件(路径在源文件的文件夹路径下)
*/ */
public static File zipCompress(File inputFile) throws Exception { public static File zipCompress(File inputFile) throws Exception {
File zipFile = null; File zipFile = null;
ZipOutputStream zos = null; ZipOutputStream zos = null;
if(inputFile != null && inputFile.exists()) { if (inputFile != null && inputFile.exists()) {
try { try {
String path = inputFile.getCanonicalPath(); String path = inputFile.getCanonicalPath();
String zipFileName = path + ".zip"; String zipFileName = path + ".zip";
zipFile = new File(zipFileName); zipFile = new File(zipFileName);
if(zipFile.exists()) { if (zipFile.exists()) {
zipFile.delete(); zipFile.delete();
} }
zipFile.createNewFile();//创建文件 zipFile.createNewFile();//创建文件
zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos = new ZipOutputStream(new FileOutputStream(zipFile));
//压缩文件或文件夹 //压缩文件或文件夹
compressFile(zos, inputFile, inputFile.getName()); compressFile(zos, inputFile, inputFile.getName());
}catch(Exception e) { } catch (Exception e) {
System.out.println("文件压缩异常:" + e); System.out.println("文件压缩异常:" + e);
throw e; throw e;
}finally { } finally {
try { try {
if(zos != null) { if (zos != null) {
//先调用outputStream的flush()再关闭流; //先调用outputStream的flush()再关闭流;
//流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象 //流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
zos.flush(); zos.flush();
zos.close(); zos.close();
} }
}catch(Exception ex) { } catch (Exception ex) {
System.out.println("输出流关闭异常:" + ex); System.out.println("输出流关闭异常:" + ex);
} }
} }
} }
return zipFile; return zipFile;
} }
/** /**
* 压缩文件或文件夹 (ZipEntry 使用org.apache.tools.zip.*,不要用 java.util.zip.*) * 压缩文件或文件夹 (ZipEntry 使用org.apache.tools.zip.*,不要用 java.util.zip.*)
* @param zos zip输出流 *
* @param zos zip输出流
* @param sourceFile 源文件 * @param sourceFile 源文件
* @param baseName 父路径 * @param baseName 父路径
* @throws Exception 异常 * @throws Exception 异常
*/ */
public static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception{ public static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception {
if(!sourceFile.exists()) { if (!sourceFile.exists()) {
return; return;
} }
//若路径为目录(文件夹) //若路径为目录(文件夹)
if(sourceFile.isDirectory()) { if (sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹) //取出文件夹中的文件(或子文件夹)
File[] fileList = sourceFile.listFiles(); File[] fileList = sourceFile.listFiles();
//若文件夹为空,则创建一个目录进入点 //若文件夹为空,则创建一个目录进入点
if(fileList.length == 0) { if (fileList.length == 0) {
//文件名称后跟File.separator表示这是一个文件夹 //文件名称后跟File.separator表示这是一个文件夹
zos.putNextEntry(new ZipEntry(baseName + File.separator)); zos.putNextEntry(new ZipEntry(baseName + File.separator));
//若文件夹非空则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩 //若文件夹非空则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
}else { } else {
for(int i = 0; i < fileList.length; i++) { for (int i = 0; i < fileList.length; i++) {
compressFile(zos, fileList[i], compressFile(zos, fileList[i],
baseName + File.separator + fileList[i].getName()); baseName + File.separator + fileList[i].getName());
} }
} }
//若为文件,则先创建目录进入点,再将文件写入zip文件中 //若为文件,则先创建目录进入点,再将文件写入zip文件中
}else { } else {
ZipEntry ze = new ZipEntry(baseName); ZipEntry ze = new ZipEntry(baseName);
//设置ZipEntry的最后修改时间为源文件的最后修改时间 //设置ZipEntry的最后修改时间为源文件的最后修改时间
ze.setTime(sourceFile.lastModified()); ze.setTime(sourceFile.lastModified());
@@ -350,27 +356,29 @@ public class TransientServiceImpl implements TransientService {
FileInputStream fis = new FileInputStream(sourceFile); FileInputStream fis = new FileInputStream(sourceFile);
copyStream(fis, zos); copyStream(fis, zos);
try { try {
if(fis != null) { if (fis != null) {
fis.close(); fis.close();
} }
}catch(Exception e) { } catch (Exception e) {
System.out.println("输入流关闭异常:" + e); System.out.println("输入流关闭异常:" + e);
} }
} }
} }
/** /**
* 流拷贝 * 流拷贝
* @param in 输入流 *
* @param in 输入流
* @param out 输出流 * @param out 输出流
* @throws IOException * @throws IOException
*/ */
public static void copyStream(InputStream in, OutputStream out) throws IOException{ public static void copyStream(InputStream in, OutputStream out) throws IOException {
int bufferLength = 1024 * 100; int bufferLength = 1024 * 100;
synchronized(in) { synchronized (in) {
synchronized(out) { synchronized (out) {
int count = 0; int count = 0;
byte[] buffer = new byte[bufferLength]; byte[] buffer = new byte[bufferLength];
while((count = in.read(buffer, 0, bufferLength)) != -1) { while ((count = in.read(buffer, 0, bufferLength)) != -1) {
out.write(buffer, 0, count); out.write(buffer, 0, count);
} }
out.flush(); out.flush();
@@ -380,14 +388,17 @@ public class TransientServiceImpl implements TransientService {
//================================================================================================================= //=================================================================================================================
/**处理文件路径和指定压缩包位置 */
/**
* 处理文件路径和指定压缩包位置
*/
public static String downloadWaveMoreFile(List<String> pathList) { public static String downloadWaveMoreFile(List<String> pathList) {
List<File> list = new ArrayList<>(); List<File> list = new ArrayList<>();
for (String string: pathList) { for (String string : pathList) {
String path = string; String path = string;
//待压缩的多个源文件 //待压缩的多个源文件
File f1 = new File(path+".CFG"); File f1 = new File(path + ".CFG");
File f2 = new File(path+".DAT"); File f2 = new File(path + ".DAT");
list.add(f1); list.add(f1);
list.add(f2); list.add(f2);
} }
@@ -401,6 +412,7 @@ public class TransientServiceImpl implements TransientService {
/** /**
* 压缩多个文件成一个zip文件 * 压缩多个文件成一个zip文件
*
* @param srcfile源文件列表 * @param srcfile源文件列表
* @param zipfile压缩后的文件 * @param zipfile压缩后的文件
*/ */
@@ -426,7 +438,9 @@ public class TransientServiceImpl implements TransientService {
} }
} }
/**删除文件(夹)和空文件夹 */ /**
* 删除文件(夹)和空文件夹
*/
private void deleteDirectoryLegacyIO(File file) { private void deleteDirectoryLegacyIO(File file) {
File[] list = file.listFiles(); //无法做到list多层文件夹数据 File[] list = file.listFiles(); //无法做到list多层文件夹数据
if (list != null) { if (list != null) {
@@ -443,6 +457,7 @@ public class TransientServiceImpl implements TransientService {
/** /**
* 删除文件 * 删除文件
*
* @param filePathAndName 指定得路径 * @param filePathAndName 指定得路径
*/ */
public static void delFile(String filePathAndName) { public static void delFile(String filePathAndName) {

View File

@@ -22,9 +22,13 @@ public class UserLog extends BaseEntity {
*/ */
private String id; private String id;
/**
* 登录名
*/
private String loginName;
/** /**
* 用户已登录:用户名 * 用户已登录:用户名
* 用户未登录:登录名
*/ */
private String userName; private String userName;