Commit 0a2757de authored by 廖旭伟's avatar 廖旭伟

基础框架升级到1.1.7,集成到政务4.0体系中,增加设备显示打印类别配置模块

parent 9b93723e
......@@ -43,7 +43,9 @@
<profiles.nacos.server-addr>192.168.0.252:8848</profiles.nacos.server-addr>
<profiles.nacos.group>DEFAULT_GROUP</profiles.nacos.group>
<profiles.nacos.namespace>smart-gov</profiles.nacos.namespace>
<profiles.log.level>info</profiles.log.level>
<profiles.log.path>/mortals/app/logs</profiles.log.path>
<profiles.publish.path>/home/publish</profiles.publish.path>
</properties>
</profile>
<profile>
......@@ -69,14 +71,16 @@
<profiles.nacos.server-addr>192.168.0.252:8848</profiles.nacos.server-addr>
<profiles.nacos.group>DEFAULT_GROUP</profiles.nacos.group>
<profiles.nacos.namespace>smart-gov</profiles.nacos.namespace>
<profiles.log.level>info</profiles.log.level>
<profiles.log.path>/mortals/app/logs</profiles.log.path>
<profiles.publish.path>/home/publish</profiles.publish.path>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<profiles.active>product</profiles.active>
<profiles.server.port>19211</profiles.server.port>
<profiles.server.port>17216</profiles.server.port>
<profiles.queue.type>rabbitmq</profiles.queue.type>
<profiles.kafka.brokers>192.168.0.100:9092</profiles.kafka.brokers>
<profiles.rabbitmq.host>192.168.0.100</profiles.rabbitmq.host>
......@@ -84,7 +88,29 @@
<profiles.nacos.server-addr>192.168.0.100:8848</profiles.nacos.server-addr>
<profiles.nacos.group>DEFAULT_GROUP</profiles.nacos.group>
<profiles.nacos.namespace>smart-gov</profiles.nacos.namespace>
<profiles.log.level>info</profiles.log.level>
<profiles.log.path>/mortals/app/logs</profiles.log.path>
<profiles.publish.path>/home/publish</profiles.publish.path>
</properties>
</profile>
<profile>
<id>yibin</id>
<properties>
<profiles.active>yibin</profiles.active>
<profiles.server.port>17216</profiles.server.port>
<profiles.queue.type>rabbitmq</profiles.queue.type>
<profiles.rabbitmq.host>172.15.28.115</profiles.rabbitmq.host>
<profiles.rabbitmq.port>5672</profiles.rabbitmq.port>
<profiles.rabbitmq.username>taxi_mq</profiles.rabbitmq.username>
<profiles.rabbitmq.password>admin@2020</profiles.rabbitmq.password>
<profiles.rabbitmq.virtualhost>/</profiles.rabbitmq.virtualhost>
<profiles.nacos.server-addr>172.15.28.120:8848</profiles.nacos.server-addr>
<profiles.nacos.group>DEFAULT_GROUP</profiles.nacos.group>
<profiles.nacos.namespace>smart-gov</profiles.nacos.namespace>
<profiles.log.level>INFO</profiles.log.level>
<profiles.log.path>/home/mortals/app/logs</profiles.log.path>
<profiles.publish.path>/home/publish</profiles.publish.path>
<profiles.filepath>/mortals/app/data</profiles.filepath>
</properties>
</profile>
</profiles>
......@@ -195,11 +221,6 @@
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
......@@ -211,11 +232,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
<outputDirectory>${project.basedir}/dist/${project.artifactId}/boot</outputDirectory>
<layout>ZIP</layout>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
......@@ -239,18 +255,66 @@
</goals>
<configuration>
<encoding>UTF-8</encoding>
<outputDirectory>${project.basedir}/dist/${project.artifactId}/bin</outputDirectory>
<outputDirectory>target/bin
</outputDirectory>
<resources>
<resource>
<directory>src/main/bin/</directory>
<excludes>
<exclude>deploy.sh</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-deploy</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<encoding>UTF-8</encoding>
<outputDirectory>${project.parent.basedir}/dist/${project.artifactId}/
</outputDirectory>
<resources>
<resource>
<directory>src/main/bin</directory>
<includes>
<include>deploy.sh</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>../assembly/assembly.xml</descriptor>
</descriptors>
<outputDirectory>${project.parent.basedir}/dist/${project.artifactId}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
#!/bin/bash
PORT="@profiles.server.port@"
PROJECT_NAME="@project.artifactId@";
MAIN_CLASS="$PROJECT_NAME-@project.version@.jar";
SHELL_NAME=$0
SHELL_LOG="${SHELL_NAME}.log"
LOG_DATE='date "+%Y-%m-%d"'
LOG_TIME='date "+%H-%M-%S"'
CDATE=$(date "+%Y-%m-%d")
CTIME=$(date "+%H-%M-%S")
#写日志
writelog() {
LOGINFO=$1
echo "${CDATE} ${CTIME}: ${SHELL_NAME} : ${LOGINFO}" >>${SHELL_LOG}
}
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ $jcpid ]; then
writelog "The $PROJECT_NAME start finished, PID is $jcpid"
exit $SUCCESS
else
writelog "start service..."
systemctl stop ${PROJECT_NAME} && systemctl start ${PROJECT_NAME}
fi
#!/bin/sh
RETVAL=$?
SHELL_NAME="deploy"
BASEDIR=$(dirname $0)
BASEDIR=$( (
cd "$BASEDIR"
pwd
))
LOCK_FILE="/tmp/deploy.lock"
# 时间变量
CDATE=$(date "+%Y-%m-%d")
CTIME=$(date "+%H:%M:%S")
SHELL_LOG="${BASEDIR}/${SHELL_NAME}.log"
JAVA_HOME="/usr/local/java/jdk1.8"
SERVICE_PATH="/usr/lib/systemd/system"
PUBLISH_PATH="@profiles.publish.path@"
PROJECT_NAME="@project.artifactId@"
PROJECT_EXECPATH="${PUBLISH_PATH}/${PROJECT_NAME}"
PROJECT_UI_EXECPATH="${PUBLISH_PATH}/${PROJECT_NAME}-ui/dist"
PROJECT_FILENAME="${PROJECT_NAME}.tar.gz"
PROJECT_UI_FILENAME="${PROJECT_NAME}-ui.tar.gz"
PROJECT_SERVICE="${SERVICE_PATH}/${PROJECT_NAME}.service"
#写日志
writelog() {
LOGINFO=$1
echo "${CDATE} ${CTIME}: ${SHELL_NAME} : ${LOGINFO}" >>${SHELL_LOG}
echo ${LOGINFO}
}
#清理目标
clear_deploy() {
SERVICE=$1
EXECPATH=$2
#清理后台自启服务
rm -rf ${SERVICE}
#清理执行文件目录
rm -rf ${EXECPATH}
}
build_service() {
SERVICE=$1
EXECPATH=$2
echo "" >${SERVICE}
echo "[Unit]" >>${SERVICE}
echo "Description=${PROJECT_NAME}" >>${SERVICE}
echo "After=network.target" >>${SERVICE}
echo "" >>${SERVICE}
echo "[Service]" >>${SERVICE}
echo "Environment=\"JAVA_HOME=$JAVA_HOME\"" >>${SERVICE}
echo "Type=forking" >>${SERVICE}
echo "ExecStart=${EXECPATH}/bin/start.sh" >>${SERVICE}
echo "ExecStop=${EXECPATH}/bin/shutdown.sh" >>${SERVICE}
echo "PrivateTmp=true" >>${SERVICE}
echo "" >>${SERVICE}
echo "[Install]" >>${SERVICE}
echo "WantedBy=multi-user.target" >>${SERVICE}
writelog "${PROJECT_NAME}服务创建完成!"
}
#启动服务与nginx
start_service() {
systemctl enable ${PROJECT_NAME}
systemctl daemon-reload
writelog "${PROJECT_NAME}服务启动..."
systemctl stop ${PROJECT_NAME} && systemctl start ${PROJECT_NAME}
project_status=$(systemctl status "${PROJECT_NAME}"|grep Active |awk '{print $2}')
jcpid=$(ps -ef | grep -v "grep" | grep "${PROJECT_NAME} " | awk '{print $2}')
writelog "${PROJECT_NAME}服务启动,PID is ${jcpid} ,status:${project_status}"
}
#部署后台服务
project_deploy() {
writelog "${PROJECT_NAME}_deploy"
systemctl stop ${PROJECT_NAME}
clear_deploy ${PROJECT_SERVICE} ${PROJECT_EXECPATH}
writelog "${PROJECT_NAME}_clear_finish"
tar -zvxf ./${PROJECT_FILENAME} -C ${PUBLISH_PATH}
build_service ${PROJECT_SERVICE} ${PROJECT_EXECPATH}
start_service
writelog "${PROJECT_NAME}_deploy_finish"
}
#主函数
main() {
echo "后台服务部署"
project_deploy
exit ${RETVAL}
}
main $1
#! /bin/sh
PORT="@profiles.server.port@"
BASEDIR=`dirname $0`
BASEDIR=`(cd "$BASEDIR"; pwd)`
BASEDIR=$(dirname $0)
BASEDIR=$( (
cd "$BASEDIR"
pwd
))
PROJECT_NAME="@project.artifactId@"
MAIN_CLASS="$PROJECT_NAME";
MAIN_CLASS="$PROJECT_NAME"
if [ ! -n "$PORT" ]; then
echo $"Usage: $0 {port}"
exit $FAIL
if [ ! -n "$PORT" ]; then
echo $"Usage: $0 {port}"
exit $FAIL
fi
pid=`ps ax | grep -i "$MAIN_CLASS" | grep java | grep -v grep | awk '{print $1}'`
if [ -z "$pid" ] ; then
echo "No Server running."
exit -1;
pid=$(ps ax | grep -i "$MAIN_CLASS" | grep java | grep -v grep | awk '{print $1}')
if [ -z "$pid" ]; then
echo "No Server running."
exit 1
fi
echo "stoping application $PROJECT_NAME......"
kill -9 ${pid}
kill -15 ${pid}
echo "Send shutdown request to Server $PROJECT_NAME OK"
......@@ -28,6 +28,7 @@ set JVM_CONFIG=%JVM_CONFIG% -Dapp.name=%PROJECT_NAME%
set JVM_CONFIG=%JVM_CONFIG% -Dapp.port=%PORT%
set JVM_CONFIG=%JVM_CONFIG% -Djava.io.tmpdir=%TEMP_PATH%
set JVM_CONFIG=%JVM_CONFIG% -Dbasedir=%BASEDIR%
set JVM_CONFIG=%JVM_CONFIG% -Dloader.path=file://%BASEDIR%/conf,file://%BASEDIR%/lib
set DEBUG_OPTS=
......
......@@ -5,9 +5,9 @@ BASEDIR=`(cd "$BASEDIR"; pwd)`
PROJECT_NAME="@project.artifactId@";
MAIN_CLASS="$PROJECT_NAME-@project.version@.jar";
LOG_PATH="@profiles.log.path@/$PROJECT_NAME"
GC_PATH=$LOG_PATH/$PORT"-gc.log"
HS_ERR_PATH=$LOG_PATH/$PORT"-hs_err.log"
HEAP_DUMP_PATH=$LOG_PATH/$PORT"-heap_dump.hprof"
GC_PATH=$LOG_PATH/PROJECT_NAME"-gc.log"
HS_ERR_PATH=$LOG_PATH/PROJECT_NAME"-hs_err.log"
HEAP_DUMP_PATH=$LOG_PATH/PROJECT_NAME"-heap_dump.hprof"
TEMP_PATH=$LOG_PATH/temp/
SUCCESS=0
FAIL=9
......@@ -32,9 +32,8 @@ if [ -z "$JAVACMD" ] ; then
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD=`which java > /dev/null 2>&1`
echo "Error: JAVA_HOME is not defined correctly."
exit $ERR_NO_JAVA
JAVACMD=`which java`
echo "Error: JAVA_HOME is $JAVACMD"
fi
fi
......@@ -60,6 +59,7 @@ exec "$JAVACMD" $JAVA_OPTS \
-Dapp.port="$PORT" \
-Dbasedir="$BASEDIR" \
-Djava.io.tmpdir=$TEMP_PATH \
-Dloader.path="file://$BASEDIR/conf,file://$BASEDIR/lib" \
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=15505 \
-jar $MAIN_CLASS \
> /dev/null &
......
#! /bin/sh
PORT="@profiles.server.port@"
BASEDIR=`dirname $0`
BASEDIR=`(cd "$BASEDIR"; pwd)`
PROJECT_NAME="@project.artifactId@"
MAIN_CLASS="$PROJECT_NAME";
if [ ! -n "$PORT" ]; then
echo $"Usage: $0 {port}"
exit $FAIL
fi
echo "stoping application $PROJECT_NAME......"
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ -z $jcpid ]; then
echo "$PROJECT_NAME is not started or has been stopped!"
else
curl -X POST -i -u $SECURITY_USERNAME:$SECURITY_PASSWORD http://127.0.0.1:$PORT/xxx_manager/shutdown
for i in {1..60}
do
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ -z $jcpid ]; then
echo "$PROJECT_NAME has been stopped!"
break
else
echo "stoping the application .. $i"
sleep 1
fi
done
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ $jcpid ]; then
[ -z $jcpid ] || kill -15 $jcpid
for i in {1..30}
do
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ -z $jcpid ]; then
echo "$PROJECT_NAME has been stopped!"
break
else
echo "stoping the application .. $i"
sleep 1
fi
done
fi
jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
if [ $jcpid ]; then
[ -z $jcpid ] || kill -9 $jcpid
[ $? -eq 0 ] && echo "Stop $PROJECT_NAME OK!" || echo "Stop $PROJECT_NAME Fail!"
fi
fi
package com.mortals.xhx.base.framework;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author: zxfei
* @date: 2022/6/30 10:49
* @description:
**/
public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = jp.getText();
if (!ObjectUtils.isEmpty(date)) {
try {
return format.parse(date);
} catch (ParseException e) {
return null;
}
} else {
return null;
}
}
}
package com.mortals.xhx.base.framework;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.util.ArrayList;
import java.util.List;
/**
* @author: zxfei
* @date: 2022/6/28 15:57
* @description:
**/
// 创建一个新的转换器 解析微信的 [text/plain]
public class WxMessageConverter extends MappingJackson2HttpMessageConverter {
public WxMessageConverter() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.TEXT_PLAIN);
setSupportedMediaTypes(mediaTypes);
}
}
\ No newline at end of file
package com.mortals.xhx.base.framework.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiUserAuth {
String msg() default "";
String params() default "";
}
......@@ -4,6 +4,9 @@ import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import com.mortals.framework.model.OperateLogPdu;
import com.mortals.framework.service.IMessageProduceService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
......@@ -22,20 +25,37 @@ import com.mortals.xhx.base.system.oper.service.OperLogService;
/**
* 操作日志记录
*
* @author: zxfei
* @date: 2021/11/5 13:28
*/
@Component
public class OperlogAspect extends FileLogServiceImpl implements ILogService {
private final static Logger logger = LoggerFactory.getLogger(OperlogAspect.class);
@Slf4j
public class OperlogAspect extends FileLogServiceImpl implements ILogService {
@Autowired
private OperLogService operLogService;
@Autowired
private IMessageProduceService messageProduceService;
@Override
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);
operLogService.insertOperLog(ip, requestUrl, userId, userName, loginName, content);
OperateLogPdu operateLogPdu = new OperateLogPdu();
operateLogPdu.initAttrValue();
operateLogPdu.setIp(ip);
operateLogPdu.setRequestUrl(requestUrl);
operateLogPdu.setUserId(userId);
operateLogPdu.setUserName(userName);
operateLogPdu.setLoginName(loginName);
operateLogPdu.setPlatformMark(platformMark);
operateLogPdu.setLogDate(logDate);
operateLogPdu.setContent(content);
operateLogPdu.setOperType(1);
messageProduceService.syncOperSend(operateLogPdu);
}
@Override
......@@ -43,9 +63,11 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
// operLogService.insertOperLog(ip, requestUrl, null, "", loginName,
// content);
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() {
}
......@@ -55,13 +77,13 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
HttpServletRequest request = attributes.getRequest();
// url
logger.info("ip[{}]url[{}]", request.getRemoteAddr(), request.getRequestURL());
log.info("ip[{}]url[{}]", request.getRemoteAddr(), request.getRequestURL());
// 参数第1和第2个参数为HttpServletRequest request, HttpServletResponse
// response
if (joinPoint.getArgs().length > 2) {
logger.info("args={}", joinPoint.getArgs()[2]);
log.info("args={}", joinPoint.getArgs()[2]);
} else {
logger.info("args={}", joinPoint.getArgs());
log.info("args={}", joinPoint.getArgs());
}
}
......@@ -69,7 +91,7 @@ public class OperlogAspect extends FileLogServiceImpl implements ILogService {
@AfterReturning(returning = "object", pointcut = "accessLog()")
public void doAfterReturning(Object object) {
if (null != object) {
logger.info("response={}", object.toString());
log.info("response={}", object.toString());
}
}
}*/
}
package com.mortals.xhx.base.framework.aspect;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
......@@ -27,11 +30,11 @@ import java.util.Map;
* @author: zxfei
* @date: 2022/4/20 9:24
*/
@Aspect
@Component
//@Aspect
//@Component
@Slf4j
@Order(1)
@Profile({"default", "develop", "test"})
//@Profile({"default", "develop", "test"})
public class WebLogAspect {
@Pointcut("execution(public * com.mortals..*Controller.*(..))")
public void webLog() {
......@@ -61,13 +64,19 @@ public class WebLogAspect {
public void afterReturning(Object result) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Map<String, String> map = MDC.getCopyOfContextMap();
if (map != null&&result!=null) {
String startTime = map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis()));
long takeTime = (System.currentTimeMillis() - Long.parseLong(startTime));
log.info(" \n 请求路径:{} \n 耗时:{}ms \n 请求报文:{} \n 响应报文:{}"
, request.getRequestURI(), takeTime, map.getOrDefault("req", ""), result == null ? "" : result.toString());
if (result instanceof String) {
log.info(" \n 请求路径:{} 耗时:{}ms 客户端IP:{} \n 请求报文:{} \n 响应报文:{} "
, request.getRequestURI(), takeTime,ServletUtil.getClientIP(request), map.getOrDefault("req", ""), result);
} else {
log.info(" \n 请求路径:{} 耗时:{}ms 客户端IP:{}\n 请求报文:{} \n 响应报文:{}"
, request.getRequestURI(), takeTime,ServletUtil.getClientIP(request), map.getOrDefault("req", ""), JSON.toJSONString(result));
}
}
}
......
package com.mortals.xhx.base.framework.config;
import com.mortals.framework.springcloud.config.web.BaseWebMvcConfigurer;
import com.mortals.xhx.base.framework.feign.HierarchicalContract;
import feign.Contract;
import com.mortals.xhx.base.framework.WxMessageConverter;
import feign.codec.Decoder;
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.Configuration;
......@@ -14,12 +17,16 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class AccountConfig {
@Bean
public Contract feignContract() {
return new HierarchicalContract();
public BaseWebMvcConfigurer getBaseWebMvc() {
return new BaseWebMvcConfigurer(false, null);
}
@Bean
public BaseWebMvcConfigurer getBaseWebMvc(){
return new BaseWebMvcConfigurer(false,null);
public Decoder feignDecoder() {
WxMessageConverter wxConverter = new WxMessageConverter();
ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(wxConverter);
return new SpringDecoder(objectFactory);
}
}
package com.mortals.xhx.base.framework.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: zxfei
* @date: 2022/2/15 13:16
* @description:
**/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter(){
//初始化配置对象
CorsConfiguration configuration = new CorsConfiguration();
//允许跨域访问的域名
configuration.addAllowedOrigin("*");
// configuration.setAllowCredentials(true); //运行携带cookie
configuration.addAllowedMethod("*"); //代表所有请求方法
configuration.addAllowedHeader("*"); //允许携带任何头信息
//初始化cors配置源对象
UrlBasedCorsConfigurationSource configurationSource=new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**",configuration);
//返回CorSfilter实例,参数
return new CorsFilter(configurationSource);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("*")
.allowedMethods(new String[] { "GET", "POST","PUT","DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}
package com.mortals.xhx.base.framework.config;
import com.mortals.framework.web.interceptor.BaseInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
......@@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletResponse;
* @description:添加跨域响应
**/
@Component
public class CrossInterceptor extends BaseInterceptor {
public class CrossInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
......@@ -24,9 +23,4 @@ public class CrossInterceptor extends BaseInterceptor {
response.setHeader("Access-Control-Allow-Credentials", "true");
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
}
package com.mortals.xhx.base.framework.config;
import com.mortals.framework.filter.RepeatableFilter;
import com.mortals.framework.filter.XssFilter;
import com.mortals.framework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;
/**
* Filter配置
*
* @author zxfei
*/
//@Configuration
public class FilterConfig {
@Value("${xss.enabled}")
private String enabled;
@Value("${xss.excludes}")
private String excludes;
@Value("${xss.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
registration.setName("xssFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("excludes", excludes);
initParameters.put("enabled", enabled);
registration.setInitParameters(initParameters);
return registration;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter());
registration.addUrlPatterns("/*");
registration.setName("repeatableFilter");
registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
return registration;
}
}
package com.mortals.xhx.base.framework.config;
import java.io.IOException;
import java.net.URLDecoder;
import javax.sql.DataSource;
import com.mortals.framework.springcloud.config.mybatis.AbstractMybatisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.mortals.framework.springcloud.config.SpringBootVFS;
import javax.sql.DataSource;
@Configuration
//@AutoConfigureAfter(DataSourceAutoConfiguration.class)
......@@ -45,7 +35,6 @@ public class MybatisConfiguration extends AbstractMybatisConfiguration {
@Value("${mybatis.config-location}")
private String configLocation;
// 提供SqlSeesion
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
......
//package com.mortals.xhx.base.framework.config;
//
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.redisson.Redisson;
//import org.redisson.api.RedissonClient;
//import org.redisson.client.codec.Codec;
//import org.redisson.codec.JsonJacksonCodec;
//import org.redisson.config.Config;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
///**
// * RedissonConfig配置
// *
// * @author: zxfei
// * @date: 2022/8/8 16:02
// */
////@Configuration
////@ConfigurationProperties(prefix = "spring.redis")
//@Slf4j
//@Data
//public class RedissonConfig {
//
// private String host;
//
// private int port;
//
// private String password;
//
// private int database;
//
// //@Bean
// public RedissonClient redissonClient() {
// RedissonClient redissonClient;
// Config config = new Config();
// String url = "redis://" + host + ":" + port;
// // 单节点配置
// config.useSingleServer().setAddress(url).setDatabase(database).setPassword(password);
// //使用json序列化方式
// Codec codec = new JsonJacksonCodec();
// config.setCodec(codec);
//
// // 主从配置
// /*config.useMasterSlaveServers()
// // 设置redis主节点
// .setMasterAddress("redis://192.168.1.120:6379")
// // 设置redis从节点
// .addSlaveAddress("redis://192.168.1.130:6379", "redis://192.168.1.140:6379");*/
// // 哨兵部署方式,sentinel是采用Paxos拜占庭协议,一般sentinel至少3个节点
// /*config.useSentinelServers()
// .setMasterName("my-sentinel-name")
// .addSentinelAddress("redis://192.168.1.120:6379")
// .addSentinelAddress("redis://192.168.1.130:6379")
// .addSentinelAddress("redis://192.168.1.140:6379");*/
// // 集群部署方式,cluster方式至少6个节点,3主3从,3主做sharding,3从用来保证主宕机后可以高可用
// /*config.useClusterServers()
// // 集群状态扫描间隔时间,单位是毫秒
// .setScanInterval(2000)
// .addNodeAddress("redis://192.168.1.120:6379")
// .addNodeAddress("redis://192.168.1.130:6379")
// .addNodeAddress("redis://192.168.1.140:6379")
// .addNodeAddress("redis://192.168.1.150:6379")
// .addNodeAddress("redis://192.168.1.160:6379")
// .addNodeAddress("redis://192.168.1.170:6379");*/
// // 云托管部署方式,这种方式主要解决redis提供商为云服务的提供商的redis连接,比如亚马逊云、微软云
// /*config.useReplicatedServers()
// // 主节点变化扫描间隔时间
// .setScanInterval(2000)
// .addNodeAddress("redis://192.168.1.120:6379")
// .addNodeAddress("redis://192.168.1.130:6379")
// .addNodeAddress("redis://192.168.1.140:6379");*/
// redissonClient = Redisson.create(config);
// return redissonClient;
// }
//}
\ No newline at end of file
package com.mortals.xhx.base.framework.filter;
import cn.hutool.core.util.IdUtil;
import com.mortals.framework.service.IAuthTokenService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
......@@ -23,19 +19,13 @@ import java.io.IOException;
* @author: zxfei
* @date: 2022/4/20 14:52
*/
@Component
//@Component
@Slf4j
public class RequestFilter extends OncePerRequestFilter implements Filter {
@Autowired
private IAuthTokenService authTokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
//每个请求记录一个traceId,可以根据traceId搜索出本次请求的全部相关日志
MDC.put("traceId", IdUtil.fastSimpleUUID().substring(0,12));
setUsername(request);
request = new ContentCachingRequestWrapper(request);
filterChain.doFilter(request, response);
} catch (Exception e) {
......@@ -47,22 +37,22 @@ public class RequestFilter extends OncePerRequestFilter implements Filter {
}
private void setUsername(HttpServletRequest request) {
/*private void setUsername(HttpServletRequest request) {
//通过token解析出username
String token = authTokenService.getToken(request);
//String token = request.getHeader("token");
if (!ObjectUtils.isEmpty(token)) {
MDC.put("token",token);
// MDC.put("token", token);
// try {
// SessionUserInfo info = tokenService.getUserInfo();
// if (info != null) {
// String username = info.getUsername();
// MDC.put("username", username);
// }
// } catch (CommonJsonException e) {
// log.info("无效的token:{}", token);
// }
MDC.put("token", token);
try {
SessionUserInfo info = tokenService.getUserInfo();
if (info != null) {
String username = info.getUsername();
MDC.put("username", username);
}
} catch (CommonJsonException e) {
log.info("无效的token:{}", token);
}
}
}
}*/
}
package com.mortals.xhx.base.framework.security;
package com.mortals.xhx.base.framework.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.SysConstains;
......@@ -14,7 +14,6 @@ import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
......@@ -28,7 +27,7 @@ import java.util.Map;
*
* @author zxfei
*/
@Primary
@Service
@Order(1)
@Slf4j
......@@ -49,11 +48,14 @@ public class AuthTokenServiceImpl implements IAuthTokenService {
@Value("${token.prefix:}")
private String tokenPrefix;
// redis db
// @Value("${spring.redis.database:}")
// private Integer db;
//
// @Value("${token.database:0}")
// private Integer portalDb;
@Value("${spring.redis.database:}")
private Integer db;
@Value("${token.database:0}")
private Integer portalDb;
@Value("${platform.type:cloud}")
private String platFormType;//版本,默认云服务版本
protected static final Long SECOND = 1l;
......@@ -85,12 +87,9 @@ public class AuthTokenServiceImpl implements IAuthTokenService {
Claims claims = parseToken(token);
String uuid = (String) claims.get(SysConstains.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
//cacheService.select(portalDb);
cacheService.select(portalDb);
String userStr = cacheService.get(userKey);
//cacheService.select(db);
// Rest<String> rest = userFeign.getToken(userKey);
// String userStr = rest.getData();
cacheService.select(db);
if (StringUtils.isNotEmpty(userStr)) {
UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
userEntity.setToken(token);
......
......@@ -2,13 +2,14 @@ package com.mortals.xhx.base.framework.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.framework.web.interceptor.BaseInterceptor;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
......@@ -19,6 +20,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import static com.mortals.xhx.common.key.ErrorCode.*;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_USER_OPERATION_CONTENT;
/**
* 用户权限验证,基于token
*
......@@ -40,7 +44,8 @@ public class AuthUserInterceptor extends BaseInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (handler instanceof HandlerMethod) {
JSONObject ret = new JSONObject();
if(handler instanceof HandlerMethod){
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
UnAuth annotation = method.getAnnotation(UnAuth.class);
......@@ -48,10 +53,9 @@ public class AuthUserInterceptor extends BaseInterceptor {
//取消校验
return true;
}
} else if (handler instanceof ResourceHttpRequestHandler) {
}else if(handler instanceof ResourceHttpRequestHandler){
return true;
}
JSONObject ret = new JSONObject();
try {
String uri = request.getServletPath();
//校验配置的请求路径是否需要检查权限
......@@ -59,23 +63,23 @@ public class AuthUserInterceptor extends BaseInterceptor {
//需要校验权限
boolean auth = this.checkAuth(request, uri, config.getSecurityKey());
if (!auth) {
//校验token不正常
String token = authTokenService.getToken(request);
if(ObjectUtils.isEmpty(token)){
ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_TOKEN_UNAUTHORIZED, ERROR_TOKEN_UNAUTHORIZED_CONTENT)));
return false;
}
//不存在时候 如果是管理员也不做拦截
IUser loginUser = authTokenService.getLoginUser(request);
//loginUser.isManager()
if(ObjectUtils.isEmpty(loginUser)){
ret.put("code", 401);
ret.put("msg", "用户未登录或登录失效,请重新登录");
ServletUtils.renderString(response, JSONObject.toJSONString(ret));
if (ObjectUtils.isEmpty(loginUser)) {
ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT)));
return false;
}else if(loginUser.isAdmin()||loginUser.getUserType()==1||loginUser.getUserType()== Constant.CUSTOMER_USER){
} else if (loginUser.isAdmin() || loginUser.getUserType() == 1) {
return super.preHandle(request, response, handler);
} else {
ret.put("code", -1);
ret.put("msg", "用户无该操作权限!");
ServletUtils.renderString(response, JSONObject.toJSONString(ret));
ServletUtils.renderString(response, JSONObject.toJSONString(Rest.fail(ERROR_USER_OPERATION, ERROR_USER_OPERATION_CONTENT)));
return false;
}
}
}
} catch (Exception e) {
......@@ -102,6 +106,4 @@ public class AuthUserInterceptor extends BaseInterceptor {
return false;
}
}
package com.mortals.xhx.base.framework.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
......@@ -16,7 +16,7 @@ public class SecurityUtils {
* 获取Authentication
*/
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
return null;
}
/**
......
......@@ -3,7 +3,6 @@ package com.mortals.xhx.base.framework.ws.handler;
import com.alibaba.fastjson.JSON;
import com.mortals.xhx.base.framework.ws.message.AuthRequest;
import com.mortals.xhx.base.framework.ws.message.AuthResponse;
import com.mortals.xhx.base.framework.ws.message.UserJoinNoticeRequest;
import com.mortals.xhx.base.framework.ws.util.WebSocketUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Component;
......
......@@ -2,8 +2,6 @@ package com.mortals.xhx.base.framework.ws.handler;
import com.mortals.xhx.base.framework.ws.message.HeartBeatRequest;
import com.mortals.xhx.base.framework.ws.message.SendResponse;
import com.mortals.xhx.base.framework.ws.message.SendToOneRequest;
import com.mortals.xhx.base.framework.ws.message.SendToUserRequest;
import com.mortals.xhx.base.framework.ws.util.WebSocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
......
......@@ -4,7 +4,6 @@ import lombok.extern.apachecommons.CommonsLog;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import java.util.Map;
......@@ -17,18 +16,20 @@ import java.util.Map;
@CommonsLog
public class WebSocketShakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override // 拦截 Handshake 事件
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, org.springframework.web.socket.WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// 获得 accessToken
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
attributes.put("accessToken", serverRequest.getServletRequest().getParameter("accessToken"));
}
// 调用父方法,继续执行逻辑
return super.beforeHandshake(request, response, wsHandler, attributes);
}
public static void main(String[] args) {
WebSocketShakeInterceptor webSocketShakeInterceptor = new WebSocketShakeInterceptor();
}
......
package com.mortals.xhx.base.login.interceptor;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.framework.ap.CookieService;
import com.mortals.framework.ap.SysConstains;
......@@ -13,10 +14,13 @@ import com.mortals.framework.web.interceptor.BaseInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Order(1)
import java.lang.reflect.Method;
@Order(1)
//@Component
public class AuthJsonInterceptor extends BaseInterceptor {
......@@ -35,6 +39,13 @@ public class AuthJsonInterceptor extends BaseInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
try {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
UnAuth annotation = method.getAnnotation(UnAuth.class);
if (annotation != null) {
//取消校验
return true;
}
String uri = request.getServletPath();
if (config.needCheckAuth(uri)) {
boolean auth = this.checkAuth(request, uri, config.getSecurityKey());
......
......@@ -19,6 +19,8 @@ import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.feign.user.IUserFeign;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -48,12 +50,27 @@ public class LoginController extends BaseCRUDJsonBodyMappingController<UserServi
@Autowired
private ICacheService cacheService;
@Autowired
private IUserFeign userFeign;
private static Log logger = LogFactory.getLog(LoginController.class);
@RequestMapping("login")
public String login(HttpServletRequest request, HttpServletResponse response, @RequestBody LoginForm loginForm) throws Exception {
public String login( @RequestBody LoginForm loginForm) throws Exception {
JSONObject ret = new JSONObject();
String loginName = loginForm.getLoginName();
String password = loginForm.getPassword();
UserPdu userPdu = new UserPdu();
userPdu.setLoginName(loginName);
userPdu.setPassword(password);
String resp = userFeign.portalLogin(userPdu);
return resp;
/*JSONObject ret = new JSONObject();
String loginName = loginForm.getLoginName();
String password = loginForm.getPassword();
//String securityCode = loginForm.getSecurityCode();
......@@ -105,7 +122,7 @@ public class LoginController extends BaseCRUDJsonBodyMappingController<UserServi
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}*/
}
@RequestMapping("logout")
......
......@@ -37,7 +37,7 @@ public class LoginForm extends BaseForm {
@Override
public String toString() {
return "loginName:" + this.loginName + " password:" + this.password;
return "loginName:" + this.loginName + " password:" + this.password + " securityCode:" + this.securityCode;
}
@Override
......@@ -48,9 +48,7 @@ public class LoginForm extends BaseForm {
if (password == null || password.trim().length() == 0) {
throw new AppException("密码不能为空!");
}
// if (securityCode == null || securityCode.trim().length() == 0) {
// throw new AppException("验证码不能为空!");
// }
return super.validate();
}
}
package com.mortals.xhx.base.login.web;
import java.awt.image.BufferedImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.util.SecurityImage;
import com.mortals.framework.web.BaseCRUDJsonController;
import com.mortals.xhx.base.login.service.GifSecurityImage;
import com.mortals.xhx.base.system.valid.model.ValidCodeEntity;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.base.system.valid.web.ValidCodeForm;
......@@ -13,9 +11,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.util.SecurityImage;
import com.mortals.framework.web.BaseCRUDJsonController;
import com.mortals.xhx.base.login.service.GifSecurityImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
@RestController
@RequestMapping("securitycode")
......
......@@ -76,6 +76,9 @@ public class MenuEntity extends BaseEntityLong{
/** 创建用户名称 */
private String createUserName;
private Integer type;
private List<MenuEntity> childList = new ArrayList<MenuEntity>();
......@@ -83,6 +86,14 @@ public class MenuEntity extends BaseEntityLong{
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
/**
* 获取 菜单名称
* @return name
......@@ -410,7 +421,7 @@ public class MenuEntity extends BaseEntityLong{
this.name = null;
this.url = null;
this.parentId = null;
this.orderId = null;
this.orderId = 0;
this.status = 1;
this.linkType = 0;
this.groupId = 1;
......
......@@ -52,4 +52,12 @@ public interface MenuService extends ICRUDService<MenuEntity,Long> {
* @throws AppException
*/
public List<MenuEntity> findTreeMenu() throws AppException;
/**
* 更新排列顺序
* @param id
* @param type
*/
void upOrDown(Long id, Integer type);
}
\ No newline at end of file
/**
* 文件:MenuServiceImpl.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
* 文件:MenuServiceImpl.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.menu.service.impl;
import com.mortals.framework.common.code.YesNo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.service.IUser;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
......@@ -19,20 +20,23 @@ import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.menu.model.MenuQuery;
import com.mortals.xhx.base.system.menu.service.MenuService;
import com.mortals.xhx.common.code.YesNoEnum;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>Title: 菜单信息</p>
* <p>Description: MenuServiceImpl service接口 </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
*
* @author
* @version 1.0.0
*/
@Service("menuService")
public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao,MenuEntity,Long> implements MenuService {
public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao, MenuEntity, Long> implements MenuService {
@Override
public List<MenuEntity> findAllEnable() throws AppException {
......@@ -48,7 +52,7 @@ public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao,MenuEntity,
@Override
public List<MenuEntity> findTreeMenu(IUser user, Set<String> urls) throws AppException {
Set<Long> authIds = new HashSet<Long>();
Set<Long> authIds = new HashSet<>();
Map<Long, MenuEntity> menuMap = new HashMap<Long, MenuEntity>();
List<MenuEntity> userModuleList = this.findAllEnable();
for (MenuEntity sysModule : userModuleList) {
......@@ -111,5 +115,69 @@ public class MenuServiceImpl extends AbstractCRUDServiceImpl<MenuDao,MenuEntity,
}
return outlookBar;
}
@Override
public void upOrDown(Long id, Integer type) {
MenuQuery query = new MenuQuery();
query.setOrderColList(Arrays.asList(new OrderCol("orderId")));
query.setOrderKind(OrderCol.ASCENDING);
//判断移动的是一级菜单还是二级菜单
MenuEntity menuEntity = this.get(id);
if (menuEntity.getParentId() == 0) {
//一级菜单
query.setParentId(0L);
} else {
//二级菜单
query.setParentId(menuEntity.getParentId());
}
List<MenuEntity> list = this.find(query);
MenuEntity preEntity = null;
MenuEntity curEntity = null;
if (type == YesNoEnum.NO.getValue()) {
//up
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId().equals(id) && i > 0) {
curEntity = list.get(i);
preEntity = list.get(i - 1);
break;
}
}
} else {
//down
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId().equals(id) && i + 1 < list.size()) {
curEntity = list.get(i);
preEntity = list.get(i + 1);
break;
}
}
}
if (preEntity != null && curEntity != null) {
//交换
int temp = preEntity.getOrderId();
preEntity.setOrderId(curEntity.getOrderId());
curEntity.setOrderId(temp);
this.update(preEntity);
this.update(curEntity);
}
}
@Override
protected void saveBefore(MenuEntity entity, Context context) throws AppException {
MenuQuery query = new MenuQuery();
query.setParentId(entity.getParentId());
Comparator<Integer> comparator = Comparator.comparing(Integer::intValue);
Optional<Integer> maxOptional = this.find(query).stream().map(MenuEntity::getOrderId).filter(f->f!=9999).max(comparator);
maxOptional.ifPresent(e -> {
e=e+1;
entity.setOrderId(e);
});
super.saveBefore(entity, context);
}
}
\ No newline at end of file
/**
* 文件:MenuController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.menu.web;
......@@ -13,9 +6,9 @@ import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.menu.model.MenuQuery;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
......@@ -35,73 +28,86 @@ import java.util.Map;
/**
* <p>Title: 菜单信息</p>
* <p>Description: MenuController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 菜单信息
*
* @author: zxfei
* @date: 2021/11/30 10:02
*/
@RestController
@RequestMapping("menu")
public class MenuController extends BaseCRUDJsonMappingController<MenuService, MenuForm,MenuEntity,Long> {
public class MenuController extends BaseCRUDJsonBodyMappingController<MenuService, MenuEntity, Long> {
public MenuController() {
super.setModuleDesc("菜单信息");
}
public MenuController(){
super.setFormClass(MenuForm.class);
super.setModuleDesc("菜单信息");
}
@Override
protected void doListBefore(MenuEntity query, Map<String, Object> model, Context context) throws AppException {
List<OrderCol> orderColList = new ArrayList<OrderCol>();
orderColList.add(new OrderCol("parentId"));
orderColList.add(new OrderCol("orderId"));
query.setOrderColList(orderColList);
}
@Override
protected void init(Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<String, Object>();
status.put("status", DataSatus.getEnumMap(DataSatus.CLOSE.getValue(), DataSatus.DELETE.getValue(), DataSatus.OVERDUE.getValue(), DataSatus.USEOUT.getValue()));
status.put("linkType", MenuLinkType.getEnumMap());
status.put("commMenu", MenuComm.getEnumMap());
status.put("menuType", MenuType.getEnumMap());
status.put("authType", MenuAuthType.getEnumMap());
model.put(KEY_RESULT_DICT, status);
}
@Override
protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MenuForm form, Map<String, Object> model, Context context) throws AppException {
List<OrderCol> orderColList = new ArrayList<OrderCol>();
orderColList.add(new OrderCol("parentId"));
orderColList.add(new OrderCol("orderId"));
form.getQuery().setOrderColList(orderColList);
}
/**
* 改变状态
*/
@RequestMapping(value = "change/status")
public String changeStatus(@RequestBody MenuEntity query) {
JSONObject ret = new JSONObject();
Context context = getContext();
try {
MenuEntity entity = this.service.get(query.getId(), context);//.doSubmitAudit(form.getEntity(), context);
if (null == entity) {
throw new AppException("菜单不存在!");
}
if (null == entity.getStatus()) {
throw new AppException("菜单状态不能为空!");
}
if (entity.getStatus() != DataSatus.ENABLE.getValue() && entity.getStatus() != DataSatus.DISENABLE.getValue()) {
throw new AppException("非法菜单状态!");
}
String busiDesc = DataSatus.getByValue(entity.getStatus()).getDesc();
entity.setStatus(entity.getStatus());
this.service.update(entity, context);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, busiDesc + "成功");
recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]");
@Override
protected void init(HttpServletRequest request, HttpServletResponse response, MenuForm form, Map<String, Object> model,
Context context) {
Map<String, Object> status = new HashMap<String, Object>();
status.put("status", DataSatus.getEnumMap(DataSatus.CLOSE.getValue(), DataSatus.DELETE.getValue(), DataSatus.OVERDUE.getValue(), DataSatus.USEOUT.getValue()));
status.put("linkType", MenuLinkType.getEnumMap());
status.put("commMenu", MenuComm.getEnumMap());
status.put("menuType", MenuType.getEnumMap());
status.put("authType", MenuAuthType.getEnumMap());
model.put(KEY_RESULT_DICT, status);
super.init(request, response, form, model, context);
}
} catch (Exception e) {
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
}
return ret.toJSONString();
}
/**
* 改变状态
*/
@RequestMapping(value = "change/status")
public String changeStatus(HttpServletRequest request, HttpServletResponse response, MenuForm form) {
JSONObject ret = new JSONObject();
Context context = getContext();
try {
MenuEntity entity = this.service.get(form.getEntity().getId(), context);//.doSubmitAudit(form.getEntity(), context);
if (null == entity) {
throw new AppException("菜单不存在!");
}
if (null == form.getEntity().getStatus()) {
throw new AppException("菜单状态不能为空!");
}
if (form.getEntity().getStatus() != DataSatus.ENABLE.getValue() && form.getEntity().getStatus() != DataSatus.DISENABLE.getValue()) {
throw new AppException("非法菜单状态!");
}
String busiDesc = DataSatus.getByValue(form.getEntity().getStatus()).getDesc();
entity.setStatus(form.getEntity().getStatus());
this.service.update(entity, context);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, busiDesc + "成功");
recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]");
} catch (Exception e) {
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
}
return ret.toJSONString();
}
/**
* 更换排序
*/
@PostMapping(value = "upOrDown")
public String upOrDownTopicList(@RequestBody MenuEntity query) {
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
try {
this.service.upOrDown(query.getId(), query.getType());
} catch (Exception e) {
log.error("更新错误", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, e.getMessage());
}
return ret.toJSONString();
}
}
\ No newline at end of file
......@@ -10,8 +10,6 @@ package com.mortals.xhx.base.system.oper.model;
import java.util.Date;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.mortals.framework.model.BaseEntityLong;
/**
......@@ -47,7 +45,6 @@ public class OperLogEntity extends BaseEntityLong{
private String ip;
/** 操作时间 */
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date logDate;
/** 操作类型,0:新增,1:修改,2:删除 */
......
......@@ -106,7 +106,7 @@ public class OperLogServiceImpl extends AbstractCRUDServiceImpl<OperLogDao,OperL
operLogEntity.setLogDate(new Date());
operLogEntity.setPlatformMark(GlobalSysInfo.getPropertyValue(SysConstains.PROP_PLATFORM_MARK));
// operLogEntity.setOperType(operType.getValue());
//operLogEntity.setOperType(operType.getValue());
operLogEntity.setRequestUrl(requestUrl);
operLogEntity.setLoginName(loginName);
operLogEntity.setUserId(userId);
......
/**
* 文件:OperLogController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
* 文件:OperLogController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.oper.web;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
......@@ -14,9 +16,15 @@ import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.oper.model.OperLogEntity;
import com.mortals.xhx.base.system.oper.service.OperLogService;
import com.mortals.xhx.common.code.OperTypeEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
......@@ -26,33 +34,36 @@ import java.util.Map;
* <p>Description: OperLogController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
*
* @author
* @version 1.0.0
*/
@RestController
@RequestMapping("oper/log")
public class OperLogController extends BaseCRUDJsonBodyMappingController<OperLogService,OperLogEntity,Long> {
public OperLogController(){
super.setFormClass(OperLogForm.class);
super.setModuleDesc("操作日志");
}
@Override
protected void init(Map<String, Object> model, Context context) {
// 返回日志类型
this.addDict(model,"operType", OperTypeEnum.getEnumMap());
super.init(model, context);
}
@Override
protected void doListBefore(OperLogEntity query, Map<String, Object> model, Context context) throws AppException {
query.setOrderColList(new ArrayList<OrderCol>() {
{
add(new OrderCol("a.logDate", "desc"));
}
});
}
public class OperLogController extends BaseCRUDJsonBodyMappingController<OperLogService, OperLogEntity, Long> {
public OperLogController() {
super.setFormClass(OperLogForm.class);
super.setModuleDesc("操作日志");
}
@Override
protected void init(Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<String, Object>(1);
// 返回日志类型
status.put("operType", OperTypeEnum.getEnumMap());
model.put(KEY_RESULT_DICT, status);
}
@Override
protected void doListBefore(OperLogEntity query, Map<String, Object> model, Context context) throws AppException {
query.setOrderColList(new ArrayList<OrderCol>() {
{
add(new OrderCol("a.logDate", "desc"));
}
});
}
}
\ No newline at end of file
......@@ -35,6 +35,7 @@ public interface ParamService extends ICRUDCacheService<ParamEntity, Long>, IPar
*/
Map<String, String> getParamByFirstOrganize(String firstOrganize, String... excludeParamKeys);
/**
* 通过firstOrganize获取配置参数key-value
*
......@@ -44,6 +45,29 @@ public interface ParamService extends ICRUDCacheService<ParamEntity, Long>, IPar
*/
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
......
......@@ -30,6 +30,8 @@ import java.util.stream.Collectors;
@Service("paramService")
public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, ParamEntity, Long>
implements ParamService {
private final String HOT_WORDS = "HotWords";
private final String PRINT_QUANTITY = "PrintDisplayQuantity";
@Override
protected String getCacheName() {
......@@ -63,6 +65,67 @@ public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, Par
).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();
......
/**
* 文件:ResourceController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.resource.web;
......@@ -16,6 +9,8 @@ import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.code.UserType;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -29,16 +24,15 @@ import com.mortals.xhx.common.code.AuthType;
import com.mortals.xhx.common.code.SourceType;
/**
* <p>Title: 资源信息</p>
* <p>Description: ResourceController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 资源信息
*
* @author: zxfei
* @date: 2022/5/7 15:27
*/
@Slf4j
@RestController
@RequestMapping("resource")
public class ResourceController extends BaseCRUDJsonMappingController<ResourceService,ResourceForm,ResourceEntity,Long> {
public class ResourceController extends BaseCRUDJsonBodyMappingController<ResourceService,ResourceEntity,Long> {
public ResourceController(){
super.setFormClass(ResourceForm.class);
......@@ -46,8 +40,7 @@ public class ResourceController extends BaseCRUDJsonMappingController<ResourceSe
}
@Override
protected void init(HttpServletRequest request, HttpServletResponse response, ResourceForm form,
Map<String, Object> model, Context context) {
protected void init(Map<String, Object> model, Context context) {
Map<String, Object> statsus = new HashMap<String, Object>();
statsus.put("authType", AuthType.getEnumMap());
statsus.put("sourceType", SourceType.getEnumMap());
......@@ -57,7 +50,6 @@ public class ResourceController extends BaseCRUDJsonMappingController<ResourceSe
statsus.put("userType", UserType.findByValue(getCurUser().getUserType()));
}
model.put(KEY_RESULT_DICT, statsus);
super.init(request, response, form, model, context);
}
/**
......
......@@ -22,7 +22,11 @@ import com.mortals.framework.model.BaseEntityLong;
*/
public class RoleEntity extends BaseEntityLong{
private static final long serialVersionUID = 1547777703344L;
/** 用户ID */
private Long userId;
/** 角色名称 */
private String name;
......
......@@ -8,13 +8,20 @@
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.xhx.base.system.role.dao.RoleDao;
import com.mortals.xhx.base.system.role.model.RoleEntity;
import com.mortals.xhx.base.system.role.model.*;
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.RoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
/**
* <p>Title: 角色信息</p>
* <p>Description: RoleServiceImpl service接口 </p>
......@@ -25,7 +32,29 @@ import org.springframework.stereotype.Service;
*/
@Service("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,6 +32,7 @@ import java.util.Map;
@Service("roleUserService")
public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,RoleUserEntity,Long> implements RoleUserService {
@Override
public void doDistributionUser(RoleUserQuery query) {
Long roleId = query.getRoleId();
......@@ -68,5 +69,7 @@ public class RoleUserServiceImpl extends AbstractCRUDServiceImpl<RoleUserDao,Rol
}
this.dao.insertBatch(list);
}
}
\ No newline at end of file
/**
* 文件:RoleAuthController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.role.web;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.role.model.RoleAuthQuery;
import lombok.extern.slf4j.Slf4j;
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;
......@@ -21,39 +18,38 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <p>Title: 角色资源权限</p>
* <p>Description: RoleAuthController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 角色资源权限
*
* @author: zxfei
* @date: 2022/5/7 15:19
*/
@Slf4j
@RestController
@RequestMapping("role/auth")
public class RoleAuthController extends BaseCRUDJsonMappingController<RoleAuthService,RoleAuthForm,RoleAuthEntity,Long> {
public RoleAuthController(){
super.setFormClass(RoleAuthForm.class);
super.setModuleDesc("角色资源权限");
}
/**
* 分配资源
*/
@PostMapping(value = "distributionSource")
public String distributionUser(HttpServletRequest request, HttpServletResponse response, RoleAuthForm form) {
try {
service.doDistributionSource(form.getQuery());
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配角色资源错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
public class RoleAuthController extends BaseCRUDJsonBodyMappingController<RoleAuthService, RoleAuthEntity, Long> {
public RoleAuthController() {
super.setFormClass(RoleAuthForm.class);
super.setModuleDesc("角色资源权限");
}
/**
* 分配资源
*/
@PostMapping(value = "distributionSource")
public String distributionUser(@RequestBody RoleAuthQuery query) {
try {
service.doDistributionSource(query);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配角色资源错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
}
\ No newline at end of file
/**
* 文件:RoleController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.role.web;
......@@ -14,11 +7,10 @@ import com.mortals.framework.common.code.UserType;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BasePhpCRUDJsonMappingController;
import com.mortals.xhx.base.system.role.model.RoleQuery;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.*;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.role.model.RoleEntity;
import com.mortals.xhx.base.system.role.model.RoleUserEntity;
......@@ -34,12 +26,10 @@ import java.util.List;
import java.util.Map;
/**
* <p>Title: 角色信息</p>
* <p>Description: RoleController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 角色信息
*
* @author: zxfei
* @date: 2022/5/7 15:15
*/
@RestController
@RequestMapping("role")
......@@ -55,17 +45,24 @@ public class RoleController extends BaseCRUDJsonBodyMappingController<RoleServic
@Override
protected void init(Map<String, Object> model, Context context) {
this.addDict(model,"userType", IBaseEnum.getEnumMap(UserType.class));
this.addDict(model,"roleType", RoleType.getEnumMap());
super.init(model, context);
Map<String, Object> status = new HashMap<>();
status.put("userType", IBaseEnum.getEnumMap(UserType.class));
status.put("roleType", RoleType.getEnumMap());
model.put(KEY_RESULT_DICT, status);
}
/**
* 根据用户id获取角色名称
* @param userId
* @return
*/
@PostMapping("roleNameByUserId")
public String getRoleNameByUserId(@RequestBody RoleUserEntity query) {
public String getRoleNameByUserId(@RequestParam(value = "userId") Long userId) {
try{
JSONObject ret = new JSONObject();
RoleUserEntity roleUserEntity = new RoleUserEntity();
roleUserEntity.setUserId(query.getUserId());
roleUserEntity.setUserId(userId);
List<RoleUserEntity> find = roleUserService.find(roleUserEntity, new Context());
List<RoleEntity> model = new ArrayList<>();
if(find.size() > 0){
......
/**
* 文件:RoleUserController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.role.web;
import com.alibaba.fastjson.JSONObject;
......@@ -15,9 +8,12 @@ import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import org.apache.commons.beanutils.MethodUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 com.mortals.framework.web.BaseCRUDJsonMappingController;
......@@ -38,29 +34,50 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
* <p>Title: 角色用户</p>
* <p>Description: RoleUserController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 角色用户
*
* @author: zxfei
* @date: 2022/5/7 15:15
*/
@RestController
@RequestMapping("role/user")
public class RoleUserController extends BaseCRUDJsonMappingController<RoleUserService,RoleUserForm,RoleUserEntity,Long> {
public class RoleUserController extends BaseCRUDJsonBodyMappingController<RoleUserService, RoleUserEntity, Long> {
@Autowired
private RoleService roleService;
@Autowired
private UserService userService;
public RoleUserController() {
super.setFormClass(RoleUserForm.class);
super.setModuleDesc("角色用户");
}
@Autowired
private RoleService roleService;
@Autowired
private UserService userService;
public RoleUserController(){
super.setFormClass(RoleUserForm.class);
super.setModuleDesc("角色用户");
}
/**
@Override
protected void init(Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<>(3);
status.put("roleId", roleService.find(new RoleEntity(), null).stream()
.collect(Collectors.toMap(e -> e.getId().toString(), RoleEntity::getName)));
List<RoleUserEntity> roleUserList = (List<RoleUserEntity>) model.get(SysConstains.RESULT_KEY);
if (roleUserList != null && roleUserList.size() > 0) {
List<Long> userIdsList = roleUserList.stream().map(RoleUserEntity::getUserId).collect(Collectors.toList());
List<UserEntity> userEntityList = userService.find(getQuery(UserQuery.class,
Sets.newHashSet("id", "realName", "loginName"), userIdsList.toArray(new Long[userIdsList.size()])), null);
if (userEntityList != null) {
status.put("userReNameMap",
userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getRealName)));
status.put("userId",
userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getLoginName)));
}
}
model.put(KEY_RESULT_DICT, status);
}
/**
* 获取查询对象,限制查询返回的结果只包含ID和名称
*
* @param IdList
* @return
*/
......@@ -79,65 +96,42 @@ public class RoleUserController extends BaseCRUDJsonMappingController<RoleUserSe
}
}
@SuppressWarnings("unchecked")
@Override
protected void init(HttpServletRequest request, HttpServletResponse response, RoleUserForm form, Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<>(3);
status.put("roleId", roleService.find(new RoleEntity(), null).stream()
.collect(Collectors.toMap(e -> e.getId().toString(), RoleEntity::getName)));
List<RoleUserEntity> roleUserList = (List<RoleUserEntity>) model.get(SysConstains.RESULT_KEY);
if(roleUserList!=null && roleUserList.size()>0) {
List<Long> userIdsList = roleUserList.stream().map(RoleUserEntity::getUserId).collect(Collectors.toList());
List<UserEntity> userEntityList = userService.find(getQuery(UserQuery.class,
Sets.newHashSet("id", "realName","loginName"), userIdsList.toArray(new Long[userIdsList.size()])), null);
if(userEntityList!=null) {
status.put("userReNameMap",
userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getRealName)));
status.put("userId",
userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getLoginName)));
}
}
model.put(KEY_RESULT_DICT, status);
super.init(request, response, form, model, context);
}
/**
* 分配用户
*/
@PostMapping(value = "distributionUser")
public String distributionUser(HttpServletRequest request, HttpServletResponse response, RoleUserForm form) {
try {
service.doDistributionUser(form.getQuery());
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配用户错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
/**
* 分配用户
*/
@PostMapping(value = "distributionUser")
public String distributionUser(@RequestBody RoleUserQuery query) {
try {
service.doDistributionUser(query);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配用户错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
/**
* 分配角色
*/
@PostMapping(value = "distributionRole")
public String distributionRole(HttpServletRequest request, HttpServletResponse response, RoleUserForm form) {
try {
service.doDistributionRole(form.getQuery());
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配角色错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
/**
* 分配角色
*/
@PostMapping(value = "distributionRole")
public String distributionRole(@RequestBody RoleUserQuery query) {
try {
service.doDistributionRole(query);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
return ret.toJSONString();
} catch (Exception e) {
log.error("分配角色错误", e);
JSONObject ret = new JSONObject();
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
}
\ No newline at end of file
......@@ -62,7 +62,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
private Thread thread = null;
/** 日志打印时间,key:任务ID,value:最后一次打印日志时间 */
private Map<Long, Long> printLogTime = new HashMap<Long, Long>();
private Map<Long, Long> printLogTime = new HashMap<>();
@Autowired(required=false)
private TaskService taskService;
......@@ -216,17 +216,17 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
}
if (interimExcuteStatus != TaskInterimExcuteStatus.UNUSE.getValue() // 启用立即执行
|| ((strategy == TaskExcuteStrategy.DAY.getValue() // 按天
|| (strategy == TaskExcuteStrategy.WEEK.getValue()
&& week == excuteDate)
// 按周
|| (strategy == TaskExcuteStrategy.MONTH.getValue()
&& (day == excuteDate
|| (excuteDate > maxDay && day == maxDay))))// 按月
&& (excuteTime == currTime
&& !lastExcuteTimeStr.equals(currDateTimeStr)) // 执行间隔最少为一天
|| (strategy == TaskExcuteStrategy.WEEK.getValue()
&& week == excuteDate)
// 按周
|| (strategy == TaskExcuteStrategy.MONTH.getValue()
&& (day == excuteDate
|| (excuteDate > maxDay && day == maxDay))))// 按月
&& (excuteTime == currTime
&& !lastExcuteTimeStr.equals(currDateTimeStr)) // 执行间隔最少为一天
) || (strategy == TaskExcuteStrategy.INTERVAL.getValue() // 按间隔时间
&& (lastExcuteTime == null || lastExcuteTime.getTime()
+ excuteDate * 1000 <= currDateTime.getTime()))) {
+ excuteDate * 1000 <= currDateTime.getTime()))) {
final boolean printLog = checkPrintLog(task);
Object excuteBean = GlobalSysInfo.getBeanByName(task.getExcuteService());
if (excuteBean == null || !(excuteBean instanceof ITaskExcuteService)) {
......@@ -261,7 +261,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
log.error("执行任务失败-->" + excuteTask, e);
}
if (strategy == TaskExcuteStrategy.INTERVAL.getValue()) {
// 按间隔时间,更新执行时间,避免一直重复执行
// 按间隔时间,更新执行时间,避免一直重复执行
excuteTask.setLastExcuteTime(currDateTime);
}
} finally {
......@@ -297,7 +297,7 @@ public class TaskServiceImpl extends AbstractCRUDServiceImpl<TaskDao, TaskEntity
executorService.shutdown();
log.info("任务执行线程退出!");
});
// thread.start();
thread.start();
}
@Override
......
/**
* 文件:TaskController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.task.web;
......@@ -14,6 +7,8 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.task.model.TaskQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -32,16 +27,14 @@ import com.mortals.xhx.common.code.TaskExcuteStrategyEnum;
import com.mortals.xhx.common.code.TaskInterimExcuteStatusEnum;
/**
* <p>Title: 任务信息</p>
* <p>Description: TaskController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 任务信息
*
* @author: zxfei
* @date: 2022/5/7 15:39
*/
@RestController
@RequestMapping("task")
public class TaskController extends BaseCRUDJsonMappingController<TaskService, TaskForm, TaskEntity, Long> {
public class TaskController extends BaseCRUDJsonBodyMappingController<TaskService, TaskEntity, Long> {
public TaskController() {
super.setFormClass(TaskForm.class);
......@@ -50,8 +43,7 @@ public class TaskController extends BaseCRUDJsonMappingController<TaskService, T
@Override
protected void init(HttpServletRequest request, HttpServletResponse response, TaskForm form,
Map<String, Object> model, Context context) {
protected void init(Map<String, Object> model, Context context) {
Map<String, Object> status = new HashMap<String, Object>();
status.put("status", TaskExcuteStatusEnum.getEnumMap());
status.put("excuteStrategy", TaskExcuteStrategyEnum.getEnumMap());
......@@ -71,60 +63,30 @@ public class TaskController extends BaseCRUDJsonMappingController<TaskService, T
}
model.put("excuteService", serviceList);
model.put(KEY_RESULT_DICT, status);
super.init(request, response, form, model, context);
}
/**
* @param request
* @param response
* @param form
* @param model
* @param context
* @throws AppException
* @Description: TODO
*/
@Override
protected void saveBefore(HttpServletRequest request, HttpServletResponse response, TaskForm form,
Map<String, Object> model, Context context) throws AppException {
if (null == form.getEntity().getExcuteService()) {
}
// TaskEntity condition = new TaskEntity();
// condition.setExcuteService(form.getEntity().getExcuteService());
// List<TaskEntity> datas = this.service.find(condition, context);
// if (null != datas && datas.size() > 0) {
// for (TaskEntity entity : datas) {
// if (entity.getId().longValue() != form.getEntity().getId().longValue()) {
// throw new AppException("任务已存在,请勿重复配置");
// }
// }
// }
super.saveBefore(request, response, form, model, context);
}
/**
* 改变状态
*/
@RequestMapping(value = "change/status")
public String changeStatus(HttpServletRequest request, HttpServletResponse response, TaskForm form) {
public String changeStatus(TaskQuery query) {
JSONObject ret = new JSONObject();
Context context = getContext();
try {
TaskEntity entity = this.service.get(form.getEntity().getId(), context);// .doSubmitAudit(form.getEntity(),
TaskEntity entity = this.service.get(query.getId(), context);// .doSubmitAudit(form.getEntity(),
// context);
if (null == entity) {
throw new AppException("任务不存在!");
}
if (null == form.getEntity().getStatus()) {
if (null == query.getStatus()) {
throw new AppException("任务状态不能为空!");
}
if (form.getEntity().getStatus() != DataSatusEnum.ENABLE.getValue()
&& form.getEntity().getStatus() != DataSatusEnum.DISENABLE.getValue()) {
if (query.getStatus() != DataSatusEnum.ENABLE.getValue()
&& query.getStatus() != DataSatusEnum.DISENABLE.getValue()) {
throw new AppException("非法任务状态!");
}
String busiDesc = DataSatusEnum.getByValue(form.getEntity().getStatus()).getDesc();
entity.setStatus(form.getEntity().getStatus());
String busiDesc = DataSatusEnum.getByValue(query.getStatus()).getDesc();
entity.setStatus(query.getStatus());
this.service.update(entity, context);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, busiDesc + "成功");
......
......@@ -52,4 +52,6 @@ public interface UploadService extends IService {
void uploadDownload(String fileName, HttpServletResponse response);
void deleteFile(String fileName);
}
\ No newline at end of file
package com.mortals.xhx.base.system.upload.service.impl;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.StringUtils;
......@@ -15,9 +16,7 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
......@@ -69,14 +68,12 @@ public class UploadServiceImpl implements UploadService {
if (!pathDir.exists()) {
pathDir.mkdirs();
}
String newName = new Date().getTime() + "." + extension;
//String newName = IdUtil.fastSimpleUUID() + "." + extension;
String filePathAll = filePath + newName;
File uploadFile = new File(filePathAll);
try {
log.info("文件正在储存");
log.info("文件正在储存,filepath:"+filePathAll);
tempFile.transferTo(uploadFile);
} catch (Exception e) {
throw new AppException(e.getMessage());
......@@ -94,7 +91,7 @@ public class UploadServiceImpl implements UploadService {
@Override
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
String filePath = getFilePath(fileName);
String filePath = this.filePath + fileName;
try {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
setAttachmentResponseHeader(response, realFileName);
......@@ -107,28 +104,14 @@ public class UploadServiceImpl implements UploadService {
@Override
public void preview(String fileName, HttpServletResponse response) {
// String filePath = this.filePath+"/preview/" + fileName;
// try {
// response.setContentType(MediaType.IMAGE_JPEG_VALUE);
// setAttachmentResponseHeader(response, fileName);
// FileUtil.writeToStream(filePath, response.getOutputStream());
// } catch (Exception e) {
// log.error("下载文件失败", e);
// }
String filePath = getFilePath(fileName);
String filePath = this.filePath+"/file/preview/" + fileName;
try {
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0L);
response.setContentType("image/jpeg");
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception var4) {
this.log.debug("响应图片消息异常-->" + var4.getMessage());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
setAttachmentResponseHeader(response, fileName);
FileUtil.writeToStream(filePath, response.getOutputStream());
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
......@@ -179,4 +162,14 @@ public class UploadServiceImpl implements UploadService {
}
}
@Override
public void deleteFile(String fileName) {
String filePath = this.filePath+ fileName;
try {
FileUtil.del(filePath);
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
}
\ No newline at end of file
......@@ -16,13 +16,10 @@ import java.util.HashMap;
import java.util.Map;
/**
* <p>Title: 上传文件</p>
* <p>Description: UploadfileController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* 上传文件
*
* @author
* @version 1.0.0
* @author: zxfei
* @date: 2021/11/30 10:06
*/
@RestController
@RequestMapping("file")
......@@ -32,7 +29,8 @@ public class UploadController extends BaseController {
private UploadService uploadService;
@RequestMapping(value = "upload")
public String doFileUpload(HttpServletRequest request, HttpServletResponse response, UploadForm form) {
@UnAuth
public String doFileUpload(HttpServletRequest request, UploadForm form) {
Map<String, Object> model = new HashMap<>();
String jsonStr = "";
try {
......@@ -57,7 +55,7 @@ public class UploadController extends BaseController {
@RequestMapping(value = "commonupload")
@UnAuth
public String doFileUpload(MultipartFile file, @RequestParam(value = "prePath",defaultValue = "file/uploadfile") String prePath) {
public String doFileUpload(MultipartFile file, @RequestParam(value = "prePath",defaultValue = "file/fileupload") String prePath) {
Map<String, Object> model = new HashMap<>();
String jsonStr = "";
try {
......@@ -96,20 +94,6 @@ public class UploadController extends BaseController {
}
}
/**
* 图片预览 (PathVariable)
*
* @param fileName 文件名称
*/
@GetMapping("preview/{prePath}/{fileName}")
public void preViewPath(@PathVariable(value="fileName") String fileName,@PathVariable(value="prePath") String prePath, HttpServletResponse response) {
try {
uploadService.preview(prePath+"/"+fileName, response);
} catch (Exception e) {
log.error("下载文件失败:", e);
}
}
/**
* 图片预览 (PathVariable)
*
......
package com.mortals.xhx.base.system.user.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.mortals.framework.model.BaseEntityLong;
import lombok.Data;
import java.util.List;
/**
*
* Description:User
* date: 2021-9-26 16:11:48
*/
* Description:User
* date: 2021-9-26 16:11:48
*/
@Data
public class UserEntityExt extends BaseEntityLong {
/**
* 唯一标识
*/
@JSONField(serialize = false)
private String token;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
private String siteName;
private List<Long> roleIds;
private String siteCode;
private String oldPassword;
private String newPassword;
private String siteIds;
/**
* 站点名称
*/
private String siteName;
private String roleIds;
/**
* 唯一标识
*/
private String token;
/**
* 菜单栏
*/
private String menuUrl;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
}
\ No newline at end of file
package com.mortals.xhx.base.system.user.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 用户信息业务视图对象
*
* @author zxfei
* @date 2022-07-05
*/
@Data
public class UserVo extends BaseEntityLong {
/**
* 站点名称
*/
private String siteName;
private String roleIds;
/**
* 唯一标识
*/
private String token;
/**
* 菜单栏
*/
private String menuUrl;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
private Long siteId;
private Long customerId;
}
\ No newline at end of file
......@@ -13,6 +13,7 @@ import com.mortals.framework.model.Result;
import com.mortals.framework.service.ICRUDService;
import com.mortals.framework.service.IUser;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.user.dao.UserDao;
import com.mortals.xhx.base.system.user.model.UserEntity;
import java.util.List;
......@@ -37,7 +38,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @return
* @throws AppException
*/
public UserEntity doLogin(String loginName, String password, String loginIp) throws AppException;
UserEntity doLogin(String loginName, String password, String loginIp) throws AppException;
/**
* 校验用户名与密码是否正确
......@@ -47,7 +48,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @return
* @throws AppException
*/
public UserEntity doCheckUser(String loginName, String password) throws AppException;
UserEntity doCheckUser(String loginName, String password) throws AppException;
/**
* 检查用户是否存在
......@@ -56,7 +57,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @param userId 密码
* @return
*/
public boolean existUser(String loginName, Long userId) throws AppException;
boolean existUser(String loginName, Long userId) throws AppException;
/**
* 通过登录用户获取菜单功能权限
......@@ -64,7 +65,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @param user
* @return
*/
public List<MenuEntity> findOutlookBarList(IUser user);
List<MenuEntity> findOutlookBarList(IUser user);
/**
* 查询用户所有有权限的菜单ID
......@@ -72,7 +73,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @param userEntity
* @return
*/
public Set<Long> findAllAuthIds(UserEntity userEntity) throws AppException;
Set<Long> findAllAuthIds(UserEntity userEntity) throws AppException;
/**
* 查询用户记录
......@@ -84,7 +85,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @return
* @throws AppException
*/
public Result<UserEntity> find(Long platformId, UserEntity params, int currPage, int prePageResult) throws AppException;
Result<UserEntity> find(Long platformId, UserEntity params, int currPage, int prePageResult) throws AppException;
/**
* 为客户创建用户
......@@ -99,7 +100,7 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @return
* @throws AppException
*/
public UserEntity createUser(IUser currUser, Long customerId, String customerName, String loginName, String password,
UserEntity createUser(IUser currUser, Long customerId, String customerName, String loginName, String password,
String userName, String mobile) throws AppException;
/**
......@@ -111,5 +112,10 @@ public interface UserService extends ICRUDService<UserEntity,Long> {
* @return
* @throws AppException
*/
public boolean updateUserPwd(String loginName, String oldPwd, String newPwd) throws AppException;
boolean updateUserPwd(String loginName, String oldPwd, String newPwd) throws AppException;
UserDao getUserDao();
}
\ No newline at end of file
/**
* 文件:UserController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.user.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.service.IUser;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.role.model.RoleEntity;
import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.common.code.UserStatus;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.code.UserType;
import com.mortals.xhx.common.key.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
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.service.UserService;
import com.mortals.xhx.common.code.UserStatus;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <p>Title: 用户信息</p>
* <p>Description: UserController </p>
* <p>Copyright: Copyright &reg; </p>
* <p>Company: </p>
* @author
* @version 1.0.0
* 用户信息
*
* @author: zxfei
* @date: 2022/5/7 15:42
*/
@RestController
@RequestMapping("user")
public class UserController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private RoleUserService roleUserService;
public UserController() {
super.setFormClass(UserForm.class);
......@@ -60,33 +56,57 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic
@Override
protected void init(Map<String, Object> model, Context context) {
this.addDict(model,"userType", IBaseEnum.getEnumMap(UserType.class));
this.addDict(model,"status", UserStatus.getEnumMap());
List<RoleEntity> roleList = roleService.find(new RoleEntity());
this.addDict(model,"roleId", roleList.stream().collect(Collectors.toMap(e->e.getId().toString(), e->e.getName())));
super.init(model, context);
this.addDict(model, "roleIds", roleService.find(new RoleQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName())));
}
@Override
protected int editAfter(Long id, Map<String, Object> model, UserEntity entity, Context context) throws AppException {
entity.setLoginPwd(null);
entity.setLoginPwd1(null);
entity.setLoginPwd2(null);
entity.setLoginPwd3(null);
return 1;
protected void doListBefore(UserEntity query, Map<String, Object> model, Context context) throws AppException {
if (!StringUtils.isEmpty(query.getRealName())) {
query.setRealName("%".concat(query.getRealName()).concat("%"));
}
if (!StringUtils.isEmpty(query.getLoginName())) {
query.setLoginName("%".concat(query.getLoginName()).concat("%"));
}
}
@RequestMapping(value = "change/password", method = RequestMethod.POST)
public String changePassword(@RequestBody UserEntity entity) {
IUser user = this.getCurUser();
if(user == null){
return this.createFailJsonResp("请先登录");
@Override
protected int editAfter(Long id, Map<String, Object> model, UserEntity entity, Context context) throws AppException {
RoleUserQuery roleUserQuery = new RoleUserQuery();
roleUserQuery.setUserId(entity.getId());
String roleIds = roleUserService.find(roleUserQuery).stream().map(RoleUserEntity::getRoleId).map(String::valueOf).collect(Collectors.joining(","));
entity.setRoleIds(roleIds);
return super.editAfter(id, model, entity, context);
}
@Override
protected int saveAfter(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
if (entity.getId() == getCurUser().getId()) {
// TODO: 2022/8/15 更新redis session信息
//saveCurrUserForSession(request, response, userService.get(form.getEntity().getId(), false));
}
return super.saveAfter(entity, model, context);
}
// @Override
// protected void saveBefore(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
// if (!ObjectUtils.isEmpty(entity.getLoginName()) && service.existUser(entity.getLoginName(), entity.getId())) {
// throw new AppException("登录名已存在!");
// }
// super.saveBefore(entity, model, context);
// }
@RequestMapping(value = "change/password", method = RequestMethod.POST)
@Operlog(msg = "密码修改成功!")
public String changePassword(@RequestParam String oldPwd, @RequestParam String newPwd) {
JSONObject ret = new JSONObject();
try {
service.updateUserPwd(super.getCurUser().getLoginName(), entity.getOldPassword(), entity.getNewPassword());
service.updateUserPwd(super.getCurUser().getLoginName(), oldPwd, newPwd);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, "密码修改成功!");
} catch (Exception e) {
......@@ -95,4 +115,22 @@ public class UserController extends BaseCRUDJsonBodyMappingController<UserServic
}
return ret.toJSONString();
}
public static void main(String[] args) {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJsb2dpbl91c2VyX2tleSI6IjIzNGE5NDA5ZDVhOTQ3MWNhMzdkYjZkYmMwY2JjZTc5In0.MWyQW40HYDxyUz7PJRf_nRsFPWx3Hr811Ime984nixs";
String secret = "026db82420614469897fcc2dc1b4ce38";
Claims claims = Jwts.parser()
.setSigningKey(Base64.getEncoder().encodeToString(secret.getBytes()))
.parseClaimsJws(token)
.getBody();
String uuid = (String) claims.get("login_user_key");
System.out.println(uuid);
}
}
\ No newline at end of file
/**
* 文件:ValidCodeController.java
* 版本:1.0.0
* 日期:
* Copyright &reg;
* All right reserved.
*/
package com.mortals.xhx.base.system.valid.web;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.model.Context;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.valid.model.ValidCodeEntity;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.common.code.ValidCodeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
......
package com.mortals.xhx.common.key;
/**
* 错误码
*
* @author: zxfei
* @date: 2022/5/12 14:56
*/
public interface ErrorCode {
public static final int STATUS_MS_EXCEPTION = 500;
public static final int STATUS_VALIDATE_EXCEPTION = 420;
public static final int STATUS_UNCHECKED_EXCEPTION = 605;
public static final int STATUS_TOKEN_NULL_EXCEPTION = 604;
public static final int STATUS_CODE_SUCCESS = 0;
public static final int STATUS_CODE_WARN = 1;
public static final int STATUS_CODE_ERROR = 2;
public static final int STATUS_CODE_INFO = 3;
public static final int STATUS_CODE_TOKEN_EXPIRED = 4;
public static final int STATUS_CODE_FATAL = 5;
public static final int STATUS_CODE_TRADE_PWD_NOT_SET = 6;
public static final int STATUS_ACCOUNT_LOCKED = 7;
public static final int STATUS_TRADE_PWD_OVER_THREE_TIME = 8;
public static final int STATUS_TRADE_PWD_ERROR = 9;
public static final int STATUS_EMPTY_PWD_ERROR = 10;
public static final int STATUS_TEL_NOT_RGI_ERROR = 11;
public static final int STATUS_TEL_ALREADY_REGI = 12;
public static final int STATUS_SAFETY_RISK = 13;
public static final int STATUS_LOGIN_CODE = 15;
public static final int BOOK_FAKUAN_CODE = 16;
public static final String ERROR_TRADE_PWD_OVER_THREE_TIME = "支付密码错误,请15分钟后再试";
public static final String ERROR_TRADE_PWD_ERROR = "支付密码错误,请重试";
public static final String ERROR_EMPTY_PWD_ERROR = "请设置登录密码";
public static final String ERROR_TEL_NOT_RGI = "该号码未注册";
public static final String ERROR_USERNAME_OR_PASSWORD = "用户名或者密码错误";
public static final String ERROR_TRADE_PWD = "交易密码错误";
public static final String ERROR_FORBIDDEN_OPER = "非法操作";
public static final String ERROR_TRADE_PWD_NOT_SET = "非法操作";
public static final String ERROR_NOT_REAL_NAME_AUTH = "您未实名认证,禁止该操作";
public static final String ERROR_INTERNAL_SERVER_ERROR = "服务器内部错误";
public static final String ERROR_UNAUTHORIZED = "token不正确或已过期";
public static final String ERROR_TOKEN_IS_NULL = "token不能为空";
public static final String ERROR_MISS_SERVLET = "服务不存在";
public static final String ERROR_CAPTCHA_OFTEN = "验证码已发送";
public static final String ERROR_CAPTCHA_WRONG = "验证码错误";
public static final String ERROR_TEL_ALREADY_REGI = "该手机号已被注册";
public static final String ERROR_CODE_DUPLICATE_KEY = "重复添加信息(含部分)";
public static final String ERROR_NOT_EXITS = "对应记录不存在";
public static final String ERROR_STATUS_CATEGORY = "状态错误";
public static final String ERROR_FRIEND_SHIP_ALREADY = "已经是你好友";
public static final String ERROR_FRIEND_SHIP_WAIT = "已向改好友发出邀请,等待接受";
public static final String ERROR_CODE_ACCOUNT_LOCKED = "账号被锁定,请联系客服";
public static final String WARN_ARGUMENT = "参数错误";
public static final String ERROR_USERNAME_EXIST = "该号码已被注册";
public static final String ERROR_SAFETY_RISK = "不在常用设备上登录";
public static final String INFO_TEL_BIND = "手机号码已经被绑定";
public static final String INFO_TEL_FORMAT_WRONG = "手机号码格式不正确";
public static final String ERROR_NOT_FOUND = "404 not found";
public static final String DISABLED="该账号已被封禁,如有疑问请联系平台";
public static final String DATENULL="缺少参数";
public static final String ERRDATE="无效参数";
public static final String ERRSTAE="状态异常";
public static final String EXTDATE="参数异常";
public static final String NUMEXE="账号异常";
public static final String CAPDON="资产已被冻结,如有疑问请联系平台";
public static final String CONOTS="操作失败";
public static final String OK="成功!";
public static final String TOKENX="身份验证失败,请重新登录";
public static final String CAPNOT="充值余额不足请充值";
public static final String SYSNOT="系统繁忙,请稍后再试...";
public static final String NOWER="没有权限";
public static final String PAGEDATA="分页参数不能为空";
public static final String CARADD_MEMBERS="该司机已有绑定车辆,不能绑定多个";
public static final int DEVICE_CODE_IS_EMPTY = 1001;
public static final String DEVICE_CODE_IS_EMPTY_CONTENT = "当前设备编码为空!";
public static final int DEVICE_CODE_IS_EXIST = 1002;
public static final String DEVICE_CODE_IS_EXIST_CONTENT = "当前设备编码已存在!";
public static final int PRODUCT_IS_EMPTY = 1003;
public static final String PRODUCT_IS_EMPTY_CONTENT = "所属产品编码不存在!";
public static final int DEVICE_UNACTIVE = 1004;
public static final String DEVICE_UNACTIVE_CONTENT = "当前设备未激活,请在后台配置后再激活!";
public static final int PLATFORM_IS_EMPTY = 1005;
public static final String PLATFORM_IS_EMPTY_CONTENT = "当前设备编码不存在!";
public static final int PLATFORM_UNEXIST = 1006;
public static final String PLATFORM_UNEXIST_CONTENT = "当前设备所属产品平台未配置,请在后台配置后再激活!";
public static final int SITEID_IS_EMPTY = 1007;
public static final String SITEID_IS_EMPTY_CONTENT = "站点ID为空!";
public static final int DEVICE_CONFIG_IS_EMPTY = 1008;
public static final String DEVICE_CONFIG_IS_EMPTY_CONTENT = "设备创建,请完善设备配置信息!";
public static final int DEVICE_NOT_EXIST = 1009;
public static final String DEVICE_NOT_EXIST_CONTENT = "当前设备不存在!";
public static final int TOKEN_AUTH_FAIL = 1010;
public static final String TOKEN_AUTH_FAIL_CONTENT = "token认证失败!";
public static final int DEVICE_VERSION_UNEXIST = 1011;
public static final String DEVICE_VERSION_UNEXIST_CONTENT = "未找到设备版本信息!";
public static final int ERROR_TOKEN_EXPIRED = 9001;
public static final String ERROR_TOKEN_EXPIRED_CONTENT = "用户登录过期,请重新登录!";
public static final int ERROR_TOKEN_UNAUTHORIZED = 9002;
public static final String ERROR_TOKEN_UNAUTHORIZED_CONTENT = "token不正确或已过期";
public static final int ERROR_USER_OPERATION = 9009;
public static final String ERROR_USER_OPERATION_CONTENT = "用户无该操作权限!";
}
package com.mortals.xhx.module.certificate.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import java.util.List;
/**
* 证照分类设备配置Dao
* 证照分类设备配置 DAO接口
*
* @author zxfei
* @date 2023-05-09
*/
public interface DeviceClassifyDao extends ICRUDDao<DeviceClassifyEntity,Long>{
}
package com.mortals.xhx.module.certificate.dao.ibatis;
import org.springframework.stereotype.Repository;
import com.mortals.xhx.module.certificate.dao.DeviceClassifyDao;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import java.util.Date;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import java.util.List;
/**
* 证照分类设备配置DaoImpl DAO接口
*
* @author zxfei
* @date 2023-05-09
*/
@Repository("deviceClassifyDao")
public class DeviceClassifyDaoImpl extends BaseCRUDDaoMybatis<DeviceClassifyEntity,Long> implements DeviceClassifyDao {
}
package com.mortals.xhx.module.certificate.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.certificate.model.vo.CertificateCatalogVo;
/**
* 证照目录实体对象
*
* @author zxfei
* @date 2022-11-08
* @date 2023-05-09
*/
public class CertificateCatalogEntity extends CertificateCatalogVo {
......@@ -88,7 +83,9 @@ public class CertificateCatalogEntity extends CertificateCatalogVo {
* 批量导入模板文件地址
*/
private String excelFile;
/**
* 是否生成PDF,0:否1:是
*/
private Integer isPdf;
......@@ -346,15 +343,24 @@ public class CertificateCatalogEntity extends CertificateCatalogVo {
public void setExcelFile(String excelFile){
this.excelFile = excelFile;
}
public Integer getIsPdf() {
/**
* 获取 是否生成PDF,0:否1:是
* @return Integer
*/
public Integer getIsPdf(){
return isPdf;
}
public void setIsPdf(Integer isPdf) {
/**
* 设置 是否生成PDF,0:否1:是
* @param isPdf
*/
public void setIsPdf(Integer isPdf){
this.isPdf = isPdf;
}
@Override
public int hashCode() {
return this.getId().hashCode();
......@@ -391,6 +397,7 @@ public class CertificateCatalogEntity extends CertificateCatalogVo {
sb.append(",paperSource:").append(getPaperSource());
sb.append(",deviceId:").append(getDeviceId());
sb.append(",excelFile:").append(getExcelFile());
sb.append(",isPdf:").append(getIsPdf());
return sb.toString();
}
......@@ -431,5 +438,7 @@ public class CertificateCatalogEntity extends CertificateCatalogVo {
this.deviceId = null;
this.excelFile = "";
this.isPdf = 0;
}
}
\ No newline at end of file
package com.mortals.xhx.module.certificate.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.certificate.model.vo.DeviceClassifyVo;
/**
* 证照分类设备配置实体对象
*
* @author zxfei
* @date 2023-05-09
*/
public class DeviceClassifyEntity extends DeviceClassifyVo {
private static final long serialVersionUID = 1L;
/**
* 设备编码
*/
private String deviceCode;
/**
* 设备名称
*/
private String deviceName;
/**
* 设备允许显示的分类
*/
private String classifyIds;
public DeviceClassifyEntity(){}
/**
* 获取 设备编码
* @return String
*/
public String getDeviceCode(){
return deviceCode;
}
/**
* 设置 设备编码
* @param deviceCode
*/
public void setDeviceCode(String deviceCode){
this.deviceCode = deviceCode;
}
/**
* 获取 设备名称
* @return String
*/
public String getDeviceName(){
return deviceName;
}
/**
* 设置 设备名称
* @param deviceName
*/
public void setDeviceName(String deviceName){
this.deviceName = deviceName;
}
/**
* 获取 设备允许显示的分类
* @return String
*/
public String getClassifyIds(){
return classifyIds;
}
/**
* 设置 设备允许显示的分类
* @param classifyIds
*/
public void setClassifyIds(String classifyIds){
this.classifyIds = classifyIds;
}
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof DeviceClassifyEntity) {
DeviceClassifyEntity tmp = (DeviceClassifyEntity) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public String toString(){
StringBuilder sb = new StringBuilder("");
sb.append(",deviceCode:").append(getDeviceCode());
sb.append(",deviceName:").append(getDeviceName());
sb.append(",classifyIds:").append(getClassifyIds());
return sb.toString();
}
public void initAttrValue(){
this.deviceCode = "";
this.deviceName = "";
this.classifyIds = "";
}
}
\ No newline at end of file
package com.mortals.xhx.module.certificate.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 证照分类设备配置视图对象
*
* @author zxfei
* @date 2023-05-09
*/
@Data
public class DeviceClassifyVo extends BaseEntityLong {
}
\ No newline at end of file
package com.mortals.xhx.module.certificate.service;
import com.mortals.framework.service.ICRUDService;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import java.util.List;
/**
* DeviceClassifyService
*
* 证照分类设备配置 service接口
*
* @author zxfei
* @date 2023-05-09
*/
public interface DeviceClassifyService extends ICRUDService<DeviceClassifyEntity,Long>{
/**
* 获取设备允许打印目录分类
* @param deviceNum
* @return
*/
List<Long> getClassifyByDevice(String deviceNum);
}
\ No newline at end of file
package com.mortals.xhx.module.certificate.service.impl;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.StringUtils;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.certificate.dao.DeviceClassifyDao;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import com.mortals.xhx.module.certificate.service.DeviceClassifyService;
import java.util.ArrayList;
import java.util.List;
/**
* DeviceClassifyService
* 证照分类设备配置 service实现
*
* @author zxfei
* @date 2023-05-09
*/
@Service("deviceClassifyService")
public class DeviceClassifyServiceImpl extends AbstractCRUDServiceImpl<DeviceClassifyDao, DeviceClassifyEntity, Long> implements DeviceClassifyService {
@Override
public List<Long> getClassifyByDevice(String deviceNum) {
DeviceClassifyEntity query = new DeviceClassifyEntity();
query.setDeviceCode(deviceNum);
DeviceClassifyEntity deviceClassifyEntity = this.selectOne(query);
if(deviceClassifyEntity!=null){
if(StringUtils.isNotEmpty(deviceClassifyEntity.getClassifyIds())){
List<Long> classifyIdList = new ArrayList<>();
String[] ids = deviceClassifyEntity.getClassifyIds().split(",");
for (String id:ids){
classifyIdList.add(DataUtil.converStr2Long(id,0l));
}
return classifyIdList;
}
}
return null;
}
}
\ No newline at end of file
......@@ -15,11 +15,14 @@ import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.module.certificate.model.CertificateCatalogEntity;
import com.mortals.xhx.module.certificate.model.CertificateClassifyEntity;
import com.mortals.xhx.module.certificate.model.CertificateClassifyQuery;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import com.mortals.xhx.module.certificate.pdu.PrintListPdu;
import com.mortals.xhx.module.certificate.pdu.PrintLogPdu;
import com.mortals.xhx.module.certificate.pdu.PrintSettingPdu;
import com.mortals.xhx.module.certificate.service.CertificateCatalogService;
import com.mortals.xhx.module.certificate.service.CertificateClassifyService;
import com.mortals.xhx.module.certificate.service.DeviceClassifyService;
import com.mortals.xhx.module.record.model.ApplyLogEntity;
import com.mortals.xhx.module.record.model.PrintWaitQueueEntity;
import com.mortals.xhx.module.record.model.PrintWaitQueueQuery;
......@@ -46,6 +49,8 @@ public class CertificatePrintController extends BaseJsonBodyController {
private CertificateCatalogService certificateCatalogService;
@Autowired
private PrintWaitQueueService printWaitQueueService;
@Autowired
private DeviceClassifyService deviceClassifyService;
@PostMapping({"setting/info"})
public Rest<Object> list() {
......@@ -179,15 +184,19 @@ public class CertificatePrintController extends BaseJsonBodyController {
@PostMapping({"home"})
@UnAuth
public Rest<Object> printHome() {
public Rest<Object> printHome(@RequestBody DeviceClassifyEntity deviceClassifyEntity) {
Rest<Object> ret = new Rest();
Map<String, Object> model = new HashMap();
String busiDesc = "终端首页" ;
int code=1;
try {
CertificateClassifyEntity query = new CertificateClassifyEntity();
List<Long> classifyIdList = deviceClassifyService.getClassifyByDevice(deviceClassifyEntity.getDeviceCode());
CertificateClassifyQuery query = new CertificateClassifyQuery();
query.setShowFront(YesNoEnum.YES.getValue());
if(CollectionUtils.isNotEmpty(classifyIdList)){
query.setIdList(classifyIdList);
}
List<CertificateClassifyEntity> showList = certificateClassifyService.find(query);
model.put("showList", showList);
model.put("printMax", paramService.getParamIntValue(ParamKey.ALLOW_PRINT_MAX_COUNT));
......
package com.mortals.xhx.module.certificate.web;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.certificate.model.DeviceClassifyEntity;
import com.mortals.xhx.module.certificate.service.DeviceClassifyService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.mortals.framework.ap.SysConstains.*;
/**
*
* 证照分类设备配置
*
* @author zxfei
* @date 2023-05-09
*/
@RestController
@RequestMapping("device/classify")
public class DeviceClassifyController extends BaseCRUDJsonBodyMappingController<DeviceClassifyService,DeviceClassifyEntity,Long> {
@Autowired
private ParamService paramService;
public DeviceClassifyController(){
super.setModuleDesc( "证照分类设备配置");
}
@Override
protected void init(Map<String, Object> model, Context context) {
super.init(model, context);
}
}
\ No newline at end of file
package com.mortals.xhx.module.record.web;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.PrintStatus;
import com.mortals.xhx.common.code.StatusEnum;
import com.mortals.xhx.module.record.model.ApplyLogEntity;
import com.mortals.xhx.module.record.model.PrintLogEntity;
import com.mortals.xhx.module.record.service.PrintLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.record.model.PrintLogEntity;
import com.mortals.xhx.module.record.service.PrintLogService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.mortals.framework.ap.SysConstains.*;
/**
*
* 证照打印记录
......
spring:
main:
allow-bean-definition-overriding: true
application:
log:
level: @profiles.log.level@
path: @profiles.log.path@
\ No newline at end of file
server:
port: @profiles.server.port@
servlet:
context-path: /cpm
tomcat:
uri-encoding: utf-8
spring:
application:
name: certificate-manager
profiles:
active: @profiles.active@
name: @project.artifactId@
profiles:
active: @profiles.active@
servlet:
multipart:
max-file-size: 100MB
......@@ -16,29 +13,19 @@ spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
security:
enable: true
user:
name: admin
password: 1
redis:
host: @profiles.redis.uri@
port: @profiles.redis.port@
username: @profiles.redis.username@
password: @profiles.redis.password@
database: @profiles.redis.database@
timeout: 30000
pool:
max-idle: 30
min-idle: 0
max-active: 100
max-wait: 1000
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: @profiles.datasource.uri@
username: @profiles.datasource.username@
password: @profiles.datasource.password@
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: @profiles.nacos.server-addr@ # Nacos 服务器地址
group: @profiles.nacos.group@
namespace: @profiles.nacos.namespace@
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr} # Nacos 服务器地址
group: ${spring.cloud.nacos.discovery.group}
namespace: ${spring.cloud.nacos.discovery.namespace} # Nacos 命名空间 dev 的编号
file-extension: yaml
mybatis:
root-path: com.mortals
type-aliases-package: com.mortals.framework.model,com.mortals.xhx.common.**.model,com.mortals.xhx.**.model
......@@ -58,8 +45,3 @@ cookie:
port: 111
token:
head: mortal
upload:
path: @profiles.filepath@
url: http://192.168.0.98:17216/cpm/file/commonupload?prePath=/file/uploadfile
qrcode:
url: http://rhpt.scjg.chengdu.gov.cn:8091/adap/spjy/process/generateQrCode.do?dto.applyId=
......@@ -9,12 +9,14 @@
<setting name="useGeneratedKeys" value="false" />
<setting name="defaultExecutorType" value="REUSE" />
<!-- 是否开始sql日志控制台打印 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- <setting name="logImpl" value="STDOUT_LOGGING" />-->
</settings>
<plugins>
<plugin interceptor="com.mortals.framework.thirty.mybatis.MortalsPagePlugin">
<property name="dialect" value="MySql" />
<property name="showSql" value="MySql" />
</plugin>
<plugin interceptor="com.mortals.framework.thirty.mybatis.LogInterceptor">
</plugin>
</plugins>
</configuration>
\ No newline at end of file
......@@ -53,7 +53,17 @@
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
......
package com.mortals.xhx.common.pdu;
import com.mortals.framework.model.PageInfo;
import lombok.Data;
/**
* @author: zxfei
* @date: 2022/7/13 14:17
* @description:
**/
@Data
public class RespData<T> {
private T data;
private T entity;
private PageInfo pageInfo;
private Object dict;
}
package com.mortals.xhx.common.pdu.device;
import com.mortals.framework.model.BaseEntityLong;
public class DeviceModuleUsePdu extends BaseEntityLong {
private static final long serialVersionUID = 1L;
/**
* 模块名称
*/
private String moduleName;
/**
* 模块消息编码
*/
private String moduleMsgCode;
/**
* 所属设备
*/
private Long deviceId;
/**
* 调用次数
*/
private Long useNum;
public DeviceModuleUsePdu(){}
/**
* 获取 模块名称
* @return String
*/
public String getModuleName(){
return moduleName;
}
/**
* 设置 模块名称
* @param moduleName
*/
public void setModuleName(String moduleName){
this.moduleName = moduleName;
}
/**
* 获取 模块消息编码
* @return String
*/
public String getModuleMsgCode(){
return moduleMsgCode;
}
/**
* 设置 模块消息编码
* @param moduleMsgCode
*/
public void setModuleMsgCode(String moduleMsgCode){
this.moduleMsgCode = moduleMsgCode;
}
/**
* 获取 所属设备
* @return Long
*/
public Long getDeviceId(){
return deviceId;
}
/**
* 设置 所属设备
* @param deviceId
*/
public void setDeviceId(Long deviceId){
this.deviceId = deviceId;
}
/**
* 获取 调用次数
* @return Long
*/
public Long getUseNum(){
return useNum;
}
/**
* 设置 调用次数
* @param useNum
*/
public void setUseNum(Long useNum){
this.useNum = useNum;
}
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof DeviceModuleUsePdu) {
DeviceModuleUsePdu tmp = (DeviceModuleUsePdu) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public String toString(){
StringBuilder sb = new StringBuilder("");
sb.append(",moduleName:").append(getModuleName());
sb.append(",moduleMsgCode:").append(getModuleMsgCode());
sb.append(",deviceId:").append(getDeviceId());
sb.append(",useNum:").append(getUseNum());
return sb.toString();
}
public void initAttrValue(){
this.moduleName = "";
this.moduleMsgCode = "";
this.deviceId = null;
this.useNum = null;
}
}
package com.mortals.xhx.common.pdu.flow;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 工作流定义前端实体类
*
* @author: finegirl
* @date: 2021/7/31 23:38
*/
@Getter
@Setter
@ApiModel("工作流定义前端实体类")
public class DefinitionVoPdu implements Serializable {
@ApiModelProperty("流程定义ID")
private String deployId;
@ApiModelProperty("状态")
private Integer state;
}
package com.mortals.xhx.common.pdu.flow;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
@Data
@Builder
public class FlowCommentPdu implements Serializable {
/**
* 意见类别 0 正常意见 1 退回意见 2 驳回意见
*/
private String type;
/**
* 意见内容
*/
private String comment;
}
package com.mortals.xhx.common.pdu.flow;
import com.mortals.xhx.common.model.SysRole;
import com.mortals.xhx.common.model.SysUser;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 动态人员、组
*
* @author: finegirl
* @date: 2021/8/1 22:49
*/
@Data
public class FlowNextPdu implements Serializable {
private String type;
/**
* 数据类型(fixed,dynamc两种)
*/
private String dateType;
private String vars;
private String name;
private String assignee;
private List<String> candidateUsers;
private List<String> candidateGroups;
}
package com.mortals.xhx.common.pdu.flow;
import lombok.Data;
import java.io.Serializable;
/**
* 流程类
*
* @author: finegirl
* @date: 2021/7/31 21:15
*/
@Data
public class FlowSaveXmlPdu implements Serializable {
/**
* 流程名称
*/
private String name;
/**
* 流程分类
*/
private String category;
/**
* xml 文件
*/
private String xml;
}
package com.mortals.xhx.common.pdu.flow;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class FlowTaskNotifyPdu implements Serializable {
/**
* 用户审核列表(一个或者多个)
*/
private List<String> userNameList;
/**
* taskId
*/
private String taskId;
/**
* taskName
*/
private String taskName;
/**
* 租户Id
*/
private String tenantId;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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