初始化

This commit is contained in:
2022-06-21 20:47:46 +08:00
parent b666a24a98
commit 59da3376c1
1246 changed files with 129600 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
package com.njcn.web.advice;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.utils.ReflectCommonUtil;
import com.njcn.web.utils.RequestUtil;
import com.njcn.web.service.ILogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年07月07日 16:46
*/
@Slf4j
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private GeneralInfo generalInfo;
@Autowired
private ILogService logService;
/**
* 无需审计记录的操作,比如根据客户端获取客户端信息
*/
private final static List<String> UN_LOG_INFO = Arrays.asList("根据客户端名查询信息","当前主题","未知业务");
/**
* controller返回的响应体包含的状态码而非全局异常捕获器处抛出来的状态码
*/
private final static List<String> FILTER_CODE = Arrays.asList(CommonResponseEnum.SUCCESS.getCode(), CommonResponseEnum.FAIL.getCode(), CommonResponseEnum.NO_DATA.getCode());
/**
* 判断下结果,是不是成功
*
* @param returnType 返回类型包含大量信息controller、method、result等等
* @param converterType 消息转换器类型目前配置的是Jackson
*/
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
/**
* 拦截所有请求成功的操作进行日志入库处理
* 需要 用户标识、事件描述、事件结果、操作IP、事件类型、事件严重度、操作时间、操作类型
*
* @param body .
* @param returnType .
* @param selectedContentType .
* @param selectedConverterType .
* @param request .
* @param response .
* @return .
*/
@Override
public Object beforeBodyWrite(Object body, @Nonnull MethodParameter returnType, @Nonnull MediaType selectedContentType, @Nonnull Class selectedConverterType, @Nonnull ServerHttpRequest request, @Nonnull ServerHttpResponse response) {
if (body instanceof HttpResult) {
HttpResult httpResult = (HttpResult) body;
if (FILTER_CODE.contains(httpResult.getCode())) {
String methodDescribe = ReflectCommonUtil.getMethodDescribeByMethod(returnType.getMethod());
if (!UN_LOG_INFO.contains(methodDescribe)) {
logService.recodeAdviceLog(request, returnType, httpResult, methodDescribe);
}
}
}
return body;
}
}

View File

@@ -0,0 +1,31 @@
package com.njcn.web.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.njcn.web.filter.XssFilter;
import com.njcn.web.filter.XssRequestWrapper;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* @author hongawen
* @version 1.0.0
* @createTime 2021年05月20日 17:00
*/
@Configuration
public class AntiSamyConfig {
/**
* 配置xss过滤器
*/
@Bean
public FilterRegistrationBean create() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new XssFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}
}

View File

@@ -0,0 +1,42 @@
package com.njcn.web.config;
import com.njcn.web.pojo.annotation.DateTimeStrValid;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;
/**
* pqs
*
* @author cdf
* @date 2022/1/11
*/
public class DateTimeValidator implements ConstraintValidator<DateTimeStrValid, String> {
private DateTimeStrValid dateTime;
@Override
public void initialize(DateTimeStrValid dateTime) {
this.dateTime = dateTime;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
String format = dateTime.format();
if (value.length() != format.length()) {
return false;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
simpleDateFormat.parse(value);
} catch (Exception e) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,64 @@
package com.njcn.web.config;
import com.nimbusds.jose.JWSObject;
import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.EnumUtils;
import com.njcn.common.utils.PubUtils;
import com.njcn.web.utils.RequestUtil;
import feign.RequestInterceptor;
import feign.Util;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Objects;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年08月24日 15:07
*/
@Configuration
@RequiredArgsConstructor
public class FeignConfig {
/**
* 自定义拦截器
*/
@Bean
public RequestInterceptor authTokenInterceptor() {
return template -> {
if(Objects.nonNull(RequestUtil.getRequest())){
String jwtPayload = RequestUtil.getRequest().getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
String realIp = RequestUtil.getRealIp();
template.header(SecurityConstants.JWT_PAYLOAD_KEY, jwtPayload);
template.header(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP, realIp);
}
};
}
/**
* 自定义openfeign的解码器
*/
@Bean
public Decoder feignDecoder() {
return (response, type) -> {
String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
//对结果进行转换
HttpResult<Object> result = PubUtils.json2obj(bodyStr, type);
//如果返回错误,且为内部错误,则直接抛出异常
CommonResponseEnum commonResponseEnum = EnumUtils.getCommonResponseEnumByCode(result.getCode());
switch (commonResponseEnum) {
case SUCCESS:
return result;
default:
throw new BusinessException(result);
}
};
}
}

View File

@@ -0,0 +1,63 @@
package com.njcn.web.constant;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年12月17日 10:16
*/
public interface ValidMessage {
String ID_NOT_BLANK = "id不能为空请检查id参数";
String ID_FORMAT_ERROR = "id格式错误请检查id参数";
String DICT_TYPE_ID_NOT_BLANK = "typeId不能为空请检查typeId参数";
String DICT_TYPE_ID_FORMAT_ERROR = "typeId格式错误请检查typeId参数";
String NAME_NOT_BLANK = "名称不能为空请检查name参数";
String NAME_FORMAT_ERROR = "名称格式错误请检查name参数";
String CODE_NOT_BLANK = "编号不能为空请检查code参数";
String CODE_FORMAT_ERROR = "编号格式错误请检查code参数";
String SORT_NOT_NULL = "排序不能为空请检查sort参数";
String SORT_FORMAT_ERROR = "排序格式错误请检查sort参数";
String OPEN_LEVEL_NOT_NULL = "开启等级不能为空请检查openLevel参数";
String OPEN_LEVEL_FORMAT_ERROR = "开启等级格式错误请检查openLevel参数";
String OPEN_DESCRIBE_NOT_NULL = "开启描述不能为空请检查openDescribe参数";
String OPEN_DESCRIBE_FORMAT_ERROR = "开启描述格式错误请检查openDescribe参数";
String AREA_NOT_BLANK = "行政区域不能为空请检查area参数";
String AREA_FORMAT_ERROR = "行政区域格式错误请检查area参数";
String PID_NOT_BLANK = "父节点不能为空请检查pid参数";
String PID_FORMAT_ERROR = "父节点格式错误请检查pid参数";
String COLOR_NOT_BLANK = "主题色不能为空请检查color参数";
String COLOR_FORMAT_ERROR = "主题色格式错误请检查color参数";
String LOGO_NOT_BLANK = "iconUrl不能为空请检查iconUrl参数";
String FAVICON_NOT_BLANK = "faviconUrl不能为空请检查faviconUrl参数";
String REMARK_NOT_BLANK = "描述不能为空请检查remark参数";
String REMARK_FORMAT_ERROR = "描述格式错误请检查remark参数";
String PARAM_FORMAT_ERROR = "参数值非法";
String IP_FORMAT_ERROR = "IP格式非法";
}

View File

@@ -0,0 +1,23 @@
package com.njcn.web.controller;
import com.njcn.common.utils.ReflectCommonUtil;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年04月21日 14:21
*/
public class BaseController {
/**
* 获取当前类指定方法上@ApiOperate内容
* @param methodName 方法名
*/
public String getMethodDescribe(String methodName){
return ReflectCommonUtil.getMethodDescribeByClassAndMethodName(this.getClass(),methodName);
}
}

View File

@@ -0,0 +1,240 @@
package com.njcn.web.exception;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
//import com.alibaba.excel.exception.ExcelAnalysisException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.common.utils.LogUtil;
import com.njcn.common.utils.ReflectCommonUtil;
import com.njcn.web.service.ILogService;
import com.njcn.web.utils.ControllerUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 全局通用业务异常处理器
*
* @author hongawen
* @version 1.0.0
* @date 2021年04月20日 18:04
*/
@Slf4j
@AllArgsConstructor
@RestControllerAdvice
public class GlobalBusinessExceptionHandler {
private final ILogService logService;
/**
* 捕获业务功能异常,通常为业务数据抛出的异常
*
* @param businessException 业务异常
*/
@ExceptionHandler(BusinessException.class)
public HttpResult<String> handleBusinessException(HttpServletRequest httpServletRequest, BusinessException businessException) {
String operate = ReflectCommonUtil.getMethodDescribeByException(businessException);
logService.recodeBusinessExceptionLog(businessException, httpServletRequest, businessException.getMessage());
return HttpResultUtil.assembleBusinessExceptionResult(businessException, null, operate);
}
/**
* 空指针异常捕捉
*
* @param nullPointerException 空指针异常
*/
@ExceptionHandler(NullPointerException.class)
public HttpResult<String> handleNullPointerException(HttpServletRequest httpServletRequest, NullPointerException nullPointerException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage(), nullPointerException);
logService.recodeBusinessExceptionLog(nullPointerException, httpServletRequest, CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NULL_POINTER_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(nullPointerException));
}
/**
* 算数运算异常
*
* @param arithmeticException 算数运算异常由于除数为0引起的异常
*/
@ExceptionHandler(ArithmeticException.class)
public HttpResult<String> handleArithmeticException(HttpServletRequest httpServletRequest, ArithmeticException arithmeticException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage(), arithmeticException);
logService.recodeBusinessExceptionLog(arithmeticException, httpServletRequest, CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ARITHMETIC_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(arithmeticException));
}
/**
* 类型转换异常捕捉
*
* @param classCastException 类型转换异常
*/
@ExceptionHandler(ClassCastException.class)
public HttpResult<String> handleClassCastException(HttpServletRequest httpServletRequest, ClassCastException classCastException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage(), classCastException);
logService.recodeBusinessExceptionLog(classCastException, httpServletRequest, CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.CLASS_CAST_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(classCastException));
}
/**
* 索引下标越界异常捕捉
*
* @param indexOutOfBoundsException 索引下标越界异常
*/
@ExceptionHandler(IndexOutOfBoundsException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, IndexOutOfBoundsException indexOutOfBoundsException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage(), indexOutOfBoundsException);
logService.recodeBusinessExceptionLog(indexOutOfBoundsException, httpServletRequest, CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(indexOutOfBoundsException));
}
/**
* 前端请求后端,请求中参数的媒体方式不支持异常
*
* @param httpMediaTypeNotSupportedException 请求中参数的媒体方式不支持异常
*/
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public HttpResult<String> httpMediaTypeNotSupportedExceptionHandler(HttpServletRequest httpServletRequest, HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage(), httpMediaTypeNotSupportedException);
// 然后提取错误提示信息进行返回
logService.recodeBusinessExceptionLog(httpMediaTypeNotSupportedException, httpServletRequest, CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(httpMediaTypeNotSupportedException));
}
/**
* 前端请求后端,参数校验异常捕捉
* RequestBody注解参数异常
*
* @param methodArgumentNotValidException 参数校验异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public HttpResult<String> methodArgumentNotValidExceptionHandler(HttpServletRequest httpServletRequest, MethodArgumentNotValidException methodArgumentNotValidException) {
// 从异常对象中拿到allErrors数据
String messages = methodArgumentNotValidException.getBindingResult().getAllErrors()
.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(""));
// 然后提取错误提示信息进行返回
LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages);
logService.recodeBusinessExceptionLog(methodArgumentNotValidException, httpServletRequest, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages, ControllerUtil.getMethodArgumentNotValidException(methodArgumentNotValidException));
}
/**
* 前端请求后端,参数校验异常捕捉
* PathVariable注解、RequestParam注解参数异常
*
* @param constraintViolationException 参数校验异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public HttpResult<String> constraintViolationExceptionExceptionHandler(HttpServletRequest httpServletRequest, ConstraintViolationException constraintViolationException) {
String exceptionMessage = constraintViolationException.getMessage();
StringBuilder messages = new StringBuilder();
if (exceptionMessage.indexOf(StrUtil.COMMA) > 0) {
String[] tempMessage = exceptionMessage.split(StrUtil.COMMA);
Stream.of(tempMessage).forEach(message -> {
messages.append(message.substring(message.indexOf(StrUtil.COLON) + 2)).append(';');
});
} else {
messages.append(exceptionMessage.substring(exceptionMessage.indexOf(StrUtil.COLON) + 2));
}
// 然后提取错误提示信息进行返回
LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages);
logService.recodeBusinessExceptionLog(constraintViolationException, httpServletRequest, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
List<ConstraintViolation<?>> constraintViolationList = new ArrayList<>(constraintViolationException.getConstraintViolations());
ConstraintViolation<?> constraintViolation = constraintViolationList.get(0);
Class<?> rootBeanClass = constraintViolation.getRootBeanClass();
//判断校验参数异常捕获的根源是controller还是service处
if (rootBeanClass.getName().endsWith("Controller")) {
String methodName = constraintViolation.getPropertyPath().toString().substring(0, constraintViolation.getPropertyPath().toString().indexOf(StrUtil.DOT));
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByClassAndMethodName(rootBeanClass, methodName));
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByException(constraintViolationException));
}
}
/**
* 索引下标越界异常捕捉
*
* @param illegalArgumentException 参数校验异常
*/
@ExceptionHandler(IllegalArgumentException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, IllegalArgumentException illegalArgumentException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), illegalArgumentException);
logService.recodeBusinessExceptionLog(illegalArgumentException, httpServletRequest, CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, illegalArgumentException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(illegalArgumentException));
}
// /**
// * 表格校验异常
// *
// * @param excelAnalysisException 表格校验异常
// */
// @ExceptionHandler(ExcelAnalysisException.class)
// public HttpResult<String> handleExcelAnalysisException(HttpServletRequest httpServletRequest, ExcelAnalysisException excelAnalysisException) {
// LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), excelAnalysisException);
// // logService.recodeBusinessExceptionLog(excelAnalysisException, httpServletRequest,CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage());
// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, excelAnalysisException.getCause().getMessage(), ReflectCommonUtil.getMethodDescribeByException(excelAnalysisException));
// }
/**
* 未声明异常捕捉
*
* @param exception 未声明异常
*/
@ExceptionHandler(Exception.class)
public HttpResult<String> handleException(HttpServletRequest httpServletRequest, Exception exception) {
//针对fallbackFactory降级异常特殊处理
Exception tempException = exception;
String exceptionCause = CommonResponseEnum.UN_DECLARE.getMessage();
String code = CommonResponseEnum.UN_DECLARE.getCode();
if (exception instanceof NestedServletException) {
Throwable cause = exception.getCause();
if (cause instanceof AssertionError) {
if (cause.getCause() instanceof BusinessException) {
tempException = (BusinessException) cause.getCause();
BusinessException tempBusinessException = (BusinessException) cause.getCause();
exceptionCause = tempBusinessException.getMessage();
code = tempBusinessException.getCode();
}
}
}
LogUtil.logExceptionStackInfo(exceptionCause, tempException);
logService.recodeBusinessExceptionLog(tempException, httpServletRequest, exceptionCause);
return HttpResultUtil.assembleResult(code, null, StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByException(tempException), StrUtil.C_COMMA, exceptionCause));
}
/**
* json解析异常
*
* @param jsonException json参数
*/
@ExceptionHandler(JSONException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, JSONException jsonException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage(), jsonException);
logService.recodeBusinessExceptionLog(jsonException, httpServletRequest, CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.JSON_CONVERT_EXCEPTION, jsonException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(jsonException));
}
}

View File

@@ -0,0 +1,29 @@
package com.njcn.web.factory;
import cn.hutool.core.util.ObjectUtil;
import com.njcn.web.pojo.param.BaseParam;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年12月20日 16:26
*/
public class PageFactory {
/**
* 默认第一页
* @param baseParam 查询参数
*/
public static Integer getPageNum(BaseParam baseParam) {
return ObjectUtil.isNull(baseParam.getPageNum()) || baseParam.getPageNum() == 0 ? 1 : baseParam.getPageNum();
}
/**
* 默认10条记录
* @param baseParam 查询参数
*/
public static Integer getPageSize(BaseParam baseParam) {
return ObjectUtil.isNull(baseParam.getPageSize()) || baseParam.getPageSize() == 0 ? 10 : baseParam.getPageSize();
}
}

View File

@@ -0,0 +1,33 @@
package com.njcn.web.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author hongawen
* @version 1.0.0
* @createTime 2021年05月20日 16:33
*/
public class XssFilter implements Filter {
private static final String[] EXCLUSIONS_URLS = {".js", ".gif", ".jpg", ".png", ".css", ".ico"};
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletRequest req = (HttpServletRequest) request;
String path = req.getServletPath();
req.getRequestURL();
//注解配置的是urlPatterns="/*"(过滤所有请求),所以这里对不需要过滤的静态资源url,作忽略处理(大家可以依照具体需求配置)
for (String str : EXCLUSIONS_URLS) {
if (path.endsWith(str)) {
chain.doFilter(request, response);
return;
}
}
chain.doFilter(new XssRequestWrapper(httpServletRequest), response);
}
}

View File

@@ -0,0 +1,244 @@
package com.njcn.web.filter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.njcn.common.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.owasp.validator.html.*;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年05月20日 16:34
*/
@Slf4j
public class XssRequestWrapper extends HttpServletRequestWrapper {
private final static String[] WHITE_PARAMETER_NAME = {"password","mxContent","bgImage"};
public XssRequestWrapper(HttpServletRequest request) {
super(request);
}
private static Policy policy = null;
/**
* 获取策略文件直接使用jar中自带的ebay策略文件
*/
private static final InputStream INPUT_STREAM = XssRequestWrapper.class.getClassLoader()
.getResourceAsStream("antisamy-ebay.xml");
static {
try {
// 使用静态代码块处理策略对象的创建
policy = Policy.getInstance(INPUT_STREAM);
} catch (PolicyException e) {
e.printStackTrace();
}
}
// static {
// try {
// // 获取策略文件路径策略文件需要放到项目的classpath下
// String antiSamyPath = Objects
// .requireNonNull(XssRequestWrapper.class.getClassLoader().getResource("antisamy-ebay.xml")).getFile();
// log.info(antiSamyPath);
// // 获取的文件路径中有空格时,空格会被替换为%20在new一个File对象时会出现找不到路径的错误
// // 对路径进行解码以解决该问题
// antiSamyPath = URLDecoder.decode(antiSamyPath, "utf-8");
// log.info(antiSamyPath);
// // 指定策略文件
// policy = Policy.getInstance(antiSamyPath);
// } catch (UnsupportedEncodingException | PolicyException e) {
// e.printStackTrace();
// }
// }
/**
* 使用AntiSamy进行过滤数据
*/
private String xssClean(String html) {
String cleanHtml = "";
try {
AntiSamy antiSamy = new AntiSamy();
CleanResults scan = antiSamy.scan(html, policy);
cleanHtml = scan.getCleanHTML();
// 对转义的HTML特殊字符<、>、"等进行反转义因为AntiSamy调用scan方法时会将特殊字符转义
cleanHtml = StringEscapeUtils.unescapeHtml4(cleanHtml);
} catch (ScanException | PolicyException e) {
log.error("使用AntiSamy进行xss过滤数据异常过滤内容{},异常为:{}", html, e.getMessage());
}
return cleanHtml;
}
/**
* 过滤请求头
*
* @param name 参数名
* @return 参数值
*/
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
// 如果Header为空则直接返回否则进行清洗
return StringUtils.isBlank(header) ? header : xssClean(header);
}
/**
* 重写处理请求参数的方法
*
* @param name 参数名
*/
@Override
public String getParameter(String name) {
String parameter = super.getParameter(name);
if (StringUtils.isEmpty(parameter)) {
return null;
}
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之前的数据{}", parameter);
parameter = xssClean(parameter);
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之后的数据{}", parameter);
return parameter;
}
/**
* 重写处理请求参数的方法
*
* @param name 参数名
*/
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
// 判断参数有值,如果没有值,直接返回
if (values == null) {
return null;
}
return Stream.of(values).map(value -> {
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之前的数据{}", value);
value = xssClean(value);
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之后的数据{}", value);
return value;
}).toArray(String[]::new);
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> requestMap = super.getParameterMap();
requestMap.forEach((key, value) -> {
for (int i = 0; i < value.length; i++) {
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之前的数据{}", value[i]);
value[i] = xssClean(value[i]);
LogUtil.njcnDebug(log, "使用AntiSamy进行过滤清理过滤清理之后的数据{}", value[i]);
}
});
return requestMap;
}
/**
* 重写处理json数据的方法
*/
@Override
public ServletInputStream getInputStream() throws IOException {
ServletInputStream inputStream = super.getInputStream();
if (Objects.isNull(inputStream)) {
return null;
}
// 读取流
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
// 获取json格式的数据
ObjectMapper objectMapper = new ObjectMapper();
String finishJson = null;
StringBuilder sb = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
sb.append(inputStr);
}
LogUtil.njcnDebug(log, "json过滤前:{}", sb.toString());
if (sb.toString().startsWith("[")) {
//jsonArray
List params = objectMapper.readValue(sb.toString(), List.class);
int size = params.size();
Object[] objects = new Object[params.size()];
for (int i = 0; i < params.size(); i++) {
Object temp = params.get(i);
if (Objects.isNull(temp)) {
objects[i] = "";
} else if (temp instanceof Number || temp instanceof List) {
objects[i] = temp;
} else {
objects[i] = xssClean(Objects.isNull(temp) ? "" : temp.toString());;
}
}
finishJson = objectMapper.writeValueAsString(objects);
} else {
//jsonObject
Map map = objectMapper.readValue(sb.toString(), Map.class);
map.keySet().forEach(k -> {
//过滤白名单参数
if (!ArrayUtils.contains(WHITE_PARAMETER_NAME, k)) {
Object temp = map.get(k);
if (Objects.isNull(temp)) {
map.put(k, temp);
//不递归所有数据
} else if (temp instanceof Number || temp instanceof List || temp.toString().startsWith("{")) {
map.put(k, temp);
} else {
map.put(k, xssClean(Objects.isNull(map.get(k)) ? "" : map.get(k).toString()));
}
}
});
finishJson = objectMapper.writeValueAsString(map);
}
// 过滤后
LogUtil.njcnDebug(log, "json过滤后:{}", finishJson);
// 把json数据转为流的格式进行返回
ByteArrayInputStream bais = new ByteArrayInputStream(finishJson.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public int read() {
return bais.read();
}
};
}
}

View File

@@ -0,0 +1,32 @@
package com.njcn.web.pojo.annotation;
/**
* pqs
*
* @author cdf
* @date 2022/1/11
*/
import com.njcn.web.config.DateTimeValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateTimeValidator.class)
public @interface DateTimeStrValid {
String message() default "时间格式错误";
String format() default "yyyy-MM-dd";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@@ -0,0 +1,25 @@
package com.njcn.web.pojo.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author denghuajun
* @date 2022/1/10
*
*/
@Data
public class BaseDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
private String id;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("父节点id")
private String pid;
}

View File

@@ -0,0 +1,43 @@
package com.njcn.web.pojo.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年12月20日 15:35
*/
@Data
public class BaseParam implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("搜索值")
private String searchValue;
@ApiModelProperty("开始时间")
private String searchBeginTime;
@ApiModelProperty("结束时间")
private String searchEndTime;
@ApiModelProperty("状态")
private Integer searchState;
@ApiModelProperty("排序字段")
private String sortBy;
@ApiModelProperty("排序方式:asc-升序,desc-降序")
private String orderBy;
@ApiModelProperty("页码")
private Integer pageNum;
@ApiModelProperty("页面尺寸")
private Integer pageSize;
}

View File

@@ -0,0 +1,21 @@
package com.njcn.web.pojo.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author denghuajun
* @date 2022/1/12
*
*/
@Data
public class DeptLineParam implements Serializable {
@ApiModelProperty("id")
private String id;
@ApiModelProperty("监测点集合ids")
private List<String> ids;
}

View File

@@ -0,0 +1,21 @@
package com.njcn.web.pojo.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author denghuajun
* @date 2022/1/6
*
*/
@Data
public class AreaIdVO implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
private String id;
}

View File

@@ -0,0 +1,29 @@
package com.njcn.web.pojo.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.w3c.dom.stylesheets.LinkStyle;
import java.io.Serializable;
import java.util.List;
/**
* @author denghuajun
* @date 2021/12/31 14:17
* 基础VO只还有id和name
*/
@Data
public class BaseVO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
private String id;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("父节点id")
private String pid;
}

View File

@@ -0,0 +1,17 @@
package com.njcn.web.pojo.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author denghuajun
* @date 2022/1/13
*
*/
@Data
public class DeptLineVO implements Serializable {
@ApiModelProperty("存放结果")
private boolean result;
}

View File

@@ -0,0 +1,55 @@
package com.njcn.web.pojo.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author denghuajun
* @date 2022/2/23
* 保存line信息表
*/
@Data
public class LineDataVO {
/**
* 监测点Id
*/
private String id;
/**
* 父节点0为根节点
*/
private String pid;
/**
* 上层所有节点
*/
private String pids;
/**
* 名称
*/
private String name;
/**
* 等级0-项目名称1- 工程名称2-单位3-部门4-终端5-母线6-监测点
*/
private Integer level;
/**
* 排序默认为0有特殊排序需要时候人为输入
*/
private Integer sort;
/**
* 备注
*/
private String remark;
/**
* 状态 0-删除1-正常;默认正常
*/
private Integer state;
}

View File

@@ -0,0 +1,51 @@
package com.njcn.web.pojo.vo;
import lombok.Data;
import java.io.Serializable;
/**
* @author denghuajun
* @Date: 2022/03/04 14:05
*/
@Data
public class SteadyDataVO implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer monitors;
private String areaIndex;
private float allTime;
private float frequency=3.1415f;
private float uBalance=3.1415f;
private float uAberrance=3.1415f;
private float voltageDeviation=3.1415f;
private float flicker=3.1415f;
private float allFlicker=3.1415f;
private float oddVoltage=3.1415f;
private float evenVoltage=3.1415f;
private float oddElectric=3.1415f;
private float evenElectric=3.1415f;
private float harmVoltage=3.1415f;
private float harmElec=3.1415f;
private float iNeg=3.1415f;
private float inUharm=3.1415f;
}

View File

@@ -0,0 +1,48 @@
package com.njcn.web.service;
import com.njcn.common.pojo.response.HttpResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.scheduling.annotation.Async;
import javax.servlet.http.HttpServletRequest;
/**
* @author hongawen
* @version 1.0.0
* @date 2022年03月14日 16:37
*/
public interface ILogService {
/**
* 异步记录controller中返回的信息内容
*
* @param request 请求头
* @param returnType 返回类型
* @param httpResult 返回结果
* @param userName 用户名
* @param methodDescribe 方法描述
*/
void recodeAdviceLog(ServerHttpRequest request, MethodParameter returnType, HttpResult httpResult, String methodDescribe);
/**
* 异步记录全局异常捕获器中返回的信息内容
*
* @param exception 异常数据
* @param request 请求信息
* @param message 信息
*/
void recodeBusinessExceptionLog(Exception exception, HttpServletRequest request, String message);
/**
* 异步记录全局异常捕获器中返回的信息内容
*
* @param exception 异常数据
* @param request 请求信息
* @param message 信息
* @param userName 用户名
*/
void recodeAuthExceptionLog(Exception exception, HttpServletRequest request, String message, String userName);
}

View File

@@ -0,0 +1,138 @@
package com.njcn.web.service.impl;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.dto.LogInfoDTO;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.ReflectCommonUtil;
import com.njcn.web.service.ILogService;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.MethodArgumentNotValidException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @author hongawen
* @version 1.0.0
* @date 2022年03月14日 15:20
*/
@Slf4j
@Service
@AllArgsConstructor
public class LogServiceImpl implements ILogService {
/**
* 部分登录前的操作,获取用户名登录名的方式需特殊处理
*/
private final static List<String> UN_LOGIN_METHOD = Arrays.asList("首次登录修改密码", "登录认证", "根据登录名查询用户信息", "认证后根据用户名判断用户状态", "更新用户登录认证密码错误次数", "根据登录名获取公钥", "根据客户端名查询信息");
private final GeneralInfo generalInfo;
/**
* 异步记录controller中返回的信息内容
*
* @param request 请求头
* @param returnType 返回类型
* @param httpResult 返回结果
* @param methodDescribe 方法描述
*/
@Override
@Async("asyncExecutor")
public void recodeAdviceLog(ServerHttpRequest request, MethodParameter returnType, HttpResult httpResult, String methodDescribe) {
//处理审计日志
String userName;
HttpServletRequest httpServletRequest = RequestUtil.getRequest(request);
if (UN_LOGIN_METHOD.contains(methodDescribe)) {
userName = RequestUtil.getLoginName(httpServletRequest);
} else {
userName = RequestUtil.getUserNickname(request);
}
String result = httpResult.getCode().equalsIgnoreCase(CommonResponseEnum.FAIL.getCode()) ? CommonResponseEnum.FAIL.getMessage() : CommonResponseEnum.SUCCESS.getMessage();
String ip = RequestUtil.getRealIp(request);
String type = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(returnType.getMethod()).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(returnType.getMethod());
LogInfoDTO logInfoDTO = new LogInfoDTO(userName, methodDescribe, result, ip, type, level, operateType, generalInfo.getMicroServiceName());
System.out.println(logInfoDTO);
}
/**
* 异步记录全局异常捕获器中返回的信息内容
*
* @param exception 异常数据
* @param request 请求信息
* @param message 信息
*/
@Override
@Async("asyncExecutor")
public void recodeBusinessExceptionLog(Exception exception, HttpServletRequest request, String message) {
LogInfoDTO tempLogInfo = RequestUtil.initLogInfo(request);
//认证前,获取用户信息
if (Objects.equals(tempLogInfo.getUserName(), LogInfo.UNKNOWN_USER)) {
tempLogInfo.setUserName(RequestUtil.getLoginName(request));
}
//根据异常获取method方法
Method method = ReflectCommonUtil.getMethod(exception);
if (exception instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
method = methodArgumentNotValidException.getParameter().getMethod();
}
String methodDescribe = StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByMethod(method), StrUtil.C_COMMA, message);
String result = CommonResponseEnum.FAIL.getMessage();
String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
LogInfoDTO logInfoDTO = new LogInfoDTO(tempLogInfo.getUserName(), methodDescribe, result, tempLogInfo.getIp(), type, level, operateType, generalInfo.getMicroServiceName());
System.out.println(logInfoDTO);
}
/**
* 异步记录全局异常捕获器中返回的信息内容
*
* @param exception 异常数据
* @param request 请求信息
* @param message 信息
* @param userName 用户名
*/
@Override
@Async("asyncExecutor")
public void recodeAuthExceptionLog(Exception exception, HttpServletRequest request, String message, String userName) {
//根据异常获取method方法
Method method = ReflectCommonUtil.getMethod(exception);
if (exception instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
method = methodArgumentNotValidException.getParameter().getMethod();
}
String methodDescribe = StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByMethod(method), StrUtil.C_COMMA, message);
String result = CommonResponseEnum.FAIL.getMessage();
String ip = RequestUtil.getRealIp(request);
String type = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateType();
String level = ReflectCommonUtil.getOperateInfoByMethod(method).getOperateLevel();
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
LogInfoDTO logInfoDTO = new LogInfoDTO(userName, methodDescribe, result, ip, type, level, operateType, generalInfo.getMicroServiceName());
System.out.println(logInfoDTO);
}
}

View File

@@ -0,0 +1,299 @@
package com.njcn.web.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author yexb(创建)-----denghuajun(移植使用)
* @version 1.0
* @date 2018/8/23 16:02
*/
//因素集U={频率偏差、电网谐波、电压波动与闪变、电压偏差、电压暂降、三相不平衡}
//评判级分为5个等级Q = {很差,较差,合格,良好,优质}
/* 电压偏差 电网谐波 三相不平衡 频率偏差 电压波动 电压暂降
(偏差绝对值/%) (电压总谐波畸变率%) (不平衡度/%) (偏差绝对值/Hz) (短时闪变值) (暂降幅度%)
第1 级 10 6..0 4.0 0.3 0.8 90
第2 级 710 4.06.0 2..04.0 0.20.3 0.60.8 4090
第3 级 47 2.04.0 1.02.0 0.10.2 0.40.6 2040
第4 级 24 1.02.0 0.51.0 0.050.1 0.20.4 1020
第5 级 02 01.0 00.5 00.05 00.2 010
*/
@Component
public class ComAssesUtil {
// 日志记录
private static final Logger logger = LoggerFactory.getLogger(ComAssesUtil.class);
private static final int ST_QT_NUM = 6;//系统评价指标数目
private static final int GRADE_NUM = 5;//指标分级数目
private static final int METHOD_NUM = 5;//评估方法数
private static final int METHOD_IDX1 = 0;//层次分析法
private static final int METHOD_IDX2 = 1;//优序图法
private static final int METHOD_IDX3 = 2;//专家打分法
private static final int METHOD_IDX4 = 3;//熵权法
private static final int METHOD_IDX5 = 4;//变异系数法
private static final int IDX_FREQ = 0;//频率
private static final int IDX_UTHD = 1;//电压畸变率
private static final int IDX_FLICK = 2;//电压闪变
private static final int IDX_UDEV = 3;//电压偏差
private static final int IDX_EVT = 4;//电压暂降
private static final int IDX_UBPH = 5;//电压不平衡
private static final int MAX_DATA_TYPE = 5;//5种统计数据
private static final int MAX_DATA_NUM = 1440 * 31;//最大统计数据个数
private static final int MAX_EVT_NUM = 1000;//最大暂态事件个数
//3种主观赋权法直接摘录文档中计算好的最终评估权重
//层次分析法
private float W1[] = {0.38f, 0.22f, 0.13f, 0.12f, 0.08f, 0.07f};
//优序图法
private float W2[] = {0.28f, 0.24f, 0.19f, 0.14f, 0.10f, 0.05f};
//专家打分法
private float W3[] = {0.39f, 0.26f, 0.12f, 0.09f, 0.07f, 0.07f};
//数据评估矩阵
private float Assess[][];
//权重矩阵
private float Weight[][];
float A[];
// 综合评估程序,返回值为评估分
public float GetComAsses(float in_data[][]) {
float fResult = 0.0f;//返回最终评分
try{
//实例化所有参数
Assess = new float[ST_QT_NUM][GRADE_NUM];
Weight = new float[ST_QT_NUM][METHOD_NUM];
A = new float[ST_QT_NUM];
float B[] = new float[GRADE_NUM];
int i, j;
float sum1, sum2;
Assess = in_data;//给评估矩阵赋值,此值直接从相应的数据库中获取
//W1-W3为主观赋权直接从文档上摘录赋权
for (i = 0; i < ST_QT_NUM; i++) {
Weight[i][METHOD_IDX1] = W1[i];
Weight[i][METHOD_IDX2] = W2[i];
Weight[i][METHOD_IDX3] = W3[i];
}
//熵权法求W4
if (getSqf()) {
//变异系数法求W5
if (getBysxf()) {
//G和F得出综合权重A
if (getZhqzf()) {
//A[0] = 0.28;A[1] = 0.23;A[2] = 0.13;A[3] = 0.16;A[4] = 0.08;A[5] = 0.12;
for (i = 0; i < GRADE_NUM; i++) {
B[i] = 0;
for (j = 0; j < ST_QT_NUM; j++) {
B[i] += A[j] * Assess[j][i];
}
}
sum1 = 0;
sum2 = 0;
for (i = 0; i < GRADE_NUM; i++) {
sum1 += (i + 1) * B[i];
sum2 += B[i];
}
fResult = sum1 / sum2;
}
}
}
fResult = FloatUtils.get2Float(fResult);
}catch (Exception e){
//Todo
}
return fResult;
}
/**
* 大批量的监测点的综合得分获取平均值
* @param pqsComasses 批量数据
*/
public float getAllComAss(List<PqsComasses> pqsComasses) {
float allData=0f;
for(int i=0;i<pqsComasses.size();i++){
PqsComasses tempPqs=pqsComasses.get(i);
//组合二维数组
float f1[][]={{tempPqs.getFreqDev1(),tempPqs.getFreqDev2(),tempPqs.getFreqDev3(),tempPqs.getFreqDev4(),tempPqs.getFreqDev5()}
,{tempPqs.getVThd1(),tempPqs.getVThd2(),tempPqs.getVThd3(),tempPqs.getVThd4(),tempPqs.getVThd5(),}
,{tempPqs.getDataPst1(),tempPqs.getDataPst2(),tempPqs.getDataPst3(),tempPqs.getDataPst4(),tempPqs.getDataPst5()}
,{tempPqs.getVuDev1(),tempPqs.getVuDev2(),tempPqs.getVuDev3(),tempPqs.getVuDev4(),tempPqs.getVuDev5(),}
,{tempPqs.getVUnbalance1(),tempPqs.getVUnbalance2(),tempPqs.getVUnbalance3(),tempPqs.getVUnbalance4(),tempPqs.getVUnbalance5(),}
,{tempPqs.getEvent1(),tempPqs.getEvent2(),tempPqs.getEvent3(),tempPqs.getEvent4(),tempPqs.getEvent5(),}};
//获取该值返回的数据
float temp=GetComAsses(f1);
allData+=temp;
}
float aveData=allData/pqsComasses.size();
return FloatUtils.get2Float(aveData);
}
//熵权法求权重
private boolean getSqf() {
boolean blSqfFlag = true;
try {
int i, j;
float k, m;
float sum[] = new float[ST_QT_NUM];
float e[] = new float[ST_QT_NUM];
float d[] = new float[ST_QT_NUM];
//计算第j个指标的熵值e(j)
m = GRADE_NUM;
//k = (1/1.6094379124341);
k = (float) (1 / ((Math.log(m)) / Math.log(2.7183)));
for (i = 0; i < ST_QT_NUM; i++) {
sum[i] = 0;
for (j = 0; j < GRADE_NUM; j++) {
if (Assess[i][j] != 0)
sum[i] += Assess[i][j] * (Math.log(Assess[i][j]) / Math.log(2.7183));
}
e[i] = -k * sum[i];
}
for (i = 0; i < ST_QT_NUM; i++)
d[i] = 1 - e[i];
sum[0] = 0;
for (i = 0; i < ST_QT_NUM; i++)
sum[0] += d[i];
for (i = 0; i < ST_QT_NUM; i++)
Weight[i][METHOD_IDX4] = d[i] / sum[0];
} catch (Exception e) {
logger.error(e.getMessage());
blSqfFlag = false;
}
return blSqfFlag;
}
//变异系数法求权重
private boolean getBysxf() {
boolean blBysxfFlag = true;
try {
float avg_f[] = new float[ST_QT_NUM];//平均值
float std_f[] = new float[ST_QT_NUM];//标准差
float byxs[] = new float[ST_QT_NUM];//变异系数
float sum;
int i, j;
for (i = 0; i < ST_QT_NUM; i++) {
avg_f[i] = 0;
std_f[i] = 0;
byxs[i] = 0;
}
//求平均值
for (i = 0; i < ST_QT_NUM; i++) {
sum = 0;
for (j = 0; j < GRADE_NUM; j++)
sum += Assess[i][j];
avg_f[i] = sum / GRADE_NUM;
}
//求标准差
for (i = 0; i < ST_QT_NUM; i++) {
sum = 0;
for (j = 0; j < GRADE_NUM; j++)
sum += Math.pow((Assess[i][j] - avg_f[i]), 2);
std_f[i] = (float) (Math.sqrt(sum / GRADE_NUM));
}
//求变异系数
for (i = 0; i < ST_QT_NUM; i++) {
if (avg_f[i] < 0)
avg_f[i] = 0 - avg_f[i];
byxs[i] = std_f[i] / avg_f[i];
}
sum = 0;
for (i = 0; i < ST_QT_NUM; i++)
sum += byxs[i];
for (i = 0; i < ST_QT_NUM; i++)
Weight[i][METHOD_IDX5] = byxs[i] / sum;
} catch (Exception e) {
logger.error(e.getMessage());
blBysxfFlag = false;
}
return blBysxfFlag;
}
//求综合权重,主观权重和客观权重占比相等各自50%
private boolean getZhqzf() {
float D[] = new float[ST_QT_NUM];
float e[] = new float[ST_QT_NUM];
float C[][] = new float[ST_QT_NUM][ST_QT_NUM];
float C1[][] = new float[ST_QT_NUM][ST_QT_NUM];
float tmp1[] = new float[ST_QT_NUM];
float tmp2[] = new float[ST_QT_NUM];
boolean blZhqzfFlag = true;
try {
int i, j, k;
float t1, t2;
//求C
for (i = 0; i < ST_QT_NUM; i++) {
tmp1[i] = 0;
for (j = 0; j < GRADE_NUM; j++)
tmp1[i] += 2 * METHOD_NUM * Math.pow(Assess[i][j], 2);
}
for (i = 0; i < ST_QT_NUM; i++) {
for (j = 0; j < ST_QT_NUM; j++) {
if (i == j)
C[i][j] = tmp1[i];
else
C[i][j] = 0;
}
}
//求C的逆矩阵C1,由于C是对角矩阵简化矩阵求逆
for (i = 0; i < ST_QT_NUM; i++) {
for (j = 0; j < ST_QT_NUM; j++) {
if (i == j)
C1[i][j] = (float) 1.0 / C[i][j];
else
C1[i][j] = 0;
}
}
//求D
for (i = 0; i < ST_QT_NUM; i++) {
tmp1[i] = 0;
for (k = 0; k < METHOD_NUM; k++)
tmp1[i] += Weight[i][k];
tmp2[i] = 0;
for (j = 0; j < GRADE_NUM; j++) {
tmp2[i] += tmp1[i] * Math.pow(Assess[i][j], 2);
}
D[i] = 2 * tmp2[i];
}
//e赋值
for (i = 0; i < ST_QT_NUM; i++)
e[i] = 1;
//计算eT*C1
for (i = 0; i < ST_QT_NUM; i++) {
tmp1[i] = 0;
for (j = 0; j < ST_QT_NUM; j++)
tmp1[i] += e[i] * C1[j][i];
}
t1 = 0;
for (i = 0; i < ST_QT_NUM; i++)
t1 += tmp1[i] * e[i];
t2 = 0;
for (i = 0; i < ST_QT_NUM; i++)
t2 += tmp1[i] * D[i];
for (i = 0; i < ST_QT_NUM; i++)
e[i] = e[i] * ((1 - t2) / t1);
for (i = 0; i < ST_QT_NUM; i++)
D[i] = D[i] + e[i];
//求A
for (i = 0; i < ST_QT_NUM; i++) {
A[i] = 0;
for (j = 0; j < ST_QT_NUM; j++)
A[i] += C1[i][j] * D[j];
}
} catch (Exception ex) {
logger.error(ex.getMessage());
blZhqzfFlag = false;
}
return blZhqzfFlag;
}
}

View File

@@ -0,0 +1,37 @@
package com.njcn.web.utils;
import com.njcn.common.pojo.constant.LogInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年06月22日 10:25
*/
@Slf4j
public class ControllerUtil {
/**
* 针对methodArgumentNotValidException 异常的处理
* @author cdf
*/
public static String getMethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
String operate = LogInfo.UNKNOWN_OPERATE;
Method method = null;
try {
method = methodArgumentNotValidException.getParameter().getMethod();
if (!Objects.isNull(method) && method.isAnnotationPresent(ApiOperation.class)) {
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
operate = apiOperation.value();
}
}catch (Exception e){
log.error("根据方法参数非法异常获取@ApiOperation注解值失败参数非法异常信息{},方法名:{},异常信息:{}",methodArgumentNotValidException.getMessage(),method,e.getMessage());
}
return operate;
}
}

View File

@@ -0,0 +1,28 @@
package com.njcn.web.utils;
import java.math.BigDecimal;
/**
* @author hongawen(创建) -----denghuajun移植使用
* @Date: 2018/8/27 11:29
*/
public class FloatUtils {
/**
* 保留传入进来的float的两位小数四舍五入的方式
*
* @param data Float参数
*/
public static float get2Float(Float data) {
if (data == null) {
return 0f;
}
int scale = 2;//设置位数
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
BigDecimal bd = new BigDecimal(data);
bd = bd.setScale(scale, roundingMode);
data = bd.floatValue();
return data;
}
}

View File

@@ -0,0 +1,34 @@
package com.njcn.web.utils;
import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.List;
/**
* pqs
*
* @author cdf
* @date 2022/2/28
*/
public class GeneralUtil {
/**
* 按指定大小分隔集合将集合按规定个数分为n个部分
* @author cdf
* @date 2021/10/26
*/
public static List<List<String>> splitList(List<String> list, int len){
if(CollectionUtil.isEmpty(list) || len<1){
return null;
}
List<List<String>> result = new ArrayList<>();
int size = list.size();
int count = (size+len-1)/1000;
for(int i=0;i<count;i++){
List<String> subList= list.subList(i*len,((i+1)*len>size?size:len*(i+1)));
result.add(subList);
}
return result;
}
}

View File

@@ -0,0 +1,41 @@
package com.njcn.web.utils;
import com.alibaba.nacos.shaded.com.google.protobuf.ServiceException;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* HttpServlet工具类获取当前request和response
*
* @author hongawen
* @version 1.0.0
* @date 2022年04月01日 11:04
*/
public class HttpServletUtil {
public static HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
throw new BusinessException(CommonResponseEnum.REQUEST_EMPTY);
} else {
return requestAttributes.getRequest();
}
}
public static HttpServletResponse getResponse() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
throw new BusinessException(CommonResponseEnum.REQUEST_EMPTY);
} else {
return requestAttributes.getResponse();
}
}
}

View File

@@ -0,0 +1,74 @@
package com.njcn.web.utils;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author hongawen
* @version 1.0.0
* @createTime 2021年05月25日 11:25
*/
@Slf4j
public class IpUtils {
private static final String UNKNOWN = "unknown";
private static final String LOCALHOST_IPV4 = "127.0.0.1";
private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
private static final String SEPARATOR = ",";
private static final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
private static final String HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
private static final String HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
/**
* 获取真实客户端IP
*/
public static String getRealIpAddress(ServerHttpRequest serverHttpRequest) {
String ipAddress;
try {
// 1.根据常见的代理服务器转发的请求ip存放协议从请求头获取原始请求ip。值类似于203.98.182.163, 203.98.182.163
ipAddress = serverHttpRequest.getHeaders().getFirst(HEADER_X_FORWARDED_FOR);
if (StrUtil.isBlankIfStr(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = serverHttpRequest.getHeaders().getFirst(HEADER_PROXY_CLIENT_IP);
}
if (StrUtil.isBlankIfStr(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = serverHttpRequest.getHeaders().getFirst(HEADER_WL_PROXY_CLIENT_IP);
}
// 2.如果没有转发的ip则取当前通信的请求端的ip
if (StrUtil.isBlankIfStr(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
InetSocketAddress inetSocketAddress = serverHttpRequest.getRemoteAddress();
if (!Objects.isNull(inetSocketAddress)) {
ipAddress = inetSocketAddress.getAddress().getHostAddress();
}
// 如果是127.0.0.1则取本地真实ip
if (LOCALHOST_IPV4.equals(ipAddress) || LOCALHOST_IPV6.equals(ipAddress)) {
InetAddress localAddress = NetUtil.getLocalhost();;
if (localAddress.getHostAddress() != null) {
ipAddress = localAddress.getHostAddress();
}
}
}
// 对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***"
if (ipAddress != null) {
ipAddress = ipAddress.split(SEPARATOR)[0].trim();
}
} catch (Exception e) {
log.error("解析请求IP失败,{}", Stream.of(e.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining(StrUtil.CRLF)));
ipAddress = "";
}
return ipAddress == null ? "" : ipAddress;
}
}

View File

@@ -0,0 +1,43 @@
package com.njcn.web.utils;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class PqsComasses implements Serializable {
private LocalDateTime timeid;
private String lineid;
private float freqDev1;
private float freqDev2;
private float freqDev3;
private float freqDev4;
private float freqDev5;
private float vuDev1;
private float vuDev2;
private float vuDev3;
private float vuDev4;
private float vuDev5;
private float dataPst1;
private float dataPst2;
private float dataPst3;
private float dataPst4;
private float dataPst5;
private float vUnbalance1;
private float vUnbalance2;
private float vUnbalance3;
private float vUnbalance4;
private float vUnbalance5;
private float vThd1;
private float vThd2;
private float vThd3;
private float vThd4;
private float vThd5;
private float event1;
private float event2;
private float event3;
private float event4;
private float event5;
}

View File

@@ -0,0 +1,367 @@
package com.njcn.web.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.dto.LogInfoDTO;
import com.njcn.common.pojo.enums.auth.AuthenticationMethodEnum;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;
/**
* 请求工具类
*
* @author hongawen
* @version 1.0.0
* @date 2021年05月11日 14:03
*/
@Slf4j
public class RequestUtil {
/**
* 获取登录认证的客户端ID
* 兼容两种方式获取OAuth2客户端信息client_id、client_secret
* 放在请求头Request Headers中的Authorization字段且经过加密例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
*/
@SneakyThrows
public static String getOAuth2ClientId() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 从请求路径中获取
String clientId = "";
// 从请求头获取
String basic = request.getHeader(SecurityConstants.AUTHORIZATION_KEY);
if (StrUtil.isNotBlank(basic) && basic.startsWith(SecurityConstants.BASIC_PREFIX)) {
basic = basic.replace(SecurityConstants.BASIC_PREFIX, Strings.EMPTY);
String basicPlainText = new String(Base64.getDecoder().decode(basic.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
clientId = basicPlainText.split(":")[0]; //client:secret
}
return clientId;
}
/**
* 解析JWT获取获取认证方式
*
* @return .
*/
@SneakyThrows
public static String getAuthenticationMethod() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String refreshToken = request.getParameter(SecurityConstants.REFRESH_TOKEN_KEY);
String payload = StrUtil.toString(JWSObject.parse(refreshToken).getPayload());
cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(payload);
String authenticationMethod = jsonObject.getStr(SecurityConstants.AUTHENTICATION_METHOD);
if (StrUtil.isBlank(authenticationMethod)) {
authenticationMethod = AuthenticationMethodEnum.USERNAME.getValue();
}
return authenticationMethod;
}
//-----------------------------------------------------------------
/**
* 获取请求体
*/
public static HttpServletRequest getRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(Objects.nonNull(requestAttributes)){
return ((ServletRequestAttributes)requestAttributes).getRequest();
}
return null;
}
/**
* 获取请求体
*/
public static HttpServletRequest getRequest(ServerHttpRequest request) {
ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
return servletServerHttpRequest.getServletRequest();
}
/**
* HttpServletRequest获取请求头中的IP地址
*/
public static String getRealIp() {
String ip = getRequest().getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP);
return StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip;
}
/**
* HttpServletRequest获取头中存储的IP地址
*/
public static String getRealIp(HttpServletRequest request) {
String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP);
return StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip;
}
/**
* ServerHttpRequest获取头中存储的IP地址
*/
public static String getRealIp(ServerHttpRequest request) {
HttpHeaders headers = request.getHeaders();
String ip = CollectionUtils.isEmpty(headers.getOrEmpty(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP)) ? "" :
headers.getOrEmpty(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP).get(0);
return StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip;
}
/**
* HttpServletRequest获取在网关中存储的用户token元信息
*/
public static JSONObject getJwtPayload() {
JSONObject jsonObject = null;
String jwtPayload = getRequest().getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
try {
if (StrUtil.isNotBlank(jwtPayload)) {
jwtPayload = URLDecoder.decode(jwtPayload, StandardCharsets.UTF_8.toString());
jsonObject = JSONObject.fromObject(jwtPayload);
}
} catch (UnsupportedEncodingException e) {
log.error("解码网关中心传递的请求头中内容异常,异常为:{}", e.getMessage());
e.printStackTrace();
}
return jsonObject;
}
/**
* HttpServletRequest获取在网关中存储的用户token元信息
*/
public static JSONObject getJwtPayload(HttpServletRequest request) {
JSONObject jsonObject = null;
String jwtPayload = request.getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
try {
if (StrUtil.isNotBlank(jwtPayload)) {
jwtPayload = URLDecoder.decode(jwtPayload, StandardCharsets.UTF_8.toString());
jsonObject = JSONObject.fromObject(jwtPayload);
}
} catch (UnsupportedEncodingException e) {
log.error("解码网关中心传递的请求头中内容异常,异常为:{}", e.getMessage());
e.printStackTrace();
}
return jsonObject;
}
/**
* ServerHttpRequest获取在网关中存储的用户token元信息
*/
public static JSONObject getJwtPayload(ServerHttpRequest request) {
JSONObject jsonObject = null;
HttpHeaders headers = request.getHeaders();
try {
String jwtPayload = headers.get(SecurityConstants.JWT_PAYLOAD_KEY).get(0);
if (StrUtil.isNotBlank(jwtPayload)) {
jwtPayload = URLDecoder.decode(jwtPayload, StandardCharsets.UTF_8.toString());
jsonObject = JSONObject.fromObject(jwtPayload);
}
} catch (UnsupportedEncodingException e) {
log.error("解码网关中心传递的请求头中内容异常,异常为:{}", e.getMessage());
e.printStackTrace();
}
return jsonObject;
}
/**
* HttpServletRequest获取在网关中存储的用户索引
*/
public static String getUserIndex() {
String userIndex = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload();
if (Objects.nonNull(jwtPayload)) {
userIndex = jwtPayload.getString(SecurityConstants.USER_INDEX_KEY);
}
return userIndex;
}
/**
* HttpServletRequest获取在网关中存储的部门索引
*/
public static String getDeptIndex() {
String deptIndex = LogInfo.UNKNOWN_DEPT;
JSONObject jwtPayload = getJwtPayload();
if (Objects.nonNull(jwtPayload)) {
deptIndex = jwtPayload.getString(SecurityConstants.DEPT_INDEX_KEY);
}
return deptIndex;
}
/**
* HttpServletRequest获取在网关中存储的用户登录名
*/
public static String getUsername() {
String userSign = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload();
if (Objects.nonNull(jwtPayload)) {
String userSignTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
userSign = StrUtil.isBlank(userSignTemp) ? LogInfo.UNKNOWN_USER : userSignTemp;
}
return userSign;
}
/**
* HttpServletRequest获取在网关中存储的用户登录名
*/
public static String getUsername(HttpServletRequest request) {
String userSign = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String userSignTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
userSign = StrUtil.isBlank(userSignTemp) ? LogInfo.UNKNOWN_USER : userSignTemp;
}
return userSign;
}
/**
* ServerHttpRequest获取在网关中存储的用户登录名
*/
public static String getUsername(ServerHttpRequest request) {
String userSign = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String userSignTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
userSign = StrUtil.isBlank(userSignTemp) ? LogInfo.UNKNOWN_USER : userSignTemp;
}
return userSign;
}
/**
* HttpServletRequest获取在网关中存储的用户昵称
*/
public static String getUserNickname() {
String nickname = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload();
if (Objects.nonNull(jwtPayload)) {
String nicknameTemp = jwtPayload.getString(SecurityConstants.USER_NICKNAME_KEY);
nickname = StrUtil.isBlank(nicknameTemp) ? LogInfo.UNKNOWN_USER : nicknameTemp;
}
return nickname;
}
/**
* HttpServletRequest获取在网关中存储的用户昵称
*/
public static String getUserNickname(HttpServletRequest request) {
String nickname = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String nicknameTemp = jwtPayload.getString(SecurityConstants.USER_NICKNAME_KEY);
nickname = StrUtil.isBlank(nicknameTemp) ? LogInfo.UNKNOWN_USER : nicknameTemp;
}
return nickname;
}
/**
* ServerHttpRequest获取在网关中存储的用户昵称
*/
public static String getUserNickname(ServerHttpRequest request) {
String nickname = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String nicknameTemp = jwtPayload.getString(SecurityConstants.USER_NICKNAME_KEY);
nickname = StrUtil.isBlank(nicknameTemp) ? LogInfo.UNKNOWN_USER : nicknameTemp;
}
return nickname;
}
/**
* HttpServletRequest获取在网关中存储的载体中的clientId
*/
public static String getClientId() {
String client = LogInfo.UNKNOWN_CLIENT;
JSONObject jwtPayload = getJwtPayload();
if (Objects.nonNull(jwtPayload)) {
String clientTemp = jwtPayload.getString(SecurityConstants.CLIENT_ID_KEY);
client = StrUtil.isBlank(clientTemp) ? LogInfo.UNKNOWN_CLIENT : clientTemp;
}
return client;
}
/**
* HttpServletRequest获取用户登录名
*/
public static String getLoginName(HttpServletRequest request) {
String loginName = (String) request.getAttribute(SecurityConstants.AUTHENTICATE_USERNAME);
return StrUtil.isBlank(loginName) ? LogInfo.UNKNOWN_USER : loginName;
}
/**
* ServerHttpRequest获取用户登录名
*/
public static String getLoginName(ServerHttpRequest serverHttpRequest) {
HttpServletRequest request = getRequest(serverHttpRequest);
String loginName = (String) request.getAttribute(SecurityConstants.AUTHENTICATE_USERNAME);
return StrUtil.isBlank(loginName) ? LogInfo.UNKNOWN_USER : loginName;
}
/**
* 获取用户登录名
*/
public static String getLoginName() {
String loginName = (String) getRequest().getAttribute(SecurityConstants.AUTHENTICATE_USERNAME);
return StrUtil.isBlank(loginName) ? LogInfo.UNKNOWN_USER : loginName;
}
/**
* 认证之前存储用户登录名
*/
public static void saveLoginName(String loginName) {
getRequest().setAttribute(SecurityConstants.AUTHENTICATE_USERNAME, loginName);
}
/**
* 获取上游服务名称
*/
public static String getServerName() {
String serverName = getRequest().getHeader(SecurityConstants.SERVER_NAME);
if (StringUtils.isBlank(serverName)) {
return LogInfo.UNKNOWN_SERVER;
} else {
return serverName;
}
}
/**
* 全局异常捕获处初始化用户名、登录名、ip信息
*/
public static LogInfoDTO initLogInfo(HttpServletRequest request) {
String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP);
LogInfoDTO temp = new LogInfoDTO();
temp.setIp(StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip);
String username = LogInfo.UNKNOWN_USER;
JSONObject jwtPayload = getJwtPayload(request);
if (Objects.nonNull(jwtPayload)) {
String userSignTemp = jwtPayload.getString(SecurityConstants.USER_NAME_KEY);
username = StrUtil.isBlank(userSignTemp) ? LogInfo.UNKNOWN_USER : userSignTemp;
}
temp.setUserName(username);
return temp;
}
}

View File

@@ -0,0 +1,34 @@
package com.njcn.web.utils;
import cn.hutool.core.collection.CollectionUtil;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年06月10日 14:10
*/
public class ValidatorUtils {
/**
* 校验所有字段并返回不合法字段
*/
public static void validate(@Valid Object domain) {
Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory()
.getValidator()
.validate(domain, new Class[0]);
if (!CollectionUtil.isEmpty(validateSet)) {
String messages = validateSet.stream()
.map(ConstraintViolation::getMessage)
.reduce((m1, m2) -> m1 + "" + m2)
.orElse("参数输入有误!");
throw new IllegalArgumentException(messages);
}
}
}

View File

@@ -0,0 +1,63 @@
package com.njcn.web.utils;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.common.pojo.enums.auth.ClientEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author hongawen
* @version 1.0.0
* @date 2021年05月24日 16:56
*/
public class WebUtil {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* @param code 响应码
* @param message 响应信息
*/
public static void responseInfo( HttpServletResponse response, String code, String message) throws IOException {
response.setStatus(HttpStatus.HTTP_OK);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "no-cache");
//可以使用封装类简写Content-Type使用该方法则无需使用setCharacterEncoding
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
HttpResult<String> result = HttpResultUtil.assembleResult(code, null, message);
response.getWriter().print(OBJECT_MAPPER.writeValueAsString(result));
response.getWriter().flush();
}
/**
* @return 对应的部门类型
*/
public static List<Integer> filterDeptType() {
List<Integer> deptType = new ArrayList<>();
String clientId = RequestUtil.getClientId();
String clientType = ClientEnum.getClientType(clientId);
switch (clientType) {
case "app":
deptType.add(2);
break;
case "screen":
deptType.add(0);
break;
default:
deptType.add(0);
deptType.add(1);
deptType.add(3);
break;
}
return deptType;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="anti-samy-rules">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="include" type="Include" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="directives" type="Directives"/>
<xsd:element name="common-regexps" type="CommonRegexps"/>
<xsd:element name="common-attributes" type="AttributeList"/>
<xsd:element name="global-tag-attributes" type="AttributeList"/>
<xsd:element name="dynamic-tag-attributes" type="AttributeList" minOccurs="0"/>
<xsd:element name="tags-to-encode" type="TagsToEncodeList" minOccurs="0"/>
<xsd:element name="tag-rules" type="TagRules"/>
<xsd:element name="css-rules" type="CSSRules"/>
<xsd:element name="allowed-empty-tags" type="AllowedEmptyTags" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="Include">
<xsd:attribute name="href" use="required" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="Directives">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="directive" type="Directive" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Directive">
<xsd:attribute name="name" use="required"/>
<xsd:attribute name="value" use="required"/>
</xsd:complexType>
<xsd:complexType name="CommonRegexps">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="regexp" type="RegExp" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="AttributeList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="attribute" type="Attribute" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="TagsToEncodeList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="tag" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="TagRules">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="tag" type="Tag" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Tag">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="attribute" type="Attribute" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required"/>
<xsd:attribute name="action" use="required"/>
</xsd:complexType>
<xsd:complexType name="AllowedEmptyTags">
<xsd:sequence>
<xsd:element name="literal-list" type="LiteralList" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Attribute">
<xsd:sequence>
<xsd:element name="regexp-list" type="RegexpList" minOccurs="0"/>
<xsd:element name="literal-list" type="LiteralList" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="name" use="required"/>
<xsd:attribute name="description"/>
<xsd:attribute name="onInvalid"/>
</xsd:complexType>
<xsd:complexType name="RegexpList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="regexp" type="RegExp" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="RegExp">
<xsd:attribute name="name" type="xsd:string"/>
<xsd:attribute name="value" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="LiteralList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="literal" type="Literal" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Literal">
<xsd:attribute name="value" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="CSSRules">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="property" type="Property" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Property">
<xsd:sequence>
<xsd:element name="category-list" type="CategoryList" minOccurs="0"/>
<xsd:element name="literal-list" type="LiteralList" minOccurs="0"/>
<xsd:element name="regexp-list" type="RegexpList" minOccurs="0"/>
<xsd:element name="shorthand-list" type="ShorthandList" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="default" type="xsd:string"/>
<xsd:attribute name="description" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="ShorthandList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="shorthand" type="Shorthand" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Shorthand">
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
<xsd:complexType name="CategoryList">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="category" type="Category" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Category">
<xsd:attribute name="value" type="xsd:string" use="required"/>
</xsd:complexType>
<xsd:complexType name="Entity">
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="cdata" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:schema>