Commit 96e8f5d3 authored by 廖旭伟's avatar 廖旭伟

移植基础平台代码

parent 0780982b
...@@ -30,10 +30,10 @@ ...@@ -30,10 +30,10 @@
<!-- <artifactId>spring-boot-starter-amqp</artifactId>--> <!-- <artifactId>spring-boot-starter-amqp</artifactId>-->
<!-- </dependency>--> <!-- </dependency>-->
<!-- <dependency> <!-- <dependency>
<groupId>io.sentry</groupId> <groupId>io.sentry</groupId>
<artifactId>sentry-spring-boot-starter</artifactId> <artifactId>sentry-spring-boot-starter</artifactId>
</dependency>--> </dependency>-->
<dependency> <dependency>
<groupId>io.sentry</groupId> <groupId>io.sentry</groupId>
<artifactId>sentry-logback</artifactId> <artifactId>sentry-logback</artifactId>
...@@ -64,11 +64,11 @@ ...@@ -64,11 +64,11 @@
<version>2.6.0</version> <version>2.6.0</version>
</dependency> </dependency>
<!-- <dependency>--> <dependency>
<!-- <groupId>com.rabbitmq</groupId>--> <groupId>com.rabbitmq</groupId>
<!-- <artifactId>amqp-client</artifactId>--> <artifactId>amqp-client</artifactId>
<!-- <version>4.8.0</version>--> <version>4.8.0</version>
<!-- </dependency>--> </dependency>
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
......
package com.mortals.xhx.common.pdu.app;
import com.mortals.framework.model.BaseEntityLong;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* appPdu对象
*
* @author zxfei
* @date 2022-10-26
*/
@Data
public class AppPdu {
/**
* appId
*/
private Long appId;
}
\ No newline at end of file
package com.mortals.xhx.feign.app.device;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.pdu.app.AppPdu;
import com.mortals.xhx.feign.IFeign;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* 设备 Feign接口
*
* @author zxfei
* @date 2022-10-26
*/
//@FeignClient(name = "sst-manager", path = "/sst", fallbackFactory = AppFeignFallbackFactory.class)
public interface IAppFeign extends IFeign {
/**
* 设备保存更新
*
* @param appPdu
* @return
*/
@PostMapping(value = "/apps/forbidden")
Rest<Void> forbidden(@RequestBody AppPdu appPdu);
}
@Slf4j
@Component
class AppFeignFallbackFactory implements FallbackFactory<IAppFeign> {
@Override
public IAppFeign create(Throwable t) {
return new IAppFeign() {
@Override
public Rest<Void> forbidden(AppPdu appPdu) {
return Rest.fail("暂时无法通知,请稍后再试!");
}
};
}
}
...@@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.*;
* @author: zxfei * @author: zxfei
* @date: 2022/5/30 10:40 * @date: 2022/5/30 10:40
*/ */
@FeignClient(name = "base-manager", path = "/base", fallbackFactory = AreaFeignFallbackFactory.class) //@FeignClient(name = "base-manager", path = "/base", fallbackFactory = AreaFeignFallbackFactory.class)
public interface IApiAreaFeign extends IFeign { public interface IApiAreaFeign extends IFeign {
......
...@@ -16,7 +16,7 @@ import java.util.List; ...@@ -16,7 +16,7 @@ import java.util.List;
* @author zxfei * @author zxfei
* @date 2022-10-26 * @date 2022-10-26
*/ */
@FeignClient(name = "device-manager", path = "/m", fallbackFactory = DeviceFeignFallbackFactory.class) //@FeignClient(name = "device-manager", path = "/m", fallbackFactory = DeviceFeignFallbackFactory.class)
public interface IDeviceFeign extends IFeign { public interface IDeviceFeign extends IFeign {
......
...@@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import java.util.List; import java.util.List;
@FeignClient(name = "base-manager", path = "/base", fallbackFactory = ModelFeignFallbackFactory.class) //@FeignClient(name = "base-manager", path = "/base", fallbackFactory = ModelFeignFallbackFactory.class)
public interface IApiModelFeign extends IFeign { public interface IApiModelFeign extends IFeign {
/** /**
......
package com.mortals.xhx.feign.user;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.feign.IFeign;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户信息业务 Feign接口
*
* @author zxfei
* @date 2022-07-06
*/
//@FeignClient(name = "portal-manager", path = "/zwfw", fallbackFactory = UserFeignFallbackFactory.class)
public interface IUserFeign extends IFeign {
/**
* 查看用户信息业务列表
*
* @param userPdu
* @return
*/
@PostMapping(value = "/user/list")
Rest<RespData<List<UserPdu>>> list(@RequestBody UserPdu userPdu);
/**
* 查看用户信息业务
*
* @param id
* @return
*/
@GetMapping(value = "/user/info")
Rest<UserPdu> info(@RequestParam(value = "id") Long id);
/**
* 删除用户信息业务
*
* @param ids
* @return
*/
@GetMapping(value = "/user/delete")
Rest<Void> delete(Long[] ids, @RequestHeader("Authorization") String authorization);
/**
* 用户信息业务保存更新
*
* @param userPdu
* @return
*/
@PostMapping(value = "/user/save")
Rest<RespData<UserPdu>> save(@RequestBody UserPdu userPdu, @RequestHeader("Authorization") String authorization);
@PostMapping(value = "/login/login")
String portalLogin(@RequestBody UserPdu userPdu);
/**
* 获取token
*
* @param
* @return
*/
@PostMapping(value = "/user/token")
Rest<String> getToken(@RequestParam(value = "userKey") String userKey);
@PostMapping(value = "/user/synchSiteAuth")
Rest<String> synchSiteAuth();
}
@Slf4j
@Component
class UserFeignFallbackFactory implements FallbackFactory<IUserFeign> {
@Override
public IUserFeign create(Throwable t) {
log.error("feign error", t);
return new IUserFeign() {
@Override
public Rest<RespData<List<UserPdu>>> list(UserPdu userPdu) {
return Rest.fail("暂时无法获取用户信息业务列表,请稍后再试!");
}
@Override
public Rest<UserPdu> info(Long id) {
return Rest.fail("暂时无法获取用户信息业务详细,请稍后再试!");
}
@Override
public Rest<Void> delete(Long[] ids, String authorization) {
return Rest.fail("暂时无法删除用户信息业务,请稍后再试!");
}
@Override
public Rest<RespData<UserPdu>> save(UserPdu userPdu, String authorization) {
return Rest.fail("暂时无法保存用户信息业务,请稍后再试!");
}
@Override
public String portalLogin(UserPdu userPdu) {
return JSON.toJSONString(Rest.fail("登录失败!"));
}
@Override
public Rest<String> getToken(String userKey) {
return Rest.fail("token获取失败");
}
@Override
public Rest<String> synchSiteAuth() {
return Rest.fail("同步请求失败,稍后再试!");
}
};
}
}
...@@ -25,12 +25,10 @@ ...@@ -25,12 +25,10 @@
// private RabbitTemplate rabbitTemplate; // private RabbitTemplate rabbitTemplate;
// //
// public void syncAccessSend(AccessLogPdu accessLogPdu) { // public void syncAccessSend(AccessLogPdu accessLogPdu) {
// // new Message()
//
// //new Message(JSON.toJSONString(accessLogPdu).getBytes(StandardCharsets.UTF_8)) // //new Message(JSON.toJSONString(accessLogPdu).getBytes(StandardCharsets.UTF_8))
// rabbitTemplate.send(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE,new Message(JSON.toJSONString(accessLogPdu).getBytes(StandardCharsets.UTF_8))); // //rabbitTemplate.send(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE,new Message(JSON.toJSONString(accessLogPdu).getBytes(StandardCharsets.UTF_8)));
// //
// //rabbitTemplate.convertAndSend(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE, JSON.toJSONString(accessLogPdu)); // rabbitTemplate.convertAndSend(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE, JSON.toJSONString(accessLogPdu));
// //rabbitTemplate.convertAndSend(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE, accessLogPdu); // //rabbitTemplate.convertAndSend(QueueKey.EXCHANGE, QueueKey.ACCESS_LOG_QUEUE, accessLogPdu);
// } // }
// //
......
This diff is collapsed.
...@@ -5,13 +5,13 @@ import java.util.Date; ...@@ -5,13 +5,13 @@ import java.util.Date;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import com.mortals.framework.model.OperateLogPdu; import com.mortals.framework.model.OperateLogPdu;
import com.mortals.framework.service.IMessageProduceService; //import com.mortals.xhx.system.MessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -30,31 +30,32 @@ import com.mortals.xhx.base.system.oper.service.OperLogService; ...@@ -30,31 +30,32 @@ import com.mortals.xhx.base.system.oper.service.OperLogService;
* @date: 2021/11/5 13:28 * @date: 2021/11/5 13:28
*/ */
@Component @Component
@Slf4j public class OperlogAspect extends FileLogServiceImpl implements ILogService {
public class OperlogAspect extends FileLogServiceImpl implements ILogService {
@Autowired @Autowired
private OperLogService operLogService; private OperLogService operLogService;
@Autowired // @Autowired
private IMessageProduceService messageProduceService; // private MessageProducer messageProducer;
@Override @Override
public void doHandlerLog(String platformMark, Long userId, String userName, String loginName, String requestUrl, public void doHandlerLog(String platformMark, Long userId, String userName, String loginName, String requestUrl,
String content, String ip, Date logDate) { String content, String ip, Date logDate) {
super.doHandlerLog(platformMark, userId, userName, loginName, requestUrl, content, ip, logDate); super.doHandlerLog(platformMark, userId, userName, loginName, requestUrl, content, ip, logDate);
//操作日志 只记录用户侧
if(userId==null) return;
operLogService.insertOperLog(ip, requestUrl, userId, userName, loginName, content); operLogService.insertOperLog(ip, requestUrl, userId, userName, loginName, content);
OperateLogPdu operateLogPdu = new OperateLogPdu(); // OperateLogPdu operateLogPdu = new OperateLogPdu();
operateLogPdu.initAttrValue(); // operateLogPdu.initAttrValue();
operateLogPdu.setIp(ip); // operateLogPdu.setIp(ip);
operateLogPdu.setRequestUrl(requestUrl); // operateLogPdu.setRequestUrl(requestUrl);
operateLogPdu.setUserId(userId); // operateLogPdu.setUserId(userId);
operateLogPdu.setUserName(userName); // operateLogPdu.setUserName(userName);
operateLogPdu.setLoginName(loginName); // operateLogPdu.setLoginName(loginName);
operateLogPdu.setPlatformMark(platformMark); // operateLogPdu.setPlatformMark(platformMark);
operateLogPdu.setLogDate(logDate); // operateLogPdu.setLogDate(logDate);
operateLogPdu.setContent(content); // operateLogPdu.setContent(content);
operateLogPdu.setOperType(1); // operateLogPdu.setOperType(1);
messageProduceService.syncOperSend(operateLogPdu); // messageProducer.syncOperSend(operateLogPdu);
} }
...@@ -63,11 +64,9 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService { ...@@ -63,11 +64,9 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
// operLogService.insertOperLog(ip, requestUrl, null, "", loginName, // operLogService.insertOperLog(ip, requestUrl, null, "", loginName,
// content); // content);
this.doHandlerLog(platformMark, null, "", loginName, requestUrl, content, ip, new Date()); this.doHandlerLog(platformMark, null, "", loginName, requestUrl, content, ip, new Date());
} }
/*
/*@Pointcut("execution(public * com.mortals.xhx..*Controller.*(..))") @Pointcut("execution(public * com.mortals.xhx..*Controller.*(..))")
public void accessLog() { public void accessLog() {
} }
...@@ -77,13 +76,13 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService { ...@@ -77,13 +76,13 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
// url // url
log.info("ip[{}]url[{}]", request.getRemoteAddr(), request.getRequestURL()); logger.info("ip[{}]url[{}]", request.getRemoteAddr(), request.getRequestURL());
// 参数第1和第2个参数为HttpServletRequest request, HttpServletResponse // 参数第1和第2个参数为HttpServletRequest request, HttpServletResponse
// response // response
if (joinPoint.getArgs().length > 2) { if (joinPoint.getArgs().length > 2) {
log.info("args={}", joinPoint.getArgs()[2]); logger.info("args={}", joinPoint.getArgs()[2]);
} else { } else {
log.info("args={}", joinPoint.getArgs()); logger.info("args={}", joinPoint.getArgs());
} }
} }
...@@ -91,7 +90,7 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService { ...@@ -91,7 +90,7 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
@AfterReturning(returning = "object", pointcut = "accessLog()") @AfterReturning(returning = "object", pointcut = "accessLog()")
public void doAfterReturning(Object object) { public void doAfterReturning(Object object) {
if (null != object) { if (null != object) {
log.info("response={}", object.toString()); logger.info("response={}", object.toString());
} }
}*/ }*/
} }
package com.mortals.xhx.base.framework.aspect; package com.mortals.xhx.base.framework.aspect;
import cn.hutool.core.net.Ipv4Util; import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil; import cn.hutool.core.net.NetUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.common.pdu.access.AccessLogPdu;
//import com.mortals.xhx.system.MessageProducer;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
...@@ -12,9 +15,12 @@ import org.aspectj.lang.annotation.Aspect; ...@@ -12,9 +15,12 @@ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingRequestWrapper;
...@@ -22,6 +28,7 @@ import org.springframework.web.util.ContentCachingRequestWrapper; ...@@ -22,6 +28,7 @@ import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map; import java.util.Map;
/** /**
...@@ -33,9 +40,19 @@ import java.util.Map; ...@@ -33,9 +40,19 @@ import java.util.Map;
//@Aspect //@Aspect
//@Component //@Component
@Slf4j @Slf4j
@Order(1) //@Order(1)
//@Profile({"default", "develop", "test"}) @Profile({"default", "develop", "test"})
public class WebLogAspect { public class WebLogAspect {
@Value("${spring.application.name:base-platform}")
private String appName;
// @Autowired
// private MessageProducer messageProducer;
private static final String TRACE_ID = "traceId";
private static final String SPAN_ID = "spanId";
private static final String PSPAN_ID = "pspanId";
@Pointcut("execution(public * com.mortals..*Controller.*(..))") @Pointcut("execution(public * com.mortals..*Controller.*(..))")
public void webLog() { public void webLog() {
} }
...@@ -52,31 +69,74 @@ public class WebLogAspect { ...@@ -52,31 +69,74 @@ public class WebLogAspect {
public void doBefore(JoinPoint joinPoint) { public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
// log.debug("请求路径 {} ,进入方法 {}", request.getRequestURI(), joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName()); // log.debug("请求路径 {} ,进入方法 {}", request.getRequestURI(), joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName());
MDC.put("req", getRequestInfo(request).toJSONString()); MDC.put("req", getRequestInfo(request).toJSONString());
MDC.put("reqParams", getRequestInfoParams(request).toJSONString());
MDC.put("startTime", String.valueOf(System.currentTimeMillis())); MDC.put("startTime", String.valueOf(System.currentTimeMillis()));
} }
/** /**
* 打印请求日志 * 打印请求日志,包含异常
*/ */
@AfterReturning(pointcut = "webLog()|| exceptions()", returning = "result") @AfterReturning(pointcut = "webLog()|| exceptions()", returning = "result")
public void afterReturning(Object result) { public void afterReturning(Object result) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
String traceId = request.getHeader(TRACE_ID);
String pspanId = request.getHeader(PSPAN_ID);
String spanId = request.getHeader(SPAN_ID);
Map<String, String> map = MDC.getCopyOfContextMap(); Map<String, String> map = MDC.getCopyOfContextMap();
if (map != null&&result!=null) { if (map != null && result != null) {
String startTime = map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis())); String startTime = map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis()));
long takeTime = (System.currentTimeMillis() - Long.parseLong(startTime)); long takeTime = (System.currentTimeMillis() - Long.parseLong(startTime));
if (result instanceof String) { if (result instanceof String) {
log.info(" \n 请求路径:{} 耗时:{}ms 客户端IP:{} \n 请求报文:{} \n 响应报文:{} " log.debug(" \n 请求路径:{} 耗时:{}ms \n traceId:{} pspanId:{} spanId:{} \n 请求报文:{} \n 响应报文:{}"
, request.getRequestURI(), takeTime,ServletUtil.getClientIP(request), map.getOrDefault("req", ""), result); , request.getRequestURI(), takeTime, traceId, pspanId, spanId, map.getOrDefault("req", ""), result);
} else { } else {
log.info(" \n 请求路径:{} 耗时:{}ms 客户端IP:{}\n 请求报文:{} \n 响应报文:{}"
, request.getRequestURI(), takeTime,ServletUtil.getClientIP(request), map.getOrDefault("req", ""), JSON.toJSONString(result)); log.debug(" \n 请求路径:{} 耗时:{}ms \n traceId:{} pspanId:{} spanId:{} \n 请求报文:{} \n 响应报文:{}"
, request.getRequestURI(), takeTime, traceId, pspanId, spanId, map.getOrDefault("req", ""), JSON.toJSONString(result));
} }
if (!ObjectUtils.isEmpty(pspanId) && !ObjectUtils.isEmpty(spanId)) {
//paspId
spanId = String.valueOf(Integer.parseInt(spanId) + 1);
pspanId = spanId;
}else{
spanId="1";
pspanId="0";
}
String ua = request.getHeader("User-Agent");
AccessLogPdu accessLogPdu = new AccessLogPdu();
accessLogPdu.initAttrValue();
accessLogPdu.setAppName(appName);
accessLogPdu.setTraceID(traceId == null ? IdUtil.objectId() : traceId);
accessLogPdu.setPspanId(Integer.parseInt(pspanId));
accessLogPdu.setSpanId(Integer.parseInt(spanId));
accessLogPdu.setSchemaData(request.getScheme());
accessLogPdu.setHostName(NetUtil.getLocalHostName());
accessLogPdu.setUri(request.getRequestURI());
accessLogPdu.setTargetServer(appName);
accessLogPdu.setRequestIp(request.getRemoteAddr());
accessLogPdu.setUa(ua==null?"":ua);
accessLogPdu.setRequestTime(DateUtils.getDate(Long.parseLong(startTime)));
accessLogPdu.setLogTime(new Date());
accessLogPdu.setMethod(request.getMethod());
accessLogPdu.setResponseTime(new Date());
accessLogPdu.setDuration(takeTime);
accessLogPdu.setRequestData(map.getOrDefault("reqParams", ""));
if (result instanceof String) {
accessLogPdu.setResponseData(result.toString());
} else {
accessLogPdu.setResponseData(JSON.toJSONString(result));
}
log.info("accessLog:{}",JSON.toJSONString(accessLogPdu));
//messageProducer.syncAccessSend(accessLogPdu);
} }
} }
...@@ -109,4 +169,30 @@ public class WebLogAspect { ...@@ -109,4 +169,30 @@ public class WebLogAspect {
} }
return requestInfo; return requestInfo;
} }
/**
* 读取请求信息,如果是表单则转换为json
*/
private JSONObject getRequestInfoParams(HttpServletRequest req) {
JSONObject requestInfo = new JSONObject();
try {
if (req.getQueryString() != null) {
requestInfo.put("queryString", URLDecoder.decode(req.getQueryString(), "UTF-8"));
}
if (req instanceof ContentCachingRequestWrapper) {
ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) req;
String bodyStr = new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
if (bodyStr.startsWith("{")) {
JSONObject jsonObject = JSON.parseObject(bodyStr);
requestInfo.put("requestBody", jsonObject);
}
}
} catch (Exception e) {
log.error("解析请求失败", e);
requestInfo.put("parseError", e.getMessage());
}
return requestInfo;
}
} }
package com.mortals.xhx.base.framework.config; package com.mortals.xhx.base.framework.config;
import com.mortals.framework.springcloud.config.web.BaseWebMvcConfigurer; import com.mortals.framework.springcloud.config.web.BaseWebMvcConfigurer;
import com.mortals.xhx.base.framework.WxMessageConverter; import com.mortals.xhx.base.framework.feign.HierarchicalContract;
import feign.codec.Decoder; import feign.Contract;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -16,17 +13,15 @@ import org.springframework.context.annotation.Configuration; ...@@ -16,17 +13,15 @@ import org.springframework.context.annotation.Configuration;
**/ **/
@Configuration @Configuration
public class AccountConfig { public class AccountConfig {
@Bean @Bean
public BaseWebMvcConfigurer getBaseWebMvc() { public Contract feignContract() {
return new BaseWebMvcConfigurer(false, null); return new HierarchicalContract();
} }
@Bean @Bean
public Decoder feignDecoder() { public BaseWebMvcConfigurer getBaseWebMvc(){
WxMessageConverter wxConverter = new WxMessageConverter(); return new BaseWebMvcConfigurer(false,null);
ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(wxConverter);
return new SpringDecoder(objectFactory);
} }
} }
package com.mortals.xhx.base.framework.config; package com.mortals.xhx.base.framework.config;
import com.alibaba.fastjson.parser.ParserConfig;
import com.mortals.xhx.module.site.model.SiteTreeSelect;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfiguration;
...@@ -18,6 +20,8 @@ public class CorsConfig implements WebMvcConfigurer { ...@@ -18,6 +20,8 @@ public class CorsConfig implements WebMvcConfigurer {
@Bean @Bean
public CorsFilter corsFilter(){ public CorsFilter corsFilter(){
ParserConfig.getGlobalInstance().putDeserializer(SiteTreeSelect.class, new SiteTreeSelect.Deserializer());
//初始化配置对象 //初始化配置对象
CorsConfiguration configuration = new CorsConfiguration(); CorsConfiguration configuration = new CorsConfiguration();
//允许跨域访问的域名 //允许跨域访问的域名
......
...@@ -21,6 +21,7 @@ public class CrossInterceptor extends HandlerInterceptorAdapter { ...@@ -21,6 +21,7 @@ public class CrossInterceptor extends HandlerInterceptorAdapter {
response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Content-Type", "true");
return true; return true;
} }
} }
...@@ -3,11 +3,15 @@ package com.mortals.xhx.base.framework.config; ...@@ -3,11 +3,15 @@ package com.mortals.xhx.base.framework.config;
import com.mortals.framework.filter.RepeatableFilter; import com.mortals.framework.filter.RepeatableFilter;
import com.mortals.framework.filter.XssFilter; import com.mortals.framework.filter.XssFilter;
import com.mortals.framework.util.StringUtils; import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.framework.filter.RepeatReadHttpRequest;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.DispatcherType; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -16,7 +20,7 @@ import java.util.Map; ...@@ -16,7 +20,7 @@ import java.util.Map;
* *
* @author zxfei * @author zxfei
*/ */
//@Configuration @Configuration
public class FilterConfig { public class FilterConfig {
@Value("${xss.enabled}") @Value("${xss.enabled}")
private String enabled; private String enabled;
...@@ -44,7 +48,7 @@ public class FilterConfig { ...@@ -44,7 +48,7 @@ public class FilterConfig {
} }
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@Bean /* @Bean
public FilterRegistrationBean someFilterRegistration() { public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean(); FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter()); registration.setFilter(new RepeatableFilter());
...@@ -52,6 +56,33 @@ public class FilterConfig { ...@@ -52,6 +56,33 @@ public class FilterConfig {
registration.setName("repeatableFilter"); registration.setName("repeatableFilter");
registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
return registration; return registration;
}*/
@Bean
public FilterRegistrationBean requestReplaceFilterRegistration() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new RequestReplaceFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("RequestReplaceFilter");
registrationBean.setOrder(1);
return registrationBean;
}
public static class RequestReplaceFilter implements Filter {
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new RepeatReadHttpRequest((HttpServletRequest) servletRequest), servletResponse);
}
} }
} }
package com.mortals.xhx.base.framework.exception; package com.mortals.xhx.base.framework.exception;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
...@@ -13,30 +14,29 @@ import com.mortals.framework.exception.AppException; ...@@ -13,30 +14,29 @@ import com.mortals.framework.exception.AppException;
* 统一异常处理 * 统一异常处理
*/ */
@ControllerAdvice @ControllerAdvice
@Slf4j
public class ExceptionHandle { public class ExceptionHandle {
private final static Logger log = LoggerFactory.getLogger(ExceptionHandle.class); public static final String KEY_RESULT_CODE = "code";
public static final String KEY_RESULT_MSG = "msg";
public static final String KEY_RESULT_DATA = "data";
public static final int VALUE_RESULT_FAILURE = -1;
public static final String KEY_RESULT_CODE = "code"; @ExceptionHandler(value = Exception.class)
public static final String KEY_RESULT_MSG = "msg"; @ResponseBody
public static final String KEY_RESULT_DATA = "data"; public String handle(Exception e) {
public static final int VALUE_RESULT_FAILURE = -1; JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
@ExceptionHandler(value = Exception.class) if (e instanceof AppException) {
@ResponseBody StackTraceElement stack = e.getStackTrace()[0];
public String handle(Exception e) { log.error("[business error]=========stack message[{}],[{},method:{},line{}][{}]", e.getMessage(),
JSONObject ret = new JSONObject(); stack.getClassName(), stack.getMethodName(), stack.getLineNumber(), e.getClass().getName());
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE); AppException ex = (AppException) e;
if (e instanceof AppException) { ret.put(KEY_RESULT_MSG, ex.getMessage());
StackTraceElement stack = e.getStackTrace()[0]; } else {
log.error("[business error]=========stack message[{}],[{},method:{},line{}][{}]", e.getMessage(), log.error("[system error]", e);
stack.getClassName(), stack.getMethodName(), stack.getLineNumber(), e.getClass().getName()); ret.put(KEY_RESULT_MSG, "未知错误!");
AppException ex = (AppException) e; }
ret.put(KEY_RESULT_MSG, ex.getMessage()); return ret.toJSONString();
} else { }
log.error("[system error]", e);
ret.put(KEY_RESULT_MSG, "unknown exception!");
}
return ret.toJSONString();
}
} }
package com.mortals.xhx.base.framework.filter;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.mortals.framework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.util.WebUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class RepeatReadHttpRequest extends HttpServletRequestWrapper {
private final ByteArrayOutputStream cachedContent;
private Map<String, String[]> cachedForm;
private ServletInputStream inputStream;
public RepeatReadHttpRequest(HttpServletRequest request) {
super(request);
this.cachedContent = new ByteArrayOutputStream();
this.cachedForm = new HashMap<>();
cacheData();
}
@Override
public ServletInputStream getInputStream() throws IOException {
this.inputStream = new RepeatReadInputStream(cachedContent.toByteArray());
return this.inputStream;
}
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
@Override
public String getParameter(String name) {
String value = null;
if (isFormPost()) {
String[] values = cachedForm.get(name);
if (null != values && values.length > 0) {
value = values[0];
}
}
if (StringUtils.isEmpty(value)) {
value = super.getParameter(name);
}
return value;
}
@Override
public Map<String, String[]> getParameterMap() {
if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
return cachedForm;
}
return super.getParameterMap();
}
@Override
public Enumeration<String> getParameterNames() {
if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
return Collections.enumeration(cachedForm.keySet());
}
return super.getParameterNames();
}
@Override
public String[] getParameterValues(String name) {
if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
return cachedForm.get(name);
}
return super.getParameterValues(name);
}
private void cacheData() {
try {
if (isFormPost()) {
this.cachedForm = super.getParameterMap();
} else {
ServletInputStream inputStream = super.getInputStream();
IOUtils.copy(inputStream, this.cachedContent);
}
} catch (IOException e) {
log.warn("[RepeatReadHttpRequest:cacheData], error: {}", e.getMessage());
}
}
private boolean isFormPost() {
String contentType = getContentType();
return (contentType != null &&
(contentType.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE) ||
contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)) &&
HttpMethod.POST.matches(getMethod()));
}
private static class RepeatReadInputStream extends ServletInputStream {
private final ByteArrayInputStream inputStream;
public RepeatReadInputStream(byte[] bytes) {
this.inputStream = new ByteArrayInputStream(bytes);
}
@Override
public int read() throws IOException {
return this.inputStream.read();
}
@Override
public int readLine(byte[] b, int off, int len) throws IOException {
return this.inputStream.read(b, off, len);
}
@Override
public boolean isFinished() {
return this.inputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
}
}
}
\ No newline at end of file
...@@ -6,53 +6,45 @@ import org.springframework.stereotype.Component; ...@@ -6,53 +6,45 @@ import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.servlet.Filter; import javax.servlet.*;
import javax.servlet.FilterChain; import javax.servlet.annotation.WebFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
*
* 请求过滤链 * 请求过滤链
*
* @author: zxfei * @author: zxfei
* @date: 2022/4/20 14:52 * @date: 2022/4/20 14:52
*/ */
//@Component //@WebFilter(urlPatterns = "/*")
@Slf4j @Slf4j
public class RequestFilter extends OncePerRequestFilter implements Filter { public class RequestFilter implements Filter {
private static final String FORM_CONTENT_TYPE = "multipart/form-data";
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { public void init(FilterConfig filterConfig) {
try {
request = new ContentCachingRequestWrapper(request);
filterChain.doFilter(request, response);
} catch (Exception e) {
throw e;
} finally {
//清理ThreadLocal
MDC.clear();
}
} }
@Override
/*private void setUsername(HttpServletRequest request) { public void doFilter(ServletRequest request, ServletResponse response,
//通过token解析出username FilterChain chain) throws IOException, ServletException {
String token = authTokenService.getToken(request); String contentType = request.getContentType();
//String token = request.getHeader("token"); if (request instanceof HttpServletRequest) {
if (!ObjectUtils.isEmpty(token)) { HttpServletRequest requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
MDC.put("token",token); // #1
MDC.put("token", token); if (contentType != null && contentType.contains(FORM_CONTENT_TYPE)) {
try { chain.doFilter(request, response);
SessionUserInfo info = tokenService.getUserInfo(); } else {
if (info != null) { chain.doFilter(requestWrapper, response);
String username = info.getUsername();
MDC.put("username", username);
}
} catch (CommonJsonException e) {
log.info("无效的token:{}", token);
} }
return;
} }
}*/ chain.doFilter(request, response);
}
@Override
public void destroy() {
}
} }
...@@ -8,14 +8,19 @@ import com.mortals.framework.service.IUser; ...@@ -8,14 +8,19 @@ import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DateUtils; import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils; import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.user.model.UserEntity; import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.feign.user.IUserFeign;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Base64; import java.util.Base64;
...@@ -27,11 +32,15 @@ import java.util.Map; ...@@ -27,11 +32,15 @@ import java.util.Map;
* *
* @author zxfei * @author zxfei
*/ */
@Primary
@Service @Service
@Order(1) @Order(1)
@Slf4j @Slf4j
public class AuthTokenServiceImpl implements IAuthTokenService { public class AuthTokenServiceImpl implements IAuthTokenService {
@Autowired
private UserService userService;
// 令牌自定义标识 // 令牌自定义标识
@Value("${token.header:Authorization}") @Value("${token.header:Authorization}")
private String header; private String header;
...@@ -54,9 +63,6 @@ public class AuthTokenServiceImpl implements IAuthTokenService { ...@@ -54,9 +63,6 @@ public class AuthTokenServiceImpl implements IAuthTokenService {
@Value("${token.database:0}") @Value("${token.database:0}")
private Integer portalDb; private Integer portalDb;
@Value("${platform.type:cloud}")
private String platFormType;//版本,默认云服务版本
protected static final Long SECOND = 1l; protected static final Long SECOND = 1l;
protected static final Long SECOND_MINUTE = 60 * SECOND; protected static final Long SECOND_MINUTE = 60 * SECOND;
...@@ -87,12 +93,21 @@ public class AuthTokenServiceImpl implements IAuthTokenService { ...@@ -87,12 +93,21 @@ public class AuthTokenServiceImpl implements IAuthTokenService {
Claims claims = parseToken(token); Claims claims = parseToken(token);
String uuid = (String) claims.get(SysConstains.LOGIN_USER_KEY); String uuid = (String) claims.get(SysConstains.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid); String userKey = getTokenKey(uuid);
// cacheService.select(portalDb); cacheService.select(portalDb);
String userStr = cacheService.get(userKey); String userStr = cacheService.get(userKey);
// cacheService.select(db); cacheService.select(db);
// Rest<String> rest = userFeign.getToken(userKey);
// String userStr = rest.getData();
if (StringUtils.isNotEmpty(userStr)) { if (StringUtils.isNotEmpty(userStr)) {
UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class); UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
userEntity.setToken(token); userEntity.setToken(token);
UserEntity temp = userService.selectOne(new UserQuery().loginName(userEntity.getLoginName()));
if(!ObjectUtils.isEmpty(temp)){
userEntity.setId(temp.getId());
}
return userEntity; return userEntity;
} }
} catch (Exception e) { } catch (Exception e) {
......
...@@ -21,7 +21,6 @@ import javax.servlet.http.HttpServletResponse; ...@@ -21,7 +21,6 @@ import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static com.mortals.xhx.common.key.ErrorCode.*; import static com.mortals.xhx.common.key.ErrorCode.*;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_USER_OPERATION_CONTENT;
/** /**
* 用户权限验证,基于token * 用户权限验证,基于token
...@@ -44,8 +43,8 @@ public class AuthUserInterceptor extends BaseInterceptor { ...@@ -44,8 +43,8 @@ public class AuthUserInterceptor extends BaseInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { throws Exception {
JSONObject ret = new JSONObject(); //response.setContentType("application/json");
if(handler instanceof HandlerMethod){ if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler; HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod(); Method method = handlerMethod.getMethod();
UnAuth annotation = method.getAnnotation(UnAuth.class); UnAuth annotation = method.getAnnotation(UnAuth.class);
...@@ -53,7 +52,7 @@ public class AuthUserInterceptor extends BaseInterceptor { ...@@ -53,7 +52,7 @@ public class AuthUserInterceptor extends BaseInterceptor {
//取消校验 //取消校验
return true; return true;
} }
}else if(handler instanceof ResourceHttpRequestHandler){ } else if (handler instanceof ResourceHttpRequestHandler) {
return true; return true;
} }
try { try {
...@@ -74,7 +73,7 @@ public class AuthUserInterceptor extends BaseInterceptor { ...@@ -74,7 +73,7 @@ public class AuthUserInterceptor extends BaseInterceptor {
if (ObjectUtils.isEmpty(loginUser)) { if (ObjectUtils.isEmpty(loginUser)) {
ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT))); ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT)));
return false; return false;
} else if (loginUser.isAdmin() || loginUser.getUserType() == 1 || loginUser.getUserType() == 2) { } else if (loginUser.isAdmin() || loginUser.getUserType() == 1) {
return super.preHandle(request, response, handler); return super.preHandle(request, response, handler);
} else { } else {
ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_USER_OPERATION, ERROR_USER_OPERATION_CONTENT))); ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_USER_OPERATION, ERROR_USER_OPERATION_CONTENT)));
...@@ -106,4 +105,5 @@ public class AuthUserInterceptor extends BaseInterceptor { ...@@ -106,4 +105,5 @@ public class AuthUserInterceptor extends BaseInterceptor {
return false; return false;
} }
} }
package com.mortals.xhx.base.framework.security; //package com.mortals.xhx.base.framework.security;
//
//import org.springframework.security.core.Authentication;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication; //import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//
/** ///**
* 安全服务工具类 // * 安全服务工具类
* // *
* @author zxfei // * @author zxfei
*/ // */
public class SecurityUtils { //public class SecurityUtils {
//
//
/** // /**
* 获取Authentication // * 获取Authentication
*/ // */
public static Authentication getAuthentication() { // public static Authentication getAuthentication() {
return null; // return SecurityContextHolder.getContext().getAuthentication();
} // }
//
/** // /**
* 生成BCryptPasswordEncoder密码 // * 生成BCryptPasswordEncoder密码
* // *
* @param password 密码 // * @param password 密码
* @return 加密字符串 // * @return 加密字符串
*/ // */
public static String encryptPassword(String password) { // public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password); // return passwordEncoder.encode(password);
} // }
//
/** // /**
* 判断密码是否相同 // * 判断密码是否相同
* // *
* @param rawPassword 真实密码 // * @param rawPassword 真实密码
* @param encodedPassword 加密后字符 // * @param encodedPassword 加密后字符
* @return 结果 // * @return 结果
*/ // */
public static boolean matchesPassword(String rawPassword, String encodedPassword) { // public static boolean matchesPassword(String rawPassword, String encodedPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword); // return passwordEncoder.matches(rawPassword, encodedPassword);
} // }
//
/** // /**
* 是否为管理员 // * 是否为管理员
* // *
* @param userId 用户ID // * @param userId 用户ID
* @return 结果 // * @return 结果
*/ // */
public static boolean isAdmin(Long userId) { // public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId; // return userId != null && 1L == userId;
} // }
} //}
package com.mortals.xhx.base.system.idgenerator.service.impl; package com.mortals.xhx.base.system.idgenerator.service.impl;
import cn.hutool.Hutool;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.mortals.xhx.base.system.idgenerator.dao.IdgeneratorDao; import com.mortals.xhx.base.system.idgenerator.dao.IdgeneratorDao;
import com.mortals.xhx.base.system.idgenerator.model.IdgeneratorEntity; import com.mortals.xhx.base.system.idgenerator.model.IdgeneratorEntity;
...@@ -68,6 +69,8 @@ public class IdgeneratorServiceImpl implements IdgeneratorService { ...@@ -68,6 +69,8 @@ public class IdgeneratorServiceImpl implements IdgeneratorService {
private final Class[] factorsClazz; private final Class[] factorsClazz;
private IdGeneratorKey(Long step, String methodName, Class[] factorsClazz) { private IdGeneratorKey(Long step, String methodName, Class[] factorsClazz) {
this.step = step; this.step = step;
this.methodName = methodName; this.methodName = methodName;
this.factorsClazz = factorsClazz; this.factorsClazz = factorsClazz;
......
...@@ -76,9 +76,6 @@ public class MenuEntity extends BaseEntityLong{ ...@@ -76,9 +76,6 @@ public class MenuEntity extends BaseEntityLong{
/** 创建用户名称 */ /** 创建用户名称 */
private String createUserName; private String createUserName;
private Integer type;
private List<MenuEntity> childList = new ArrayList<MenuEntity>(); private List<MenuEntity> childList = new ArrayList<MenuEntity>();
...@@ -86,14 +83,6 @@ public class MenuEntity extends BaseEntityLong{ ...@@ -86,14 +83,6 @@ public class MenuEntity extends BaseEntityLong{
} }
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
/** /**
* 获取 菜单名称 * 获取 菜单名称
* @return name * @return name
...@@ -421,7 +410,7 @@ public class MenuEntity extends BaseEntityLong{ ...@@ -421,7 +410,7 @@ public class MenuEntity extends BaseEntityLong{
this.name = null; this.name = null;
this.url = null; this.url = null;
this.parentId = null; this.parentId = null;
this.orderId = 0; this.orderId = null;
this.status = 1; this.status = 1;
this.linkType = 0; this.linkType = 0;
this.groupId = 1; this.groupId = 1;
......
...@@ -52,7 +52,7 @@ public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao, MenuEntity ...@@ -52,7 +52,7 @@ public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao, MenuEntity
@Override @Override
public List<MenuEntity> findTreeMenu(IUser user, Set<String> urls) throws AppException { public List<MenuEntity> findTreeMenu(IUser user, Set<String> urls) throws AppException {
Set<Long> authIds = new HashSet<>(); Set<Long> authIds = new HashSet<Long>();
Map<Long, MenuEntity> menuMap = new HashMap<Long, MenuEntity>(); Map<Long, MenuEntity> menuMap = new HashMap<Long, MenuEntity>();
List<MenuEntity> userModuleList = this.findAllEnable(); List<MenuEntity> userModuleList = this.findAllEnable();
for (MenuEntity sysModule : userModuleList) { for (MenuEntity sysModule : userModuleList) {
......
...@@ -6,9 +6,10 @@ import com.mortals.framework.exception.AppException; ...@@ -6,9 +6,10 @@ import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context; import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol; import com.mortals.framework.model.OrderCol;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController; import org.springframework.web.bind.annotation.PostMapping;
import com.mortals.xhx.base.system.menu.model.MenuQuery; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.web.BaseCRUDJsonMappingController; import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.menu.model.MenuEntity; import com.mortals.xhx.base.system.menu.model.MenuEntity;
...@@ -35,79 +36,82 @@ import java.util.Map; ...@@ -35,79 +36,82 @@ import java.util.Map;
*/ */
@RestController @RestController
@RequestMapping("menu") @RequestMapping("menu")
public class MenuController extends BaseCRUDJsonBodyMappingController<MenuService, MenuEntity, Long> { public class MenuController extends BaseCRUDJsonMappingController<MenuService, MenuForm,MenuEntity,Long> {
public MenuController() { public MenuController(){
super.setModuleDesc("菜单信息"); super.setFormClass(MenuForm.class);
} super.setModuleDesc("菜单信息");
}
@Override @Override
protected void doListBefore(MenuEntity query, Map<String, Object> model, Context context) throws AppException { protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MenuForm form, Map<String, Object> model, Context context) throws AppException {
List<OrderCol> orderColList = new ArrayList<OrderCol>(); List<OrderCol> orderColList = new ArrayList<OrderCol>();
orderColList.add(new OrderCol("parentId")); orderColList.add(new OrderCol("parentId"));
orderColList.add(new OrderCol("orderId")); orderColList.add(new OrderCol("orderId"));
query.setOrderColList(orderColList); form.getQuery().setOrderColList(orderColList);
} }
@Override @Override
protected void init(Map<String, Object> model, Context context) { protected void init(HttpServletRequest request, HttpServletResponse response, MenuForm form, Map<String, Object> model,
Map<String, Object> status = new HashMap<String, Object>(); Context context) {
status.put("status", DataSatus.getEnumMap(DataSatus.CLOSE.getValue(), DataSatus.DELETE.getValue(), DataSatus.OVERDUE.getValue(), DataSatus.USEOUT.getValue())); Map<String, Object> status = new HashMap<String, Object>();
status.put("linkType", MenuLinkType.getEnumMap()); status.put("status", DataSatus.getEnumMap(DataSatus.CLOSE.getValue(), DataSatus.DELETE.getValue(), DataSatus.OVERDUE.getValue(), DataSatus.USEOUT.getValue()));
status.put("commMenu", MenuComm.getEnumMap()); status.put("linkType", MenuLinkType.getEnumMap());
status.put("menuType", MenuType.getEnumMap()); status.put("commMenu", MenuComm.getEnumMap());
status.put("authType", MenuAuthType.getEnumMap()); status.put("menuType", MenuType.getEnumMap());
model.put(KEY_RESULT_DICT, status); status.put("authType", MenuAuthType.getEnumMap());
} model.put(KEY_RESULT_DICT, status);
super.init(request, response, form, model, context);
}
/** /**
* 改变状态 * 改变状态
*/ */
@RequestMapping(value = "change/status") @RequestMapping(value = "change/status")
public String changeStatus(@RequestBody MenuEntity query) { public String changeStatus(HttpServletRequest request, HttpServletResponse response, MenuForm form) {
JSONObject ret = new JSONObject(); JSONObject ret = new JSONObject();
Context context = getContext(); Context context = getContext();
try { try {
MenuEntity entity = this.service.get(query.getId(), context);//.doSubmitAudit(form.getEntity(), context); MenuEntity entity = this.service.get(form.getEntity().getId(), context);//.doSubmitAudit(form.getEntity(), context);
if (null == entity) { if (null == entity) {
throw new AppException("菜单不存在!"); throw new AppException("菜单不存在!");
} }
if (null == entity.getStatus()) { if (null == form.getEntity().getStatus()) {
throw new AppException("菜单状态不能为空!"); throw new AppException("菜单状态不能为空!");
} }
if (entity.getStatus() != DataSatus.ENABLE.getValue() && entity.getStatus() != DataSatus.DISENABLE.getValue()) { if (form.getEntity().getStatus() != DataSatus.ENABLE.getValue() && form.getEntity().getStatus() != DataSatus.DISENABLE.getValue()) {
throw new AppException("非法菜单状态!"); throw new AppException("非法菜单状态!");
} }
String busiDesc = DataSatus.getByValue(entity.getStatus()).getDesc(); String busiDesc = DataSatus.getByValue(form.getEntity().getStatus()).getDesc();
entity.setStatus(entity.getStatus()); entity.setStatus(form.getEntity().getStatus());
this.service.update(entity, context); this.service.update(entity, context);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS); ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, busiDesc + "成功"); ret.put(KEY_RESULT_MSG, busiDesc + "成功");
recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]"); recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]");
} catch (Exception e) { } catch (Exception e) {
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE); ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e)); ret.put(KEY_RESULT_MSG, super.convertException(e));
} }
return ret.toJSONString(); return ret.toJSONString();
} }
/** /**
* 更换排序 * 更换排序
*/ */
@PostMapping(value = "upOrDown") @PostMapping(value = "upOrDown")
public String upOrDownTopicList(@RequestBody MenuEntity query) { public String upOrDownTopicList(@RequestParam(value = "id") Long id, @RequestParam(value = "type") Integer type) {
JSONObject ret = new JSONObject(); JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS); ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
try { try {
this.service.upOrDown(query.getId(), query.getType()); this.service.upOrDown(id,type);
} catch (Exception e) { } catch (Exception e) {
log.error("更新错误", e); log.error("更新错误", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE); ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, e.getMessage()); ret.put(KEY_RESULT_MSG, e.getMessage());
} }
return ret.toJSONString(); return ret.toJSONString();
} }
} }
\ No newline at end of file
package com.mortals.xhx.base.system.message;
public interface MessageService {
/**
* 发送第三方平台四二班透传消息
*
* @param sendUrl
* @param content
* @return
*/
void sendThirdParty(String sendUrl, String content);
}
\ No newline at end of file
package com.mortals.xhx.base.system.message.impl;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.ICacheService;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.common.utils.SendTask;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* DeviceService
* 设备 service实现
*
* @author zxfei
* @date 2022-03-09
*/
@Service("messageService")
@Slf4j
public class MessageServiceImpl implements MessageService {
@Autowired
private SendTaskThreadPool sendTaskThreadPool;
@Override
public void sendThirdParty(String sendUrl, String content) {
SendTask sendTask = new SendTask(sendUrl, content);
sendTaskThreadPool.execute(sendTask);
}
public static void main(String[] args) {
}
}
\ No newline at end of file
...@@ -76,5 +76,6 @@ public interface OperLogService extends ICRUDService<OperLogEntity,Long> { ...@@ -76,5 +76,6 @@ public interface OperLogService extends ICRUDService<OperLogEntity,Long> {
void insertOperLog(HttpServletRequest request, IUser user, BaseEntity oldEntity, BaseEntity newEntity, OperTypeEnum operType, String content, String id); void insertOperLog(HttpServletRequest request, IUser user, BaseEntity oldEntity, BaseEntity newEntity, OperTypeEnum operType, String content, String id);
void insertOperLog(String ip, String requestUrl, Long userId, String userName, String loginName, String content); void insertOperLog(String ip, String requestUrl, Long userId, String userName, String loginName, String content);
} }
\ No newline at end of file
...@@ -114,6 +114,9 @@ public class OperLogServiceImpl extends AbstractCRUDServiceImpl<OperLogDao,OperL ...@@ -114,6 +114,9 @@ public class OperLogServiceImpl extends AbstractCRUDServiceImpl<OperLogDao,OperL
operLogEntity.setContent(content); operLogEntity.setContent(content);
save(operLogEntity, null); save(operLogEntity, null);
} }
private void formatterLogContent(OperLogEntity operLogEntity, String content, String id, OperTypeEnum operType) { private void formatterLogContent(OperLogEntity operLogEntity, String content, String id, OperTypeEnum operType) {
if (operType == OperTypeEnum.SAVE) { if (operType == OperTypeEnum.SAVE) {
......
/** /**
* 文件:OperLogController.java * 文件:OperLogController.java
* 版本:1.0.0 * 版本:1.0.0
* 日期: * 日期:
* Copyright &reg; * Copyright &reg;
* All right reserved. * All right reserved.
*/ */
package com.mortals.xhx.base.system.oper.web; package com.mortals.xhx.base.system.oper.web;
...@@ -12,7 +12,6 @@ import com.alibaba.fastjson.JSONObject; ...@@ -12,7 +12,6 @@ import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context; import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol; import com.mortals.framework.model.OrderCol;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.oper.model.OperLogEntity; import com.mortals.xhx.base.system.oper.model.OperLogEntity;
import com.mortals.xhx.base.system.oper.service.OperLogService; import com.mortals.xhx.base.system.oper.service.OperLogService;
import com.mortals.xhx.common.code.OperTypeEnum; import com.mortals.xhx.common.code.OperTypeEnum;
...@@ -34,36 +33,37 @@ import java.util.Map; ...@@ -34,36 +33,37 @@ import java.util.Map;
* <p>Description: OperLogController </p> * <p>Description: OperLogController </p>
* <p>Copyright: Copyright &reg; </p> * <p>Copyright: Copyright &reg; </p>
* <p>Company: </p> * <p>Company: </p>
* * @author
* @author
* @version 1.0.0 * @version 1.0.0
*/ */
@RestController @RestController
@RequestMapping("oper/log") @RequestMapping("oper/log")
public class OperLogController extends BaseCRUDJsonBodyMappingController<OperLogService, OperLogEntity, Long> { public class OperLogController extends BaseCRUDJsonMappingController<OperLogService,OperLogForm,OperLogEntity,Long> {
public OperLogController() { public OperLogController(){
super.setFormClass(OperLogForm.class); super.setFormClass(OperLogForm.class);
super.setModuleDesc("操作日志"); super.setModuleDesc("操作日志");
} }
@Override @Override
protected void init(Map<String, Object> model, Context context) { protected void init(HttpServletRequest request, HttpServletResponse response, OperLogForm form,
Map<String, Object> status = new HashMap<String, Object>(1); Map<String, Object> model, Context context) {
// 返回日志类型 Map<String, Object> status = new HashMap<String, Object>(1);
status.put("operType", OperTypeEnum.getEnumMap()); // 返回日志类型
status.put("operType", OperTypeEnum.getEnumMap());
model.put(KEY_RESULT_DICT, status); model.put(KEY_RESULT_DICT, status);
} super.init(request, response, form, model, context);
}
@Override @Override
protected void doListBefore(OperLogEntity query, Map<String, Object> model, Context context) throws AppException { protected void doListBefore(HttpServletRequest request, HttpServletResponse response, OperLogForm form, Map<String, Object> model, Context context) throws AppException {
query.setOrderColList(new ArrayList<OrderCol>() { form.getQuery().setOrderColList(new ArrayList<OrderCol>() {
{ {
add(new OrderCol("a.logDate", "desc")); add(new OrderCol("a.logDate", "desc"));
} }
}); });
} }
} }
\ No newline at end of file
...@@ -21,7 +21,7 @@ import java.util.Date; ...@@ -21,7 +21,7 @@ import java.util.Date;
* @author * @author
* @version 1.0.0 * @version 1.0.0
*/ */
public class ParamEntity extends ParamEntityExt implements IParam { public class ParamEntity extends BaseEntityLong implements IParam {
private static final long serialVersionUID = 1536307966363L; private static final long serialVersionUID = 1536307966363L;
/** 参数名称 */ /** 参数名称 */
......
...@@ -5,7 +5,6 @@ import com.mortals.framework.service.ICRUDCacheService; ...@@ -5,7 +5,6 @@ import com.mortals.framework.service.ICRUDCacheService;
import com.mortals.framework.service.IParamService; import com.mortals.framework.service.IParamService;
import com.mortals.xhx.base.system.param.model.ParamEntity; import com.mortals.xhx.base.system.param.model.ParamEntity;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
...@@ -45,35 +44,4 @@ public interface ParamService extends ICRUDCacheService<ParamEntity, Long>, IPar ...@@ -45,35 +44,4 @@ public interface ParamService extends ICRUDCacheService<ParamEntity, Long>, IPar
*/ */
Map<String, String> getParamBySecondOrganize(String firstOrganize,String secondOrganize, String... excludeParamKeys); Map<String, String> getParamBySecondOrganize(String firstOrganize,String secondOrganize, String... excludeParamKeys);
/**
* 获取热词列表
* @return
*/
String getHotWords();
/**
* 设置热词列表
* @return
*/
void setHotWords(String value);
/**
* 空白打印材料展示数量
* @return
*/
int getPrintDisplayQuantity();
/**
* 设置空白打印材料展示数量
* @return
*/
void setPrintDisplayQuantity(int value);
/**
* 通过Key设置参数值 value
* @param key
* @param value
* @return
*/
void setValueByKey(String key,String value);
} }
\ No newline at end of file
package com.mortals.xhx.base.system.param.service.impl; package com.mortals.xhx.base.system.param.service.impl;
import com.mortals.framework.common.code.YesNo; import cn.hutool.core.util.StrUtil;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.IParam; import com.mortals.framework.service.IParam;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl; import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.framework.util.DataUtil; import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.StringUtils; import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.dao.ParamDao; import com.mortals.xhx.base.system.param.dao.ParamDao;
import com.mortals.xhx.base.system.param.model.ParamEntity; import com.mortals.xhx.base.system.param.model.ParamEntity;
import com.mortals.xhx.base.system.param.model.ParamQuery;
import com.mortals.xhx.base.system.param.service.ParamService; import com.mortals.xhx.base.system.param.service.ParamService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -30,14 +29,25 @@ import java.util.stream.Collectors; ...@@ -30,14 +29,25 @@ import java.util.stream.Collectors;
@Service("paramService") @Service("paramService")
public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, ParamEntity, Long> public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, ParamEntity, Long>
implements ParamService { implements ParamService {
private final String HOT_WORDS = "HotWords";
private final String PRINT_QUANTITY = "PrintDisplayQuantity";
@Override @Override
protected String getCacheName() { protected String getCacheName() {
return "ParamEntity.paramKey"; return "ParamEntity.paramKey";
} }
/**
* @param entity
* @param context
* @throws AppException
*/
@Override
protected void saveBefore(ParamEntity entity, Context context) throws AppException {
//过滤换行符
entity.setParamKey(StrUtil.removeAllLineBreaks(entity.getParamKey()));
entity.setParamValue(StrUtil.removeAllLineBreaks(entity.getParamValue()));
super.saveBefore(entity, context);
}
@Override @Override
public String getValueByKey(String key) { public String getValueByKey(String key) {
List<ParamEntity> list = this.getCacheList(); List<ParamEntity> list = this.getCacheList();
...@@ -65,92 +75,6 @@ public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, Par ...@@ -65,92 +75,6 @@ public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, Par
).collect(Collectors.toMap(ParamEntity::getParamKey, ParamEntity::getParamValue, (o, n) -> n)); ).collect(Collectors.toMap(ParamEntity::getParamKey, ParamEntity::getParamValue, (o, n) -> n));
} }
@Override
public String getHotWords() {
return this.getParamValue(HOT_WORDS);
}
@Override
public void setHotWords(String value) {
List<ParamEntity> list = this.getCacheList();
ParamEntity entity = null;
for(ParamEntity paramEntity:list){
if(HOT_WORDS.equals(paramEntity.getParamKey())){
entity = paramEntity;
break;
}
}
if(entity!=null){
entity.setParamValue(value);
this.update(entity);
}else {
entity = new ParamEntity();
entity.setParamValue(value);
entity.setParamKey(HOT_WORDS);
entity.setName("热门搜索词汇");
entity.setCreateTime(new Date());
entity.setCreateUserId(1l);
entity.setCreateUserName("系统管理员");
this.save(entity);
}
}
@Override
public int getPrintDisplayQuantity() {
String printV = this.getParamValue(PRINT_QUANTITY);
return DataUtil.converStr2Int(printV,20);
}
@Override
public void setPrintDisplayQuantity(int value) {
List<ParamEntity> list = this.getCacheList();
ParamEntity entity = null;
for(ParamEntity paramEntity:list){
if(PRINT_QUANTITY.equals(paramEntity.getParamKey())){
entity = paramEntity;
break;
}
}
if(entity!=null){
entity.setParamValue(String.valueOf(value));
this.update(entity);
}else {
entity = new ParamEntity();
entity.setParamValue(String.valueOf(value));
entity.setParamKey(PRINT_QUANTITY);
entity.setName("空白打印材料展示数量");
entity.setCreateTime(new Date());
entity.setCreateUserId(1l);
entity.setCreateUserName("系统管理员");
this.save(entity);
}
}
@Override
public void setValueByKey(String key, String value) {
List<ParamEntity> list = this.getCacheList();
ParamEntity entity = null;
for(ParamEntity paramEntity:list){
if(key.equals(paramEntity.getParamKey())){
entity = paramEntity;
break;
}
}
if(entity!=null){
entity.setParamValue(String.valueOf(value));
this.update(entity);
}else {
entity = new ParamEntity();
entity.setParamValue(String.valueOf(value));
entity.setParamKey(key);
entity.setName("key");
entity.setCreateTime(new Date());
entity.setCreateUserId(1l);
entity.setCreateUserName("系统管理员");
this.save(entity);
}
}
@Override @Override
public boolean needRefresh() { public boolean needRefresh() {
......
...@@ -7,6 +7,7 @@ import com.mortals.framework.common.code.PageDisplayType; ...@@ -7,6 +7,7 @@ import com.mortals.framework.common.code.PageDisplayType;
import com.mortals.framework.model.Context; import com.mortals.framework.model.Context;
import com.mortals.framework.util.FileUtil; import com.mortals.framework.util.FileUtil;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -24,14 +25,14 @@ import java.util.HashMap; ...@@ -24,14 +25,14 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
*
* 参数信息 * 参数信息
*
* @author: zxfei * @author: zxfei
* @date: 2021/11/30 10:04 * @date: 2022/5/7 15:38
*/ */
@RestController @RestController
@RequestMapping("param") @RequestMapping("param")
public class ParamController extends BaseCRUDJsonMappingController<ParamService, ParamForm, ParamEntity, Long> { public class ParamController extends BaseCRUDJsonBodyMappingController<ParamService, ParamEntity, Long> {
public ParamController() { public ParamController() {
super.setFormClass(ParamForm.class); super.setFormClass(ParamForm.class);
...@@ -39,21 +40,17 @@ public class ParamController extends BaseCRUDJsonMappingController<ParamService, ...@@ -39,21 +40,17 @@ public class ParamController extends BaseCRUDJsonMappingController<ParamService,
} }
@Override @Override
protected void init(HttpServletRequest request, HttpServletResponse response, ParamForm form, protected void init(Map<String, Object> model, Context context) {
Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<String, Object>(); Map<String, Object> status = new HashMap<String, Object>();
status.put("validStatus", DataSatusEnum.getEnumMap(DataSatusEnum.CLOSE.getValue(), status.put("validStatus", DataSatusEnum.getEnumMap(DataSatusEnum.CLOSE.getValue(),
DataSatusEnum.DELETE.getValue(), DataSatusEnum.OVERDUE.getValue(), DataSatusEnum.USEOUT.getValue())); DataSatusEnum.DELETE.getValue(), DataSatusEnum.OVERDUE.getValue(), DataSatusEnum.USEOUT.getValue()));
status.put("modStatus", ModStatusEnum.getEnumMap()); status.put("modStatus", ModStatusEnum.getEnumMap());
status.put("displayType", getPageDisplayType()); status.put("displayType", getPageDisplayType());
model.put(KEY_RESULT_DICT, status); model.put(KEY_RESULT_DICT, status);
super.init(request, response, form, model, context);
} }
private Map<String, Object> getPageDisplayType() { private Map<String, Object> getPageDisplayType() {
PageDisplayType[] pageDisplayTypes = PageDisplayType.values(); PageDisplayType[] pageDisplayTypes = PageDisplayType.values();
Map<String, Object> result = new HashMap<>(pageDisplayTypes.length); Map<String, Object> result = new HashMap<>(pageDisplayTypes.length);
for (PageDisplayType pageDisplayType : pageDisplayTypes) { for (PageDisplayType pageDisplayType : pageDisplayTypes) {
...@@ -62,7 +59,6 @@ public class ParamController extends BaseCRUDJsonMappingController<ParamService, ...@@ -62,7 +59,6 @@ public class ParamController extends BaseCRUDJsonMappingController<ParamService,
return result; return result;
} }
public static void main(String[] args) { public static void main(String[] args) {
FileUtil.delete("E:\\pic\\1.png"); FileUtil.delete("E:\\pic\\1.png");
} }
......
...@@ -63,4 +63,5 @@ public interface ResourceService extends ICRUDService<ResourceEntity,Long> { ...@@ -63,4 +63,5 @@ public interface ResourceService extends ICRUDService<ResourceEntity,Long> {
* @param userType * @param userType
*/ */
List<ResourceEntity> findAll(int userType); List<ResourceEntity> findAll(int userType);
} }
\ No newline at end of file
...@@ -8,15 +8,30 @@ ...@@ -8,15 +8,30 @@
package com.mortals.xhx.base.system.resource.service.impl; package com.mortals.xhx.base.system.resource.service.impl;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl; import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.StringUtils; import com.mortals.framework.util.StringUtils;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.base.system.resource.dao.ResourceDao; import com.mortals.xhx.base.system.resource.dao.ResourceDao;
import com.mortals.xhx.base.system.resource.model.ResourceEntity; import com.mortals.xhx.base.system.resource.model.ResourceEntity;
import com.mortals.xhx.base.system.resource.model.ResourceQuery; import com.mortals.xhx.base.system.resource.model.ResourceQuery;
import com.mortals.xhx.base.system.resource.service.ResourceService; import com.mortals.xhx.base.system.resource.service.ResourceService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.common.utils.SyncTreeSiteThread;
import com.mortals.xhx.feign.user.IUserFeign;
import com.mortals.xhx.module.site.service.SiteService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
...@@ -52,7 +67,7 @@ public class ResourceServiceImpl extends AbstractCRUDServiceImpl<ResourceDao,Res ...@@ -52,7 +67,7 @@ public class ResourceServiceImpl extends AbstractCRUDServiceImpl<ResourceDao,Res
@Override @Override
public Set<String> findUrlSetByUserId(Long userId) throws AppException { public Set<String> findUrlSetByUserId(Long userId) throws AppException {
Set<String> urls = new HashSet<String>(); Set<String> urls = new HashSet<>();
List<ResourceEntity> resList = this.findListByUserId(userId); List<ResourceEntity> resList = this.findListByUserId(userId);
for (ResourceEntity res : resList) { for (ResourceEntity res : resList) {
String url = res.getUrl(); String url = res.getUrl();
...@@ -69,5 +84,7 @@ public class ResourceServiceImpl extends AbstractCRUDServiceImpl<ResourceDao,Res ...@@ -69,5 +84,7 @@ public class ResourceServiceImpl extends AbstractCRUDServiceImpl<ResourceDao,Res
public List<ResourceEntity> findAll(int userType) { public List<ResourceEntity> findAll(int userType) {
return dao.getAll(userType); return dao.getAll(userType);
} }
} }
\ No newline at end of file
...@@ -8,20 +8,13 @@ ...@@ -8,20 +8,13 @@
package com.mortals.xhx.base.system.role.service.impl; package com.mortals.xhx.base.system.role.service.impl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl; import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.base.system.role.dao.RoleDao; import com.mortals.xhx.base.system.role.dao.RoleDao;
import com.mortals.xhx.base.system.role.model.*; import com.mortals.xhx.base.system.role.model.RoleEntity;
import com.mortals.xhx.base.system.role.service.RoleAuthService;
import com.mortals.xhx.base.system.role.service.RoleService; import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Arrays;
/** /**
* <p>Title: 角色信息</p> * <p>Title: 角色信息</p>
* <p>Description: RoleServiceImpl service接口 </p> * <p>Description: RoleServiceImpl service接口 </p>
...@@ -32,29 +25,7 @@ import java.util.Arrays; ...@@ -32,29 +25,7 @@ import java.util.Arrays;
*/ */
@Service("roleService") @Service("roleService")
public class RoleServiceImpl extends AbstractCRUDServiceImpl<RoleDao,RoleEntity,Long> implements RoleService { public class RoleServiceImpl extends AbstractCRUDServiceImpl<RoleDao,RoleEntity,Long> implements RoleService {
@Autowired
private RoleAuthService roleAuthService;
@Autowired
private RoleUserService roleUserService;
@Override
protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
//删除关联角色
Arrays.asList(ids).stream().peek(roleId->{
RoleAuthQuery roleAuthQuery = new RoleAuthQuery();
roleAuthQuery.setRoleId(roleId);
Long[] roleAuthIds = roleAuthService.find(roleAuthQuery).stream().map(RoleAuthEntity::getId).toArray(Long[]::new);
roleAuthService.remove(roleAuthIds,context);
RoleUserQuery roleUserQuery = new RoleUserQuery();
roleUserQuery.setRoleId(roleId);
Long[] roleUserIds = roleUserService.find(roleUserQuery).stream().map(RoleUserEntity::getId).toArray(Long[]::new);
roleUserService.remove(roleUserIds,context);
}).count();
super.removeAfter(ids, context, result);
}
} }
\ No newline at end of file
...@@ -32,7 +32,6 @@ import java.util.Map; ...@@ -32,7 +32,6 @@ import java.util.Map;
@Service("roleUserService") @Service("roleUserService")
public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,RoleUserEntity,Long> implements RoleUserService { public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,RoleUserEntity,Long> implements RoleUserService {
@Override @Override
public void doDistributionUser(RoleUserQuery query) { public void doDistributionUser(RoleUserQuery query) {
Long roleId = query.getRoleId(); Long roleId = query.getRoleId();
...@@ -69,7 +68,5 @@ public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,Rol ...@@ -69,7 +68,5 @@ public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,Rol
} }
this.dao.insertBatch(list); this.dao.insertBatch(list);
} }
} }
\ No newline at end of file
...@@ -62,7 +62,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity ...@@ -62,7 +62,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
private Thread thread = null; private Thread thread = null;
/** 日志打印时间,key:任务ID,value:最后一次打印日志时间 */ /** 日志打印时间,key:任务ID,value:最后一次打印日志时间 */
private Map<Long, Long> printLogTime = new HashMap<>(); private Map<Long, Long> printLogTime = new HashMap<Long, Long>();
@Autowired(required=false) @Autowired(required=false)
private TaskService taskService; private TaskService taskService;
...@@ -216,17 +216,17 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity ...@@ -216,17 +216,17 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
} }
if (interimExcuteStatus != TaskInterimExcuteStatus.UNUSE.getValue() // 启用立即执行 if (interimExcuteStatus != TaskInterimExcuteStatus.UNUSE.getValue() // 启用立即执行
|| ((strategy == TaskExcuteStrategy.DAY.getValue() // 按天 || ((strategy == TaskExcuteStrategy.DAY.getValue() // 按天
|| (strategy == TaskExcuteStrategy.WEEK.getValue() || (strategy == TaskExcuteStrategy.WEEK.getValue()
&& week == excuteDate) && week == excuteDate)
// 按周 // 按周
|| (strategy == TaskExcuteStrategy.MONTH.getValue() || (strategy == TaskExcuteStrategy.MONTH.getValue()
&& (day == excuteDate && (day == excuteDate
|| (excuteDate > maxDay && day == maxDay))))// 按月 || (excuteDate > maxDay && day == maxDay))))// 按月
&& (excuteTime == currTime && (excuteTime == currTime
&& !lastExcuteTimeStr.equals(currDateTimeStr)) // 执行间隔最少为一天 && !lastExcuteTimeStr.equals(currDateTimeStr)) // 执行间隔最少为一天
) || (strategy == TaskExcuteStrategy.INTERVAL.getValue() // 按间隔时间 ) || (strategy == TaskExcuteStrategy.INTERVAL.getValue() // 按间隔时间
&& (lastExcuteTime == null || lastExcuteTime.getTime() && (lastExcuteTime == null || lastExcuteTime.getTime()
+ excuteDate * 1000 <= currDateTime.getTime()))) { + excuteDate * 1000 <= currDateTime.getTime()))) {
final boolean printLog = checkPrintLog(task); final boolean printLog = checkPrintLog(task);
Object excuteBean = GlobalSysInfo.getBeanByName(task.getExcuteService()); Object excuteBean = GlobalSysInfo.getBeanByName(task.getExcuteService());
if (excuteBean == null || !(excuteBean instanceof ITaskExcuteService)) { if (excuteBean == null || !(excuteBean instanceof ITaskExcuteService)) {
...@@ -261,7 +261,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity ...@@ -261,7 +261,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
log.error("执行任务失败-->" + excuteTask, e); log.error("执行任务失败-->" + excuteTask, e);
} }
if (strategy == TaskExcuteStrategy.INTERVAL.getValue()) { if (strategy == TaskExcuteStrategy.INTERVAL.getValue()) {
// 按间隔时间,更新执行时间,避免一直重复执行 // 按间隔时间,更新执行时间,避免一直重复执行
excuteTask.setLastExcuteTime(currDateTime); excuteTask.setLastExcuteTime(currDateTime);
} }
} finally { } finally {
......
...@@ -46,12 +46,24 @@ public interface UploadService extends IService { ...@@ -46,12 +46,24 @@ public interface UploadService extends IService {
*/ */
void fileDownload(String fileName, Boolean delete, HttpServletResponse response); void fileDownload(String fileName, Boolean delete, HttpServletResponse response);
/**
* 预览
* @param fileName
* @param response
*/
void preview(String fileName, HttpServletResponse response); void preview(String fileName, HttpServletResponse response);
/**
* 上传
* @param fileName
* @param response
*/
void uploadDownload(String fileName, HttpServletResponse response); void uploadDownload(String fileName, HttpServletResponse response);
/**
* 刪除
* @param fileName
*/
void deleteFile(String fileName); void deleteFile(String fileName);
} }
\ No newline at end of file
...@@ -7,6 +7,7 @@ import com.mortals.framework.service.IUser; ...@@ -7,6 +7,7 @@ import com.mortals.framework.service.IUser;
import com.mortals.framework.util.StringUtils; import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.upload.service.UploadService; import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.UploadFileType; import com.mortals.xhx.common.code.UploadFileType;
import com.mortals.xhx.utils.SpringUtils;
import lombok.Getter; import lombok.Getter;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
......
...@@ -2,7 +2,6 @@ package com.mortals.xhx.base.system.upload.web; ...@@ -2,7 +2,6 @@ package com.mortals.xhx.base.system.upload.web;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.framework.web.BaseController; import com.mortals.framework.web.BaseController;
import com.mortals.xhx.base.system.upload.service.UploadService; import com.mortals.xhx.base.system.upload.service.UploadService;
...@@ -29,7 +28,6 @@ public class UploadController extends BaseController { ...@@ -29,7 +28,6 @@ public class UploadController extends BaseController {
private UploadService uploadService; private UploadService uploadService;
@RequestMapping(value = "upload") @RequestMapping(value = "upload")
@UnAuth
public String doFileUpload(HttpServletRequest request, UploadForm form) { public String doFileUpload(HttpServletRequest request, UploadForm form) {
Map<String, Object> model = new HashMap<>(); Map<String, Object> model = new HashMap<>();
String jsonStr = ""; String jsonStr = "";
...@@ -54,7 +52,6 @@ public class UploadController extends BaseController { ...@@ -54,7 +52,6 @@ public class UploadController extends BaseController {
@RequestMapping(value = "commonupload") @RequestMapping(value = "commonupload")
@UnAuth
public String doFileUpload(MultipartFile file, @RequestParam(value = "prePath",defaultValue = "file/fileupload") String prePath) { public String doFileUpload(MultipartFile file, @RequestParam(value = "prePath",defaultValue = "file/fileupload") String prePath) {
Map<String, Object> model = new HashMap<>(); Map<String, Object> model = new HashMap<>();
String jsonStr = ""; String jsonStr = "";
......
...@@ -9,18 +9,12 @@ import com.mortals.framework.model.Context; ...@@ -9,18 +9,12 @@ import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController; import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BaseCRUDJsonMappingController; import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.framework.annotation.Operlog; import com.mortals.xhx.base.framework.annotation.Operlog;
import com.mortals.xhx.base.system.role.model.RoleQuery;
import com.mortals.xhx.base.system.role.model.RoleUserEntity;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.base.system.user.model.UserEntity; import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService; import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.UserStatus; import com.mortals.xhx.common.code.UserStatus;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
...@@ -32,7 +26,6 @@ import javax.servlet.http.HttpServletResponse; ...@@ -32,7 +26,6 @@ import javax.servlet.http.HttpServletResponse;
import java.util.Base64; import java.util.Base64;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
/** /**
* 用户信息 * 用户信息
...@@ -45,9 +38,7 @@ import java.util.stream.Collectors; ...@@ -45,9 +38,7 @@ import java.util.stream.Collectors;
public class UserController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> { public class UserController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> {
@Autowired @Autowired
private RoleService roleService; private UserService userService;
@Autowired
private RoleUserService roleUserService;
public UserController() { public UserController() {
super.setFormClass(UserForm.class); super.setFormClass(UserForm.class);
...@@ -56,10 +47,10 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic ...@@ -56,10 +47,10 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic
@Override @Override
protected void init(Map<String, Object> model, Context context) { protected void init(Map<String, Object> model, Context context) {
this.addDict(model,"userType", IBaseEnum.getEnumMap(UserType.class)); Map<String, Object> statsus = new HashMap<String, Object>();
this.addDict(model,"status", UserStatus.getEnumMap()); statsus.put("userType", IBaseEnum.getEnumMap(UserType.class));
this.addDict(model, "roleIds", roleService.find(new RoleQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName()))); statsus.put("status", UserStatus.getEnumMap());
model.put(KEY_RESULT_DICT, statsus);
} }
@Override @Override
...@@ -73,32 +64,32 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic ...@@ -73,32 +64,32 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic
} }
@Override @Override
protected int editAfter(Long id, Map<String, Object> model, UserEntity entity, Context context) throws AppException { protected int editAfter(Long id, Map<String, Object> model, UserEntity entity, Context context) throws AppException {
RoleUserQuery roleUserQuery = new RoleUserQuery(); entity.setLoginPwd(null);
roleUserQuery.setUserId(entity.getId()); entity.setLoginPwd1(null);
String roleIds = roleUserService.find(roleUserQuery).stream().map(RoleUserEntity::getRoleId).map(String::valueOf).collect(Collectors.joining(",")); entity.setLoginPwd2(null);
entity.setRoleIds(roleIds);
return super.editAfter(id, model, entity, context); return super.editAfter(id, model, entity, context);
} }
@Override @Override
protected int saveAfter(UserEntity entity, Map<String, Object> model, Context context) throws AppException { protected int saveAfter(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
if (entity.getId() == getCurUser().getId()) { if (entity.getId() == getCurUser().getId()) {
// TODO: 2022/8/15 更新redis session信息
//saveCurrUserForSession(request, response, userService.get(form.getEntity().getId(), false)); //saveCurrUserForSession(request, response, userService.get(form.getEntity().getId(), false));
} }
return super.saveAfter(entity, model, context); return super.saveAfter(entity, model, context);
} }
// @Override @Override
// protected void saveBefore(UserEntity entity, Map<String, Object> model, Context context) throws AppException { protected void saveBefore(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
// if (!ObjectUtils.isEmpty(entity.getLoginName()) && service.existUser(entity.getLoginName(), entity.getId())) { if (service.existUser(entity.getLoginName(), entity.getId())) {
// throw new AppException("登录名已存在!"); throw new AppException("登录名已存在!");
// } }
// super.saveBefore(entity, model, context); super.saveBefore(entity, model, context);
// } }
@RequestMapping(value = "change/password", method = RequestMethod.POST) @RequestMapping(value = "change/password", method = RequestMethod.POST)
......
package com.mortals.xhx.busiz.req;
import lombok.Data;
@Data
public class ApiThirdPartyReq<T> {
/**
* 结果编码
*/
private int code;
/**
* 结果描述
*/
private String msg;
private Integer type;
private Integer status;
private T data;
}
package com.mortals.xhx.busiz.req;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
/**
* 业务类
*
* @author:
* @date: 2022/9/7 14:35
*/
@Data
public class BussinessThirdPartyReq {
private Long id;
/**
* 业务名称
*/
private String name;
/**
* 备注
*/
private String remark;
/**
* 是否允许预约(1.允许,0.不允许)
*/
private Integer canorder;
/**
* 是否允许取号(1.允许,0.不允许)
*/
private Integer cantake;
/**
* 大厅情况展示 (1.展示,0.不展示)
*/
private Integer datashow;
/**
* 英语业务名
*/
private String englishname;
/**
* 业务状态 (0.停用,1.正常)
*/
private Integer status;
}
package com.mortals.xhx.busiz.req;
import lombok.Data;
/**
* 微中台请求接口
* @author:
* @date: 2023/3/2 18:08
*/
@Data
public class MidReq{
private String method;
private String body;
private String path;
}
package com.mortals.xhx.busiz.rsp;
import lombok.Data;
/**
* @author karlhoo
*/
@Data
public class MidResp {
private String appId;
private String appKey;
private String timeStamp;
private String nonce;
private String secretKey;
private String sign;
}
package com.mortals.xhx.busiz.rsp;
import lombok.Data;
/**
* @author karlhoo
*/
@Data
public class SignResp {
private String appId;
private String appKey;
private String timeStamp;
private String nonce;
private String secretKey;
private String sign;
}
package com.mortals.xhx.busiz.web;
import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.model.vo.MatterInfo;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.site.model.SiteMatterEntity;
import com.mortals.xhx.module.site.model.SiteMatterQuery;
import com.mortals.xhx.module.site.service.SiteMatterService;
import com.mortals.xhx.module.window.model.*;
import com.mortals.xhx.module.window.service.WindowBusinessService;
import com.mortals.xhx.module.window.service.WindowMatterService;
import com.mortals.xhx.module.window.service.WindowService;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.mortals.framework.ap.SysConstains.MESSAGE_INFO;
import static com.mortals.framework.ap.SysConstains.PAGEINFO_KEY;
/**
* 测试接口
*
* @author:
* @date: 2022/12/14 9:18
*/
@RestController
@RequestMapping("test")
@Slf4j
public class DemoWebApiController {
@Autowired
private WindowService windowService;
@Autowired
private SiteMatterService siteMatterService;
@Autowired
private WindowMatterService windowMatterService;
@Autowired
private DeptService deptService;
@Autowired
private MatterService matterService;
@PostMapping(value = "testGov")
@UnAuth
public Rest<String> testGov(@RequestBody MatterQuery query) {
String resp = HttpUtil.get(query.getUrl());
return Rest.ok(resp);
}
@PostMapping(value = "testCookie")
@UnAuth
public Rest<String> testCookie(@RequestBody MatterQuery query) {
log.info("测试cookie");
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
/* do stuff */
HttpGet httpRequest = new HttpGet(query.getUrl());
HttpResponse httpResponse = null;
try {
httpResponse = http.execute(httpRequest);
byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
String encode = Base64.encode(data);
//String content = EntityUtils.toString(entity, charset);
//httpResponse.getEntity()
//httpResponse.toString()
} catch (Exception e) {
log.error("异常", e);
}
/* check cookies */
String cookieStr = Arrays.asList(httpCookieStore.getCookies()).stream().map(item -> JSON.toJSONString(item)).collect(Collectors.joining("|"));
log.info("cookies:{}", cookieStr);
return Rest.ok(cookieStr);
}
@PostMapping(value = "reEventShow")
@UnAuth
public Rest<String> reEventShow() {
List<SiteMatterEntity> siteMatterEntities = siteMatterService.find(new SiteMatterQuery());
for (SiteMatterEntity siteMatterEntity : siteMatterEntities) {
if(ObjectUtils.isEmpty(siteMatterEntity.getEventTypeShow())){
MatterEntity matterEntity = matterService.get(siteMatterEntity.getMatterId());
if(!ObjectUtils.isEmpty(matterEntity)&&!ObjectUtils.isEmpty(matterEntity.getEventTypeShow())){
siteMatterEntity.setEventTypeShow(matterEntity.getEventTypeShow());
siteMatterService.update(siteMatterEntity);
}
}
}
return Rest.ok();
}
@PostMapping(value = "reDepts")
@UnAuth
public Rest<String> reDepts() {
log.info("更新部门与设备关联");
//更新窗口部门
List<WindowEntity> windowEntities = windowService.find(new WindowQuery());
for (WindowEntity windowEntity : windowEntities) {
String deptName = windowEntity.getDeptName();
//根据部门名称查询部门
DeptEntity deptEntity = deptService.selectOne(new DeptQuery().name(deptName+"%"));
if (!ObjectUtils.isEmpty(deptEntity)) {
if (deptEntity.getId() != windowEntity.getDeptId()&&deptEntity.getName().trim().equals(windowEntity.getDeptName().trim())) {
log.info("部门:{},更新部门id:orgin deptId:{} ,updateDeptId:{}", deptName, windowEntity.getDeptId(), deptEntity.getId());
WindowEntity temp = new WindowEntity();
temp.setId(windowEntity.getId());
temp.setDeptId(deptEntity.getId());
windowService.getDao().update(temp);
// windowService.update(windowEntity);
}
}
}
//更新窗口事项中的部门id
List<WindowMatterEntity> windowMatterEntities = windowMatterService.find(new WindowMatterQuery());
for (WindowMatterEntity windowMatterEntity : windowMatterEntities) {
DeptEntity deptEntity = deptService.selectOne(new DeptQuery().name(windowMatterEntity.getDeptName()+"%"));
if (!ObjectUtils.isEmpty(deptEntity)) {
if (deptEntity.getId() != windowMatterEntity.getDeptId()&&windowMatterEntity.getDeptName().trim().equals(deptEntity.getName())) {
WindowMatterEntity temp = new WindowMatterEntity();
temp.setId(windowMatterEntity.getId());
temp.setDeptId(deptEntity.getId());
temp.setDeptCode(deptEntity.getDeptNumber());
windowMatterService.getDao().update(temp);
// windowMatterService.update(windowMatterEntity);
}
}
}
List<SiteMatterEntity> siteMatterEntities = siteMatterService.find(new SiteMatterQuery());
for (SiteMatterEntity siteMatterEntity : siteMatterEntities) {
DeptEntity deptEntity = deptService.selectOne(new DeptQuery().name(siteMatterEntity.getDeptName()+"%"));
if (!ObjectUtils.isEmpty(deptEntity)) {
if (deptEntity.getId() != siteMatterEntity.getDeptId()&&siteMatterEntity.getDeptName().trim().equals(deptEntity.getName().trim())) {
SiteMatterEntity temp = new SiteMatterEntity();
temp.setId(siteMatterEntity.getId());
temp.setDeptId(deptEntity.getId());
temp.setDeptCode(deptEntity.getDeptNumber());
siteMatterService.getDao().update(temp);
//siteMatterService.update(siteMatterEntity);
}
}
}
return Rest.ok();
}
public static void main(String[] args) {
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
/* do stuff */
HttpGet httpRequest = new HttpGet("http://zxbl.sczwfw.gov.cn/app/account/imageCode");
HttpResponse httpResponse = null;
try {
httpResponse = http.execute(httpRequest);
byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
String encode = Base64.encode(data);
log.info("encode64:{}", encode);
// String resp = com.mortals.framework.util.HttpUtil.processMultipartResponse(httpResponse);
// log.info("resp:{}", resp);
//String content = EntityUtils.toString(entity, charset);
//httpResponse.getEntity()
//httpResponse.toString()
} catch (Exception e) {
log.error("异常", e);
}
/* check cookies */
String cookieStr = Arrays.asList(httpCookieStore.getCookies()).stream().map(item -> JSON.toJSONString(item)).collect(Collectors.joining("|"));
// log.info("cookies:{}", cookieStr);
}
}
package com.mortals.xhx.busiz.web;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.model.vo.MatterInfo;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.matters.service.MattersService;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static com.mortals.framework.ap.SysConstains.MESSAGE_INFO;
import static com.mortals.framework.ap.SysConstains.PAGEINFO_KEY;
/**
* 微官网接口
*
* @author:
* @date: 2022/12/14 9:18
*/
@RestController
@Slf4j
@RequestMapping("micro")
public class MicroWebApiController extends BaseJsonBodyController {
@Autowired
private MatterService matterService;
@PostMapping(value = "matter/list")
@UnAuth
public Rest<Object> list(@RequestBody MatterQuery query) {
Rest<Object> ret = new Rest<>();
Map<String, Object> model = new HashMap<>();
Context context = this.getContext();
String busiDesc = "查询微官网事项列表";
int code = VALUE_RESULT_SUCCESS;
try {
PageInfo pageInfo = this.buildPageInfo(query);
Result<MatterInfo> result = matterService.findMicroList(query, pageInfo, context);
model.put(KEY_RESULT_DATA, result.getList());
model.put(PAGEINFO_KEY, result.getPageInfo());
model.put(MESSAGE_INFO, busiDesc + "成功");
recordSysLog(request, busiDesc + " 【成功】");
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
this.doException(request, busiDesc, model, e);
}
ret.setCode(code);
ret.setData(model);
ret.setMsg(model.get(MESSAGE_INFO) == null ? "" : model.remove(MESSAGE_INFO).toString());
return ret;
}
@PostMapping(value = "getPicAndCookie")
@UnAuth
public Rest<Map<String,String>> getPicAndCookie(@RequestBody MatterQuery query) {
log.info("请求查询图片与cookies:{}",JSON.toJSONString(query));
HashMap<String, String> resultMap = new HashMap<>();
CookieStore httpCookieStore = new BasicCookieStore();
HttpClient http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
HttpGet httpRequest = new HttpGet(query.getUrl());
HttpResponse httpResponse = null;
try {
httpResponse = http.execute(httpRequest);
byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
String encode = Base64.encode(data);
resultMap.put("base64img","data:image/jpg;base64,"+encode);
resultMap.put("cookieStr",JSON.toJSONString(httpCookieStore.getCookies()));
} catch (Exception e) {
log.error("异常", e);
}
return Rest.ok(resultMap);
}
protected PageInfo buildPageInfo(MatterQuery query) {
PageInfo pageInfo = new PageInfo();
if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getPage())) {
pageInfo.setCurrPage(query.getPage());
}
if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getSize())) {
pageInfo.setPrePageResult(query.getSize());
}
return pageInfo;
}
}
package com.mortals.xhx.common.utils;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
@Slf4j
public class EncryptionUtils {
private enum DigestType{
MD5("MD5"),
SHA("SHA"),
SHA256("SHA-256");
private String name;
private DigestType(String name){
this.name = name;
}
public String getName() {
return name;
}
}
private final static String digest(String sourceStr,DigestType type) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = sourceStr.getBytes();
// 获得摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance(type.name);
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int length = md.length;
char str[] = new char[length * 2];
int k = 0;
for (int i = 0; i < length; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
log.error("签名失败", e);
return "";
}
}
public final static String MD5(String s) {
return digest(s, DigestType.MD5);
}
public final static String SHA(String s) {
return digest(s, DigestType.SHA);
}
public final static String SHA256(String s){
return digest(s, DigestType.SHA256);
}
}
...@@ -51,10 +51,40 @@ public class MatterHtmlParseUtil { ...@@ -51,10 +51,40 @@ public class MatterHtmlParseUtil {
return Rest.ok(resultMap); return Rest.ok(resultMap);
} }
public static Rest<Map<String, Integer>> statSiteMatterDeptCount(Map<String, String> params, String url) {
String matterTotalExp = "//input[@id=\"result_countDept\"]";
String matterPageExp = "//input[@id=\"pageNumDept\"]";
Map<String, Integer> resultMap = new HashMap<>();
try {
Document dom = Jsoup.connect(url).data(params).get();
Elements elements = dom.selectXpath(matterTotalExp);
if (elements.size() > 0) {
Integer total = elements.get(0) == null ? 0 : DataUtil.converStr2Int(elements.get(0).attr("value"), 0);
resultMap.put("total", total);
}
elements = dom.selectXpath(matterPageExp);
if (elements.size() > 0) {
Integer pageNum = elements.get(0) == null ? 0 : DataUtil.converStr2Int(elements.get(0).attr("value"), 0);
resultMap.put("pageNum", pageNum);
}
} catch (Exception e) {
log.error("获取事项数量异常!params:" + JSON.toJSONString(params), e);
return Rest.fail(e.getMessage());
}
return Rest.ok(resultMap);
}
public static Rest<List<MatterEntity>> getMatterList(Map<String, String> params, String url) { public static Rest<List<MatterEntity>> getMatterList(Map<String, String> params, String url) {
String matterListExp = "//div[@class=\"sx_list\"]//span[1]"; String matterListExp = "//div[@class=\"sx_list\"]//span[1]";
String matterListLiExp = "//div[@class=\"sx_list\"]//li/a[1]"; String matterListLiExp = "//div[@class=\"sx_list\"]//li/a[1]";
List<MatterEntity> matterEntityList = new ArrayList<>(); List<MatterEntity> matterEntityList = new ArrayList<>();
String evaluationUrl = "";
String netApplyUrl = "";
String href = "";
try { try {
Document dom = Jsoup.connect(url).data(params).get(); Document dom = Jsoup.connect(url).data(params).get();
//System.out.println(dom.html()); //System.out.println(dom.html());
...@@ -66,7 +96,7 @@ public class MatterHtmlParseUtil { ...@@ -66,7 +96,7 @@ public class MatterHtmlParseUtil {
continue; continue;
} }
String title = element.attr("title"); String title = element.attr("title");
String href = element.firstElementChild().attr("href"); href = element.firstElementChild().attr("href");
//element.child() //element.child()
if (href.equalsIgnoreCase("javascript:void(0)")) { if (href.equalsIgnoreCase("javascript:void(0)")) {
...@@ -74,18 +104,22 @@ public class MatterHtmlParseUtil { ...@@ -74,18 +104,22 @@ public class MatterHtmlParseUtil {
} }
//抓取申请与评价页面地址 //抓取申请与评价页面地址
Element nextElementSibling = element.nextElementSibling(); Element nextElementSibling = element.nextElementSibling();
Elements elementsA = nextElementSibling.children();
String evaluationUrl = ""; //Elements elementsA = nextElementSibling.selectXpath("//a");
String netApplyUrl = "";
Elements elementsA = nextElementSibling.selectXpath("//a");
if (elementsA != null) { if (elementsA != null) {
for (Element tempElement : elementsA) { for (Element tempElement : elementsA) {
if (tempElement.text().trim().equals("好差评")) { if ("办事指南".equals(tempElement.text().trim())) {
String onclick = tempElement.attr("onclick");
List<String> list = ReUtil.findAllGroup0("'(.*?)'", onclick);
if (list.size() > 1) {
href = StrUtil.subBetween(list.get(0), "'", "'");
}
}
if ("好差评".equals(tempElement.text().trim())) {
String onclick = tempElement.attr("onclick"); String onclick = tempElement.attr("onclick");
evaluationUrl = StrUtil.subBetween(onclick, "evaluation('", "')"); evaluationUrl = StrUtil.subBetween(onclick, "evaluation('", "')");
} }
if (tempElement.text().trim().equals("申请")) { if ("申请".equals(tempElement.text().trim())) {
String onclick = tempElement.attr("onclick"); String onclick = tempElement.attr("onclick");
List<String> list = ReUtil.findAllGroup0("'(.*?)'", onclick); List<String> list = ReUtil.findAllGroup0("'(.*?)'", onclick);
if (list.size() > 4) { if (list.size() > 4) {
...@@ -94,6 +128,11 @@ public class MatterHtmlParseUtil { ...@@ -94,6 +128,11 @@ public class MatterHtmlParseUtil {
} }
} }
} }
if (ObjectUtils.isEmpty(href)) {
log.info("error href ,title:" + title);
}
buildMatter(matterEntityList, title, href, evaluationUrl, netApplyUrl); buildMatter(matterEntityList, title, href, evaluationUrl, netApplyUrl);
} }
...@@ -104,14 +143,23 @@ public class MatterHtmlParseUtil { ...@@ -104,14 +143,23 @@ public class MatterHtmlParseUtil {
continue; continue;
} }
String title = element.attr("title"); String title = element.attr("title");
String href = element.attr("href"); href = element.attr("href");
//抓取申请与评价页面地址 //抓取申请与评价页面地址
String evaluationUrl = "";
String netApplyUrl = "";
Element nextElementSibling = element.nextElementSibling(); Element nextElementSibling = element.nextElementSibling();
if (nextElementSibling != null) { if (nextElementSibling != null) {
Elements elementsA = nextElementSibling.selectXpath("//a");
Elements elementsA = nextElementSibling.children();
//Elements elementsA = nextElementSibling.selectXpath("//a");
for (Element tempElement : elementsA) { for (Element tempElement : elementsA) {
if ("办事指南".equals(tempElement.text().trim())) {
String onclick = tempElement.attr("onclick");
if(ObjectUtils.isEmpty(onclick)) continue;
List<String> list = ReUtil.findAllGroup0("'(.*?)'", onclick);
if (list.size() > 1) {
href = StrUtil.subBetween(list.get(0), "'", "'");
}
}
if ("好差评".equals(tempElement.text().trim())) { if ("好差评".equals(tempElement.text().trim())) {
String onclick = tempElement.attr("onclick"); String onclick = tempElement.attr("onclick");
evaluationUrl = StrUtil.subBetween(onclick, "evaluation('", "')"); evaluationUrl = StrUtil.subBetween(onclick, "evaluation('", "')");
...@@ -123,6 +171,11 @@ public class MatterHtmlParseUtil { ...@@ -123,6 +171,11 @@ public class MatterHtmlParseUtil {
netApplyUrl = StrUtil.subBetween(list.get(3), "'", "'"); netApplyUrl = StrUtil.subBetween(list.get(3), "'", "'");
} }
} }
if (ObjectUtils.isEmpty(href)) {
log.info("error href ,title:" + title);
}
} }
} }
buildMatter(matterEntityList, title, href, evaluationUrl, netApplyUrl); buildMatter(matterEntityList, title, href, evaluationUrl, netApplyUrl);
...@@ -243,17 +296,19 @@ public class MatterHtmlParseUtil { ...@@ -243,17 +296,19 @@ public class MatterHtmlParseUtil {
// System.out.println(JSON.toJSONString(allList)); // System.out.println(JSON.toJSONString(allList));
String url = "http://www.sczwfw.gov.cn/jiq/interface/item/tags"; /* String url = "http://www.sczwfw.gov.cn/jiq/interface/item/tags";
HashMap<String, String> params = new HashMap<>(); HashMap<String, String> params = new HashMap<>();
params.put("areaCode", "510110006007"); params.put("areaCode", "511500000000");
params.put("dxType", "56"); params.put("dxType", "3");
params.put("deptCode", ""); params.put("deptCode", "");
params.put("searchtext", ""); params.put("searchtext", "");
params.put("type", "2");//类型 2.部门 1.主题 3.热度
params.put("taskType", ""); params.put("taskType", "");
params.put("pageno", "1"); // params.put("pageno", "1");
Rest<Map<String, Integer>> rest = MatterHtmlParseUtil.statSiteMatterCount(params, url); Rest<Map<String, Integer>> rest = MatterHtmlParseUtil.statSiteMatterDeptCount(params, url);
System.out.println(JSON.toJSONString(rest)); System.out.println(JSON.toJSONString(rest));*/
/*
List<MatterEntity> allList = new ArrayList<>(); List<MatterEntity> allList = new ArrayList<>();
String url1 = "http://www.sczwfw.gov.cn/jiq/interface/item/tags"; String url1 = "http://www.sczwfw.gov.cn/jiq/interface/item/tags";
...@@ -282,6 +337,7 @@ public class MatterHtmlParseUtil { ...@@ -282,6 +337,7 @@ public class MatterHtmlParseUtil {
Rest<Map<String, String>> rest1 = MatterHtmlParseUtil.syncDeptBySiteId(params, url); Rest<Map<String, String>> rest1 = MatterHtmlParseUtil.syncDeptBySiteId(params, url);
System.out.println(JSON.toJSONString(rest1)); System.out.println(JSON.toJSONString(rest1));
*/
} }
......
package com.mortals.xhx.common.utils;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.busiz.req.ApiThirdPartyReq;
import com.mortals.xhx.common.code.MessageTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
import static com.mortals.framework.util.HttpUtil.HEADER_CONTENT_TYPE;
/**
* 发通知第三方
*
* @author: zxfei
* @date: 2022/4/28 10:56
* @description:
**/
@Slf4j
@AllArgsConstructor
public class SendTask implements Runnable {
private String sendUrl;
private String content;
@Override
public void run() {
String resp = null;
try {
Map<String, String> header = new HashMap<>();
header.put(HEADER_CONTENT_TYPE, "application/json");
log.info("sendUrl:{} \nsendMessageReq:{}",sendUrl, content);
resp = HttpUtil.doPost(sendUrl, header, content);
log.debug("sendMessageResp:{}", resp);
} catch (Exception e) {
log.error("异常:", e);
}
}
}
package com.mortals.xhx.common.utils;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.matter.service.MatterService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* 同步部门数据
*
* @author: zxfei
* @date: 2022/4/13 13:34
* @description:
**/
@AllArgsConstructor
@Slf4j
public class SyncDeptThread implements Runnable {
private DeptService deptService;
private String areaCode;
@Override
public void run() {
deptService.syncDept(areaCode,null);
}
}
...@@ -20,6 +20,8 @@ import com.mortals.xhx.module.site.model.SiteMatterEntity; ...@@ -20,6 +20,8 @@ import com.mortals.xhx.module.site.model.SiteMatterEntity;
import com.mortals.xhx.module.site.model.SiteQuery; import com.mortals.xhx.module.site.model.SiteQuery;
import com.mortals.xhx.module.site.service.SiteMatterService; import com.mortals.xhx.module.site.service.SiteMatterService;
import com.mortals.xhx.module.site.service.SiteService; import com.mortals.xhx.module.site.service.SiteService;
import com.mortals.xhx.module.site.service.SiteThemeMatterService;
import com.mortals.xhx.module.site.service.SiteThemeService;
import com.mortals.xhx.utils.SpringUtils; import com.mortals.xhx.utils.SpringUtils;
import lombok.extern.apachecommons.CommonsLog; import lombok.extern.apachecommons.CommonsLog;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
...@@ -40,9 +42,9 @@ public class SyncGovMatterDetailThread implements Runnable { ...@@ -40,9 +42,9 @@ public class SyncGovMatterDetailThread implements Runnable {
private SiteMatterService siteMatterService; private SiteMatterService siteMatterService;
// private SiteThemeService siteThemeService; private SiteThemeService siteThemeService;
//
// private SiteThemeMatterService siteThemeMatterService; private SiteThemeMatterService siteThemeMatterService;
private SiteEntity siteEntity; private SiteEntity siteEntity;
...@@ -59,23 +61,23 @@ public class SyncGovMatterDetailThread implements Runnable { ...@@ -59,23 +61,23 @@ public class SyncGovMatterDetailThread implements Runnable {
this.areaService = SpringUtils.getBean(AreaService.class); this.areaService = SpringUtils.getBean(AreaService.class);
this.deptService = SpringUtils.getBean(DeptService.class); this.deptService = SpringUtils.getBean(DeptService.class);
this.siteMatterService = SpringUtils.getBean(SiteMatterService.class); this.siteMatterService = SpringUtils.getBean(SiteMatterService.class);
// this.siteThemeService = SpringUtils.getBean(SiteThemeService.class); this.siteThemeService = SpringUtils.getBean(SiteThemeService.class);
// this.siteThemeMatterService = SpringUtils.getBean(SiteThemeMatterService.class); this.siteThemeMatterService = SpringUtils.getBean(SiteThemeMatterService.class);
this.cacheService = SpringUtils.getBean(ICacheService.class); this.cacheService = SpringUtils.getBean(ICacheService.class);
} }
@Override @Override
public void run() { public void run() {
log.info("同步站点事项开始....."); log.info("同步站点事项开始.....");
Rest<String> deptRest = deptService.syncDeptBySiteId(siteEntity, context); // Rest<String> deptRest = deptService.syncDeptBySiteId(siteEntity, context);
log.info("同步站点部门:" + JSON.toJSONString(deptRest)); // log.info("同步站点部门:" + JSON.toJSONString(deptRest));
Rest<String> rest = siteService.syncMatterBySiteId(siteEntity, context); Rest<String> rest = siteService.syncMatterBySiteId(siteEntity, context);
AreaEntity areaEntity = areaService.getCache(siteEntity.getAreaCode()); AreaEntity areaEntity = areaService.getCache(siteEntity.getAreaCode());
log.info("同步事项列表:" + JSON.toJSONString(rest)); log.info("同步事项列表:" + JSON.toJSONString(rest));
if (rest.getCode() == YesNoEnum.YES.getValue()) { if (rest.getCode() == YesNoEnum.YES.getValue()) {
List<MatterEntity> matterEntityList = matterService.find(new MatterQuery().areaCode(siteEntity.getAreaCode()).source(SourceEnum.政务网.getValue())); List<MatterEntity> matterEntityList = matterService.find(new MatterQuery().areaCode(siteEntity.getAreaCode()).source(SourceEnum.政务网.getValue()));
List<MatterEntity> unSyncDetailMatterList = matterEntityList.stream() List<MatterEntity> unSyncDetailMatterList = matterEntityList.stream()
//.filter(f -> f.getHaveGetMatterInfo().equalsIgnoreCase("false")) .filter(f -> f.getHaveGetMatterInfo().equalsIgnoreCase("false"))
.collect(Collectors.toList()); .collect(Collectors.toList());
//查询站点事项相关 //查询站点事项相关
...@@ -106,37 +108,37 @@ public class SyncGovMatterDetailThread implements Runnable { ...@@ -106,37 +108,37 @@ public class SyncGovMatterDetailThread implements Runnable {
matterService.update(matterEntity, context); matterService.update(matterEntity, context);
}); });
} }
// log.info("同步站点主题事项开始....."); log.info("同步站点主题事项开始.....");
//
//判断站点区域乡镇情况 //判断站点区域乡镇情况
// if (areaEntity.getAreaLevel() <= 3) { if (areaEntity.getAreaLevel() <= 3) {
// //省,市,区 //省,市,区
// Rest<String> themeRest = siteThemeService.syncThemeBySiteId(siteEntity, context); Rest<String> themeRest = siteThemeService.syncThemeBySiteId(siteEntity, context);
// log.info("同步站点主题:" + JSON.toJSONString(themeRest)); log.info("同步站点主题:" + JSON.toJSONString(themeRest));
// log.info("同步站点个人主题事项开始....."); log.info("同步站点个人主题事项开始.....");
// siteThemeMatterService.deleteGovBySiteId(siteEntity.getId(), context); siteThemeMatterService.deleteGovBySiteId(siteEntity.getId(), context);
// Rest<String> grRest = siteThemeMatterService.syncThemeMatterBySiteId(siteEntity.getId(), "2", context); Rest<String> grRest = siteThemeMatterService.syncThemeMatterBySiteId(siteEntity.getId(), "2", context);
// log.info("同步站点主题个人事项:" + JSON.toJSONString(grRest)); log.info("同步站点主题个人事项:" + JSON.toJSONString(grRest));
// log.info("同步站点法人主题事项开始....."); log.info("同步站点法人主题事项开始.....");
// Rest<String> frRest = siteThemeMatterService.syncThemeMatterBySiteId(siteEntity.getId(), "3", context); Rest<String> frRest = siteThemeMatterService.syncThemeMatterBySiteId(siteEntity.getId(), "3", context);
// log.info("同步站点主题法人事项:" + JSON.toJSONString(frRest)); log.info("同步站点主题法人事项:" + JSON.toJSONString(frRest));
// } else if (areaEntity.getAreaLevel() > 3) { } else if (areaEntity.getAreaLevel() > 3) {
// //街道,镇,乡 //街道,镇,乡
// Rest<String> themeTownRest = siteThemeService.syncTownThemeBySiteId(siteEntity, context); Rest<String> themeTownRest = siteThemeService.syncTownThemeBySiteId(siteEntity, context);
// log.info("同步乡镇站点主题:" + JSON.toJSONString(themeTownRest)); log.info("同步乡镇站点主题:" + JSON.toJSONString(themeTownRest));
// if (themeTownRest.getCode() == YesNoEnum.YES.getValue()) { if (themeTownRest.getCode() == YesNoEnum.YES.getValue()) {
// siteThemeMatterService.deleteGovBySiteId(siteEntity.getId(), context); siteThemeMatterService.deleteGovBySiteId(siteEntity.getId(), context);
// String dxType = DxTypeEnum.街道镇服务.getValue(); String dxType = DxTypeEnum.街道镇服务.getValue();
// if (areaEntity.getAreaLevel() == 5) { if (areaEntity.getAreaLevel() == 5) {
// dxType = DxTypeEnum.乡村服务.getValue(); dxType = DxTypeEnum.乡村服务.getValue();
// } }
// Rest<String> townThemeRest = siteThemeMatterService.syncTownThemeMatterBySiteId(siteEntity, dxType, context); Rest<String> townThemeRest = siteThemeMatterService.syncTownThemeMatterBySiteId(siteEntity, dxType, context);
// log.info("同步站点乡镇主题事项:" + JSON.toJSONString(townThemeRest)); log.info("同步站点乡镇主题事项:" + JSON.toJSONString(townThemeRest));
// } else { } else {
// cacheService.hdel(RedisCacheKeys.getSyncMatterLockKey() + siteEntity.getAreaCode(), siteEntity.getAreaCode()); cacheService.hdel(RedisCacheKeys.getSyncMatterLockKey() + siteEntity.getAreaCode(), siteEntity.getAreaCode());
// log.info("同步站点乡镇主题事项失败:" + themeTownRest.getData()); log.info("同步站点乡镇主题事项失败:" + themeTownRest.getData());
// } }
// } }
log.info("同步站点事项结束....."); log.info("同步站点事项结束.....");
} }
} }
package com.mortals.xhx.common.utils;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.base.model.BaseAreaEntity;
import com.mortals.xhx.module.base.service.BaseAreaService;
import com.mortals.xhx.module.dept.service.DeptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* 同步区域子数据
*
* @author: zxfei
* @date: 2022/4/13 13:34
* @description:
**/
@AllArgsConstructor
@Slf4j
public class SyncSubAreaThread implements Runnable {
private BaseAreaService baseAreaService;
private BaseAreaEntity baseAreaEntity;
private Context context;
@Override
public void run() {
log.info("子区域同步开始!");
Rest<String> rest = baseAreaService.genSubAreaByRootName(baseAreaEntity, context);
log.info("子区域同步结束!结果:{}", JSON.toJSONString(rest));
}
}
package com.mortals.xhx.common.utils;
import com.mortals.xhx.module.matter.service.MatterService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* 同步基础事项数据
*
* @author: zxfei
* @date: 2022/4/13 13:34
* @description:
**/
@AllArgsConstructor
@Slf4j
public class SyncTreeMatterThread implements Runnable {
private MatterService matterService;
private String areaCode;
@Override
public void run() {
matterService.syncMatter(areaCode, null);
}
}
package com.mortals.xhx.daemon;
import cn.hutool.setting.Setting;
import com.google.common.collect.BiMap;
import com.mortals.framework.common.Rest;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import com.mortals.xhx.common.utils.SyncDeptThread;
import com.mortals.xhx.common.utils.SyncTreeMatterThread;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.matter.service.MatterService;
import lombok.extern.apachecommons.CommonsLog;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 事项数据同步更新
*
* @author: zxfei
* @date: 2022/3/30 9:45
*/
@CommonsLog
@RestController
@RequestMapping("test")
public class RequestDataController {
@Autowired
private MatterService matterService;
@Autowired
private DeptService deptService;
/**
* 生成基础数据prop
*
* @return
*/
@PostMapping("/baseprop")
public ApiRespPdu<String> baseprop() {
ApiRespPdu<String> respPdu = new ApiRespPdu<>();
Map<String, String> baseInfoMap = matterService.getBaseInfoMap(null);
//保存为
Setting setting = Setting.create();
setting.putAll(baseInfoMap);
setting.store("E://baseinfo.setting");
Map<String, String> sqclInfoMap = matterService.getSqclInfoMap(null);
sqclInfoMap.entrySet().stream().peek(item -> {
String[] split = item.getValue().split(",");
if (split.length > 1) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
sb.append(".");
sb.append(split[i]);
if (i != split.length - 1) {
sb.append(",");
}
}
item.setValue(sb.toString());
}
}).count();
setting = Setting.create();
setting.putAll(sqclInfoMap);
setting.store("E://sqclinfo.setting");
return respPdu;
}
/**
* 同步部门数据
*
* @return
*/
@GetMapping("/syncDept")
public Rest<String> syncDept() {
//ThreadPool.getInstance().execute(new SyncDeptThread(deptService));
return Rest.ok("接收同步部门成功");
}
/**
* 同步事项数据
*
* @return
*/
@GetMapping("/syncMatter")
public Rest<String> syncMatter() {
// ThreadPool.getInstance().execute(new SyncTreeMatterThread(matterService));
return Rest.ok("接收同步成功");
}
private void checkKeyValue(BiMap<String, String> map, Map.Entry<String, Object> m, String value) {
if ("0".equals(value)) {
//查看是否为空
String temp = map.get(m.getValue().toString());
if (ObjectUtils.isEmpty(temp)) {
//打印枚举类型值
System.out.println("uncheck name:" + m.getKey() + " value:" + m.getValue());
}
}
}
public static void main(String[] args) {
}
}
...@@ -9,19 +9,7 @@ import org.springframework.stereotype.Component; ...@@ -9,19 +9,7 @@ import org.springframework.stereotype.Component;
import com.mortals.framework.springcloud.service.IApplicationService; import com.mortals.framework.springcloud.service.IApplicationService;
/**
* 应用级服务,在应用启动、停止过程中调用
*
* 缺陷:类加载完成后就调用,会由于某些组件还未初始化而导致服务异常,
* 比如Kafka的连接以及订阅初始化比较靠后,在服务启动过程中就调用操作kafka相关API,将导致失败
* 比如开启Socket监听端口,可能端口都接收到连接请求了,但数据库连接还未初始化完成,导致请求处理失败
* 比如定时任务,任务执行时,相关缓存还未初始化,导致处理失败
*
* 应用场景:
* 1、无依赖其它模块或框架的数据初始化等操作
* @author GM
* @date 2020年7月15日
*/
@Component @Component
public class DemoStartService implements IApplicationService { public class DemoStartService implements IApplicationService {
......
package com.mortals.xhx.daemon.applicationservice; package com.mortals.xhx.daemon.applicationservice;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.springcloud.config.web.BaseWebMvcConfigurer; import com.mortals.framework.springcloud.config.web.BaseWebMvcConfigurer;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.common.utils.SyncTreeSiteThread;
import com.mortals.xhx.feign.user.IUserFeign;
import com.mortals.xhx.module.site.model.SiteTreeSelect;
import com.mortals.xhx.module.site.service.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.mortals.framework.springcloud.service.IApplicationStartedService; import com.mortals.framework.springcloud.service.IApplicationStartedService;
import org.springframework.util.ObjectUtils;
/** import java.util.List;
* 应用级服务,在应用启动后、停止过程中调用
* 应用已经完成启动完成,才调用该服务
* 应用场景:
* 1、应用任务,应用启动后定时或间隔执行的任务
* 2、Socket服务端
* @author GM
* @date 2020年7月15日
*/
@Component @Component
//@ConditionalOnProperty(name="com.mortal",prefix = "",havingValue = "xxx") @Slf4j
public class DemoStartedService implements IApplicationStartedService { public class DemoStartedService implements IApplicationStartedService {
private static Log logger = LogFactory.getLog(DemoStartedService.class); private static Log logger = LogFactory.getLog(DemoStartedService.class);
// @Autowired
// private IUserFeign userFeign;
@Autowired
private UserService userService;
@Override @Override
public void start() { public void start() {
logger.info("开始服务..[配置已加载完成,并且所有框架都已经初始化]"); logger.info("开始服务..[初始化用户站点树]");
UserEntity userEntity = new UserEntity();
userEntity.initAttrValue();
userEntity.setId(0L);
Context contextTemp = new Context();
contextTemp.setUser(userEntity);
SyncTreeSiteThread syncTreeSiteThread = new SyncTreeSiteThread(contextTemp);
ThreadPool.getInstance().execute(syncTreeSiteThread);
userEntity = new UserEntity();
userEntity.initAttrValue();
userEntity.setId(1L);
contextTemp = new Context();
contextTemp.setUser(userEntity);
syncTreeSiteThread = new SyncTreeSiteThread(contextTemp);
ThreadPool.getInstance().execute(syncTreeSiteThread);
/* userService.find(new UserQuery()).forEach(user->{
Context context = new Context();
context.setUser(user);
ThreadPool.getInstance().execute(new SyncTreeSiteThread(context));
});*/
/* if(ObjectUtils.isEmpty(userFeign)){
logger.info("userFeign未加载,加载本地用户");
userService.find(new UserQuery()).forEach(user->{
Context context = new Context();
context.setUser(user);
ThreadPool.getInstance().execute(new SyncTreeSiteThread(context));
});
return;
}*/
/* userFeign.list(new UserPdu()).getData().getData().stream().forEach(userPdu->{
Context context = new Context();
UserEntity entity = new UserEntity();
entity.initAttrValue();
BeanUtils.copyProperties(userPdu, entity, BeanUtil.getNullPropertyNames(userPdu));
context.setUser(entity);
ThreadPool.getInstance().execute(new SyncTreeSiteThread(context));
});*/
} }
@Override @Override
......
package com.mortals.xhx.daemon.task;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.matters.service.MattersService;
import com.mortals.xhx.module.site.model.SiteMatterQuery;
import com.mortals.xhx.module.site.service.SiteMatterService;
import com.mortals.xhx.module.site.service.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* 统计站点部门事项
*/
@Slf4j
@Service("StatSiteDeptMatterTask")
public class StatSiteDeptMatterTaskImpl implements ITaskExcuteService {
@Autowired
private DeptService deptService;
@Autowired
private MatterService matterService;
@Override
public void excuteTask(ITask task) throws AppException {
log.info("开始同步事项列表!");
List<DeptEntity> deptEntities = deptService.find(new DeptQuery());
for (DeptEntity deptEntity : deptEntities) {
int total = matterService.count(new MatterQuery().deptCode(deptEntity.getDeptNumber()), null);
if (total > 0) {
DeptEntity deptQuery = new DeptEntity();
deptQuery.setTotal(total);
deptQuery.setUpdateTime(new Date());
DeptEntity condition = new DeptEntity();
condition.setId(deptEntity.getId());
deptService.getDao().update(deptQuery, condition);
// deptService.update(deptEntity, null);
}
}
}
@Override
public void stopTask(ITask task) throws AppException {
}
}
package com.mortals.xhx.module.app.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.app.model.AppEntity;
import java.util.List;
/**
* 自助终端应用Dao
* 自助终端应用 DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
public interface AppDao extends ICRUDDao<AppEntity,Long>{
}
package com.mortals.xhx.module.app.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.module.app.model.AppDatasetEntity;
import com.mortals.xhx.module.app.model.AppDatasetQuery;
import com.mortals.xhx.module.app.model.AppInfoFieldEntity;
import com.mortals.xhx.module.matter.model.MatterEntity;
import java.util.List;
/**
* 自助终端应用数据集Dao
* 自助终端应用数据集 DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
public interface AppDatasetDao extends ICRUDDao<AppDatasetEntity, Long> {
String SQLID_CUSTOM_LIST = "getCustomList";
String SQLID_CUSTOM_COUNT = "getCustomListCount";
Result<AppInfoFieldEntity> getCustomList(AppDatasetQuery appDatasetQuery, PageInfo pageInfo);
}
package com.mortals.xhx.module.app.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.app.model.AppInfoFieldEntity;
import java.util.List;
/**
* 自助终端应用信息字段Dao
* 自助终端应用信息字段 DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
public interface AppInfoFieldDao extends ICRUDDao<AppInfoFieldEntity,Long>{
}
package com.mortals.xhx.module.app.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.app.model.AppInfoTempleteFieldEntity;
import java.util.List;
/**
* 自助终端应用模板信息字段Dao
* 自助终端应用模板信息字段 DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
public interface AppInfoTempleteFieldDao extends ICRUDDao<AppInfoTempleteFieldEntity,Long>{
}
package com.mortals.xhx.module.app.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.app.model.AppVersionEntity;
import java.util.List;
/**
* 自助终端应用版本历史Dao
* 自助终端应用版本历史 DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
public interface AppVersionDao extends ICRUDDao<AppVersionEntity,Long>{
}
package com.mortals.xhx.module.app.dao.ibatis;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.app.dao.AppDao;
import com.mortals.xhx.module.app.model.AppEntity;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 自助终端应用DaoImpl DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
@Repository("appDao")
public class AppDaoImpl extends BaseCRUDDaoMybatis<AppEntity,Long> implements AppDao {
}
package com.mortals.xhx.module.app.dao.ibatis;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.ParamDto;
import com.mortals.framework.model.Result;
import com.mortals.xhx.module.app.model.AppDatasetQuery;
import com.mortals.xhx.module.app.model.AppInfoFieldEntity;
import com.mortals.xhx.module.matter.model.MatterEntity;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.app.dao.AppDatasetDao;
import com.mortals.xhx.module.app.model.AppDatasetEntity;
import java.util.ArrayList;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 自助终端应用数据集DaoImpl DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
@Repository("appDatasetDao")
public class AppDatasetDaoImpl extends BaseCRUDDaoMybatis<AppDatasetEntity,Long> implements AppDatasetDao {
@Override
public Result<AppInfoFieldEntity> getCustomList(AppDatasetQuery appDatasetQuery, PageInfo pageInfo) {
Result<AppInfoFieldEntity> result = new Result();
ParamDto paramDto = this.getQueryParam(appDatasetQuery);
int count = this.getCustomCount(paramDto);
List list = null;
if (count == 0) {
list = new ArrayList();
} else if (pageInfo.getPrePageResult() == -1) {
list = this.getSqlSession().selectList(this.getSqlId(SQLID_CUSTOM_LIST), paramDto);
} else {
list = this.getSqlSession().selectList(this.getSqlId(SQLID_CUSTOM_LIST), paramDto);
/* RowBounds rowBounds = new RowBounds(pageInfo.getBeginIndex(), pageInfo.getPrePageResult());
list = this.getSqlSession().selectList(this.getSqlId(SQLID_CUSTOM_LIST), this.cpyQueryParamDto(paramDto), rowBounds);*/
}
pageInfo.setTotalResult(count);
result.setPageInfo(pageInfo);
result.setList(list);
return result;
}
public int getCustomCount(ParamDto paramDto) {
return this.getSqlSession().selectOne(this.getSqlId(SQLID_CUSTOM_COUNT), this.cpyQueryParamDto(paramDto));
}
}
package com.mortals.xhx.module.app.dao.ibatis;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.app.dao.AppInfoFieldDao;
import com.mortals.xhx.module.app.model.AppInfoFieldEntity;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 自助终端应用信息字段DaoImpl DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
@Repository("appInfoFieldDao")
public class AppInfoFieldDaoImpl extends BaseCRUDDaoMybatis<AppInfoFieldEntity,Long> implements AppInfoFieldDao {
}
package com.mortals.xhx.module.app.dao.ibatis;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.app.dao.AppInfoTempleteFieldDao;
import com.mortals.xhx.module.app.model.AppInfoTempleteFieldEntity;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 自助终端应用模板信息字段DaoImpl DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
@Repository("appInfoTempleteFieldDao")
public class AppInfoTempleteFieldDaoImpl extends BaseCRUDDaoMybatis<AppInfoTempleteFieldEntity,Long> implements AppInfoTempleteFieldDao {
}
package com.mortals.xhx.module.app.dao.ibatis;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.app.dao.AppVersionDao;
import com.mortals.xhx.module.app.model.AppVersionEntity;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 自助终端应用版本历史DaoImpl DAO接口
*
* @author zxfei
* @date 2022-11-28
*/
@Repository("appVersionDao")
public class AppVersionDaoImpl extends BaseCRUDDaoMybatis<AppVersionEntity,Long> implements AppVersionDao {
}
package com.mortals.xhx.module.app.model;
import com.mortals.xhx.module.app.model.vo.AppDatasetVo;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用数据集实体对象
*
* @author zxfei
* @date 2022-11-28
*/
public class AppDatasetEntity extends AppDatasetVo {
private static final long serialVersionUID = 1L;
/**
* appId
*/
private Long appId;
/**
* 自助终端应用信息字段信息
*/
private List<AppInfoFieldEntity> appInfoFieldList=new ArrayList<>();;
public AppDatasetEntity(){}
/**
* 获取 appId
* @return Long
*/
public Long getAppId(){
return appId;
}
/**
* 设置 appId
* @param appId
*/
public void setAppId(Long appId){
this.appId = appId;
}
public List<AppInfoFieldEntity> getAppInfoFieldList(){
return appInfoFieldList;
}
public void setAppInfoFieldList(List<AppInfoFieldEntity> appInfoFieldList){
this.appInfoFieldList = appInfoFieldList;
}
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof AppDatasetEntity) {
AppDatasetEntity tmp = (AppDatasetEntity) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public String toString(){
StringBuilder sb = new StringBuilder("");
sb.append(",appId:").append(getAppId());
return sb.toString();
}
public void initAttrValue(){
this.appId = null;
}
}
\ No newline at end of file
package com.mortals.xhx.module.app.model;
import java.util.List;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.mortals.framework.annotation.Excel;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.vo.AppInfoFieldVo;
/**
* 自助终端应用信息字段实体对象
*
* @author zxfei
* @date 2022-12-02
*/
public class AppInfoFieldEntity extends AppInfoFieldVo {
private static final long serialVersionUID = 1L;
/**
* 应用数据集id
*/
private Long datasetId;
/**
* 字段编码
*/
private String fieldCode;
/**
* 字段名称
*/
private String fieldName;
/**
* 字段类型(input.单行输入框,textarea.多行输入框,SELECT.下拉选项框,date.日期选择框)
*/
private String fieldType;
/**
* 数据类型(number.数字,string.字符串)
*/
private String dataType;
/**
* 字段值
*/
private String fieldValue;
/**
* 数据长度,默认128
*/
private Integer fieldLen;
/**
* 是否允许为空,(0.否,1.是)
*/
private Integer fieldNull;
/**
* 字段是否列表显示(0.否,1.是)
*/
private Integer isList;
/**
* 排序号
*/
private Integer fieldOrderNo;
/**
* 备注
*/
private String remark;
public AppInfoFieldEntity(){}
/**
* 获取 应用数据集id
* @return Long
*/
public Long getDatasetId(){
return datasetId;
}
/**
* 设置 应用数据集id
* @param datasetId
*/
public void setDatasetId(Long datasetId){
this.datasetId = datasetId;
}
/**
* 获取 字段编码
* @return String
*/
public String getFieldCode(){
return fieldCode;
}
/**
* 设置 字段编码
* @param fieldCode
*/
public void setFieldCode(String fieldCode){
this.fieldCode = fieldCode;
}
/**
* 获取 字段名称
* @return String
*/
public String getFieldName(){
return fieldName;
}
/**
* 设置 字段名称
* @param fieldName
*/
public void setFieldName(String fieldName){
this.fieldName = fieldName;
}
/**
* 获取 字段类型(input.单行输入框,textarea.多行输入框,SELECT.下拉选项框,date.日期选择框)
* @return String
*/
public String getFieldType(){
return fieldType;
}
/**
* 设置 字段类型(input.单行输入框,textarea.多行输入框,SELECT.下拉选项框,date.日期选择框)
* @param fieldType
*/
public void setFieldType(String fieldType){
this.fieldType = fieldType;
}
/**
* 获取 数据类型(number.数字,string.字符串)
* @return String
*/
public String getDataType(){
return dataType;
}
/**
* 设置 数据类型(number.数字,string.字符串)
* @param dataType
*/
public void setDataType(String dataType){
this.dataType = dataType;
}
/**
* 获取 字段值
* @return String
*/
public String getFieldValue(){
return fieldValue;
}
/**
* 设置 字段值
* @param fieldValue
*/
public void setFieldValue(String fieldValue){
this.fieldValue = fieldValue;
}
/**
* 获取 数据长度,默认128
* @return Integer
*/
public Integer getFieldLen(){
return fieldLen;
}
/**
* 设置 数据长度,默认128
* @param fieldLen
*/
public void setFieldLen(Integer fieldLen){
this.fieldLen = fieldLen;
}
/**
* 获取 是否允许为空,(0.否,1.是)
* @return Integer
*/
public Integer getFieldNull(){
return fieldNull;
}
/**
* 设置 是否允许为空,(0.否,1.是)
* @param fieldNull
*/
public void setFieldNull(Integer fieldNull){
this.fieldNull = fieldNull;
}
/**
* 获取 字段是否列表显示(0.否,1.是)
* @return Integer
*/
public Integer getIsList(){
return isList;
}
/**
* 设置 字段是否列表显示(0.否,1.是)
* @param isList
*/
public void setIsList(Integer isList){
this.isList = isList;
}
/**
* 获取 排序号
* @return Integer
*/
public Integer getFieldOrderNo(){
return fieldOrderNo;
}
/**
* 设置 排序号
* @param fieldOrderNo
*/
public void setFieldOrderNo(Integer fieldOrderNo){
this.fieldOrderNo = fieldOrderNo;
}
/**
* 获取 备注
* @return String
*/
public String getRemark(){
return remark;
}
/**
* 设置 备注
* @param remark
*/
public void setRemark(String remark){
this.remark = remark;
}
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof AppInfoFieldEntity) {
AppInfoFieldEntity tmp = (AppInfoFieldEntity) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public String toString(){
StringBuilder sb = new StringBuilder("");
sb.append(",datasetId:").append(getDatasetId());
sb.append(",fieldCode:").append(getFieldCode());
sb.append(",fieldName:").append(getFieldName());
sb.append(",fieldType:").append(getFieldType());
sb.append(",dataType:").append(getDataType());
sb.append(",fieldValue:").append(getFieldValue());
sb.append(",fieldLen:").append(getFieldLen());
sb.append(",fieldNull:").append(getFieldNull());
sb.append(",isList:").append(getIsList());
sb.append(",fieldOrderNo:").append(getFieldOrderNo());
sb.append(",remark:").append(getRemark());
return sb.toString();
}
public void initAttrValue(){
this.datasetId = null;
this.fieldCode = "";
this.fieldName = "";
this.fieldType = "";
this.dataType = "";
this.fieldValue = "";
this.fieldLen = 0;
this.fieldNull = 1;
this.isList = 0;
this.fieldOrderNo = 1;
this.remark = "";
}
}
\ No newline at end of file
package com.mortals.xhx.module.app.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.AppDatasetEntity;
import com.mortals.xhx.module.app.model.AppDatasetQuery;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用数据集视图对象
*
* @author zxfei
* @date 2022-11-28
*/
@Data
public class AppDatasetVo extends BaseEntityLong {
/**
* 字段编码
*/
private String fieldCode;
/**
* 字段名称
*/
private String fieldName;
/**
* 字段值
*/
private String fieldValue;
private Long appId;
private List<Long> idList;
private List<String> fieldNameList;
private List<String> fieldValueList;
/** OR条件集合,列表项之间是OR,项内容之间是AND,如:(list[0].1 and list[0].2) or (list[1].3 and list[1].4) */
private List<AppDatasetQuery> orConditionList;
/** AND条件集合,列表项之间是AND,项内容之间是OR,如:(list[0].1 or list[0].2) and (list[1].3 or list[1].4) */
private List<AppDatasetQuery> andConditionList;
}
\ No newline at end of file
package com.mortals.xhx.module.app.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.AppInfoFieldEntity;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用信息字段视图对象
*
* @author zxfei
* @date 2022-11-28
*/
public class AppInfoFieldVo extends BaseEntityLong {
}
\ No newline at end of file
package com.mortals.xhx.module.app.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.AppInfoTempleteFieldEntity;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用模板信息字段视图对象
*
* @author zxfei
* @date 2022-11-28
*/
public class AppInfoTempleteFieldVo extends BaseEntityLong {
}
\ No newline at end of file
package com.mortals.xhx.module.app.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.AppVersionEntity;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用版本历史视图对象
*
* @author zxfei
* @date 2022-11-28
*/
public class AppVersionVo extends BaseEntityLong {
}
\ No newline at end of file
package com.mortals.xhx.module.app.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.app.model.AppEntity;
import com.mortals.xhx.module.site.model.SiteEntity;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 自助终端应用视图对象
*
* @author zxfei
* @date 2022-11-28
*/
@Data
public class AppVo extends BaseEntityLong {
/**
* 适用站点范围数量
*/
private Integer applianceSiteScope;
private List<Long> siteIdList;
private List <Long> idList;
/**
* 自主应用访问地址
*/
private String custUrl;
/**
* 图标访问地址
*/
private String appIconUrl;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment