Commit c61401cd by 刘宇峰

迁移项目到git

0 parents
Showing 253 changed files with 15278 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-admin</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-alarmcenter</artifactId>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>glsx-ne-shield-api</artifactId>
<dependencies>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
package cn.com.glsx.admin.api;
import cn.com.glsx.admin.services.notifyservice.model.MailTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.SmsTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import com.glsx.plat.core.web.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(name = "glsx-ne-shield-notifycenter", contextId = "notifycenter", path = "/api/notify/", decode404 = true)
public interface NotifyCenterFeignClient {
@PostMapping(value = "/sendSms", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R sendSms(@RequestBody SmsTemplateMessageDTO messageDTO);
@PostMapping(value = "/sendMail", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R sendMail(@RequestBody MailTemplateMessageDTO messageDTO);
@PostMapping(value = "/sendPC", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R sendPC(@RequestBody PCTemplateMessageDTO messageDTO);
@PostMapping(value = "/sendWechat", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R sendWechat(@RequestBody WechatTemplateMessageDTO messageDTO);
}
package cn.com.glsx.admin.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author payu
*/
@FeignClient(name = "glsx-ne-shield-usercenter", contextId = "usercenter", path = "/api/user/", decode404 = true)
public interface UserCenterFeignClient {
/**
* 一、FeignClients使用注意事项:
* 1. @EnableFeignClients 默认扫描 xxxxApplication启动入口 所在包路径下的 @FeignClient bean,若无法扫描到, 可以在使用Feign调用外部模块的api时候,需要在引用服务中 xxxxApplication 中的 `@EnableFeignClients(basePackages = "cn.tendyron.customer")` 添加外部包需要扫描FeignClient的路径,否则无法注入bean
* 2. @FeignClient 声明的类,使用 spring.application.name 作为 name配置 @FeignClient(name="xxxx"),如果想保留 context-path , 则需要配置 path 属性 ,如:@FeignClient(name="xxxx" , path="xxxx(context-path)")
* 3. @FeignClient 接口对应的实现类,需要使用 @RestController注解 声明
* 4. mapper注解不支持 : @GetMapping,@PostMapping , 参数要加 @RequestParam(“xxx”)
* 5. FeignClient 调用,实质是httpClient调用 ,若我们暴露的接口api,声明了对应的 http mapper 信息,在调用方调用时候,通过代理 发起了 http请求,到服务提供方对应的http服务上去,所以在服务提供方的接口,可以使用 @RestController
* 来声明接口的 实现,否则调用方无法找到 http 对应的路径,会报404 ;
* 或者 根据 api 声明的http 信息,构建一个 Controller ,再来调用接口的实现类,但是这样不太方便;
* 6.FeignClient是一个“客户端”,它是用来发起请求的,不是提供服务的。
* <p>
* <p>
* 二、fallback 几种模式:
* 1.EchoCenterFeignServiceFallback.class 直接fallback,获取不到HTTP请求错误状态码和信息
* 2.EchoCenterFeignFactory.class 特定类型工厂模式
* 3.FunFallbackFactory 使用统一的工厂模式处理
* <p>
* <p>
* 三、性能问题
* 1.Feign是一个http请求调用的轻量级框架,基于http协议,性能不如rpc
* 2.可以为Feign配置连接池,配合使用okhttp等
*/
}
package cn.com.glsx.admin.services.notifyservice.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MailTemplateMessageDTO implements Serializable {
private String from;
private String to;
private String title;
private String content;
private List<Map<String, String>> attachments;
}
package cn.com.glsx.admin.services.notifyservice.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PCTemplateMessageDTO implements Serializable {
private String application;//应用服务,也是xxx_notify_topic
private String from;//消息来源
private String to;//对应应用用户标识
private String template;
private String content;
private Map<String, Object> args;
private Integer type;//推送方式:1私信,2广播
}
package cn.com.glsx.admin.services.notifyservice.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SmsTemplateMessageDTO implements Serializable {
private String phone;
private String template;
private String content;
private Map<String, Object> args;
}
package cn.com.glsx.admin.services.notifyservice.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WechatTemplateMessageDTO implements Serializable {
private String appid;
private String openid;
private String templateId;
private String url;
private Map<String, String> data;
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-assetscenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.assets", "cn.com.glsx.auth"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<dependencies>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.auth.api;
import com.glsx.plat.core.web.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author payu
*/
@FeignClient(name = "glsx-ne-shield-usercenter", contextId = "authcenter", path = "/usercenter/auth/")
public interface AuthFeignClient {
/**
* 判断用户是否登录
*
* @return
*/
@GetMapping(value = "/isLogin", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R isLogin();
/**
* 获取当前登录用户对应资源等权限
*
* @return
*/
@GetMapping(value = "/getAuthUser", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R getAuthUser();
/**
* 获取当前登录用户角色数据权限内的部门id
*
* @return
*/
@GetMapping(value = "/getAuthDeptIds", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R getAuthDeptIds();
/**
* 获取当前登录用户角色数据权限内的用户id
*
* @return
*/
@GetMapping(value = "/getAuthUserIds", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R getAuthUserIds();
/**
* 获取当前登录用户角色授权的功能菜单
*
* @return
*/
@GetMapping(value = "/getPermMenus", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R getPermMenus();
}
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.common.annotation.DataPerm;
import com.glsx.plat.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.springframework.stereotype.Component;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Set;
import static cn.com.glsx.admin.common.constant.UserConstants.RolePermitCastType.*;
/**
* 处理针对某一或某些特定数据操作(增、删、改、查)作数据权限校验
* 1、获取用户角色,得到数据权限范围类型
* 2、得到当前操作用户信息和部门信息
* 3、根据数据创建者id,得到对应用户或部门
* 4、比较2,3判断该数据是否有权被操作权限
*
* @author: taoyr
**/
@Slf4j
@Component
@Intercepts({
@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class}
)
})
public class DataPermissionInterceptor implements Interceptor {
private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
private static final ReflectorFactory REFLECTOR_FACTORY = new DefaultReflectorFactory();
private final static String MAPPEDSTATEMENT_NAME = "delegate.mappedStatement";
private final static String BOUNDSQL_NAME = "delegate.boundSql";
private final static String BOUNDSQL_SQL_NAME = "delegate.boundSql.sql";
private final static String SQL_PARAM_NAME = "delegate.parameterHandler.parameterObject";
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
if (target instanceof RoutingStatementHandler) {
try {
RoutingStatementHandler statementHandler = (RoutingStatementHandler) target;
// MetaObject是mybatis里面提供的一个工具类,类似反射的效果
MetaObject metaStatementHandler = MetaObject.forObject(statementHandler,
DEFAULT_OBJECT_FACTORY,
DEFAULT_OBJECT_WRAPPER_FACTORY,
REFLECTOR_FACTORY);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue(MAPPEDSTATEMENT_NAME);
//当前拦截器只处理查询数据权限
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
if (sqlCommandType != SqlCommandType.SELECT) {
return invocation.proceed();
}
//没自定义注解直接按通过
DataPerm dataAuth = getDataPerm(mappedStatement);
if (dataAuth == null) {
return invocation.proceed();
}
//超级管理员不过滤
if (ShieldContextHolder.isSuperAdmin()) {
return invocation.proceed();
}
//拼装sql
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue(BOUNDSQL_NAME);
String originSql = boundSql.getSql(); //获取到当前需要被执行的SQL
String authSql = assemblePermitSql(originSql, dataAuth); //进行数据权限过滤组装
log.info("\nbaseSql:{}\nauthSql:{}", originSql, authSql);
//替换
// MappedStatement newStatement = newMappedStatement(mappedStatement, new BoundSqlSqlSource(boundSql));
// MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
metaStatementHandler.setValue(BOUNDSQL_SQL_NAME, authSql);
} catch (Exception e) {
log.error("数据权限拦截器异常", e);
throw e;
}
}
return invocation.proceed();
}
/**
* 获取方法上的数据权限注解
*
* @param mappedStatement
* @return
* @throws ClassNotFoundException
*/
private DataPerm getDataPerm(MappedStatement mappedStatement) throws ClassNotFoundException {
DataPerm dataPerm = null;
String id = mappedStatement.getId();
String className = id.substring(0, id.lastIndexOf("."));
String methodName = id.substring(id.lastIndexOf(".") + 1);
final Method[] method = Class.forName(className).getDeclaredMethods();
for (Method me : method) {
if (me.getName().equals(methodName) && me.isAnnotationPresent(DataPerm.class)) {
dataPerm = me.getAnnotation(DataPerm.class);
break;
}
}
return dataPerm;
}
/**
* 核心代码: 将原SQL 进行解析并拼装 一个子查询 id in ( 数据权限过滤SQL )
*
* @param sql
* @param dataAuth
* @return
* @throws JSQLParserException
*/
private String assemblePermitSql(String sql, DataPerm dataAuth) throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
Table fromItem = (Table) plain.getFromItem();
//有别名用别名,无别名用表名,防止字段冲突报错
String mainTableName = fromItem.getAlias() == null ? fromItem.getName() : fromItem.getAlias().getName();
Set<Long> deptIds = ShieldContextHolder.getVisibleDeptIds();
Set<Long> creatorIds = ShieldContextHolder.getVisibleCreatorIds();
String linkTable = dataAuth.linkTable();
String linkField = dataAuth.linkField();
String deptIdsStr = StringUtils.join(deptIds, ',');
String creatorIdsStr = StringUtils.join(creatorIds, ',');
log.info("deptIds:{}", deptIdsStr);
log.info("creatorIds:{}", creatorIdsStr);
String dataAuthSql = "";
//构建子查询
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
if (oneself.getCode().equals(rolePermissionType)) {
dataAuthSql = mainTableName + ".created_by in (" + creatorIdsStr + ") ";
} else if (subordinate.getCode().equals(rolePermissionType)) {
dataAuthSql = mainTableName + ".created_by in (" + creatorIdsStr + ") ";
} else if (selfDepartment.getCode().equals(rolePermissionType)) {
//dataAuthSql = mainTableName + ".created_by in (select " + linkTable + "." + linkField + " from " + linkTable + " where " + linkTable + ".department_id = " + ShieldContextHolder.getDepartmentId() + ") ";
dataAuthSql = mainTableName + ".created_by in (" + creatorIdsStr + ") ";
} else if (subDepartment.getCode().equals(rolePermissionType)) {
//dataAuthSql = mainTableName + ".created_by in (select " + linkTable + "." + linkField + " from " + linkTable + " where " + linkTable + ".department_id in (" + ShieldContextHolder.getVisibleCreatorDeptIds() + ")) ";
dataAuthSql = mainTableName + ".created_by in (" + creatorIdsStr + ") ";
} else if (all.getCode().equals(rolePermissionType)) {
//do nothing
}
//构建子查询
if (plain.getWhere() == null) {
plain.setWhere(CCJSqlParserUtil.parseCondExpression(dataAuthSql));
} else {
plain.setWhere(new AndExpression(plain.getWhere(), CCJSqlParserUtil.parseCondExpression(dataAuthSql)));
}
return select.toString();
}
private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
StringBuilder keyProperties = new StringBuilder();
for (String keyProperty : ms.getKeyProperties()) {
keyProperties.append(keyProperty).append(",");
}
keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
builder.keyProperty(keyProperties.toString());
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
private class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.common.annotation.DataPermShare;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.List;
/**
* 二期后面绝对权限,分享的业务数据权限控制(读、写)
*
* @author payu
*/
@Slf4j
//@Component
//@Intercepts({
// @Signature(
// type = StatementHandler.class,
// method = "prepare",
// args = {Connection.class, Integer.class}
// )
//})
public class DataPermitLinkInterceptor implements Interceptor {
private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
private static final ReflectorFactory REFLECTOR_FACTORY = new DefaultReflectorFactory();
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
if (target instanceof RoutingStatementHandler) {
try {
RoutingStatementHandler statementHandler = (RoutingStatementHandler) target;
// MetaObject是mybatis里面提供的一个工具类,类似反射的效果
MetaObject metaStatementHandler = MetaObject.forObject(statementHandler,
DEFAULT_OBJECT_FACTORY,
DEFAULT_OBJECT_WRAPPER_FACTORY,
REFLECTOR_FACTORY);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
//当前拦截器只处理查询数据权限
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
if (sqlCommandType != SqlCommandType.SELECT) {
return invocation.proceed();
}
//没自定义注解直接按通过
DataPermShare dataAuth = getAnnotation(mappedStatement);
if (dataAuth == null) {
return invocation.proceed();
}
//超级管理员不过滤
if (ShieldContextHolder.isSuperAdmin()) {
return invocation.proceed();
}
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
String originSql = boundSql.getSql();
String linkPermitSql = assembleLinkPermitSql(originSql, dataAuth, ShieldContextHolder.getUserId()); //进行数据权限过滤组装
//放回sql
metaStatementHandler.setValue("delegate.boundSql.sql", linkPermitSql);
} catch (Exception e) {
log.error("数据权限拦截器异常", e);
throw e;
}
}
return invocation.proceed();
}
private String assembleLinkPermitSql(String sql, DataPermShare dataAuth, Long userId) throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
SelectBody selectBody = select.getSelectBody();
PlainSelect plain = (PlainSelect) selectBody;
FromItem fromItem = plain.getFromItem();
//有别名用别名,无别名用表名,防止字段冲突报错
Table table = (Table) fromItem;
String mainTableName = table.getAlias() == null ? table.getName() : table.getAlias().getName();
String permitTable = mainTableName + dataAuth.permSuffix();
//处理where条件
handleWhereCriterial(userId, plain, mainTableName, permitTable);
//处理排序条件
handleOrderCriterial(plain, mainTableName);
//增加join语句
addJoinMethod(dataAuth.linkField(), plain, mainTableName, permitTable);
String plainStr = plain.toString();
return plainStr;
}
/**
* 处理where条件
*
* @param userId
* @param plain
* @param mainTableName
* @param permitTable
* @throws JSQLParserException
*/
private void handleWhereCriterial(Long userId, PlainSelect plain, String mainTableName, String permitTable) throws JSQLParserException {
Expression where = plain.getWhere();
String dataAuthSql = permitTable + ".receiver_id = " + userId;
if (where == null) {
plain.setWhere(CCJSqlParserUtil.parseCondExpression(dataAuthSql));
} else {
addTableAliasToColumns(mainTableName, plain);
plain.setWhere(new AndExpression(where, CCJSqlParserUtil.parseCondExpression(dataAuthSql)));
}
}
/**
* 处理排序条件
*
* @param plain
* @param mainTableName
* @throws JSQLParserException
*/
private void handleOrderCriterial(PlainSelect plain, String mainTableName) throws JSQLParserException {
List<OrderByElement> orderByElements = plain.getOrderByElements();
if (CollectionUtils.isNotEmpty(orderByElements)) {
for (OrderByElement orderByElement : orderByElements) {
Expression expression = orderByElement.getExpression();
String orderCol = expression.toString();
orderCol = mainTableName + "." + orderCol;
orderByElement.setExpression(CCJSqlParserUtil.parseCondExpression(orderCol));
}
}
}
/**
* 增加join语句
*
* @param accessField
* @param plain
* @param mainTableName
* @param permitTable
*/
private void addJoinMethod(String accessField, PlainSelect plain, String mainTableName, String permitTable) {
Join join = new Join();
join.setRight(true);
join.setRightItem(new Table(permitTable));
EqualsTo appendExpression = new EqualsTo();
appendExpression.setLeftExpression(new StringValue(mainTableName + "." + accessField));
appendExpression.setRightExpression(new StringValue(permitTable + ".content_id"));
join.setOnExpression(appendExpression);
plain.setJoins(Lists.newArrayList(join));
}
/**
* 修改字段名称
*
* @param tableName
* @param plainSelect
*/
private void addTableAliasToColumns(String tableName, PlainSelect plainSelect) {
plainSelect.getWhere().accept(new ExpressionVisitorAdapter() {
@Override
public void visit(Column column) {
column.setColumnName(tableName + "." + column.getColumnName());
}
});
}
/**
* 获取方法上的数据权限注解
*
* @param mappedStatement
* @return
* @throws ClassNotFoundException
*/
private DataPermShare getAnnotation(MappedStatement mappedStatement) throws ClassNotFoundException {
DataPermShare dataAuth = null;
String id = mappedStatement.getId();
String className = id.substring(0, id.lastIndexOf("."));
String methodName = id.substring(id.lastIndexOf(".") + 1);
final Method[] method = Class.forName(className).getDeclaredMethods();
for (Method me : method) {
if (me.getName().equals(methodName) && me.isAnnotationPresent(DataPermShare.class)) {
dataAuth = me.getAnnotation(DataPermShare.class);
break;
}
}
return dataAuth;
}
}
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.FunctionPermissions;
import cn.com.glsx.auth.model.MenuPermission;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 功能菜单权限
*
* @author: taoyr
**/
@Slf4j
@Component
public class WebFunctionPermissionInterceptor implements HandlerInterceptor {
@Autowired
private AuthFeignClient authFeignClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
FunctionPermissions permissionRequired = ((HandlerMethod) handler).getMethodAnnotation(FunctionPermissions.class);
if (permissionRequired == null) {
return true;
}
SyntheticUser currentUser = ShieldContextHolder.getUser();
if (currentUser == null) {
return true;
}
String uri = request.getRequestURI();
log.info("RequestURI:" + uri);
List<MenuPermission> menuPermissionList = Lists.newArrayList();
R r = authFeignClient.getPermMenus();
if (r.isSuccess()) {
Object obj = r.getData();
if (obj instanceof JSONArray) {
menuPermissionList = JSON.parseArray(((JSONArray) obj).toJSONString(), MenuPermission.class);
} else if (obj instanceof ArrayList) {
menuPermissionList = (List<MenuPermission>) obj;
}
}
boolean isPermit = menuPermissionList.stream().map(MenuPermission::getInterfaceUrl).collect(Collectors.toList()).contains(uri);
if (!isPermit) {
needPermission(response);
return false;
}
}
return true;
}
private void needPermission(HttpServletResponse response) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.write(JSON.toJSONString(R.error(
SystemMessage.OPERATE_PERMISSION_DENIED.getCode(),
SystemMessage.OPERATE_PERMISSION_DENIED.getMsg())
));
writer.flush();
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* 授权验证拦截器
*
* @author payu
*/
@Slf4j
@Component
public class WebRequestAuthorizeInterceptor implements HandlerInterceptor {
@Autowired
private AuthFeignClient authFeignClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ShieldContextHolder.setUser(null);
ShieldContextHolder.removeUser();
SyntheticUser user = null;
R r = authFeignClient.getAuthUser();
if (r.isSuccess()) {
Object obj = r.getData();
if (obj instanceof JSONObject) {
JSONObject userJO = (JSONObject) obj;
user = JSON.toJavaObject(userJO, SyntheticUser.class);
} else if (obj instanceof SyntheticUser) {
user = (SyntheticUser) obj;
}
}
if (user != null) {
ShieldContextHolder.setUser(user);
return true;
}
//需要登录
needLogin(response);
return false;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
ShieldContextHolder.setUser(null);
ShieldContextHolder.removeUser();
}
private void needLogin(HttpServletResponse response) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.write(JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg())));
writer.flush();
}
}
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class Department {
private Long deptId;
private String departmentName;
private Long tenantId;
}
package cn.com.glsx.auth.model;
import lombok.Getter;
/**
* @author: taoyr
**/
@Getter
public enum FunctionPermissionType {
USER_QUERY(1, "usercenter:user:query", "查询用户"),
USER_ADD(2, "usercenter:user:add", "新增用户"),
USER_EDIT(3, "usercenter:user:edit", "编辑用户"),
USER_DELETE(4, "usercenter:user:delete", "删除用户"),
ROLE_QUERY(1, "usercenter:role:query", "查询角色"),
ROLE_ADD(2, "usercenter:role:add", "新增角色"),
ROLE_EDIT(3, "usercenter:role:edit", "编辑角色"),
ROLE_DELETE(4, "usercenter:role:delete", "删除角色"),
MENU_QUERY(1, "usercenter:menu:query", "查询菜单"),
MENU_ADD(2, "usercenter:menu:add", "新增菜单"),
MENU_EDIT(3, "usercenter:menu:edit", "编辑菜单"),
MENU_DELETE(4, "usercenter:menu:delete", "删除菜单"),
ORG_QUERY(1, "usercenter:org:query", "查询组织"),
ORG_ADD(2, "usercenter:org:add", "新增组织"),
ORG_EDIT(3, "usercenter:org:edit", "编辑组织"),
ORG_DELETE(4, "usercenter:org:delete", "删除组织"),
DEVICE_QUERY(1, "ordercenter:device:query", "查询设备"),
DEVICE_ADD(2, "ordercenter:device:add", "新增设备"),
DEVICE_EDIT(3, "ordercenter:device:edit", "编辑设备"),
DEVICE_DELETE(4, "ordercenter:device:delete", "删除设备"),
;
FunctionPermissionType(int code, String name, String desc) {
this.code = code;
this.name = name;
this.desc = desc;
}
/**
* 权限编号
*/
private int code;
/**
* 权限名
*/
private String name;
/**
* 权限描述
*/
private String desc;
public FunctionPermissionType getByCode(int code) {
FunctionPermissionType[] values = FunctionPermissionType.values();
for (FunctionPermissionType value : values) {
if (code == value.code) {
return value;
}
}
return null;
}
}
package cn.com.glsx.auth.model;
import java.lang.annotation.*;
/**
* 需要功能权限
*
* @author: taoyr
**/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FunctionPermissions {
FunctionPermissionType permissionType();
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
public class Menu implements Serializable {
private Long menuId;
/**
* 菜单名
*/
private String menuName;
/**
* 前端路由
*/
private String frontRoute;
/**
* 后端路由
*/
private String afterRoute;
private String permissionTag;
/**
* 类型 1目录,2菜单,3按钮
*/
private Integer type;
/**
* 父菜单id
*/
private Long parentId;
/**
* 排序
*/
private Integer orderNum;
/**
* 状态 0=不显示 1=显示
*/
private Integer enableStatus;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class MenuPermission {
private String permissionTag;
private String interfaceUrl;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.util.List;
@Data
public class Role {
private Long tenantId;
private Long roleId;
private String roleName;
/**
* 角色权限类型 0=本人 1=本人及下属 2=本部门 3=本部门及下级部门 4=全部
*/
private Integer rolePermissionType;
private Integer roleVisibility;
private List<MenuPermission> menuPermissionList;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
public class SyntheticUser {
private Long userId;
/**
* 用户账号
*/
private String account;
private boolean isAdmin;
/**
* 用户组
*/
// private UserGroup userGroup;
/**
* 用户所属租户
*/
private Tenant tenant;
/**
* 用户所属部门
*/
private Department department;
/**
* 用户角色
*/
private List<Role> roles;
/**
* 数据创建人部门id
*/
private Set<Long> visibleDeptIds;
/**
* 数据创建人id
*/
private Set<Long> visibleCreatorIds;
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class Tenant {
private Long tenantId;
private String tenantName;
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class UserGroup {
private Long tenantId;
private Long groupId;
private String userGroupName;
}
package cn.com.glsx.auth.utils;
import cn.com.glsx.auth.model.Department;
import cn.com.glsx.auth.model.Role;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.model.Tenant;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author payu
*/
@NoArgsConstructor
public class ShieldContextHolder {
private static final Long ADMIN_ROLE_ID = 1L;
private static final ThreadLocal<SyntheticUser> USER_THREAD_LOCAL = new ThreadLocal<>();
// 设置当前用户
public static void setUser(SyntheticUser user) {
USER_THREAD_LOCAL.set(user);
}
// 获取当前用户
public static SyntheticUser getUser() {
SyntheticUser user = USER_THREAD_LOCAL.get();
Assert.notNull(user, "获取当前用户信息失败");
return user;
}
// 移除当前用户
public static void removeUser() {
USER_THREAD_LOCAL.remove();
}
public static boolean isSuperAdmin() {
return getUser().isAdmin();
}
public static boolean isRoleAdmin() {
Long roleId = getRoleId();
return ADMIN_ROLE_ID.equals(roleId);
}
public static Long getUserId() {
SyntheticUser user = getUser();
return user.getUserId();
}
public static String getAccount() {
SyntheticUser user = getUser();
return user.getAccount();
}
// public static UserGroup getUserGroup() {
// SyntheticUser user = getUser();
// return user.getUserGroup();
// }
public static Tenant getTenant() {
SyntheticUser user = getUser();
Tenant tenant = user.getTenant();
Assert.notNull(tenant, "获取当前用户租户信息失败");
return tenant;
}
public static Department getDepartment() {
SyntheticUser user = getUser();
Department dept = user.getDepartment();
Assert.notNull(dept, "获取当前用户部门信息失败");
return dept;
}
public static Long getTenantId() {
return getTenant().getTenantId();
}
public static Long getDepartmentId() {
return getDepartment().getDeptId();
}
public static List<Long> getRoleIds() {
SyntheticUser user = getUser();
if (user != null) {
if (CollectionUtils.isNotEmpty(user.getRoles())) {
return user.getRoles().stream().map(Role::getRoleId).collect(Collectors.toList());
}
}
return new ArrayList<>();
}
/**
* 获取当前用户角色数据权限可见的部门id
*
* @return
*/
public static Set<Long> getVisibleDeptIds() {
SyntheticUser user = getUser();
return user.getVisibleDeptIds();
}
/**
* 获取当前用户角色数据权限可见的创建人id
*
* @return
*/
public static Set<Long> getVisibleCreatorIds() {
SyntheticUser user = getUser();
return user.getVisibleCreatorIds();
}
public static Role getRole() {
Role role = getUser().getRoles().get(0);
Assert.notNull(role, "获取当前用户角色信息失败");
return role;
}
public static Long getRoleId() {
return getRole().getRoleId();
}
public static Integer getRoleVisibility() {
return getRole().getRoleVisibility();
}
public static Integer getRolePermissionType() {
return getRole().getRolePermissionType();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>glsx-ne-shield-common</artifactId>
<dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
package cn.com.glsx.admin.common.constant;
import com.glsx.plat.core.constant.BasicConstants;
/**
* 〈一句话功能简述〉<br>
* 公共常量类
*
* @author liuyf
* @since 1.0.0
*/
public final class Constants extends BasicConstants {
public final static String SERVER_NAME = "glsx_ne_shield";
public final static int IS_ROOT_DEPARTMENT = 1;
public final static int IS_NOT_ROOT_DEPARTMENT = 0;
}
package cn.com.glsx.admin.common.constant;
/**
* @author: taoyr
**/
public interface RedisConstants {
String MENU_NO_LOCK = "menu_no_lock";
Integer FIVE_SECONDS = 5;
}
package cn.com.glsx.admin.common.constant;
import com.glsx.plat.core.enums.SysConstants;
/**
* @author: taoyr
**/
public interface UserConstants extends SysConstants {
Long adminRoleId = 1L;
/**
* 角色权限传播类型
*/
enum RolePermitCastType implements SysConstants {
oneself {
@Override
public Integer getCode() {
return 0;
}
@Override
public String getValue() {
return "本人";
}
@Override
public String getBeanName(){
return "oneselfStrategy";
}
},
subordinate {
@Override
public Integer getCode() {
return 1;
}
@Override
public String getValue() {
return "本人及下属";
}
@Override
public String getBeanName(){
return "subOrdinateStrategy";
}
},
selfDepartment {
@Override
public Integer getCode() {
return 2;
}
@Override
public String getValue() {
return "本部门";
}
@Override
public String getBeanName(){
return "selfDepartmentStrategy";
}
},
subDepartment {
@Override
public Integer getCode() {
return 3;
}
@Override
public String getValue() {
return "本部门及下属部门";
}
@Override
public String getBeanName(){
return "subDepartmentStrategy";
}
},
all {
@Override
public Integer getCode() {
return 4;
}
@Override
public String getValue() {
return "全部";
}
@Override
public String getBeanName(){
return "allStrategy";
}
},
;
public abstract String getBeanName();
public static String getValueByCode(Integer code) {
for (RolePermitCastType status : RolePermitCastType.values()) {
if (status.getCode().equals(code)) {
return status.getValue();
}
}
return null;
}
public static String getBeanNameByCode(Integer code) {
for (RolePermitCastType status : RolePermitCastType.values()) {
if (status.getCode().equals(code)) {
return status.getBeanName();
}
}
return null;
}
}
/**
* 角色可见度(0=共享,1=系统管理员,2=指定租户)
*/
enum RoleVisibility implements SysConstants {
share {
@Override
public Integer getCode() {
return 0;
}
@Override
public String getValue() {
return "共享";
}
},
onlyAdmin {
@Override
public Integer getCode() {
return 1;
}
@Override
public String getValue() {
return "超级管理员";
}
},
specifyTenants {
@Override
public Integer getCode() {
return 2;
}
@Override
public String getValue() {
return "指定租户";
}
},
;
public static String getValueByCode(Integer code) {
for (EnableStatus status : EnableStatus.values()) {
if (status.getCode().equals(code)) {
return status.getValue();
}
}
return null;
}
}
}
package cn.com.glsx.admin.common.enums;
import com.google.common.collect.Lists;
import lombok.Getter;
import java.util.List;
/**
* @author payu
*/
@Getter
public enum MenuType {
DIRECTORY(1, "目录"), MENU(2, "菜单"), BUTTON(3, "按钮");
private Integer code;
private String type;
MenuType(Integer code, String type) {
this.code = code;
this.type = type;
}
public static List<Integer> getAllTypes() {
List<Integer> list = Lists.newArrayList();
MenuType[] types = MenuType.values();
for (MenuType type : types) {
list.add(type.getCode());
}
return list;
}
}
package cn.com.glsx.admin.common.util;
/**
* @author taoyr
*/
public class RegexUtil {
//public static final String pwdRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
public static final String pwdRegex = "^[0-9A-Za-z]{6,18}$";
public static final String mobileRegex = "^1(3|4|5|7|8|9)\\d{9}$";
public static boolean regexPwd(String pwd) {
return pwd.matches(pwdRegex);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-loggincenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-loggin</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@EnableDiscoveryClient
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.loggin", "cn.com.glsx.auth"}, exclude = {DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.loggin.config;
import cn.com.glsx.auth.interceptor.WebRequestAuthorizeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* @author payu
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private WebRequestAuthorizeInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
registry.addInterceptor(authInterceptor).addPathPatterns("/**")
.excludePathPatterns("/")
.excludePathPatterns("/actuator/**")
.excludePathPatterns("/api/**");
}
}
package cn.com.glsx.loggin.modules;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.core.web.R;
import com.glsx.plat.web.controller.AbstractController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liuyf
* @Title BaseController.java
* @Package com.glsx.vasp.controller
* @Description
* @date 2019年10月24日 下午2:24:00
*/
@RestController
public class BaseController extends AbstractController {
/**
* 这个给Spring Boot Admin探测用
*
* @return
*/
@GetMapping(value = "/")
public R index() {
return R.ok("You get it!");
}
/**
* 从session中获取当前用户
*
* @return
*/
@Override
public SyntheticUser getSessionUser() {
return ShieldContextHolder.getUser();
}
@Override
public Long getUserId() {
return ShieldContextHolder.getUserId();
}
@Override
public String getAccount() {
return ShieldContextHolder.getAccount();
}
}
package cn.com.glsx.loggin.modules.controller;
import cn.com.glsx.loggin.modules.model.SysLogSearch;
import cn.com.glsx.loggin.modules.service.LogginService;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.loggin.entity.SysLogEntity;
import com.glsx.plat.office.excel.EasyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("loggin")
public class LogginController {
@Autowired
private LogginService logginService;
//只需要加上下面这段即可,注意不能忘记注解
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//转换日期
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
}
@GetMapping("/search")
public R search(SysLogSearch search) {
Page<SysLogEntity> pageInfo = logginService.search(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping(value = "/export")
public void export(HttpServletResponse response, SysLogSearch search) throws Exception {
List<SysLogEntity> list = logginService.export(search);
EasyExcelUtils.writeExcel(response, list, "操作日志_" + DateUtils.formatSerial(new Date()), "Sheet1", SysLogEntity.class);
}
}
package cn.com.glsx.loggin.modules.model;
import cn.hutool.db.Page;
import com.glsx.plat.common.utils.DateUtils;
import lombok.Data;
import java.util.Date;
@Data
public class SysLogSearch extends Page {
private String sDate;
private String eDate;
public Date getStartDate() {
if (sDate == null) {
return null;
}
return DateUtils.parse(sDate);
}
public Date getEndDate(boolean withTime) {
if (eDate == null) {
return null;
}
if (withTime) {
Date date = DateUtils.parse(eDate);
//如果不带时间,日期加一天,相当于取当天最大时分秒 59:59:59
if (date.getHours() == 0 && date.getMinutes() == 0 && date.getSeconds() == 0) {
date = DateUtils.addDateDays(date, 1);
}
return date;
}
return DateUtils.parse(eDate);
}
}
package cn.com.glsx.loggin.modules.service;
import cn.com.glsx.admin.common.constant.UserConstants;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.loggin.modules.model.SysLogSearch;
import com.glsx.plat.loggin.entity.SysLogEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class LogginService {
@Autowired
private AuthFeignClient authFeignClient;
@Autowired
private MongoTemplate mongoTemplate;
public Page<SysLogEntity> search(SysLogSearch search) {
Query query = new Query();
Criteria criteria = buildCriteria(search);
query.addCriteria(criteria);
Sort sort = Sort.by(Sort.Direction.DESC, "createdDate");
long total = mongoTemplate.count(query, SysLogEntity.class);
//注意:分页索引从0开始
Pageable pageable = PageRequest.of(search.getPageNumber() - 1, search.getPageSize(), sort);
List<SysLogEntity> list = mongoTemplate.find(query.with(pageable), SysLogEntity.class);
return new PageImpl(list, pageable, total);
}
public List<SysLogEntity> export(SysLogSearch search) {
Query query = new Query();
Criteria criteria = buildCriteria(search);
query.addCriteria(criteria);
Sort sort = Sort.by(Sort.Direction.DESC, "createdDate");
List<SysLogEntity> list = mongoTemplate.find(query.with(sort), SysLogEntity.class);
return list;
}
/**
* 构建查询条件
*
* @param search
* @return
*/
private Criteria buildCriteria(SysLogSearch search) {
Criteria criteria = new Criteria();
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
//非管理员 并且 数据权限不是全部 的需要加上用户权限涉及的全部用户id
if (!ShieldContextHolder.isSuperAdmin() && !UserConstants.RolePermitCastType.all.getCode().equals(rolePermissionType)) {
Set<Long> userIdList = ShieldContextHolder.getVisibleCreatorIds();
if (CollectionUtils.isNotEmpty(userIdList)) {
criteria = Criteria.where("operator").in(ShieldContextHolder.getVisibleCreatorIds());
} else {
// 2020/10/13 直接无法查看日志数据
criteria = Criteria.where("operator").is(0L);
}
}
Date sDate = search.getStartDate();
Date eDate = search.getEndDate(true);
if (sDate != null && eDate != null) {
criteria.andOperator(
Criteria.where("createdDate").gte(Objects.requireNonNull(dateToISODate(sDate))),
Criteria.where("createdDate").lt(Objects.requireNonNull(dateToISODate(eDate)))
);
}
return criteria;
}
/**
* mongo 日期查询isodate
*
* @param originDate
* @return
*/
public static Date dateToISODate(Date originDate) {
//T代表后面跟着时间,Z代表UTC统一时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
try {
String isoDate = format.format(originDate);
return format.parse(isoDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
#项目名称
spring.application.name=glsx-ne-shield-loggincenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=${profile.active}
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8884"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-ne-shield-loggincenter"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-ne-shield-loggincenter"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-notifycenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-sms</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mail</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-wechat</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-kafka</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-im</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.notify.netty.NettyServer;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
//启动NettyServer服务端
NettyServer nettyServer = new NettyServer();
nettyServer.run();
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.notify.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.api;
import cn.com.glsx.admin.api.NotifyCenterFeignClient;
import cn.com.glsx.admin.services.notifyservice.model.MailTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.SmsTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import cn.com.glsx.notify.modules.service.MailService;
import cn.com.glsx.notify.modules.service.PCService;
import cn.com.glsx.notify.modules.service.SmsService;
import cn.com.glsx.notify.modules.service.WeixinService;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
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 java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping(value = "/api/notify")
class NotifyApiController implements NotifyCenterFeignClient {
@Autowired
private SmsService smsService;
@Autowired
private MailService mailService;
@Autowired
private PCService pcService;
@Autowired
private WeixinService weixinService;
@Override
@PostMapping(value = "/sendSms")
public R sendSms(@RequestBody SmsTemplateMessageDTO messageDTO) {
smsService.sendSms(messageDTO.getPhone(), messageDTO.getTemplate(), messageDTO.getArgs().values());
return R.ok();
}
@Override
@PostMapping(value = "/sendMail")
public R sendMail(@RequestBody MailTemplateMessageDTO messageDTO) {
Map<String, Object> args = new HashMap<>();
args.put("arg1", "刘宇峰");
args.put("arg2", "B73493098765");
args.put("arg3", 1234);
mailService.sendEmail("liuyf@didihu.com.cn", "notifycenter test", "MAIL_TEMPLATE_ORDER_PAID_NOTIFY_OPERATOR", args.values());
return R.ok();
}
@Override
@PostMapping(value = "/sendPC")
public R sendPC(@RequestBody PCTemplateMessageDTO messageDTO) {
// TODO: 2020/9/21 名称约束
// 2020/9/21 kafka消息队列
pcService.sendMessage(messageDTO);
return R.ok();
}
@Override
@PostMapping(value = "/sendWechat")
public R sendWechat(@RequestBody WechatTemplateMessageDTO messageDTO) {
weixinService.push(messageDTO.getAppid(), messageDTO);
return R.ok();
}
}
package cn.com.glsx.notify.modules.controller;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Component
@EqualsAndHashCode
@ServerEndpoint(value = "/ws/asset")
public class WebSocketServer {
@PostConstruct
public void init() {
log.info("websocket 加载");
}
private Session session;
public static CopyOnWriteArraySet<WebSocketServer> SocketSet = new CopyOnWriteArraySet<>();
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
SocketSet.add(this);
this.session = session;
// 在线数加1
int cnt = OnlineCount.incrementAndGet();
log.info(String.valueOf(session.getRequestURI()));
log.info("有连接加入,当前连接数为:{},sessionId={}", cnt, session.getId());
SendMessage(session, "连接成功");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
SocketSet.remove(this);
int cnt = OnlineCount.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:{}", message);
SendMessage(session, "收到消息,消息内容:" + message);
}
/**
* 出现错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
}
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
}
/**
* 群发消息
*
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if (session.isOpen()) {
SendMessage(session, message);
}
}
}
/**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String message, String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
SendMessage(session, message);
} else {
log.warn("没有找到你指定ID的会话:{}", sessionId);
}
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
}
package cn.com.glsx.notify.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_message_log")
public class MessageLog extends BaseEntity {
@Column(name = "from_user")
private String fromUser;
@Column(name = "to_user")
private String toUser;
private String template;
private String subject;
private String content;
private String attachment;
private String type;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Table;
@Data
@Table(name = "t_message_template")
public class MessageTemplate extends BaseEntity {
private String template;
private String subject;
private String content;
private String type;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.kafka;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
import static cn.com.glsx.notify.modules.controller.WebSocketServer.SocketSet;
/**
* @author payu
*/
@Slf4j
@Component
public class MessageConsumer {
@KafkaListener(id = "messageConsumer",
topics = "#{'${topic.message.application}'.split(',')}",
errorHandler = "consumerAwareErrorHandler")
public void listener(ConsumerRecord<?, ?> record) {
//errorHandler异常处理器注解里面使用的也是bean的名称
//判断是否为null
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
//得到Optional实例中的值
Object message = kafkaMessage.get();
log.info("消费消息:" + message);
try {
for (WebSocketServer socketServer : SocketSet) {
socketServer.sendMessage(message.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package cn.com.glsx.notify.modules.mapper;
import cn.com.glsx.notify.modules.entity.MessageLog;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MessageLogMapper extends CommonBaseMapper<MessageLog> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.mapper;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface MessageTemplateMapper extends CommonBaseMapper<MessageTemplate> {
MessageTemplate findByTemplate(@Param("template") String template);
MessageTemplate findByTemplateAndType(@Param("template") String template, @Param("type") String type);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import com.glsx.plat.mail.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
/**
* @author payu
*/
@Service
public class MailService {
@Autowired
private MailUtils mailUtils;
@Autowired
private MessageLogMapper messageLogMapper;
@Autowired
private MessageTemplateMapper messageTemplateMapper;
public void sendEmail(String to, String title, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) return;
String content = MessageFormat.format(mt.getContent(), arg);
mailUtils.sendTextMail(to, title, content);
MessageLog log = new MessageLog();
log.setSubject(title);
log.setToUser(to);
log.setContent(content);
log.setTemplate(template);
log.setType(mt.getType());
messageLogMapper.insert(log);
}
}
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import javax.annotation.Resource;
/**
* @author payu
*/
@Slf4j
@Service
public class PCService {
@Resource
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(PCTemplateMessageDTO messageDTO) {
// 发送消息,json 作为消息体
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(messageDTO.getApplication() + "_topic", JSONObject.toJSONString(messageDTO));
// 监听回调
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
log.info("## Send message success ...");
}
@Override
public void onFailure(Throwable throwable) {
log.error("## Send message fail ...{}", throwable.getMessage());
}
});
}
}
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import cn.com.glsx.notify.modules.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
/**
* @author payu
*/
@Service
public class SmsService {
@Autowired
private SmsUtils smsUtils;
@Autowired
private MessageLogMapper messageLogMapper;
@Autowired
private MessageTemplateMapper messageTemplateMapper;
public void sendSms(String phone, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) return;
String content = MessageFormat.format(mt.getContent(), arg);
smsUtils.send(phone, content);
MessageLog log = new MessageLog();
log.setToUser(phone);
log.setContent(content);
log.setTemplate(template);
log.setType(mt.getType());
messageLogMapper.insert(log);
}
}
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import com.glsx.plat.wechat.modules.service.WxPushService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author payu
*/
@Service
public class WeixinService {
@Autowired
private WxPushService wxPushService;
public void push(String appid, WechatTemplateMessageDTO wtmm) {
WxMpTemplateMessage wechatTemplate = new WxMpTemplateMessage();
wechatTemplate.setTemplateId(wtmm.getTemplateId());
wechatTemplate.setToUser(wtmm.getOpenid());
wechatTemplate.setUrl(wtmm.getUrl());
List<WxMpTemplateData> data = new ArrayList<>();
for (Map.Entry<String, String> entry : wtmm.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.toLowerCase().contains("keyword")) {
data.add(new WxMpTemplateData(key, value, "#173177"));
} else {
data.add(new WxMpTemplateData(key, value));
}
}
wechatTemplate.setData(data);
wxPushService.push(appid, wechatTemplate);
}
}
package cn.com.glsx.notify.modules.utils;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.HttpUtils;
import com.glsx.plat.sms.properties.SMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.TreeMap;
/**
* @author payu
*/
@Slf4j
@Component("smsUtils")
public class SmsUtils {
@Resource
private SMSProperties properties;
/**
* 短信
*
* @param phone
* @param content
*/
// @Async
public void send(String phone, String content) {
send(phone, content, properties.getSource());
}
/**
* 短信派单
*
* @param phone
* @param content
* @param source
*/
// @Async
public void send(String phone, String content, String source) {
TreeMap<String, Object> treeMap = new TreeMap<>();
treeMap.put("method", "glsx.message.sendmessage");
treeMap.put("format", "json");
treeMap.put("akey", properties.getAccessKeyId());
treeMap.put("v", "1.0.0");
treeMap.put("channel", "1001");
treeMap.put("lock", "2AC16F3AB37C129E273A4979FD0A46B0");
treeMap.put("source", source);
treeMap.put("type", "1");
treeMap.put("phone", phone);
treeMap.put("content", content);
treeMap.put("subcode", "");
log.info("Send Sms:" + treeMap.toString());
String url = properties.getUrl();
log.info("短信接口:" + url);
try {
String res = HttpUtils.get(url, treeMap);
log.info("Result:" + res);
if (StringUtils.isNotEmpty(res)) {
if (res.contains("<html>")) {
log.error("短信服务不可用,返回html...");
}
if (res.contains("{")) {
JSONObject jsonObject = JSONObject.parseObject(res);
String code = jsonObject.getString("code");
if (!"0".equals(code)) {
res = HttpUtils.get(url, treeMap);
log.info("Failure resend result:" + res);
}
}
} else {
log.error("短信服务不可用,返回为空");
}
} catch (IllegalStateException ex) {
if (StringUtils.isNotEmpty(url)) {
log.error("IllegalStateException", ex);
}
} catch (Exception ex) {
log.error("SendSmsException", ex);
try {
String res1 = HttpUtils.get(url, treeMap);
log.info("Exception resend result:" + res1);
} catch (Exception e) {
log.error("ReSendSmsException", ex);
}
}
}
// public static void main(String[] args) {
// SmsUtils util = new SmsUtils();
// util.send("18682185876", "您本次操作验证码为:{0},五分钟内有效。", "frms_sms_assign");
// }
}
package cn.com.glsx.notify.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ChannelHandler.Sharable
public class MyByteEncoder extends MessageToByteEncoder<byte[]> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, byte[] bytes, ByteBuf out) throws Exception {
log.info("MyByteEncoder 被调用");
//字节数组
out.writeBytes(bytes);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class NettyDataSvervice {
private static final ReentrantLock Lock = new ReentrantLock();
/**
* 将传送过来的数据进行解析,包括异或运算 (第一次服务器端给客户端发)
*
* @param receiveData
* @return
*/
public static String sendData(String receiveData) {
final ReentrantLock putLock = Lock;
log.info("接收数据" + receiveData);
putLock.lock();
try {
//此处需要读数据进行校验以及分包黏包处理,本文主要提供思路所以省略
/*
* 处理分包黏包、拆分、解析等
*/
//数据解析
parseData(receiveData);
try {
//数据帧WebSocket推送
WebSocketServer.BroadCastInfo(receiveData);
} catch (IOException e) {
e.printStackTrace();
}
return receiveData;
} finally {
putLock.unlock();
}
}
/**
* 数据入库处理
*/
public static void parseData(String receiveData) {
System.out.println("执行入库操作");
}
}
package cn.com.glsx.notify.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyInitializer extends ChannelInitializer {
@Autowired
public MyByteEncoder myByteEncoder;
@Override
protected void initChannel(Channel channel) throws Exception {
//创建一个通道初始化对象(匿名对象)
//给pipeline 设置处理器
//可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue
// 或者 scheduleTaskQueue
log.info("客户socketchannel hashcode=" + channel.hashCode());
//入站解码
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//出站编码
channel.pipeline().addLast(new MyByteEncoder());
channel.pipeline().addLast(new NettyServerHandler());
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalTime;
import java.util.Objects;
@Slf4j
public class NettySendThread implements Runnable {
private ChannelHandlerContext ctx;
private String data;
public NettySendThread(ChannelHandlerContext ctx, String data) {
this.ctx = ctx;
this.data = data;
}
@Override
public void run() {
String bcc = NettyDataSvervice.sendData(data);
log.info("接收需要返回的消息:" + bcc);
if (Objects.isNull(bcc)) {
return;
}
//数据的发送与接收都是16进制
byte[] sendData = NettyByteAndStringUtils.hexToByte(bcc);
log.info("发送数据时间: " + LocalTime.now());
ctx.writeAndFlush(sendData);
}
}
package cn.com.glsx.notify.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@Configuration
public class NettyServer {
@Value("${netty.server.port}")
private Integer port;
final EventLoopGroup bossGroup = new NioEventLoopGroup();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
public void run() throws Exception {
//创建BossGroup 和 WorkerGroup
//说明
//1. 创建两个线程组 bossGroup 和 workerGroup
//2. bossGroup 只是处理连接请求 , 真正的和客户端业务处理,会交给 workerGroup完成
//3. 两个都是无限循环
//4. bossGroup 和 workerGroup 含有的子线程(NioEventLoop)的个数
//默认实际 cpu核数 * 2
try {
//创建服务器端的启动对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
//使用链式编程来进行设置
//设置两个线程组
bootstrap.group(bossGroup, workerGroup)
//使用NioSocketChannel 作为服务器的通道实现
.channel(NioServerSocketChannel.class)
// 设置线程队列得到连接个数(也可以说是并发数)
.option(ChannelOption.SO_BACKLOG, 2048)
//设置保持活动连接状态
.childOption(ChannelOption.SO_KEEPALIVE, true)
//.handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
//.childOption(ChannelOption.TCP_NODELAY,true)//socketchannel的设置,关闭延迟发送
.childHandler(new NettyInitializer());
log.info(".....服务器 is ready.....");
//绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
//启动服务器(并绑定端口)
ChannelFuture cf = bootstrap.bind(port).sync();
//给cf 注册监听器,监控我们关心的事件
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (cf.isSuccess()) {
log.info("监听端口[{}]成功!", port);
} else {
log.error("监听端口[{}]失败!", port);
}
}
});
//对关闭通道进行监听
cf.channel().closeFuture().sync();
} catch (Exception e) {
log.error(" netty服务启动异常 " + e.getMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static Lock lock_1 = new ReentrantLock();
private static Lock lock_2 = new ReentrantLock();
private static Lock lock_3 = new ReentrantLock();
private static Lock lock_4 = new ReentrantLock();
/**
* 管理一个全局map,保存连接进服务端的通道数量
*/
private static final ConcurrentHashMap<ChannelId, ChannelHandlerContext> CHANNEL_MAP = new ConcurrentHashMap<>();
@Override //数据读取完毕
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//writeAndFlush 是 write + flush
//将数据写入到缓存,并刷新
//一般讲,我们对这个发送的数据进行编码
//ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
}
/**
* 处理异常, 一般是需要关闭通道
*
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
log.info("服务端异常关闭" + ctx.channel());
}
/**
* @param ctx
* @DESCRIPTION: 有客户端连接服务器会触发此函数
* @return: void
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
lock_1.lock();
try {
//获取连接通道唯一标识
ChannelId channelId = ctx.channel().id();
//如果map中不包含此连接,就保存连接
if (CHANNEL_MAP.containsKey(channelId)) {
log.info("客户端【" + channelId + "】是连接状态,连接通道数量: " + CHANNEL_MAP.size());
} else {
//保存连接
CHANNEL_MAP.put(channelId, ctx);
log.info("客户端【" + channelId + "】连接netty服务器");
log.info("连接通道数量: " + CHANNEL_MAP.size());
}
} finally {
lock_1.unlock();
}
}
/**
* @param ctx
* @DESCRIPTION: 有客户端终止连接服务器会触发此函数
* @return: void
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
lock_2.lock();
try {
ChannelId channelId = ctx.channel().id();
//包含此客户端才去删除
if (CHANNEL_MAP.containsKey(channelId)) {
//删除连接
CHANNEL_MAP.remove(channelId);
System.out.println();
log.info("客户端【" + channelId + "】退出netty服务器");
log.info("连接通道数量: " + CHANNEL_MAP.size());
}
} finally {
lock_2.unlock();
}
}
/**
* 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
* 2. Object msg: 就是客户端发送的数据 默认Object
* <p>
* 读取数据实际(这里我们可以读取客户端发送的消息)
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
lock_3.lock();
try {
log.info("服务器读取线程 " + Thread.currentThread().getName() + " channle = " + ctx.channel());
Channel channel = ctx.channel();
//将 msg 转成一个 ByteBuf
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ByteBuf buf = (ByteBuf) msg;
//得到此时客户端的数据长度
int bytes_length = buf.readableBytes();
//组件新的字节数组
byte[] buffer = new byte[bytes_length];
buf.readBytes(buffer);
final String allData = NettyByteAndStringUtils.byteToHex(buffer);
log.info("进入服务端数据:" + allData);
ctx.executor().execute(new NettySendThread(ctx, allData));
} finally {
lock_3.unlock();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
lock_4.lock();
try {
String socketString = ctx.channel().remoteAddress().toString();
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
log.info("Client: " + socketString + " READER_IDLE 读超时");
ctx.disconnect();
} else if (event.state() == IdleState.WRITER_IDLE) {
log.info("Client: " + socketString + " WRITER_IDLE 写超时");
ctx.disconnect();
} else if (event.state() == IdleState.ALL_IDLE) {
log.info("Client: " + socketString + " ALL_IDLE 总超时");
ctx.disconnect();
}
}
} finally {
lock_4.unlock();
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty.utils;
import java.util.concurrent.locks.ReentrantLock;
public class NettyByteAndStringUtils {
private final static ReentrantLock Lock = new ReentrantLock();
/**
* byte数组转hex
*/
public static String byteToHex(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
String strHex = "";
StringBuilder sb = new StringBuilder("");
for (byte aByte : bytes) {
strHex = Integer.toHexString(aByte & 0xFF);
// 每个字节由两个字符表示,位数不够,高位补0
sb.append((strHex.length() == 1) ? "0" + strHex : strHex);
}
return sb.toString().trim();
} finally {
putLock.unlock();
}
}
/**
* hex转byte数组
*/
public static byte[] hexToByte(String hex) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
int m = 0, n = 0;
// 每两个字符描述一个字节
int byteLen = hex.length() / 2;
byte[] ret = new byte[byteLen];
for (int i = 0; i < byteLen; i++) {
m = i * 2 + 1;
n = m + 1;
int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
ret[i] = (byte) intVal;
}
return ret;
} finally {
putLock.unlock();
}
}
/**
* 字节数组的大小
*/
public static int getByteSize(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
int size = 0;
if (bytes == null || bytes.length == 0) {
return 0;
}
for (byte aByte : bytes) {
if (aByte == '\0') {
break;
}
size++;
}
return size;
} finally {
putLock.unlock();
}
}
}
#项目名称
spring.application.name=glsx-ne-shield-notifycenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=${profile.active}
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.notify.modules.mapper.MessageLogMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageLog">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="from_user" jdbcType="VARCHAR" property="fromUser" />
<result column="to_user" jdbcType="VARCHAR" property="toUser" />
<result column="template" jdbcType="VARCHAR" property="template" />
<result column="subject" jdbcType="VARCHAR" property="subject" />
<result column="content" jdbcType="VARCHAR" property="content" />
<result column="attachment" jdbcType="VARCHAR" property="attachment" />
<result column="type" jdbcType="VARCHAR" property="type" />
<result column="del_flag" jdbcType="INTEGER" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, from_user, to_user, `template`, subject, content, attachment, `type`,
del_flag, created_date, created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.notify.modules.mapper.MessageTemplateMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageTemplate">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="template" jdbcType="VARCHAR" property="template"/>
<result column="subject" jdbcType="VARCHAR" property="subject"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
<result column="type" jdbcType="VARCHAR" property="type"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, `template`, subject, content, `type`, del_flag, created_date,
created_by, updated_date, updated_by
</sql>
<select id="findByTemplate" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from d_message_template
where template = #{template}
</select>
<select id="findByTemplateAndType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from d_message_template
where template = #{template}
and type = #{type}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.test;
import cn.com.glsx.Application;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import cn.com.glsx.notify.modules.service.MailService;
import cn.com.glsx.notify.modules.service.PCService;
import cn.com.glsx.notify.modules.service.SmsService;
import cn.com.glsx.notify.modules.service.WeixinService;
import com.glsx.plat.common.utils.DateUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class NotifyApplicationTests {
@Autowired
private SmsService smsService;
@Autowired
private MailService mailService;
@Autowired
private PCService pcService;
@Autowired
private WeixinService weixinService;
@Test
public void testSms() {
Map<String, Object> args = new HashMap<>();
args.put("code", 1234);
smsService.sendSms("18682185876", "SMS_TEMPLATE_VERIFY_CODE", args.values());
}
@Test
public void testMail() {
Map<String, Object> args = new HashMap<>();
args.put("arg1", "刘宇峰");
args.put("arg2", "B73493098765");
args.put("arg3", 1234);
mailService.sendEmail("liuyf@didihu.com.cn", "notifycenter test", "MAIL_TEMPLATE_ORDER_PAID_NOTIFY_OPERATOR", args.values());
}
@Test
public void testPC() {
PCTemplateMessageDTO templateMessageDTO = PCTemplateMessageDTO.builder()
.application(Constants.SERVER_NAME + "_TOPIC")
.from("alarmcenter")
.to("1")
.template("test")
.content("设备离线报警")
.type(1)
.build();
pcService.sendMessage(templateMessageDTO);
}
@Test
public void testWeixinSend() {
Map<String, String> data = new HashMap<>();
data.put("first", "您的趣融贷款账单已出," + DateUtils.formatNormal(new Date()) + "是您的趣融贷款还款日。");
data.put("keyword1", "1856.65" + "元");
data.put("keyword2", "第" + 5 + "期");
data.put("remark", "如有疑问,请联系客服,客服热线:400-8060-999");
WechatTemplateMessageDTO model = WechatTemplateMessageDTO.builder()
.templateId("nclNdUjGPpXgQQth55Cx2BoJQscWlcKkEy97uZ9MXK0")
.openid("oxAQwwMiYESDE8--YOopaAl6F4uo")
.url("http://www.baidu.com")
.data(data).build();
weixinService.push("wxa9b785873a4b0793", model);
}
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-ordercenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.order", "cn.com.glsx.auth"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.order.config;
import cn.com.glsx.auth.interceptor.WebFunctionPermissionInterceptor;
import cn.com.glsx.auth.interceptor.WebRequestAuthorizeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* @author payu
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private WebRequestAuthorizeInterceptor authInterceptor;
@Resource
private WebFunctionPermissionInterceptor permissionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
registry.addInterceptor(authInterceptor).addPathPatterns("/**")
.excludePathPatterns("/")
.excludePathPatterns("/actuator/**")
.excludePathPatterns("/api/**");
registry.addInterceptor(permissionInterceptor).addPathPatterns("/**");
}
}
package cn.com.glsx.order.modules.controller;
import cn.com.glsx.auth.model.FunctionPermissions;
import cn.com.glsx.order.modules.entity.Device;
import cn.com.glsx.order.modules.service.DeviceService;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static cn.com.glsx.auth.model.FunctionPermissionType.DEVICE_QUERY;
@Slf4j
@RestController
@RequestMapping(value = "/device")
public class DeviceController {
@Autowired
private DeviceService deviceService;
@FunctionPermissions(permissionType = DEVICE_QUERY)
@GetMapping("/search")
public R search() {
String username = deviceService.test();
return R.ok().data(username + "-->this is a test");
}
@GetMapping("/all")
public R all() {
List<Device> list = deviceService.selectList();
return R.ok().data(list);
}
}
package cn.com.glsx.order.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Table(name = "t_device")
public class Device extends BaseEntity {
/**
* 硬件名称
*/
private String name;
/**
* 硬件类型
*/
private Integer type;
/**
* 型号id
*/
@Column(name = "model_id")
private Integer modelId;
/**
* 型号名称
*/
@Column(name = "model_name")
private String modelName;
/**
* 版本
*/
private String version;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.order.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.*;
@Accessors(chain = true)
@Data
@Table(name = "t_device_permit")
public class DevicePermit extends BaseEntity {
/**
* 授权人id
*/
@Column(name = "accorder_id")
private Long accorderId;
/**
* 获权人id
*/
@Column(name = "receiver_id")
private Long receiverId;
/**
* 内容类型
*/
@Column(name = "content_type")
private Byte contentType;
/**
* 权限类型 0=读写 1=只读
*/
@Column(name = "permit_type")
private Byte permitType;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.order.modules.mapper;
import cn.com.glsx.order.modules.entity.Device;
import com.glsx.plat.common.annotation.DataPerm;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface DeviceMapper extends CommonBaseMapper<Device> {
@DataPerm
List<Device> selectList();
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.order.modules.mapper;
import cn.com.glsx.order.modules.entity.DevicePermit;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DevicePermitMapper extends CommonBaseMapper<DevicePermit> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.order.modules.service;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.order.modules.entity.Device;
import cn.com.glsx.order.modules.mapper.DeviceMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class DeviceService {
@Resource
private DeviceMapper deviceMapper;
public String test() {
String username = ShieldContextHolder.getAccount();
return username;
}
public List<Device> selectList() {
return deviceMapper.selectList();
}
}
#项目名称
spring.application.name=glsx-ne-shield-ordercenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=${profile.active}
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.order.modules.mapper.DeviceMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.order.modules.entity.Device">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="type" jdbcType="INTEGER" property="type"/>
<result column="model_id" jdbcType="INTEGER" property="modelId"/>
<result column="model_name" jdbcType="VARCHAR" property="modelName"/>
<result column="version" jdbcType="VARCHAR" property="version"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, `name`, `type`, model_id, model_name, version, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectList" resultMap="BaseResultMap">
select * from t_device
where del_flag = 0
order by id
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.order.modules.mapper.DevicePermitMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.order.modules.entity.DevicePermit">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="accorder_id" jdbcType="INTEGER" property="accorderId"/>
<result column="receiver_id" jdbcType="INTEGER" property="receiverId"/>
<result column="content_type" jdbcType="TINYINT" property="contentType"/>
<result column="permit_type" jdbcType="TINYINT" property="permitType"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, accorder_id, receiver_id, content_type, permit_type, del_flag, created_date,
created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-publiccenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-dfs</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-office</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.base", "cn.com.glsx.auth"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.base.common.exception;
import com.glsx.plat.exception.SystemMessage;
import lombok.Getter;
/**
* @author payu
*/
@Getter
public class PublicCenterException extends RuntimeException {
private int errorCode = SystemMessage.FAILURE.getCode();
public PublicCenterException(String message) {
super(message);
}
public PublicCenterException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public static PublicCenterException of(SystemMessage message) {
return new PublicCenterException(message.getCode(), message.getMsg());
}
public PublicCenterException(Throwable cause) {
super(cause);
}
public PublicCenterException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.com.glsx.base.common.exception;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.ExceptionLevel;
import com.glsx.plat.exception.GlobalExceptionHandler;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.loggin.LogginConstants;
import com.glsx.plat.loggin.LogginStrategyFactory;
import feign.FeignException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理
*
* @author payu
*/
@Slf4j
@RestControllerAdvice
public class PublicCenterExceptionHandler extends GlobalExceptionHandler {
@Autowired
private LogginStrategyFactory logginStrategyFactory;
@ExceptionHandler(PublicCenterException.class)
public R handleAdminException(PublicCenterException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.getErrorCode(), e.getMessage());
}
/**
* 引入Feign服务的话
*
* @param e
* @return
*/
@ExceptionHandler(FeignException.class)
public R handleFeignException(FeignException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.status(), e.getMessage());
}
/**
* Mybatis BindingException
*
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
public R handleBindingException(BindingException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.getMessage());
}
@ExceptionHandler(value = MyBatisSystemException.class)
public R myBatisSystemException(MyBatisSystemException e) {
log.error("数据存储出错", e);
this.saveException(e, ExceptionLevel.fatal);
return SystemMessage.DATA_HANDLE_ERROR.result();
}
@ExceptionHandler(value = UnrecognizedPropertyException.class)
public R unrecognizedPropertyException(UnrecognizedPropertyException e) {
log.error("不能识别的字段", e);
this.saveException(e, ExceptionLevel.fatal);
return SystemMessage.ARGS_ERROR.result();
}
@SneakyThrows
@Async
@Override
protected void saveException(Exception e, ExceptionLevel level) {
// TODO: 2020/10/14 异常入库,对此方法进行aop处理
String logId = MDC.get(LogginConstants.MDC_LOG_DB_ID);
log.error("操作异常/失败ID:{}", MDC.get(LogginConstants.MDC_LOG_DB_ID));
logginStrategyFactory.getStrategy().updateLogStatus(logId, "失败");
MDC.clear();
}
}
package cn.com.glsx.base.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author payu
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
// @Resource
// private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
// registry.addInterceptor(authInterceptor).addPathPatterns("/**")
// .excludePathPatterns("/")
// .excludePathPatterns("/actuator/**")
// .excludePathPatterns("/api/**");
}
}
package cn.com.glsx.base.modules;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.core.web.R;
import com.glsx.plat.web.controller.AbstractController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liuyf
* @Title BaseController.java
* @Package com.glsx.vasp.controller
* @Description
* @date 2019年10月24日 下午2:24:00
*/
@RestController
public class BaseController extends AbstractController {
/**
* 这个给Spring Boot Admin探测用
*
* @return
*/
@GetMapping(value = "/")
public R index() {
return R.ok("You get it!");
}
/**
* 从session中获取当前用户
*
* @return
*/
@Override
public SyntheticUser getSessionUser() {
return ShieldContextHolder.getUser();
}
@Override
public Long getUserId() {
return ShieldContextHolder.getUserId();
}
@Override
public String getAccount() {
return ShieldContextHolder.getAccount();
}
}
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.base.modules.entity.BaseArea;
import cn.com.glsx.base.modules.service.BaseAreasService;
import com.glsx.plat.core.web.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* @author liuyf
* @date 2019-04-03 11:33:49
*/
@RestController
@RequestMapping("basic/area")
public class BaseAreasController {
@Autowired
private BaseAreasService baseAreasService;
@RequestMapping("/list")
public R list(@NotBlank(message = "城市编码不能为空") String cityCode) {
List<BaseArea> list = baseAreasService.searchByCityCode(cityCode);
return R.ok().data(list);
}
}
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.base.modules.entity.BaseCity;
import cn.com.glsx.base.modules.service.BaseCitiesService;
import com.glsx.plat.core.web.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* 市区
*
* @author Mark
* @date 2019-03-28 13:49:24
*/
@RestController
@RequestMapping("basic/city")
@Validated
public class BaseCitiesController {
@Autowired
private BaseCitiesService baseCitiesService;
/**
* 根据条件查询
*/
@RequestMapping("/list")
public R list(@NotBlank(message = "省份编码不能为空") String provCode) {
List<BaseCity> list = baseCitiesService.list(provCode);
return R.ok().data(list);
}
}
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.base.modules.entity.BaseProvince;
import cn.com.glsx.base.modules.service.BaseProvincesService;
import com.glsx.plat.core.web.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 省份
*
* @author Mark
* @date 2019-03-28 10:17:01
*/
@RestController
@RequestMapping("basic/province")
public class BaseProvincesController {
@Autowired
private BaseProvincesService baseProvinceService;
/**
* 列表
*/
@RequestMapping("/list")
public R list() {
List<BaseProvince> list = baseProvinceService.list();
return R.ok().data(list);
}
}
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.base.modules.converter.DictDataConverter;
import cn.com.glsx.base.modules.entity.SysDictData;
import cn.com.glsx.base.modules.model.DictDataBO;
import cn.com.glsx.base.modules.model.DictDataDTO;
import cn.com.glsx.base.modules.model.DictDataSearch;
import cn.com.glsx.base.modules.model.export.DictDataExport;
import cn.com.glsx.base.modules.service.DictDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.office.excel.EasyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
/**
* @author payu
*/
@RestController
@RequestMapping("dict/data")
public class DictDataController {
private final static String MODULE = "字典管理";
@Autowired
private DictDataService dictDataService;
@GetMapping("/search")
public R search(DictDataSearch search) {
PageHelper.startPage(search.getPageNumber(), search.getPageSize());
PageInfo<DictDataDTO> pageInfo = dictDataService.searchData(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping(value = "/export")
public void export(HttpServletResponse response, DictDataSearch search) throws Exception {
List<DictDataExport> list = dictDataService.exportData(search);
EasyExcelUtils.writeExcel(response, list, "字典数据_" + DateUtils.formatSerial(new Date()), "Sheet1", DictDataExport.class);
}
/**
* 根据字典类型查询字典数据信息
*/
@GetMapping(value = "/type/{dictType}")
public R dictType(@PathVariable("dictType") String dictType) {
List<DictDataDTO> list = dictDataService.getDictDataByTypeWithCached(dictType);
return R.ok().data(list);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping("/add")
public R add(@RequestBody @Valid DictDataBO dataBO) {
SysDictData data = DictDataConverter.INSTANCE.bo2do(dataBO);
if (StringUtils.isNullOrEmpty(data.getIsDefault())) data.setIsDefault("N");
dictDataService.addData(data);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping("/edit")
public R edit(@RequestBody @Valid DictDataBO dataBO) {
AssertUtils.isNull(dataBO.getId(), "ID不能为空");
SysDictData data = DictDataConverter.INSTANCE.bo2do(dataBO);
dictDataService.editData(data);
return R.ok();
}
@GetMapping("/info")
public R info(@RequestParam("dataId") Long id) {
SysDictData data = dictDataService.getDictDataById(id);
DictDataDTO dataDTO = DictDataConverter.INSTANCE.do2dto(data);
return R.ok().data(dataDTO);
}
@GetMapping("/delete")
public R delete(@RequestParam("dataId") Long id) {
dictDataService.logicDeleteDataById(id);
return R.ok();
}
}
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.base.modules.converter.DictTypeConverter;
import cn.com.glsx.base.modules.entity.SysDictType;
import cn.com.glsx.base.modules.model.DictDataSearch;
import cn.com.glsx.base.modules.model.DictTypeBO;
import cn.com.glsx.base.modules.model.DictTypeDTO;
import cn.com.glsx.base.modules.model.export.DictTypeExport;
import cn.com.glsx.base.modules.service.DictDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.office.excel.EasyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
/**
* @author payu
*/
@RestController
@RequestMapping("dict/type")
public class DictTypeController {
private final static String MODULE = "字典管理";
@Autowired
private DictDataService dictDataService;
@GetMapping("/search")
public R search(DictDataSearch search) {
PageHelper.startPage(search.getPageNumber(), search.getPageSize());
PageInfo<DictTypeDTO> pageInfo = dictDataService.searchType(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping(value = "/export")
public void export(HttpServletResponse response, DictDataSearch search) throws Exception {
List<DictTypeExport> list = dictDataService.exportType(search);
EasyExcelUtils.writeExcel(response, list, "字典类型_" + DateUtils.formatSerial(new Date()), "Sheet1", DictTypeExport.class);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping("/add")
public R add(@RequestBody @Valid DictTypeBO typeBO) {
SysDictType type = DictTypeConverter.INSTANCE.bo2do(typeBO);
dictDataService.addType(type);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping("/edit")
public R edit(@RequestBody @Valid DictTypeBO typeBO) {
AssertUtils.isNull(typeBO.getId(), "ID不能为空");
SysDictType type = DictTypeConverter.INSTANCE.bo2do(typeBO);
dictDataService.editType(type);
return R.ok();
}
@GetMapping("/info")
public R info(@RequestParam("typeId") Long id) {
SysDictType type = dictDataService.getDictTypeById(id);
DictTypeDTO typeDTO = DictTypeConverter.INSTANCE.do2dto(type);
return R.ok().data(typeDTO);
}
@GetMapping("/delete")
public R delete(@RequestParam("typeId") Long id) {
dictDataService.logicDeleteTypeById(id);
return R.ok();
}
@GetMapping("/options")
public R options() {
List<DictTypeDTO> list = dictDataService.getAllDictType2();
return R.ok().data(list);
}
}
package cn.com.glsx.base.modules.controller;
import com.glsx.plat.common.utils.SnowFlake;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.context.properties.UploadProperties;
import com.glsx.plat.core.web.R;
import com.glsx.plat.fastdfs.FastDfsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
/**
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "basic/file")
public class FileController {
@Resource
private FastDfsUtils fastDfsUtils;
@Resource
private UploadProperties uploadProperties;
/**
* 文件上传到本地服务器
*/
@PostMapping(value = "/upload2local", headers = "content-type=multipart/form-data")
public R upload2local(@RequestParam("file") MultipartFile file) throws Exception {
String result;
//获取文件存放路径
String path = uploadProperties.getBasePath();
File targetDir = new File(path);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.indexOf("."));
String newFilename = SnowFlake.nextId() + suffix;
String tempPath = targetDir + File.separator + newFilename;
// 转存文件
File desc = new File(tempPath);
FileUtils.copyInputStreamToFile(file.getInputStream(), desc);
path = tempPath;
if (StringUtils.isNotEmpty(path)) {
result = uploadProperties.getFilepath() + newFilename;
return R.ok().data(result);
} else {
result = "上传失败";
return R.error(result);
}
}
/**
* 文件上传分布式文件服务器
*/
@PostMapping(value = "/upload2dfs", headers = "content-type=multipart/form-data")
public R upload2dfs(@RequestParam("file") MultipartFile file) {
String result;
try {
String path = fastDfsUtils.upload(file);
if (StringUtils.isNotEmpty(path)) {
result = path;
} else {
result = "上传失败";
}
return R.ok().data(result);
} catch (Exception e) {
e.printStackTrace();
result = "文件服务异常";
return R.error(result);
}
}
/**
* 文件删除
*
* @param url
* @return
*/
@GetMapping(value = "/deleteByUrl")
public R deleteByUrl(@RequestParam("url") String url) {
fastDfsUtils.delete(url);
return R.ok();
}
}
package cn.com.glsx.base.modules.converter;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface DictDataConverter {
DictDataConverter INSTANCE = Mappers.getMapper(DictDataConverter.class);
cn.com.glsx.base.modules.model.DictDataDTO do2dto(cn.com.glsx.base.modules.entity.SysDictData data);
cn.com.glsx.base.modules.entity.SysDictData bo2do(cn.com.glsx.base.modules.model.DictDataBO dataBO);
}
package cn.com.glsx.base.modules.converter;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface DictTypeConverter {
DictTypeConverter INSTANCE = Mappers.getMapper(DictTypeConverter.class);
cn.com.glsx.base.modules.model.DictTypeDTO do2dto(cn.com.glsx.base.modules.entity.SysDictType type);
cn.com.glsx.base.modules.entity.SysDictType bo2do(cn.com.glsx.base.modules.model.DictTypeBO typeBO);
}
package cn.com.glsx.base.modules.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Entity
@Table(name = "base_areas")
public class BaseArea implements Serializable {
@Id
private Long id;
@Column(name = "city_code")
private String cityCode;
private String code;
private String name;
@Column(name = "province_code")
private String provCode;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Entity
@Table(name = "base_cities")
public class BaseCity implements Serializable {
@Id
private Long id;
private String code;
private String name;
@Column(name = "province_code")
private String provCode;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Entity
@Table(name = "base_provinces")
public class BaseProvince implements Serializable {
@Id
private Long id;
private String code;
private String name;
@Column(name = "region_code")
private String regionCode;
@Column(name = "region_name")
private String regionName;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Accessors(chain = true)
@Table(name = "t_dict_data")
public class SysDictData extends BaseEntity {
/**
* 字典类型
*/
@Column(name = "dict_type")
private String dictType;
/**
* 字典标签
*/
@Column(name = "dict_label")
private String dictLabel;
/**
* 字典键值
*/
@Column(name = "dict_value")
private String dictValue;
/**
* 字典排序
*/
@Column(name = "dict_sort")
private Integer dictSort;
/**
* 是否默认(Y是 N否)
*/
@Column(name = "is_default")
private String isDefault;
@Column(name = "enable_status")
private Integer enableStatus;
/**
* 备注
*/
private String remark;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Accessors(chain = true)
@Table(name = "t_dict_type")
public class SysDictType extends BaseEntity {
/**
* 字典名称
*/
@Column(name = "dict_name")
private String dictName;
/**
* 字典类型
*/
@Column(name = "dict_type")
private String dictType;
/**
* 备注
*/
private String remark;
@Column(name = "enable_status")
private Integer enableStatus;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.mapper;
import cn.com.glsx.base.modules.entity.BaseArea;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface BaseAreaMapper extends CommonBaseMapper<BaseArea> {
List<BaseArea> selectByCityCode(@Param("cityCode") String cityCode);
BaseArea selectByCode(@Param("areaCode") String areaCode);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.mapper;
import cn.com.glsx.base.modules.entity.BaseCity;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface BaseCityMapper extends CommonBaseMapper<BaseCity> {
List<BaseCity> selectByProvCode(@Param("provCode") String provCode);
BaseCity selectByCode(@Param("cityCode") String cityCode);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.mapper;
import cn.com.glsx.base.modules.entity.BaseProvince;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface BaseProvinceMapper extends CommonBaseMapper<BaseProvince> {
BaseProvince selectByCode(@Param("provCode") String provCode);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.mapper;
import cn.com.glsx.base.modules.entity.SysDictData;
import cn.com.glsx.base.modules.entity.SysDictType;
import cn.com.glsx.base.modules.model.DictDataDTO;
import cn.com.glsx.base.modules.model.DictDataSearch;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface SysDictDataMapper extends CommonBaseMapper<SysDictData> {
List<DictDataDTO> selectList(DictDataSearch search);
List<SysDictData> selectByType(@Param("type") String type);
List<DictDataDTO> selectByType2(@Param("type") String type);
List<DictDataDTO> selectByTypeWithDeleted(@Param("type") String type);
SysDictData selectById(@Param("id") Long id);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.mapper;
import cn.com.glsx.base.modules.entity.SysDictType;
import cn.com.glsx.base.modules.model.DictDataSearch;
import cn.com.glsx.base.modules.model.DictTypeDTO;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface SysDictTypeMapper extends CommonBaseMapper<SysDictType> {
List<DictTypeDTO> selectList(DictDataSearch search);
List<SysDictType> selectAllDictType();
List<DictTypeDTO> selectAllDictType2();
SysDictType selectById(@Param("id") Long id);
SysDictType selectByType(@Param("type") String dictType);
SysDictType selectByNameWithDeleted(@Param("name") String dictName);
SysDictType selectByTypeWithDeleted(@Param("type") String dictType);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.base.modules.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class DictDataBO implements Serializable {
private Long id;
private String dictType;
private String dictLabel;
private String dictValue;
private Integer dictSort;
private String isDefault;
private Integer enableStatus;
private String remark;
}
package cn.com.glsx.base.modules.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class DictDataDTO implements Serializable {
private Long id;
private String dictLabel;
private String dictValue;
private String dictType;
private Integer dictSort;
private String isDefault;
private Integer enableStatus;
@JsonIgnore
private Integer delFlag;
private String remark;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
private boolean typeDisabled;
private boolean disabled;
private boolean typeDeleted;
private boolean deleted;
}
package cn.com.glsx.base.modules.model;
import cn.hutool.db.Page;
import lombok.Data;
@Data
public class DictDataSearch extends Page {
private String name;
private String type;
private String tag;
private Integer status;
private String sDate;
private String eDate;
}
package cn.com.glsx.base.modules.model;
import lombok.Data;
import java.io.Serializable;
@Data
public class DictTypeBO implements Serializable {
private Long id;
private String dictName;
private String dictType;
private String remark;
private Integer enableStatus;
}
package cn.com.glsx.base.modules.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class DictTypeDTO implements Serializable {
private Long id;
private String dictName;
private String dictType;
private String remark;
private Integer enableStatus;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
@JsonIgnore
private Integer delFlag;
}
package cn.com.glsx.base.modules.model.export;
public class DictDataExport {
}
package cn.com.glsx.base.modules.model.export;
public class DictTypeExport {
}
package cn.com.glsx.base.modules.service;
import cn.com.glsx.base.modules.entity.BaseArea;
import cn.com.glsx.base.modules.mapper.BaseAreaMapper;
import com.glsx.plat.redis.utils.RedisUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BaseAreasService {
@Resource
private BaseAreaMapper areaMapper;
@Autowired
private RedisUtils redisUtils;
public List<BaseArea> searchByCityCode(String cityCode) {
List<BaseArea> list = null;//redisUtils.getListByPrex(ConstantCacheKeys.REDIS_AREA_KEY + cityCode);
// Collections.sort(list, Comparator.comparing(BaseArea::getCode));
if (CollectionUtils.isEmpty(list)) list = areaMapper.selectByCityCode(cityCode);
return list;
}
}
package cn.com.glsx.base.modules.service;
import cn.com.glsx.base.modules.entity.BaseCity;
import cn.com.glsx.base.modules.mapper.BaseCityMapper;
import com.glsx.plat.redis.utils.RedisUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BaseCitiesService {
@Resource
private BaseCityMapper cityMapper;
@Autowired
private RedisUtils redisUtils;
public List<BaseCity> list(String provCode) {
List<BaseCity> list = null;//redisUtils.getListByPrex(ConstantCacheKeys.REDIS_CITY_KEY + provinceCode);
// Collections.sort(list, Comparator.comparing(BaseCity::getCode));
if (CollectionUtils.isEmpty(list)) list = cityMapper.selectByProvCode(provCode);
return list;
}
}
package cn.com.glsx.base.modules.service;
import cn.com.glsx.base.modules.entity.BaseProvince;
import cn.com.glsx.base.modules.mapper.BaseProvinceMapper;
import com.glsx.plat.redis.utils.RedisUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BaseProvincesService {
@Resource
private BaseProvinceMapper provinceMapper;
@Autowired
private RedisUtils redisUtils;
public List<BaseProvince> list() {
List<BaseProvince> list = null;//redisUtils.getListByPrex(ConstantCacheKeys.REDIS_PROVINCES_KEY);
//排序
// Collections.sort(list, Comparator.comparing(BaseProvince::getCode));
if (CollectionUtils.isEmpty(list)) list = provinceMapper.selectAll();
return list;
}
}
package cn.com.glsx.base.modules.service;
import cn.com.glsx.base.modules.entity.SysDictData;
import cn.com.glsx.base.modules.entity.SysDictType;
import cn.com.glsx.base.modules.mapper.SysDictDataMapper;
import cn.com.glsx.base.modules.mapper.SysDictTypeMapper;
import cn.com.glsx.base.modules.model.DictDataDTO;
import cn.com.glsx.base.modules.model.DictDataSearch;
import cn.com.glsx.base.modules.model.DictTypeDTO;
import cn.com.glsx.base.modules.model.export.DictDataExport;
import cn.com.glsx.base.modules.model.export.DictTypeExport;
import cn.com.glsx.base.modules.utils.DictUtils;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.core.enums.SysConstants;
import com.glsx.plat.exception.BusinessException;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class DictDataService implements InitializingBean {
@Autowired
private SysDictTypeMapper typeMapper;
@Autowired
private SysDictDataMapper dataMapper;
@Autowired
private DictUtils dictUtils;
/**
* 项目启动时,初始化字典到缓存
*/
public void init() {
List<DictTypeDTO> dictTypeList = this.getAllDictType2();
for (DictTypeDTO dictType : dictTypeList) {
List<DictDataDTO> dictDatas = this.getDictDataByType2(dictType.getDictType());
dictUtils.setDictCache(dictType.getDictType(), dictDatas);
}
}
public PageInfo<DictTypeDTO> searchType(DictDataSearch search) {
List<DictTypeDTO> list = typeMapper.selectList(search);
return new PageInfo<>(list);
}
public PageInfo<DictDataDTO> searchData(DictDataSearch search) {
List<DictDataDTO> list = dataMapper.selectList(search);
return new PageInfo<>(list);
}
public List<SysDictType> getAllDictType() {
return typeMapper.selectAllDictType();
}
public List<DictTypeDTO> getAllDictType2() {
return typeMapper.selectAllDictType2();
}
public List<SysDictData> getDictDataByType(String type) {
return dataMapper.selectByType(type);
}
public List<DictDataDTO> getDictDataByType2(String type) {
return dataMapper.selectByType2(type);
}
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
public List<DictDataDTO> getDictDataByTypeWithCached(String dictType) {
// TODO: 2020/11/2 使用缓存
List<DictDataDTO> dictDatas = Lists.newArrayList();//dictUtils.getDictCache(dictType);
if (CollectionUtils.isNotEmpty(dictDatas)) {
return dictDatas;
}
SysDictType type = typeMapper.selectByTypeWithDeleted(dictType);
Optional<SysDictType> typeOpt = Optional.ofNullable(type);
if (typeOpt.isPresent()) {
dictDatas = dataMapper.selectByTypeWithDeleted(dictType);
if (CollectionUtils.isNotEmpty(dictDatas)) {
boolean typeDisabled = !SysConstants.EnableStatus.enable.getCode().equals(type.getEnableStatus());
boolean typeDeleted = SysConstants.DeleteStatus.delete.getCode().equals(type.getDelFlag());
dictDatas.forEach(dd -> {
boolean disabled = !SysConstants.EnableStatus.enable.getCode().equals(dd.getEnableStatus());
boolean deleted = SysConstants.DeleteStatus.delete.getCode().equals(dd.getDelFlag());
//字典数据停用
dd.setDisabled(disabled);
//字典数据删除
dd.setDeleted(deleted);
//字典类型停用
if (typeDisabled) {
dd.setTypeDisabled(typeDisabled);
dd.setDisabled(typeDisabled);
}
//字典类型删除
if (typeDeleted) {
dd.setTypeDeleted(typeDeleted);
dd.setDeleted(typeDeleted);
}
});
dictUtils.setDictCache(dictType, dictDatas);
return dictDatas;
}
}
return Lists.newArrayList();
}
public void addType(SysDictType type) {
checkAddType(type);
// TODO: 2020/11/2 更新缓存
typeMapper.insert(type);
}
public void editType(SysDictType type) {
checkEditType(type);
// TODO: 2020/11/2 更新缓存
typeMapper.updateByPrimaryKeySelective(type);
}
public void addData(SysDictData data) {
checkAddData(data);
// TODO: 2020/11/2 更新缓存
dataMapper.insert(data);
}
public void editData(SysDictData data) {
checkEditData(data);
// TODO: 2020/11/2 更新缓存
dataMapper.updateByPrimaryKeySelective(data);
}
private void checkAddType(SysDictType type) {
SysDictType dbType1 = typeMapper.selectByNameWithDeleted(type.getDictName());
if (dbType1 != null) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbType1.getDelFlag());
throw BusinessException.create("字典名称已存在" + (delFlag ? ",但处于删除状态" : ""));
}
SysDictType dbType2 = typeMapper.selectByTypeWithDeleted(type.getDictType());
if (dbType2 != null) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbType2.getDelFlag());
throw BusinessException.create("字典类型已存在" + (delFlag ? ",但处于删除状态" : ""));
}
}
private void checkEditType(SysDictType type) {
SysDictType dbType1 = typeMapper.selectByNameWithDeleted(type.getDictName());
if (dbType1 != null && !dbType1.getId().equals(type.getId())) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbType1.getDelFlag());
throw BusinessException.create("字典名称已存在" + (delFlag ? ",但处于删除状态" : ""));
}
SysDictType dbType2 = typeMapper.selectByTypeWithDeleted(type.getDictType());
if (dbType2 != null && !dbType2.getId().equals(type.getId())) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbType2.getDelFlag());
throw BusinessException.create("字典类型已存在" + (delFlag ? ",但处于删除状态" : ""));
}
}
private void checkAddData(SysDictData data) {
SysDictData condition = new SysDictData()
.setDictType(data.getDictType())
.setDictValue(data.getDictValue());
condition.setDelFlag(null);
SysDictData dbData = dataMapper.selectOne(condition);
if (dbData != null) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbData.getDelFlag());
throw BusinessException.create("字典数据键值已存在" + (delFlag ? ",但处于删除状态" : ""));
}
}
private void checkEditData(SysDictData data) {
SysDictData condition = new SysDictData()
.setDictType(data.getDictType())
.setDictValue(data.getDictValue());
condition.setDelFlag(null);
SysDictData dbData = dataMapper.selectOne(condition);
if (dbData != null && !dbData.getId().equals(data.getId())) {
boolean delFlag = SysConstants.DeleteStatus.delete.getCode().equals(dbData.getDelFlag());
throw BusinessException.create("字典数据键值已存在" + (delFlag ? ",但处于删除状态" : ""));
}
}
public SysDictType getDictTypeById(Long id) {
return typeMapper.selectById(id);
}
public SysDictData getDictDataById(Long id) {
return dataMapper.selectById(id);
}
public void logicDeleteTypeById(Long id) {
// TODO: 2020/11/2 更新缓存
typeMapper.logicDeleteById(id);
}
public void logicDeleteDataById(Long id) {
// TODO: 2020/11/2 更新缓存
dataMapper.logicDeleteById(id);
}
@Override
public void afterPropertiesSet() throws Exception {
// init();
}
public List<DictTypeExport> exportType(DictDataSearch search) {
return Lists.newArrayList();
}
public List<DictDataExport> exportData(DictDataSearch search) {
return Lists.newArrayList();
}
}
package cn.com.glsx.base.modules.utils;
import cn.com.glsx.base.modules.model.DictDataDTO;
import com.glsx.plat.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* 字典工具类
*/
@Component
public class DictUtils {
@Autowired
private RedisUtils redisUtils;
/**
* 字典管理 cache key
*/
public static final String SYS_DICT_KEY = "sys_dict:";
/**
* 设置字典缓存
*
* @param key 参数键
* @param dictDatas 字典数据列表
*/
public void setDictCache(String key, List<DictDataDTO> dictDatas) {
String fullKey = getCacheKey(key);
redisUtils.set(fullKey, dictDatas);
}
/**
* 获取字典缓存
*
* @param key 参数键
* @return dictDatas 字典数据列表
*/
public List<DictDataDTO> getDictCache(String key) {
Object cacheObj = redisUtils.get(getCacheKey(key));
if (Objects.isNull(cacheObj)) {
return null;
}
return cast(cacheObj);
}
/**
* 清空字典缓存
*/
public void clearDictCache() {
Collection<String> keys = redisUtils.keys(SYS_DICT_KEY + "*");
redisUtils.del(keys);
}
/**
* 设置cache key
*
* @param configKey 参数键
* @return 缓存键key
*/
public static String getCacheKey(String configKey) {
return SYS_DICT_KEY + configKey;
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj) {
return (T) obj;
}
}
#项目名称
spring.application.name=glsx-ne-shield-publiccenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.base.modules.mapper.BaseAreaMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.base.modules.entity.BaseArea">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="city_code" jdbcType="VARCHAR" property="cityCode"/>
<result column="code" jdbcType="VARCHAR" property="code"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="province_code" jdbcType="VARCHAR" property="provCode"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, city_code, code, `name`, province_code
</sql>
<select id="selectByCityCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_areas
where city_code =#{cityCode}
order by code
</select>
<select id="selectByCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_areas
where code =#{areaCode}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.base.modules.mapper.BaseCityMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.base.modules.entity.BaseCity">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="code" jdbcType="VARCHAR" property="code"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="province_code" jdbcType="VARCHAR" property="provCode"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, code, `name`, province_code
</sql>
<select id="selectByProvCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_cities
where province_code =#{provCode}
order by code
</select>
<select id="selectByCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_cities
where code =#{cityCode}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.base.modules.mapper.BaseProvinceMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.base.modules.entity.BaseProvince">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="code" jdbcType="VARCHAR" property="code"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="region_code" jdbcType="VARCHAR" property="regionCode"/>
<result column="region_name" jdbcType="VARCHAR" property="regionName"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, code, `name`, region_code, region_name
</sql>
<select id="selectByCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_provinces
where code =#{provCode}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.base.modules.mapper.SysDictDataMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.base.modules.entity.SysDictData">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="dict_sort" jdbcType="INTEGER" property="dictSort"/>
<result column="dict_label" jdbcType="VARCHAR" property="dictLabel"/>
<result column="dict_value" jdbcType="VARCHAR" property="dictValue"/>
<result column="dict_type" jdbcType="VARCHAR" property="dictType"/>
<result column="is_default" jdbcType="CHAR" property="isDefault"/>
<result column="enable_status" jdbcType="INTEGER" property="enableStatus"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
</resultMap>
<resultMap id="DTOResultMap" type="cn.com.glsx.base.modules.model.DictDataDTO">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="dict_sort" jdbcType="INTEGER" property="dictSort"/>
<result column="dict_label" jdbcType="VARCHAR" property="dictLabel"/>
<result column="dict_value" jdbcType="VARCHAR" property="dictValue"/>
<result column="dict_type" jdbcType="VARCHAR" property="dictType"/>
<result column="is_default" jdbcType="CHAR" property="isDefault"/>
<result column="enable_status" jdbcType="INTEGER" property="enableStatus"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, dict_sort, dict_label, dict_value, dict_type, is_default, enable_status, del_flag,
created_by, created_date, updated_by, updated_date, remark
</sql>
<select id="selectByType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_data
where dict_type = #{type}
and del_flag = 0
</select>
<select id="selectByType2" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_data
where dict_type = #{type}
and del_flag = 0
</select>
<select id="selectByTypeWithDeleted" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_data
where dict_type = #{type}
</select>
<select id="selectList" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_data
where del_flag = 0
and dict_type = #{type}
<if test="tag != null and tag != ''">
and dict_label LIKE CONCAT('%',#{tag},'%')
</if>
<if test="status != null">
and enable_status = #{status}
</if>
<if test="sDate != null and sDate != '' and eDate != null and eDate != ''">
and DATE_FORMAT(created_date, '%Y-%m-%d') &gt;= #{sDate}
and DATE_FORMAT(created_date, '%Y-%m-%d') &lt;= #{eDate}
</if>
order by id desc
</select>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_data
where id = #{id}
and del_flag = 0
</select>
<update id="logicDeleteById">
update t_dict_data set del_flag = -1 where id = #{id}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.base.modules.mapper.SysDictTypeMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.base.modules.entity.SysDictType">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="dict_name" jdbcType="VARCHAR" property="dictName"/>
<result column="dict_type" jdbcType="VARCHAR" property="dictType"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<result column="enable_status" jdbcType="INTEGER" property="enableStatus"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
</resultMap>
<resultMap id="DTOResultMap" type="cn.com.glsx.base.modules.model.DictTypeDTO">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="dict_name" jdbcType="VARCHAR" property="dictName"/>
<result column="dict_type" jdbcType="VARCHAR" property="dictType"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<result column="enable_status" jdbcType="INTEGER" property="enableStatus"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, dict_name, dict_type, remark, enable_status, del_flag, created_by, created_date, updated_by,
updated_date
</sql>
<select id="selectList" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where del_flag = 0
<if test="name != null and name != ''">
and dict_name LIKE CONCAT('%',#{name},'%')
</if>
<if test="type != null and type != ''">
and dict_type LIKE CONCAT('%',#{type},'%')
</if>
<if test="status != null">
and enable_status = #{status}
</if>
<if test="sDate != null and sDate != '' and eDate != null and eDate != ''">
and DATE_FORMAT(created_date, '%Y-%m-%d') &gt;= #{sDate}
and DATE_FORMAT(created_date, '%Y-%m-%d') &lt;= #{eDate}
</if>
order by id desc
</select>
<select id="selectAllDictType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where del_flag = 0
</select>
<select id="selectAllDictType2" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where del_flag = 0
</select>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where del_flag = 0
and id = #{id}
</select>
<select id="selectByType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where del_flag = 0
and dict_type = #{type}
</select>
<select id="selectByNameWithDeleted" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where dict_name = #{name}
</select>
<select id="selectByTypeWithDeleted" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_dict_type
where dict_type = #{type}
</select>
<update id="logicDeleteById">
update t_dict_type set del_flag = -1 where id = #{id}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8881"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-ne-shield-publiccenter"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-ne-shield-publiccenter"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-reportcenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-usercenter</artifactId>
<properties>
<kaptcha.version>0.0.9</kaptcha.version>
<shiro.version>1.6.0</shiro.version>
</properties>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-office</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--验证码-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--mybatis 逆向生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<!-- <phase>package</phase>-->
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>false</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/config/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.neshield", "cn.com.glsx.auth"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.neshield.common.exception;
import com.glsx.plat.exception.SystemMessage;
import lombok.Getter;
/**
* @author payu
*/
@Getter
public class UserCenterException extends RuntimeException {
private int errorCode = SystemMessage.FAILURE.getCode();
public UserCenterException(String message) {
super(message);
}
public UserCenterException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public static UserCenterException of(SystemMessage message) {
return new UserCenterException(message.getCode(), message.getMsg());
}
public UserCenterException(Throwable cause) {
super(cause);
}
public UserCenterException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.com.glsx.neshield.common.exception;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.ExceptionLevel;
import com.glsx.plat.exception.GlobalExceptionHandler;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.loggin.LogginConstants;
import com.glsx.plat.loggin.LogginStrategyFactory;
import feign.FeignException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
* 全局异常处理
*
* @author payu
*/
@Slf4j
@RestControllerAdvice
public class UserCenterExceptionHandler extends GlobalExceptionHandler {
@Autowired
private LogginStrategyFactory logginStrategyFactory;
@ExceptionHandler(UserCenterException.class)
public R handleAdminException(UserCenterException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.getErrorCode(), e.getMessage());
}
/**
* 引入Feign服务的话
*
* @param e
* @return
*/
@ExceptionHandler(FeignException.class)
public R handleFeignException(FeignException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.status(), e.getMessage());
}
/**
* Mybatis BindingException
*
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
public R handleBindingException(BindingException e) {
this.saveException(e, ExceptionLevel.fatal);
return R.error(e.getMessage());
}
@ExceptionHandler(value = MyBatisSystemException.class)
public R myBatisSystemException(MyBatisSystemException e, HttpServletRequest request) {
log.error("数据存储出错", e);
this.saveException(e, ExceptionLevel.fatal);
return SystemMessage.DATA_HANDLE_ERROR.result();
}
@ExceptionHandler(value = UnrecognizedPropertyException.class)
public R unrecognizedPropertyException(UnrecognizedPropertyException e) {
log.error("不能识别的字段", e);
this.saveException(e, ExceptionLevel.fatal);
return SystemMessage.ARGS_ERROR.result();
}
@SneakyThrows
@Async
@Override
protected void saveException(Exception e, ExceptionLevel level) {
// TODO: 2020/10/14 异常入库,对此方法进行aop处理
String logId = MDC.get(LogginConstants.MDC_LOG_DB_ID);
log.error("操作异常/失败ID:{}", MDC.get(LogginConstants.MDC_LOG_DB_ID));
logginStrategyFactory.getStrategy().updateLogStatus(logId, "失败");
MDC.clear();
}
}
package cn.com.glsx.neshield.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class BeansConfig {
/**
* 验证码
*
* @return
*/
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "4");
properties.put("kaptcha.textproducer.char.length", "4");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
/**
* 加密
*
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//加密方式
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//加密次数
hashedCredentialsMatcher.setHashIterations(8);
//存储散列后的密码是否为16进制
//hashedCredentialsMatcher.isStoredCredentialsHexEncoded();
return hashedCredentialsMatcher;
}
}
package cn.com.glsx.neshield.config;
import cn.com.glsx.auth.interceptor.WebRequestAuthorizeInterceptor;
import cn.com.glsx.auth.interceptor.WebFunctionPermissionInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* @author payu
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private WebRequestAuthorizeInterceptor authInterceptor;
@Resource
private WebFunctionPermissionInterceptor permissionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/")
.excludePathPatterns("/login")
.excludePathPatterns("/captcha")
.excludePathPatterns("/actuator/**")
.excludePathPatterns("/auth/**")
.excludePathPatterns("/api/**");
registry.addInterceptor(permissionInterceptor).addPathPatterns("/**");
}
}
package cn.com.glsx.neshield.modules;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.service.UserService;
import com.glsx.plat.core.web.R;
import com.glsx.plat.web.controller.AbstractController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author liuyf
* @Title BaseController.java
* @Package com.glsx.vasp.controller
* @Description
* @date 2019年10月24日 下午2:24:00
*/
@RestController
public class BaseController extends AbstractController {
@Resource
private UserService userService;
/**
* 这个给Spring Boot Admin探测用
*
* @return
*/
@GetMapping(value = "/")
public R index() {
return R.ok("You get it!");
}
/**
* 从session中获取当前用户
*
* @return
*/
@Override
public User getSessionUser() {
return userService.getByToken();
}
@Override
public Long getUserId() {
User user = getSessionUser();
if (user != null) {
return user.getId();
}
return null;
}
@Override
public String getAccount() {
User user = getSessionUser();
if (user != null) {
return user.getAccount();
}
return null;
}
}
package cn.com.glsx.neshield.modules;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.model.LoginBO;
import cn.com.glsx.neshield.modules.model.view.UserDTO;
import cn.com.glsx.neshield.modules.service.UserService;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.SnowFlake;
import com.glsx.plat.core.constant.BasicConstants;
import com.glsx.plat.core.enums.SysConstants;
import com.glsx.plat.core.web.R;
import com.glsx.plat.redis.utils.RedisUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @author payu
*/
@Slf4j
@RefreshScope
@RestController
public class LoginController {
@Value("${captcha.open}")
private Boolean captchaOpen;
@Value("${captcha.text:1111}")
private String captchaText;
@Resource
private RedisUtils redisUtils;
@Resource
private Producer producer;
@Autowired
private UserService userService;
@GetMapping("captcha")
public R captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
// response.setHeader("Cache-Control", "no-store, no-cache");
// response.setContentType("image/jpeg");
String captchaSerialNumber = SnowFlake.nextSerialNumber();
response.setHeader(BasicConstants.REQUEST_HEADERS_CAPTCHA, captchaSerialNumber);
//生成文字验证码
String text;
if (captchaOpen) {
text = producer.createText();
redisUtils.setex(Constants.KAPTCHA_SESSION_KEY + "_" + captchaSerialNumber, text, 60);
} else {
text = captchaText;
}
//生成图片验证码
BufferedImage image = producer.createImage(text);
//保存到 session,单机模式,集群会有问题
// request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
// ServletOutputStream out = response.getOutputStream();
// ImageIO.write(image, "jpg", out);
//输出流
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, "png", stream);
String imgBase64 = Base64.getEncoder().encodeToString(stream.toByteArray());
Map<String, String> captchaMap = new HashMap<>();
captchaMap.put("text", text);
captchaMap.put("captcha", imgBase64);
captchaMap.put(BasicConstants.REQUEST_HEADERS_CAPTCHA, captchaSerialNumber);
return R.ok().data(captchaMap);
}
/**
* 登录
*/
// @SysLog(module = "系统登录", action = OperateType.LOGIN, saveRequest = false)
@PostMapping(value = "/login")
public R login(@RequestBody @Valid LoginBO loginBO) {
verifyCaptcha(loginBO.getCaptcha(), loginBO.getCaptchaId());
User user = userService.findByAccount(loginBO.getAccount());
verify(user, loginBO.getPassword());
Map<String, Object> rtnMap = new HashMap<>();
String token = userService.createToken(user);
rtnMap.put("token", token);
UserDTO userInfo = userService.userInfo(user.getId());
rtnMap.put("user", userInfo);
return R.ok().data(rtnMap);
}
/**
* 验证码校验
*
* @param captcha
* @param captchaId
*/
protected void verifyCaptcha(String captcha, String captchaId) {
if (captchaOpen) {
// HttpServletRequest request = SessionUtils.request();
// // 从session中获取图形吗字符串
// Object kaptcha = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
// //删除缓存验证码
// request.getSession().removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String key = Constants.KAPTCHA_SESSION_KEY + "_" + captchaId;
String kaptcha = (String) redisUtils.get(key);
redisUtils.del(key);
// 校验
if (kaptcha == null || !kaptcha.equals(captcha)) {
throw new UserCenterException("验证码错误");
}
}
}
private void verify(User user, String inputPassword) {
//是否存在
if (user == null) {
throw new UserCenterException("账号或密码不正确");
}
//是否停用
if (!SysConstants.EnableStatus.enable.getCode().equals(user.getEnableStatus())) {
throw new UserCenterException("账号正在审核中或已停用");
}
//密码是否ok
boolean pwdFlag = userService.verifyPassword(user, inputPassword);
if (!pwdFlag) {
throw new UserCenterException("账号或密码不正确");
}
}
/**
* 登出
*/
@SysLog(module = "系统登出", action = OperateType.LOGOUT)
@GetMapping(value = "/logout")
public R logout() {
userService.removeToken();
return R.ok();
}
}
package cn.com.glsx.neshield.modules.api;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.MenuPermission;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.neshield.modules.service.UserService;
import com.glsx.plat.core.web.R;
import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils;
import com.glsx.plat.web.utils.SessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequestMapping(value = "/auth")
public class AuthApiController implements AuthFeignClient {
@Autowired
private UserService userService;
@Autowired
private JwtUtils<ComJwtUser> jwtUtils;
@Override
@GetMapping("/isLogin")
public R isLogin() {
String token = SessionUtils.request().getHeader(HttpHeaders.AUTHORIZATION);
boolean verifyFlag = jwtUtils.verifyToken(token);
return R.ok().data(verifyFlag);
}
@Override
@GetMapping("/getAuthUser")
public R getAuthUser() {
SyntheticUser authUser = userService.getSyntheticUser();
return R.ok().data(authUser);
}
@Override
@GetMapping("/getAuthDeptIds")
public R getAuthDeptIds() {
SyntheticUser authUser = userService.getSyntheticUser();
return R.ok().data(authUser.getVisibleDeptIds());
}
@Override
@GetMapping("/getAuthUserIds")
public R getAuthUserIds() {
SyntheticUser authUser = userService.getSyntheticUser();
return R.ok().data(authUser.getVisibleCreatorIds());
}
@Override
@GetMapping("/getPermMenus")
public R getPermMenus() {
SyntheticUser authUser = userService.getSyntheticUser();
List<MenuPermission> list = userService.getPermissionMenus(authUser);
return R.ok().data(list);
}
}
package cn.com.glsx.neshield.modules.api;
import cn.com.glsx.admin.api.UserCenterFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 微服务应用在网关中处理统一返回体
*
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "/api/user")
public class UserApiController implements UserCenterFeignClient {
}
package cn.com.glsx.neshield.modules.controller;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: taoyr
**/
@Slf4j
@RestController
@RequestMapping(value = "/department")
public class DepartmentController {
private final static String MODULE = "部门管理";
@GetMapping("/simplelist")
public R simpleList() {
return R.ok();
}
}
package cn.com.glsx.neshield.modules.controller;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.modules.BaseController;
import cn.com.glsx.neshield.modules.model.MenuModel;
import cn.com.glsx.neshield.modules.model.export.MenuExport;
import cn.com.glsx.neshield.modules.model.param.MenuBO;
import cn.com.glsx.neshield.modules.model.param.MenuSearch;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.MenuDTO;
import cn.com.glsx.neshield.modules.service.MenuService;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.office.excel.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
/**
* @author: taoyr
**/
@Slf4j
@RestController
@RequestMapping(value = "/menu")
public class MenuController extends BaseController {
private final static String MODULE = "菜单管理";
@Resource
private MenuService menuService;
@GetMapping("/search")
public R search(MenuSearch search) {
PageInfo<MenuDTO> pageInfo = menuService.search(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping("/children")
public R children(@RequestParam("parentId") Long parentId) {
List<MenuDTO> list = menuService.children(parentId);
return R.ok().data(list);
}
@GetMapping(value = "/export")
public void export(HttpServletResponse response, UserSearch search) throws Exception {
List<MenuExport> list = menuService.export(search);
EasyExcelUtils.writeExcel(response, list, "菜单_" + DateUtils.formatSerial(new Date()), "Sheet1", MenuExport.class);
}
/**
* 用户登录加载系统资源
*
* @return
*/
@GetMapping("/permtree")
public R getMenuPermTree() {
List<MenuModel> menuTree = menuService.getMenuTree(ShieldContextHolder.getRoleIds());
return R.ok().data(menuTree);
}
/**
* 子页面加载资源
*
* @return
*/
@GetMapping("/subtree")
public R getMenuSubtree(@RequestParam("parentId") Long parentId) {
List<MenuModel> menuTree = menuService.getMenuTreeByParentId(parentId, ShieldContextHolder.getRoleIds());
return R.ok().data(menuTree);
}
/**
* 新增、编辑角色时加载菜单树
*
* @param roleId
* @return
*/
@GetMapping("/checkedtree")
public R getMenuFullTree(@RequestParam(value = "roleId", required = false) Long roleId) {
List<MenuModel> menuTree = menuService.getMenuFullTreeWithChecked(ShieldContextHolder.getRoleIds(), roleId);
Set<Long> checkedIds = menuService.getMenuCheckedIds(roleId);
Map<String, Object> rtnMap = new HashMap<>();
rtnMap.put("menuTree", menuTree);
rtnMap.put("checkedIds", checkedIds);
return R.ok().data(rtnMap);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping("/add")
public R add(@RequestBody @Valid MenuBO menuBO) {
menuService.add(menuBO);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping("/edit")
public R edit(@RequestBody @Valid MenuBO menuBO) {
AssertUtils.isNull(menuBO.getId(), "ID不能为空");
menuService.edit(menuBO);
return R.ok();
}
@GetMapping("/info")
public R info(@RequestParam("menuId") Long id) {
MenuDTO menuDTO = menuService.getMenuById(id);
return R.ok().data(menuDTO);
}
// @RequireFunctionPermissions(permissionType = FunctionPermissionType.MENU_DELETE)
@SysLog(module = MODULE, action = OperateType.DELETE)
@GetMapping("/delete")
public R delete(@RequestParam("menuId") Long id) {
menuService.logicDeleteById(id);
return R.ok();
}
}
package cn.com.glsx.neshield.modules.controller;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.OrganizationBO;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import cn.com.glsx.neshield.modules.service.OrganizationService;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
/**
* @author: taoyr
**/
@Slf4j
@RestController
@RequestMapping(value = "/organization")
public class OrganizationController {
private final static String MODULE = "组织管理";
@Resource
private OrganizationService organizationService;
@Resource
private DepartmentService departmentService;
@GetMapping("/search")
public R search(OrganizationSearch search) {
search.setForPage(true);
search.setHasChild(true);
search.setHasUserNumber(false);
PageInfo<DepartmentDTO> pageInfo = departmentService.rootDepartmentList(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping("/children")
public R children(OrganizationSearch search) {
AssertUtils.isNull(search.getRootId(), "参数有误");
List<DepartmentDTO> list = organizationService.childrenList(search);
return R.ok().data(list);
}
@GetMapping("/orgtree")
public R orgTree(OrgTreeSearch search) {
List<? extends TreeModel> list = organizationService.orgTree(search);
return R.ok().data(list);
}
@GetMapping("/simplelist")
public R simpleList(Long rootId) {
List<DepartmentDTO> simpleList = organizationService.simpleList(rootId);
return R.ok().data(simpleList);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping("/add")
public R addOrganization(@RequestBody @Valid OrganizationBO orgBO) {
if (orgBO.getSuperiorId() == null) {
organizationService.addRootOrganization(orgBO);
} else {
organizationService.addNodeToOrganization(orgBO);
}
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping("/edit")
public R editOrganization(@RequestBody @Valid OrganizationBO orgBO) {
AssertUtils.isNull(orgBO.getId(), "参数有误");
organizationService.editOrganization(orgBO);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.DELETE)
@GetMapping("/delete")
public R deleteOrganization(@RequestParam("id") Long organizationId) {
organizationService.deleteOrganization(organizationId);
return R.ok();
}
@GetMapping("/info")
public R organizationInfo(@RequestParam("id") Long organizationId) {
DepartmentDTO departmentDTO = organizationService.organizationInfo(organizationId);
return R.ok().data(departmentDTO);
}
@GetMapping("/strategy")
public R rolePermission(OrgTreeSearch search) {
List<DepartmentDTO> dtoList = organizationService.permissionStrategy(search);
return R.ok().data(dtoList);
}
}
package cn.com.glsx.neshield.modules.controller;
import cn.com.glsx.admin.common.constant.UserConstants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.model.param.RoleBO;
import cn.com.glsx.neshield.modules.model.param.RoleSearch;
import cn.com.glsx.neshield.modules.model.view.RoleDTO;
import cn.com.glsx.neshield.modules.model.view.SimpleRoleDTO;
import cn.com.glsx.neshield.modules.service.RoleService;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static cn.com.glsx.admin.common.constant.UserConstants.RoleVisibility.onlyAdmin;
import static cn.com.glsx.admin.common.constant.UserConstants.adminRoleId;
/**
* @author: taoyr
**/
@Slf4j
@RestController
@RequestMapping(value = "/role")
public class RoleController {
private final static String MODULE = "角色管理";
@Autowired
private RoleService roleService;
@GetMapping("/search")
public R search(RoleSearch search) {
PageInfo<RoleDTO> pageInfo = roleService.search(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping("/simplelist")
public R simplelist() {
List<SimpleRoleDTO> list = roleService.simpleList();
return R.ok().data(list);
}
@GetMapping("/visibility")
public R visibility() {
List<UserConstants.RoleVisibility> vList = Arrays.asList(UserConstants.RoleVisibility.values());
List<Map<String, Object>> list = Lists.newArrayList();
vList.forEach(rv -> {
Map<String, Object> map = Maps.newHashMap();
map.put("code", rv.getCode());
map.put("value", rv.getValue());
if (ShieldContextHolder.isSuperAdmin()) {
list.add(map);
} else {
if (!onlyAdmin.getCode().equals(rv.getCode())) {
list.add(map);
}
}
});
return R.ok().data(list);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping("/add")
public R add(@RequestBody @Valid RoleBO roleBO) {
roleService.addRole(roleBO);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping("/edit")
public R edit(@RequestBody @Valid RoleBO roleBO) {
AssertUtils.isNull(roleBO.getRoleId(), "ID不能为空");
if (roleBO.getRoleId().equals(adminRoleId)) {
throw UserCenterException.of(SystemMessage.OPERATE_PERMISSION_DENIED);
}
roleService.editRole(roleBO);
return R.ok();
}
@GetMapping("/info")
public R info(@RequestParam("id") Long id) {
RoleDTO roleDTO = roleService.roleInfo(id);
return R.ok().data(roleDTO);
}
// @RequireFunctionPermissions(permissionType = FunctionPermissionType.ROLE_DELETE)
@SysLog(module = MODULE, action = OperateType.DELETE)
@GetMapping("/delete")
public R delete(@RequestParam("id") Long id) {
if (id.equals(adminRoleId)) {
throw UserCenterException.of(SystemMessage.OPERATE_PERMISSION_DENIED);
}
roleService.deleteRole(id);
return R.ok();
}
}
package cn.com.glsx.neshield.modules.controller;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "/tenant")
public class TenantController {
@Resource
private DepartmentService departmentService;
@GetMapping("/simplelist")
public R simpleList() {
OrganizationSearch search = new OrganizationSearch()
.setForPage(false)
.setHasChild(false)
.setHasUserNumber(false);
PageInfo<DepartmentDTO> pageInfo = departmentService.rootDepartmentList(search);
return R.ok().data(pageInfo.getList());
}
}
package cn.com.glsx.neshield.modules.controller;
import cn.com.glsx.admin.common.util.RegexUtil;
import cn.com.glsx.neshield.modules.BaseController;
import cn.com.glsx.neshield.modules.model.export.UserExport;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.SuperTreeModel;
import cn.com.glsx.neshield.modules.model.view.UserDTO;
import cn.com.glsx.neshield.modules.service.UserService;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.office.excel.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
* 单体应用Controller处理统一返回体
*
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {
private final static String MODULE = "用户管理";
@Resource
private UserService userService;
@GetMapping("/search")
public R search(UserSearch search) {
PageInfo<UserDTO> pageInfo = userService.search(search);
return R.ok().putPageData(pageInfo);
}
@GetMapping(value = "/export")
public void export(HttpServletResponse response, UserSearch search) throws Exception {
List<UserExport> list = userService.export(search);
EasyExcelUtils.writeExcel(response, list, "用户_" + DateUtils.formatSerial(new Date()), "Sheet1", UserExport.class);
}
@SysLog(module = MODULE, action = OperateType.ADD)
@PostMapping(value = "/add")
public R add(@RequestBody @Validated UserBO userBO) {
// User user = UserConverter.INSTANCE.bo2do(userBO);
// String password = userBO.getPassword();
// if (StringUtils.isBlank(password) || !RegexUtil.regexPwd(password)) {
// return R.error(SystemMessage.ARGS_ERROR.getCode(), "密码格式错误");
// }
AssertUtils.isNull(userBO.getPassword(), "密码不能为空");
userService.addUser(userBO);
return R.ok();
}
@SysLog(module = MODULE, action = OperateType.EDIT)
@PostMapping(value = "/edit")
public R edit(@RequestBody @Validated UserBO userBO) {
AssertUtils.isNull(userBO.getId(), "ID不能为空");
// User user = UserConverter.INSTANCE.bo2do(userBO);
userService.editUser(userBO);
return R.ok();
}
@GetMapping(value = "/info")
public R info(@RequestParam("id") Long id) {
UserDTO user = userService.userInfo(id);
return R.ok().data(user);
}
// @RequireFunctionPermissions(permissionType = FunctionPermissionType.USER_DELETE)
@SysLog(module = MODULE, action = OperateType.DELETE)
@GetMapping(value = "/delete")
public R delete(@RequestParam("id") Long id) {
userService.logicDeleteById(id);
return R.ok();
}
@GetMapping("/suitableSuperUsers")
public R suitableSuperUsers(@RequestParam("departmentId") Long departmentId) {
List<SuperTreeModel> superTreeModels = userService.suitableSuperUsers(departmentId);
return R.ok().data(superTreeModels);
}
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Department;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthDepartmentConverter {
AuthDepartmentConverter INSTANCE = Mappers.getMapper(AuthDepartmentConverter.class);
@Mappings(@Mapping(source = "id", target = "deptId"))
cn.com.glsx.auth.model.Department toAuthDepartment(Department department);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Menu;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthMenuConverter {
AuthMenuConverter INSTANCE = Mappers.getMapper(AuthMenuConverter.class);
@Mappings(@Mapping(source = "id", target = "menuId"))
cn.com.glsx.auth.model.Menu toAuthMentu(Menu menu);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.MenuPermission;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthMenuPermissionConverter {
AuthMenuPermissionConverter INSTANCE = Mappers.getMapper(AuthMenuPermissionConverter.class);
cn.com.glsx.auth.model.MenuPermission toAuthMenuPermission(MenuPermission permission);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Role;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthRoleConverter {
AuthRoleConverter INSTANCE = Mappers.getMapper(AuthRoleConverter.class);
@Mappings(@Mapping(source = "id", target = "roleId"))
cn.com.glsx.auth.model.Role toAuthRole(Role role);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Tenant;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthTenantConverter {
AuthTenantConverter INSTANCE = Mappers.getMapper(AuthTenantConverter.class);
@Mappings(@Mapping(source = "id", target = "tenantId"))
cn.com.glsx.auth.model.Tenant toAuthTenant(Tenant menu);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.UserGroup;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface AuthUserGroupConverter {
AuthUserGroupConverter INSTANCE = Mappers.getMapper(AuthUserGroupConverter.class);
@Mappings(@Mapping(source = "id", target = "groupId"))
cn.com.glsx.auth.model.UserGroup toAuthUserGroup(UserGroup group);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface DepartmentConverter {
DepartmentConverter INSTANCE = Mappers.getMapper(DepartmentConverter.class);
DepartmentDTO do2dto(Department department);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Menu;
import cn.com.glsx.neshield.modules.model.param.MenuBO;
import cn.com.glsx.neshield.modules.model.view.MenuDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface MenuConverter {
MenuConverter INSTANCE = Mappers.getMapper(MenuConverter.class);
MenuDTO do2dto(Menu menu);
Menu bo2do(MenuBO menuBO);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.Role;
import cn.com.glsx.neshield.modules.model.param.RoleBO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface RoleConverter {
RoleConverter INSTANCE = Mappers.getMapper(RoleConverter.class);
//RoleDTO do2dto(Role role);
@Mappings({
@Mapping(source = "roleId", target = "id"),
@Mapping(source = "roleName", target = "roleName"),
@Mapping(source = "remark", target = "remark"),
@Mapping(source = "rolePermissionType", target = "rolePermissionType"),
@Mapping(source = "roleVisibility", target = "roleVisibility"),
@Mapping(source = "enableStatus", target = "enableStatus"),
})
Role bo2do(RoleBO roleBO);
}
package cn.com.glsx.neshield.modules.converter;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.view.UserDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
/**
* 解耦dao与api的实体映射
* 字段名不一样,用@Mapping来处理
* https://github.com/mapstruct/mapstruct-examples
*
* @author payu
*/
@Mapper
public interface UserConverter {
UserConverter INSTANCE = Mappers.getMapper(UserConverter.class);
UserDTO do2dto(User user);
User dto2do(UserDTO userDTO);
UserBO do2bo(User user);
User bo2do(UserBO userBO);
}
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_department")
public class Department extends BaseEntity {
public Department(){
super();
}
public Department(boolean isAdd){
if (isAdd){
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 部门名称
*/
@Column(name = "department_name")
private String departmentName;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
/**
* 排序值
*/
@Column(name = "order_num")
private Integer orderNum;
/**
* 状态(1=启用 2=禁用)
*/
@Column(name = "enable_status")
private Integer enableStatus;
@Column(name = "is_root")
private Integer isRoot;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "t_menu")
@Data
@Accessors(chain = true)
public class Menu extends BaseEntity {
public Menu() {
super();
}
public Menu(boolean isAdd) {
if (isAdd) {
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 菜单no
*/
@Column(name = "menu_no")
private Long menuNo;
/**
* 菜单名
*/
@Column(name = "menu_name")
private String menuName;
/**
* 前端路由
*/
@Column(name = "front_route")
private String frontRoute;
/**
* 权限名称
*/
@Column(name = "permission_tag")
private String permissionTag;
/**
* 类型 1目录,2菜单,3按钮
*/
private Integer type;
/**
* 图标
*/
private String icon;
/**
* 父菜单id
*/
@Column(name = "parent_id")
private Long parentId;
/**
* 排序
*/
@Column(name = "order_num")
private Integer orderNum;
/**
* 状态 0=不显示 1=显示
*/
@Column(name = "enable_status")
private Integer enableStatus;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_permission")
public class MenuPermission extends BaseEntity {
/**
* 菜单权限标识
*/
@Column(name = "permission_tag")
private String permissionTag;
/**
* 接口路径
*/
@Column(name = "interface_url")
private String interfaceUrl;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_organization")
public class Organization extends BaseEntity {
public Organization(){
super();
}
public Organization(boolean isAdd){
if (isAdd){
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 上级id
*/
@Column(name = "superior_id")
private Long superiorId;
/**
* 下级id
*/
@Column(name = "sub_id")
private Long subId;
/**
* 深度(下级节点-上级节点层数)
*/
private Integer depth;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_role")
public class Role extends BaseEntity {
/**
* 角色名称
*/
@Column(name = "role_name")
private String roleName;
/**
* 角色权限类型 0=本人 1=本人及下属 2=本部门 3=本部门及下级部门 4=全部
*/
@Column(name = "role_permission_type")
private Integer rolePermissionType;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
/**
* 最大拥有用户数
*/
@Column(name = "max_user")
private Long maxUser;
/**
* 互斥角色集合
*/
@Column(name = "repel_roles")
private String repelRoles;
/**
* 备注
*/
@Column(name = "remark")
private String remark;
/**
* 角色可见度(0=共享,1=系统管理员,2=指定租户)
*/
@Column(name = "role_visibility")
private Integer roleVisibility;
/**
* 角色租户范围,逗号分割
*/
// @Column(name = "role_tenants")
// private String roleTenants;
@Column(name = "enable_status")
private Integer enableStatus;
public void setContextInfo(boolean isAdd) {
Date date = new Date();
if (isAdd) {
setCreatedBy(ShieldContextHolder.getUserId());
setCreatedDate(date);
}
setUpdatedBy(ShieldContextHolder.getUserId());
setUpdatedDate(date);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@Table(name = "t_role_menu")
@Accessors(chain = true)
public class RoleMenu extends BaseEntity {
public RoleMenu() {
super();
}
public RoleMenu(boolean isAdd) {
if (isAdd) {
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 角色id
*/
@Column(name = "role_id")
private Long roleId;
/**
* 菜单id
*/
@Column(name = "menu_id")
private Long menuNo;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Accessors(chain = true)
@Table(name = "t_role_tenant")
public class RoleTenant extends BaseEntity {
/**
* 角色id
*/
@Column(name = "role_id")
private Long roleId;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_tenant")
public class Tenant extends BaseEntity {
/**
* 租户名称
*/
@Column(name = "tenant_name")
private String tenantName;
public Tenant(){
super();
}
public Tenant(boolean isAdd){
if (isAdd){
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_user")
public class User extends BaseEntity {
public User() {
super();
}
public User(boolean isAdd) {
if (isAdd) {
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 手机号
*/
@Column(name = "phone_number")
private String phoneNumber;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
/**
* 部门id
*/
@Column(name = "department_id")
private Long departmentId;
/**
* 上级id
*/
@Column(name = "superior_id")
private Long superiorId;
/**
* 账户名
*/
@Column(name = "account")
private String account;
/**
* 头像
*/
@Column(name = "portrait")
private String portrait;
/**
* 邮箱
*/
@Column(name = "email")
private String email;
/**
* 性别
*/
@Column(name = "gender")
private Long gender;
/**
* 岗位
*/
@Column(name = "position")
private String position;
@Column(name = "enable_status")
private Integer enableStatus;
private String salt;
@Column(name = "is_admin")
private boolean isAdmin;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Table(name = "t_user_group")
public class UserGroup extends BaseEntity {
/**
* 用户组名称
*/
@Column(name = "user_group_name")
private String userGroupName;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
/**
* 开启状态
*/
@Column(name = "enableStatus")
private Integer enableStatus;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Table(name = "t_user_group_relation")
public class UserGroupRelation extends BaseEntity {
/**
* 用户id
*/
@Column(name = "user_id")
private Long userId;
/**
* 用户组id
*/
@Column(name = "user_group_id")
private Long userGroupId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Table(name = "t_user_group_role_relation")
public class UserGroupRoleRelation extends BaseEntity {
/**
* 用户组id
*/
@Column(name = "user_group_id")
private Long userGroupId;
/**
* 角色id
*/
@Column(name = "role_id")
private Long roleId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Table(name = "t_user_path")
public class UserPath extends BaseEntity {
public UserPath() {
super();
}
public UserPath(boolean isAdd) {
if (isAdd) {
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 上级用户
*/
@Column(name = "superior_id")
private Long superiorId;
/**
* 下级用户id
*/
@Column(name = "sub_id")
private Long subId;
/**
* 深度(下级节点-上级节点层数)
*/
private Integer depth;
/**
* 租户id
*/
@Column(name = "tenant_id")
private Long tenantId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.entity;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Accessors(chain = true)
@Data
@Entity
@Table(name = "t_user_role_relation")
public class UserRoleRelation extends BaseEntity {
public UserRoleRelation() {
super();
}
public UserRoleRelation(boolean isAdd) {
if (isAdd) {
SyntheticUser user = ShieldContextHolder.getUser();
this.setCreatedBy(user.getUserId());
this.setCreatedDate(new Date());
}
}
/**
* 用户id
*/
@Column(name = "user_id")
private Long userId;
/**
* 角色id
*/
@Column(name = "role_id")
private Long roleId;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.Department;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface DepartmentMapper extends CommonBaseMapper<Department> {
List<Department> selectDepartmentList(Department department);
List<Department> selectByIds(@Param("ids") List<Long> ids);
List<Department> selectAllNotDel();
Department selectById(@Param("id") Long departmentId);
int logicDeleteByIdList(@Param("ids") List<Long> ids);
/**
* 根据根组织标识和租户id获取根组织
*
* @param tenantId
* @return
*/
Department selectRootDepartmentByTenantId(@Param("tenantId") Long tenantId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.Menu;
import cn.com.glsx.neshield.modules.model.MenuModel;
import cn.com.glsx.neshield.modules.model.param.MenuSearch;
import cn.com.glsx.neshield.modules.model.param.MenuTreeSearch;
import cn.com.glsx.neshield.modules.model.view.MenuDTO;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface MenuMapper extends CommonBaseMapper<Menu> {
Menu selectById(Long id);
Menu selectByMenuNo(@Param("menuNo") Long menuNo);
List<MenuDTO> selectDTOList(MenuSearch search);
/**
* 根据条件获得菜单树-全部菜单
*
* @return
*/
List<MenuModel> selectMenuFullTree();
/**
* 根据条件获得菜单树-授权菜单
*
* @param search
* @return
*/
List<MenuModel> selectMenuPermTree(MenuTreeSearch search);
/**
* 获取角色菜单树
*
* @param parentNo
* @param roleIds
* @return
*/
List<MenuModel> selectMenuTreeByParentId(@Param("parentNo") Long parentNo, List<Long> roleIds);
/**
* 根据条件获得菜单
*
* @param roleIds
* @return
*/
List<Menu> selectList(@Param("roleIds") List<Long> roleIds);
/**
* 根据父菜单id获得子菜单列表
*
* @param parentNo
* @return
*/
List<Menu> selectByParentId(@Param("parentNo") Long parentNo);
/**
* 根据父菜单no获得子菜单列表
*
* @param parentNo
* @return
*/
List<Menu> selectByLikeParentNo(@Param("parentNo") Long parentNo);
/**
* 获取子菜单数量
*
* @param parentNo
* @return
*/
int selectChildrenCntByParentId(@Param("parentNo") Long parentNo);
/**
* 逻辑删除
*
* @param id
* @return
*/
@Deprecated
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.MenuPermission;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface MenuPermissionMapper extends CommonBaseMapper<MenuPermission> {
List<MenuPermission> selectByMenuIds(@Param("menuIds") List<Long> menuIds);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.Organization;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgSuperiorModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.OrganizationBO;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface OrganizationMapper extends CommonBaseMapper<Organization> {
/**
* 插入根节点路径
*
* @param organization
* @return
*/
int insertRootPath(Organization organization);
/**
* 插入闭包路径
*
* @param organization
* @return
*/
int insertOrganizationPath(Organization organization);
/**
* 删除闭包路径
*
* @param nodeId
* @return
*/
int deleteOrganizationPath(Long nodeId);
/**
* 获取父级id(含自己)
*
* @param search
* @return
*/
List<OrgSuperiorModel> selectSuperiorIdsByOrg(OrgTreeSearch search);
/**
* 获取组织机构
*
* @param search
* @return
*/
List<OrgModel> selectOrgList(OrgTreeSearch search);
/**
* 找到所有子节点
*
* @param organizationId
* @return
*/
List<Organization> selectByRootId(Long organizationId);
/**
* 找到根节点list
*
* @param subIds
* @return
*/
List<Organization> selectRootIdList(@Param("subIds") List<Long> subIds);
/**
* 找到根路径
*
* @param tenantId
* @return
*/
Organization selectRootPath(@Param("tenantId") Long tenantId);
/**
* 找到根路径
*
* @param subId
* @return
*/
Organization selectRootPathBySubId(@Param("subId") Long subId);
/**
* 得到上级节点
*
* @param organizationId
* @return
*/
Organization selectSuperiorOrganization(Long organizationId);
/**
* 逻辑删除
*
* @param subId
* @return
*/
int logicDeleteSelfBySubId(Long subId);
/**
* 删除所有
*
* @param organizationId
* @return
*/
int logicDeleteAllSubOrganization(Long organizationId);
/**
* 查找子节点列表
*
* @param organizationSearch
* @return
*/
List<Department> selectChildrenList(OrganizationSearch organizationSearch);
/**
* 查找确定深度的子节点列表
*
* @param departmentIds
* @return
*/
List<Organization> selectSubList(@Param("departmentIds") List<Long> departmentIds, @Param("depth") Integer depth);
/**
* 根据条件筛选符合的路径
*
* @param organizationBO
* @return
*/
List<Organization> selectList(OrganizationBO organizationBO);
/**
* @param rootId
* @param subId
* @return
*/
Organization selectRootByRootIdAndSubId(@Param("rootId") Long rootId, @Param("subId") Long subId);
List<Organization> selectAllSuperiorBySubId(@Param("subId") Long subId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.Role;
import cn.com.glsx.neshield.modules.model.param.RoleSearch;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface RoleMapper extends CommonBaseMapper<Role> {
Role selectById(@Param("id") Long id);
List<Role> selectList(RoleSearch search);
List<Role> selectVisibilityList(RoleSearch search);
/**
* 根据roleIds获取角色列表
*
* @param roleIds
* @return
*/
List<Role> selectRoleListByIds(@Param("roleIds") List<Long> roleIds);
/**
* 根据用户id查询角色列表
*
* @return
*/
List<Role> selectUserRoleList(@Param("userId") Long userId);
/**
* 逻辑删除
*
* @param id
* @return
*/
int logicDeleteById(Long id);
int selectCntByName(@Param("roleName") String roleName);
Role selectByName(@Param("roleName") String roleName);
List<Role> selectByVisibilityType(@Param("roleVisibility") Integer roleVisibility);
List<Long> selectRoleIdsByVisibilityType(@Param("roleVisibility") Integer roleVisibility);
List<Role> selectByTenantIds(@Param("tenantIds") List<Long> tenantIds);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.RoleMenu;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface RoleMenuMapper extends CommonBaseMapper<RoleMenu> {
List<RoleMenu> selectByRoleId(@Param("roleId") Long roleId);
List<RoleMenu> selectByMenuId(@Param("menuId") Long menuId);
List<Long> selectMenuIdsByRoleId(@Param("roleId") Long roleId);
List<Long> selectMenuIdsByRoleIds(@Param("roleIds") List<Long> roleIds);
List<Long> selectRoleIdsByMenuId(@Param("menuId") Long menuId);
/**
* 逻辑删除
*
* @param roleId
* @return
*/
int logicDelByRoleId(Long roleId);
/**
* 物理删除
*
* @param menuNo
* @return
*/
int deleteByMenuNo(Long menuNo);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.RoleTenant;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface RoleTenantMapper extends CommonBaseMapper<RoleTenant> {
List<RoleTenant> selectByRoleId(Long roleId);
List<Long> selectTenantIdsByRoleId(Long roleId);
List<Long> selectRoleIdsByTenantId(Long roleId);
List<RoleTenant> selectByTenantId(Long tenantId);
int logicDeleteByRoleId(Long roleId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.Tenant;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface TenantMapper extends CommonBaseMapper<Tenant> {
Tenant selectById(@Param("id") Long tenantId);
int logicDeleteById(Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.UserGroup;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserGroupMapper extends CommonBaseMapper<UserGroup> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.UserGroupRelation;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserGroupRelationMapper extends CommonBaseMapper<UserGroupRelation> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.UserGroupRoleRelation;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserGroupRoleRelationMapper extends CommonBaseMapper<UserGroupRoleRelation> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentCount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper extends CommonBaseMapper<User> {
User selectById(@Param("id") Long id);
List<User> selectByDepartmentId(@Param("departmentId") Long departmentId);
List<User> selectExcludeUserIdByDepartmentId(@Param("departmentId") Long departmentId, @Param("userId") Long userId);
User selectByAccount(@Param("account") String username);
int selectCntByAccount(@Param("account") String username);
List<User> selectList(UserSearch search);
Integer countByCriterial(UserBO userBO);
List<DepartmentCount> countDepartmentsUser(@Param("departmentIds") List<Long> departmentIds);
List<User> selectDepartmentsSubordinate(UserSearch search);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.UserPath;
import cn.com.glsx.neshield.modules.model.view.DepartmentUserCount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserPathMapper extends CommonBaseMapper<UserPath> {
List<DepartmentUserCount> selectSubordinateDepartmentList(Long userId);
List<UserPath> selectUserSubordinateList(Long userId);
/**
* 插入根节点路径
*
* @param userPath
* @return
*/
int insertRootPath(UserPath userPath);
/**
* 插入闭包路径
*
* @param userPath
* @return
*/
int insertUserPath(UserPath userPath);
/**
* 找到根路径
*
* @param tenantId
* @return
*/
UserPath selectRootPath(@Param("tenantId") Long tenantId);
/**
* 找到根路径
*
* @param subId
* @return
*/
UserPath selectRootPathBySubId(@Param("subId") Long subId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.mapper;
import cn.com.glsx.neshield.modules.entity.UserRoleRelation;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserRoleRelationMapper extends CommonBaseMapper<UserRoleRelation> {
/**
* 获取用户角色列表
*
* @param relation
* @return
*/
List<UserRoleRelation> selectUserRoleRelationList(UserRoleRelation relation);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class LoginBO {
@NotBlank
private String account;
@NotBlank
private String password;
private String captcha;
private String captchaId;
}
package cn.com.glsx.neshield.modules.model;
import lombok.Data;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
public class MenuModel implements Serializable {
private Long menuNo;
private String menuName;
private Long parentId;
private Integer type;
private String icon;
private String frontRoute;
private Integer orderNum;
private boolean hasChildren;
private boolean checked;
}
package cn.com.glsx.neshield.modules.model;
import com.glsx.plat.common.model.TreeModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author: taoyr
**/
public class MenuTreeModel implements TreeModel<MenuModel> {
protected MenuModel menu;
protected List<TreeModel> children = new ArrayList<>();
public MenuTreeModel(MenuModel menu) {
this.menu = menu;
}
@Override
public Long getId() {
return menu.getMenuNo();
}
@Override
public Long getParentId() {
return menu.getParentId();
}
@Override
public String getLabel() {
return menu.getMenuName();
}
@Override
public Integer getDepth() {
return null;
}
@Override
public Integer getOrder() {
return menu.getOrderNum();
}
@Override
public boolean checked() {
return menu.isChecked();
}
@Override
public MenuModel getOrigin() {
return menu;
}
@Override
public List getChildren() {
return children;
}
@Override
public void setChildren(List data) {
List<MenuModel> menuModelList = (List<MenuModel>) data;
Collections.sort(menuModelList, Comparator.comparing(MenuModel::getOrderNum));
this.children = data;
}
}
package cn.com.glsx.neshield.modules.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Data
public class OrgModel {
private Long orgId;
private String orgName;
private Long parentId;
private Long tenantId;
@JsonIgnore
private Integer depth;
@JsonIgnore
private Integer userNumber;
@JsonIgnore
private Integer orderNum;
public Integer getUserNumber() {
return userNumber == null ? 0 : userNumber;
}
}
package cn.com.glsx.neshield.modules.model;
import lombok.Data;
@Data
public class OrgSuperiorModel {
private Long orgId;
private String superiorIds;
}
package cn.com.glsx.neshield.modules.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.glsx.plat.common.model.TreeModel;
import java.util.ArrayList;
import java.util.List;
public class OrgTreeModel implements TreeModel<OrgModel> {
protected OrgModel org;
private Integer userNumber;
private List<TreeModel> children = new ArrayList<>();
public OrgTreeModel(OrgModel org) {
this.org = org;
this.userNumber = org.getUserNumber();
}
@Override
public Long getId() {
return org.getOrgId();
}
@Override
public Long getParentId() {
return org.getParentId();
}
@Override
public String getLabel() {
return org.getOrgName();
}
@Override
public Integer getDepth() {
return org.getDepth();
}
@JsonIgnore
@Override
public Integer getOrder() {
return org.getOrderNum();
}
public Integer getUserNumber() {
return userNumber;
}
public void setUserNumber(Integer userNumber) {
this.userNumber = userNumber;
}
@Override
public boolean checked() {
return false;
}
@Override
public OrgModel getOrigin() {
return org;
}
@Override
public List<TreeModel> getChildren() {
return children;
}
@Override
public void setChildren(List data) {
this.children = data;
}
}
package cn.com.glsx.neshield.modules.model.export;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class MenuExport {
@ExcelIgnore
private Long id;
@ExcelProperty(value = "菜单名称", index = 0)
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "创建时间", index = 1)
private Date createdDate;
}
package cn.com.glsx.neshield.modules.model.export;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class UserExport {
@ExcelIgnore
private Long id;
@ExcelProperty(value = "用户名", index = 0)
private String username;
@ExcelProperty(value = "手机号码", index = 1)
private String phoneNumber;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "创建时间", index = 2)
private Date createdDate;
}
package cn.com.glsx.neshield.modules.model.param;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class MenuBO implements Serializable {
private Long id;
private Integer type;
private Long parentId;
private String menuName;
private String permissionTag;
private String frontRoute;
private Integer orderNum;
private Integer enableStatus;
private String icon;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.hutool.db.Page;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class MenuSearch extends Page {
private String name;
private Long parentId;
private Integer enableStatus;
}
package cn.com.glsx.neshield.modules.model.param;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.List;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class MenuTreeSearch {
private List<Long> roleIds;
private List<Long> menuIds;
private List<Long> menuNos;
private List<Integer> menuTypes;
}
package cn.com.glsx.neshield.modules.model.param;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Collection;
/**
* @author payu
*/
@Data
@Accessors(chain = true)
public class OrgTreeSearch {
private Long tenantId;
private Long orgId;
private String orgName;
private Collection<Long> orgIds;
private Integer rolePermissionType;
}
package cn.com.glsx.neshield.modules.model.param;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.List;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class OrganizationBO {
private Long id;
private String departmentName;
private Long superiorId;
private Integer orderNum;
private Integer enableStatus;
private List<Long> subIdList;
private List<Long> superiorIdList;
private Integer biggerDepth;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.hutool.db.Page;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class OrganizationListParam extends Page implements Serializable {
private Long organizationId;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.hutool.db.Page;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author taoyr
*/
@Data
@Accessors(chain = true)
public class OrganizationSearch extends Page {
private boolean forPage;
private String orgName;
private Integer enableStatus;
private Long rootId;
private boolean hasChild;
private boolean hasUserNumber;
}
package cn.com.glsx.neshield.modules.model.param;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;
/**
* @author taoyr
*/
@Data
@Accessors(chain = true)
public class RoleBO implements Serializable {
private Long roleId;
@NotBlank
@Size(max = 50)
private String roleName;
private String remark;
//数据权限(0=本人 1=本人及下属 2=本部门 3=本部门及下级部门 4=全部)
@NotNull
private Integer rolePermissionType;
//角色租户可见度(0=共享,1=系统管理员,2=指定租户)
@NotNull
private Integer roleVisibility;
//可见租户id列表
private String roleTenants;
//状态(1正常 ,2停用)
@NotNull
private Integer enableStatus;
//选中菜单列表
private List<Long> menuIdList;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.hutool.db.Page;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author payu
*/
@Data
@Accessors(chain = true)
public class RoleSearch extends Page {
private String roleName;
private Integer enableStatus;
private Long tenantId;
private Integer roleVisibility;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.com.glsx.admin.common.util.RegexUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.List;
/**
* @author payu
*/
@Data
@Accessors(chain = true)
public class UserBO {
private Long id;
@Size(min = 5, max = 50)
@NotBlank
private String account;
/**
* 部门id
*/
@NotNull
private Long departmentId;
/**
* 上级id
*/
private Long superiorId;
@Size(min = 2, max = 50)
@NotBlank
private String username;
private String password;
@NotNull
private Long roleId;
@NotBlank
@Pattern(regexp = RegexUtil.mobileRegex, message = "手机号码格式有误")
private String phoneNumber;
private String email;
private Long gender;
/**
* 岗位
*/
private String position;
@NotNull
private Integer enableStatus;
private String remark;
private Long tenantId;
private List<Long> departmentIds;
}
package cn.com.glsx.neshield.modules.model.param;
import cn.hutool.db.Page;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.List;
/**
* @author payu
*/
@Data
@Accessors(chain = true)
public class UserSearch extends Page {
private String searchField;
private Long userId;
private Integer userStatus;
private Long departmentId;
private List<Long> departmentIdList;
}
package cn.com.glsx.neshield.modules.model.view;
import lombok.Data;
/**
* @author taoyr
*/
@Data
public class DepartmentCount {
private Long departmentId;
private Integer userNumber;
}
package cn.com.glsx.neshield.modules.model.view;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Date;
@Accessors(chain = true)
@Data
public class DepartmentDTO {
private Long id;
/**
* 部门名称
*/
private String departmentName;
/**
* 租户id
*/
private Long tenantId;
/**
* 上级id
*/
private Long superiorId;
private String superiorName;
/**
* 排序值
*/
private Integer orderNum;
/**
* 状态(1=启用 2=禁用)
*/
private Integer enableStatus;
private Integer isRoot;
private boolean hasChildren;
/**
* 用户数
*/
private Integer userNumber;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.neshield.modules.model.view;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author taoyr
*/
@Data
@Accessors(chain = true)
public class DepartmentUserCount {
private Long departmentId;
private Integer userNumber;
}
package cn.com.glsx.neshield.modules.model.view;
import lombok.Data;
@Data
public class MenuDTO {
private Long id;
private Long menuNo;
private String menuName;
private String frontRoute;
private String permissionTag;
private Integer type;
private String icon;
/**
* 父级物理主键id
*/
private Long ppId;
/**
* 父级菜单编号menuNo
*/
private Long parentId;
private String parentName;
private boolean hasChildren;
private Integer orderNum;
private Integer enableStatus;
}
package cn.com.glsx.neshield.modules.model.view;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class OrganizationListView implements Serializable {
private boolean hasChild;
private String organizationName;
private Integer orderNum;
private Integer enableStatus;
private String createDate;
}
package cn.com.glsx.neshield.modules.model.view;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class RoleDTO {
private Long id;
/**
* 角色名称
*/
private String roleName;
/**
* 角色权限类型 0=本人 1=本人及下属 2=本部门 3=本部门及下级部门 4=全部
*/
private Integer rolePermissionType;
/**
* 角色最大拥有用户数
*/
private Long maxUser;
/**
* 备注
*/
private String remark;
/**
* 角色可见度(0=共享,1=系统管理员,2=指定租户)
*/
private Integer roleVisibility;
/**
* 角色可见租户
*/
private String roleTenants;
private Integer enableStatus;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
}
package cn.com.glsx.neshield.modules.model.view;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
* @author payu
*/
@Setter
@Getter
@Accessors(chain = true)
public class SimpleRoleDTO {
private Long roleId;
private String roleName;
}
package cn.com.glsx.neshield.modules.model.view;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
/**
* @author taoyr
*/
@Accessors(chain = true)
@Data
public class SuperTreeModel implements Serializable {
private Long id;
private String label;
private Integer order = 0;
private boolean isRoot;
private List<SuperTreeModel> children;
private boolean disabled;
}
package cn.com.glsx.neshield.modules.model.view;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @author payu
*/
@Data
public class UserDTO {
private Long id;
private String account;
private String username;
private String departmentName;
private Integer deptDepth;
private String phoneNumber;
/**
* 部门id
*/
private Long departmentId;
/**
* 上级id
*/
private Long superiorId;
/**
* 邮箱
*/
private String email;
/**
* 性别
*/
private Long gender;
/**
* 岗位
*/
private String position;
private Integer enableStatus;
private Long roleId;
private String roleName;
private String superiorName;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.Organization;
import cn.com.glsx.neshield.modules.entity.Role;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.*;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentCount;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.model.view.DepartmentUserCount;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static cn.com.glsx.admin.common.constant.UserConstants.RolePermitCastType.*;
/**
* @author: taoyr
**/
@Service
public class DepartmentService {
@Resource
private DepartmentMapper departmentMapper;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private RoleMapper roleMapper;
@Resource
private UserService userService;
@Resource
private UserPathMapper userPathMapper;
@Resource
private UserMapper userMapper;
/**
* 获取当前用户所拥有的部门权限
*
* @return
*/
public List<Department> getCurrentUserDepartment() {
Long roleId = ShieldContextHolder.getRoleId();
Long userId = ShieldContextHolder.getUserId();
return getRoleDepartment(userId, roleId);
}
/**
* 获取用户所拥有的部门权限
*
* @param userId
* @return
*/
public List<Department> getUserDepartment(Long userId) {
List<Role> roles = roleMapper.selectUserRoleList(userId);
if (CollectionUtils.isEmpty(roles)) {
return Lists.newArrayList();
}
return getRoleDepartment(userId, roles.get(0).getId());
}
public List<Department> getRoleDepartment(Long userId, Long roleId) {
List<Department> departmentList = Lists.newArrayList();
Role role = roleMapper.selectById(roleId);
if (role == null) {
return departmentList;
}
if (oneself.getCode().equals(role.getRolePermissionType())) {
User user = userMapper.selectById(userId);
Long departmentId = user.getDepartmentId();
Department department = departmentMapper.selectById(departmentId);
departmentList.add(department);
return departmentList;
} else if (all.getCode().equals(role.getRolePermissionType())) {
return departmentMapper.selectAllNotDel();
} else if (selfDepartment.getCode().equals(role.getRolePermissionType())) {
User user = userMapper.selectById(userId);
Long departmentId = user.getDepartmentId();
Department department = departmentMapper.selectById(departmentId);
departmentList.add(department);
return departmentList;
} else if (subDepartment.getCode().equals(role.getRolePermissionType())) {
User user = userMapper.selectById(userId);
Long departmentId = user.getDepartmentId();
List<Organization> organizationList = organizationMapper.selectByRootId(departmentId);
List<Long> departmentIds = organizationList.stream().map(Organization::getSubId).collect(Collectors.toList());
return departmentMapper.selectByIds(departmentIds);
} else if (subordinate.getCode().equals(role.getRolePermissionType())) {
List<DepartmentUserCount> departmentUserCountList = userPathMapper.selectSubordinateDepartmentList(userId);
List<Long> departmentIdList = departmentUserCountList.stream().map(DepartmentUserCount::getDepartmentId).collect(Collectors.toList());
return departmentMapper.selectByIds(departmentIdList);
} else {
return departmentList;
}
}
public Department getDepartmentById(Long departmentId) {
return departmentMapper.selectById(departmentId);
}
/**
* 根部门列表
*
* @param search
* @return
*/
public PageInfo<DepartmentDTO> rootDepartmentList(OrganizationSearch search) {
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
List<Department> rootList = Lists.newArrayList();
Page page = null;
if (!ShieldContextHolder.isRoleAdmin() && !all.getCode().equals(rolePermissionType)) {
//只能看自己公司的
Long tenantId = ShieldContextHolder.getTenantId();
if (search.isForPage()) {
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
}
Department department = departmentMapper.selectRootDepartmentByTenantId(tenantId);
if (department != null) {
rootList.add(department);
}
} else {
Department department = new Department()
.setIsRoot(Constants.IS_ROOT_DEPARTMENT)
.setEnableStatus(search.getEnableStatus())
.setDepartmentName(search.getOrgName());
if (search.isForPage()) {
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
}
rootList = departmentMapper.selectDepartmentList(department);
}
List<DepartmentDTO> departmentDTOList = getDepartmentAssembled(rootList, search.isHasChild(), search.isHasUserNumber());
PageInfo<DepartmentDTO> pageInfo = new PageInfo<>(departmentDTOList);
if (search.isForPage()) {
pageInfo.setPages(page.getPages());//总页数
pageInfo.setTotal(page.getTotal());//总条数
}
return pageInfo;
}
/**
* 封装部门数据
*
* @param departmentList
* @param hasChild
* @param hasUserNumber
* @return
*/
public List<DepartmentDTO> getDepartmentAssembled(List<Department> departmentList, final boolean hasChild, final boolean hasUserNumber) {
List<Long> departmentIds = departmentList.stream().map(Department::getId).collect(Collectors.toList());
List<DepartmentDTO> departmentDTOList = departmentList.stream().map(dep -> {
DepartmentDTO departmentDTO = new DepartmentDTO();
BeanUtils.copyProperties(dep, departmentDTO);
return departmentDTO;
}
).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(departmentIds)) {
if (hasChild) {
List<Organization> organizationList = organizationMapper.selectSubList(departmentIds, 1);
Map<Long, List<Long>> subOrganizationMap = organizationList.stream().collect(Collectors.toMap(Organization::getSuperiorId, org -> Lists.newArrayList(org.getSubId()),
(List<Long> newValueList, List<Long> oldValueList) -> {
oldValueList.addAll(newValueList);
return oldValueList;
}));
departmentDTOList.forEach(dep -> dep.setHasChildren(subOrganizationMap.get(dep.getId()) != null));
}
if (hasUserNumber) {
Map<Long, Integer> recursiveDepartmentUser = countRecursiveDepartmentUser(departmentIds);
departmentDTOList.forEach(dep -> {
Integer number = recursiveDepartmentUser.get(dep.getId());
dep.setUserNumber(number == null ? 0 : number);
});
}
}
return departmentDTOList;
}
/**
* 统计部门及下级部门用户数 (批量)
*
* @param departmentIds
* @return
*/
public Map<Long, Integer> countRecursiveDepartmentUser(List<Long> departmentIds) {
HashMap<Long, Integer> departmentUserMap = Maps.newHashMap();
//这里只得到存在下级的组织
List<Organization> allSubList = organizationMapper.selectSubList(departmentIds, null);
Map<Long, List<Long>> departmentSubIdListMap = allSubList.stream().collect(Collectors.groupingBy(Organization::getSuperiorId))
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(Organization::getSubId)
.collect(Collectors.toList())));
//加上没有下级的组织
departmentIds.forEach(item -> {
if (!departmentSubIdListMap.containsKey(item)) {
departmentSubIdListMap.put(item, Lists.newArrayList());
}
});
List<Long> subDepartmentIdList = allSubList.stream().map(Organization::getSubId).distinct().collect(Collectors.toList());
List<DepartmentCount> departmentCountList = this.countDepartmentUserNumber(subDepartmentIdList);
Map<Long, Integer> departmentUserNumberMap = departmentCountList.stream().collect(Collectors.toMap(DepartmentCount::getDepartmentId, DepartmentCount::getUserNumber));
for (Map.Entry<Long, List<Long>> entry : departmentSubIdListMap.entrySet()) {
Long parentId = entry.getKey();
List<Long> subIdList = entry.getValue();
if (!subIdList.contains(parentId)) {
subIdList.add(parentId);
}
Integer departmentUserNumber = 0;
for (Long subId : subIdList) {
if (departmentUserNumberMap.get(subId) != null) {
departmentUserNumber += departmentUserNumberMap.get(subId);
}
}
departmentUserMap.put(entry.getKey(), departmentUserNumber);
}
return departmentUserMap;
}
/**
* 统计部门及下级部门用户数
*
* @param departmentId
* @return
*/
public Integer countRecursiveDepartmentUser(Long departmentId) {
List<Organization> subList = organizationMapper.selectSubList(Lists.newArrayList(departmentId), null);
List<Long> subDepartmentIdList = subList.stream().map(Organization::getSubId).distinct().collect(Collectors.toList());
List<DepartmentCount> departmentCountList = this.countDepartmentUserNumber(subDepartmentIdList);
Map<Long, Integer> departmentUserNumberMap = departmentCountList.stream().collect(Collectors.toMap(DepartmentCount::getDepartmentId, DepartmentCount::getUserNumber));
Integer departmentUserNumber = 0;
for (Map.Entry<Long, Integer> entry : departmentUserNumberMap.entrySet()) {
Integer userNumber = entry.getValue();
departmentUserNumber += userNumber;
}
return departmentUserNumber;
}
public List<DepartmentCount> countDepartmentUserNumber(List<Long> departmentIdList) {
return userMapper.countDepartmentsUser(departmentIdList);
}
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.admin.common.enums.MenuType;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.converter.MenuConverter;
import cn.com.glsx.neshield.modules.entity.Menu;
import cn.com.glsx.neshield.modules.entity.MenuPermission;
import cn.com.glsx.neshield.modules.entity.RoleMenu;
import cn.com.glsx.neshield.modules.mapper.MenuMapper;
import cn.com.glsx.neshield.modules.mapper.MenuPermissionMapper;
import cn.com.glsx.neshield.modules.mapper.RoleMenuMapper;
import cn.com.glsx.neshield.modules.model.MenuModel;
import cn.com.glsx.neshield.modules.model.MenuTreeModel;
import cn.com.glsx.neshield.modules.model.export.MenuExport;
import cn.com.glsx.neshield.modules.model.param.MenuBO;
import cn.com.glsx.neshield.modules.model.param.MenuSearch;
import cn.com.glsx.neshield.modules.model.param.MenuTreeSearch;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.MenuDTO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.glsx.plat.redis.utils.RedisUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import static cn.com.glsx.admin.common.constant.RedisConstants.FIVE_SECONDS;
import static cn.com.glsx.admin.common.constant.RedisConstants.MENU_NO_LOCK;
/**
* @author: taoyr
**/
@Slf4j
@Service
public class MenuService {
@Resource
private MenuMapper menuMapper;
@Resource
private RoleMenuMapper roleMenuMapper;
@Resource
private MenuPermissionMapper menuPermissionMapper;
@Autowired
private RedisUtils redisUtils;
public PageInfo<MenuDTO> search(MenuSearch search) {
Page page = null;
//查子菜单数据不分页
if (Objects.isNull(search.getParentId())) {
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
} else {
page = PageHelper.startPage(1, Short.MAX_VALUE);
}
List<MenuDTO> menuDTOList = menuMapper.selectDTOList(search);
menuDTOList.forEach(m -> {
int cnt = menuMapper.selectChildrenCntByParentId(m.getMenuNo());
m.setHasChildren(cnt > 0);
setParentMenuInfo(m);
});
PageInfo<MenuDTO> pageInfo = new PageInfo<>(menuDTOList);
pageInfo.setPages(page.getPages());//总页数
pageInfo.setTotal(page.getTotal());//总条数
return pageInfo;
}
public List<MenuExport> export(UserSearch search) {
return Lists.newArrayList();
}
public List<MenuDTO> children(Long parentId) {
List<Menu> menuList = menuMapper.selectByParentId(parentId);
List<MenuDTO> list = new ArrayList<>(menuList.size());
for (Menu menu : menuList) {
MenuDTO menuDTO = MenuConverter.INSTANCE.do2dto(menu);
int cnt = menuMapper.selectChildrenCntByParentId(menuDTO.getMenuNo());
menuDTO.setHasChildren(cnt > 0);
setParentMenuInfo(menuDTO);
list.add(menuDTO);
}
return list;
}
private void setParentMenuInfo(MenuDTO menuDTO) {
if (menuDTO.getParentId() != 0L) {
Menu pMenu = menuMapper.selectByMenuNo(menuDTO.getParentId());
if (pMenu != null) {
menuDTO.setPpId(pMenu.getId());
menuDTO.setParentName(pMenu.getMenuName());
}
}
}
/**
* 获取菜单树-全部菜单
*
* @param roleIds
* @return
*/
public List<MenuModel> getMenuFullTreeWithChecked(List<Long> roleIds, Long editRoleId) {
List<MenuModel> modelList = Lists.newArrayList();
//当前登录用户所拥有的权限
if (ShieldContextHolder.isSuperAdmin()) {
modelList = menuMapper.selectMenuFullTree();
} else {
modelList = menuMapper.selectMenuPermTree(new MenuTreeSearch().setRoleIds(roleIds).setMenuTypes(MenuType.getAllTypes()));
}
//被编辑角色的权限,editRoleId==null为新增角色时查询
if (editRoleId != null) {
List<MenuModel> permMenuList = menuMapper.selectMenuPermTree(new MenuTreeSearch().setRoleIds(Lists.newArrayList(editRoleId)).setMenuTypes(MenuType.getAllTypes()));
modelList.forEach(mm -> {
for (MenuModel mm2 : permMenuList) {
if (mm.getMenuNo().equals(mm2.getMenuNo())) {
mm.setChecked(true);
break;
}
}
});
}
List<MenuTreeModel> menuTreeModelList = modelList.stream().map(MenuTreeModel::new).collect(Collectors.toList());
List menuTree = TreeModelUtil.fastConvertByRootId(menuTreeModelList, 0L);
Collections.sort(menuTree, Comparator.comparing(MenuTreeModel::getOrder));
return menuTree;
}
public Set<Long> getMenuCheckedIds(Long editRoleId) {
List<MenuModel> permMenuList = menuMapper.selectMenuPermTree(new MenuTreeSearch().setRoleIds(Lists.newArrayList(editRoleId)).setMenuTypes(MenuType.getAllTypes()));
Set<Long> permMenuIds = permMenuList.stream().map(MenuModel::getMenuNo).collect(Collectors.toSet());
//info(permMenuIds.toString());
permMenuList.forEach(pmm -> {
//按钮直接添加
if (!MenuType.BUTTON.getCode().equals(pmm.getType())) {
List<Menu> menuList = menuMapper.selectByParentId(pmm.getParentId());
List<Long> menuIds = menuList.stream().map(Menu::getMenuNo).distinct().collect(Collectors.toList());
boolean flag = permMenuIds.containsAll(menuIds);
//log.info(pmm.getMenuNo() + " " + pmm.getParentId() + " " + menuIds.toString() + " " + flag);
if (!flag) {
permMenuIds.remove(pmm.getParentId());
}
}
});
return permMenuIds;
}
/**
* 获取菜单树-带权限
*
* @param roleIds
* @return
*/
public List<MenuModel> getMenuTree(List<Long> roleIds) {
List<MenuModel> modelList = menuMapper.selectMenuPermTree(
new MenuTreeSearch().setRoleIds(roleIds).setMenuTypes(Lists.newArrayList(MenuType.DIRECTORY.getCode(), MenuType.MENU.getCode()))
);
List<MenuTreeModel> menuTreeModelList = modelList.stream().map(MenuTreeModel::new).collect(Collectors.toList());
List menuTree = TreeModelUtil.fastConvertByRootId(menuTreeModelList, 0L);
Collections.sort(menuTree, Comparator.comparing(MenuTreeModel::getOrder));
return menuTree;
}
/**
* 获取菜单树by父级id
*
* @param parentId
* @param roleIds
* @return
*/
public List<MenuModel> getMenuTreeByParentId(Long parentId, List<Long> roleIds) {
List<MenuModel> modelList = menuMapper.selectMenuTreeByParentId(parentId, roleIds);
List<MenuTreeModel> menuTreeModelList = modelList.stream().map(MenuTreeModel::new).collect(Collectors.toList());
List menuTree = TreeModelUtil.fastConvertByRootId(menuTreeModelList, parentId);
Collections.sort(menuTree, Comparator.comparing(MenuTreeModel::getOrder));
return menuTree;
}
/**
* 获取菜单列表
*
* @param roleIds
* @return
*/
public List<Menu> getMenuList(List<Long> roleIds) {
return menuMapper.selectList(roleIds);
}
/**
* 根据父菜单号生成菜单号
* 根菜单的父菜单号为null
*
* @return
*/
public Long generateMenuNo(Long parentMenuNo) {
String releaseId = String.valueOf(System.currentTimeMillis());
boolean setnx = redisUtils.lock(MENU_NO_LOCK, releaseId, FIVE_SECONDS);
if (!setnx) {
throw new UserCenterException(600, "系统繁忙,请稍后重试");
}
String menuNo;
try {
if (parentMenuNo == null || parentMenuNo == 0L) {
//起始编号
int startNo = 100;
List<Menu> menus = menuMapper.selectByParentId(0L);
long maxMenuNo = menus.stream().map(Menu::getMenuNo).max(Long::compareTo).orElse(0L);
maxMenuNo = maxMenuNo + startNo;
if (maxMenuNo <= startNo) {
menuNo = String.valueOf(maxMenuNo + 1);
} else {
menuNo = String.valueOf(maxMenuNo);
}
} else {
List<Menu> menus = menuMapper.selectByParentId(parentMenuNo);
if (CollectionUtils.isEmpty(menus)) {
menuNo = parentMenuNo + "01";
} else {
Long maxMenuNo = menus.stream().map(Menu::getMenuNo).max(Long::compareTo).orElse(0L);
long menuNoLong = maxMenuNo + 1;
menuNo = String.valueOf(menuNoLong);
}
}
} finally {
redisUtils.unlock(MENU_NO_LOCK, releaseId);
}
return Long.parseLong(menuNo);
}
public MenuDTO getMenuById(Long id) {
Menu menu = menuMapper.selectById(id);
MenuDTO menuDTO = MenuConverter.INSTANCE.do2dto(menu);
if (menuDTO.getParentId() != 0L) {
Menu pMenu = menuMapper.selectByMenuNo(menuDTO.getParentId());
if (pMenu != null) {
menuDTO.setPpId(pMenu.getId());
menuDTO.setParentName(pMenu.getMenuName());
}
}
return menuDTO;
}
@Transactional(rollbackFor = Exception.class)
public void add(MenuBO menuBO) {
if (menuBO.getParentId() == null) {
menuBO.setParentId(0L);
}
checkAddMenu(menuBO);
Menu menu = new Menu(false);
BeanUtils.copyProperties(menuBO, menu);
Integer menuDept = getMenuDepth(menu, 0);
if (menuDept >= 3) {
throw new UserCenterException("目前系统菜单最大层级限制3级");
}
Long menuNo = generateMenuNo(menu.getParentId());
menu.setMenuNo(menuNo);
menuMapper.insertUseGeneratedKeys(menu);
MenuPermission permission = new MenuPermission();
permission.setPermissionTag(menu.getPermissionTag());
permission.setInterfaceUrl(menu.getPermissionTag());
menuPermissionMapper.insert(permission);
//如果是超级管理员,创建菜单自动分配权限到超级管理员角色
if (ShieldContextHolder.isSuperAdmin()) {
RoleMenu roleMenu = new RoleMenu(true);
roleMenu.setMenuNo(menuNo);
roleMenu.setRoleId(ShieldContextHolder.getRoleId());
roleMenuMapper.insert(roleMenu);
}
}
public void checkAddMenu(MenuBO menuBO) {
Menu menu = new Menu().setMenuName(menuBO.getMenuName()).setParentId(menuBO.getParentId());
int cnt = menuMapper.selectCount(menu);
if (cnt > 0) {
throw new UserCenterException("同级菜单名称已存在");
}
}
public Integer getMenuDepth(Menu menu, Integer depth) {
if (menu == null || menu.getParentId() == null) {
return 0;
}
depth++;
menu = menuMapper.selectByMenuNo(menu.getParentId());
if (menu == null || menu.getParentId() == 0) {
return depth;
}
return getMenuDepth(menu, depth);
}
@Transactional(rollbackFor = Exception.class)
public void edit(MenuBO menuBO) {
if (menuBO.getParentId() == null) {
menuBO.setParentId(0L);
}
checkEditMenu(menuBO);
Menu menu = new Menu(false);
BeanUtils.copyProperties(menuBO, menu);
menuMapper.updateByPrimaryKeySelective(menu);
}
public void checkEditMenu(MenuBO menuBO) {
Menu condition = new Menu().setMenuName(menuBO.getMenuName()).setParentId(menuBO.getParentId());
Menu menu = menuMapper.selectOne(condition);
if (menu != null && !menu.getId().equals(menuBO.getId())) {
throw new UserCenterException("同级菜单名称已存在");
}
}
public List<MenuPermission> getMenuPermissions(List<Long> menuIdList) {
return menuPermissionMapper.selectByMenuIds(menuIdList);
}
public void logicDeleteById(Long id) {
Menu menu = menuMapper.selectById(id);
log.warn("{}删除菜单{}", ShieldContextHolder.getAccount(), menu.toString());
// menuMapper.logicDeleteById(id);
menuMapper.deleteByPrimaryKey(id);
//删除菜单和角色关系
roleMenuMapper.deleteByMenuNo(menu.getMenuNo());
}
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.converter.DepartmentConverter;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.Organization;
import cn.com.glsx.neshield.modules.entity.Tenant;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.mapper.TenantMapper;
import cn.com.glsx.neshield.modules.mapper.UserMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.OrganizationBO;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.permissionStrategy.PermissionStrategy;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.glsx.plat.exception.SystemMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static cn.com.glsx.admin.common.constant.UserConstants.RolePermitCastType.*;
/**
* @author: taoyr
**/
@Slf4j
@Service
public class OrganizationService {
@Resource
private OrganizationMapper organizationMapper;
@Resource
private TenantMapper tenantMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private UserMapper userMapper;
@Resource
private DepartmentService departmentService;
private final Map<String, PermissionStrategy> permissionStrategyMap;
public OrganizationService(Map<String, PermissionStrategy> permissionStrategyMap) {
this.permissionStrategyMap = permissionStrategyMap;
}
/**
* 插入根节点路径
*
* @param orgBO
* @return
*/
@Transactional(rollbackFor = Exception.class)
public void addRootOrganization(OrganizationBO orgBO) {
Tenant duplicateNameTenant = tenantMapper.selectOne(new Tenant().setTenantName(orgBO.getDepartmentName()));
if (duplicateNameTenant != null) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "已有同名的根节点");
}
Tenant tenant = new Tenant(true);
tenant.setTenantName(orgBO.getDepartmentName());
tenantMapper.insertUseGeneratedKeys(tenant);
Long tenantId = tenant.getId();
Department department = new Department(true);
department.setEnableStatus(orgBO.getEnableStatus());
department.setTenantId(tenantId);
department.setIsRoot(Constants.IS_ROOT_DEPARTMENT);
department.setOrderNum(orgBO.getOrderNum());
department.setDepartmentName(orgBO.getDepartmentName());
departmentMapper.insertUseGeneratedKeys(department);
Long departmentId = department.getId();
Organization organization = new Organization(true);
organization.setSuperiorId(departmentId);
organization.setSubId(departmentId);
organization.setTenantId(tenantId);
organizationMapper.insertRootPath(organization);
log.info("新增根组织关系{}", organization.toString());
}
/**
* 增加组织树节点
*
* @param organizationBO
* @return
*/
@Transactional(rollbackFor = Exception.class)
public void addNodeToOrganization(OrganizationBO organizationBO) {
Long superiorId = organizationBO.getSuperiorId();
//选中的上级组织
Department parentDept = departmentMapper.selectById(superiorId);
if (parentDept == null) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "上级组织已删除,请刷新页面");
}
Long tenantId = parentDept.getTenantId();
Department department = new Department(true);
department.setTenantId(tenantId);
department.setEnableStatus(organizationBO.getEnableStatus());
department.setOrderNum(organizationBO.getOrderNum());
department.setIsRoot(Constants.IS_NOT_ROOT_DEPARTMENT);
department.setDepartmentName(organizationBO.getDepartmentName());
departmentMapper.insertUseGeneratedKeys(department);
Long departmentId = department.getId();
Organization organization = new Organization(true);
organization.setSuperiorId(superiorId);
organization.setSubId(departmentId);
organization.setTenantId(tenantId);
int insertCnt = organizationMapper.insertOrganizationPath(organization);
log.info("新增组织{}关系{}条", departmentId, insertCnt);
}
/**
* 获取组织机构树
*
* @param search
* @return
*/
public List<? extends TreeModel> fullOrgTree(OrgTreeSearch search) {
List<OrgModel> modelList = organizationMapper.selectOrgList(search);
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
return orgTree;
}
@Transactional(rollbackFor = Exception.class)
public void editOrganization(OrganizationBO orgBO) {
Long organizationId = orgBO.getId();
Department department = departmentMapper.selectById(organizationId);
if (department == null) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "组织部门不存在");
}
department.setOrderNum(orgBO.getOrderNum());
department.setDepartmentName(orgBO.getDepartmentName());
department.setEnableStatus(orgBO.getEnableStatus());
department.setUpdatedDate(new Date());
department.setUpdatedBy(ShieldContextHolder.getUserId());
departmentMapper.updateByPrimaryKeySelective(department);
//如果是根组织部门,则同时修改租户
if (department.getIsRoot() == Constants.IS_ROOT_DEPARTMENT) {
Tenant tenant = tenantMapper.selectById(department.getTenantId());
if (tenant == null) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "组织租户不存在");
}
tenant.setTenantName(orgBO.getDepartmentName());
tenantMapper.updateByPrimaryKeySelective(tenant);
}
}
/**
* 删除组织
*
* @param organizationId
* @return
*/
@Transactional(rollbackFor = Exception.class)
public void deleteOrganization(Long organizationId) {
Department department = departmentMapper.selectById(organizationId);
if (department == null) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "该组织不可用,请重新刷新列表");
}
List<Organization> organizations = organizationMapper.selectByRootId(organizationId);
List<Long> organizationIdList = organizations.stream().map(Organization::getSubId).collect(Collectors.toList());
organizationIdList.add(organizationId);
Integer userNum = userMapper.countByCriterial(new UserBO().setDepartmentIds(organizationIdList));
if (userNum > 0) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "该组织下仍关联有用户,请转移这部分用户后再重试");
}
//删除包括自己和下级所有部门
departmentMapper.logicDeleteByIdList(organizationIdList);
//删除自己下级所有路径
organizationMapper.logicDeleteAllSubOrganization(organizationId);
//删除自己对上级的所有路径
organizationMapper.logicDeleteSelfBySubId(organizationId);
//删除租户
if (Constants.IS_ROOT_DEPARTMENT == department.getIsRoot()) {
Long tenantId = department.getTenantId();
tenantMapper.logicDeleteById(tenantId);
}
}
public DepartmentDTO organizationInfo(Long organizationId) {
DepartmentDTO departmentDTO = null;
Department department = departmentMapper.selectById(organizationId);
if (department != null) {
departmentDTO = DepartmentConverter.INSTANCE.do2dto(department);
if (department.getIsRoot() == Constants.IS_NOT_ROOT_DEPARTMENT) {
Organization superiorOrg = organizationMapper.selectSuperiorOrganization(department.getId());
if (superiorOrg != null) {
Department superiorDept = departmentMapper.selectById(superiorOrg.getSuperiorId());
departmentDTO.setSuperiorId(superiorDept.getId());
departmentDTO.setSuperiorName(superiorDept.getDepartmentName());
}
}
}
return departmentDTO;
}
public List<DepartmentDTO> childrenList(OrganizationSearch search) {
List<Department> departmentList = organizationMapper.selectChildrenList(search);
List<DepartmentDTO> departmentDTOList = departmentService.getDepartmentAssembled(departmentList, true, false);
if (ShieldContextHolder.isRoleAdmin() || all.getCode().equals(ShieldContextHolder.getRolePermissionType())) {
return departmentDTOList;
}
List<Department> currentUserDepartmentList = departmentService.getCurrentUserDepartment();
List<Long> departmentIdList = currentUserDepartmentList.stream().map(Department::getId).collect(Collectors.toList());
departmentDTOList = departmentDTOList.stream().filter(d -> departmentIdList.contains(d.getId())).collect(Collectors.toList());
return departmentDTOList;
}
/**
* @param rootId
* @return
*/
public List<DepartmentDTO> simpleList(Long rootId) {
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
String beanName = getBeanNameByCode(rolePermissionType);
if (StringUtils.isBlank(beanName)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色权限类型未知");
}
PermissionStrategy permissionStrategy = permissionStrategyMap.get(beanName);
List<DepartmentDTO> departmentDTOList = permissionStrategy.orgSimpleList(rootId);
return departmentDTOList;
}
/**
* @param search
* @return
*/
public List<DepartmentDTO> permissionStrategy(OrgTreeSearch search) {
Integer rolePermissionType = search.getRolePermissionType();
String beanName = getBeanNameByCode(rolePermissionType);
if (StringUtils.isBlank(beanName)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色权限类型未知");
}
PermissionStrategy permissionStrategy = permissionStrategyMap.get(beanName);
if (all.getCode().equals(rolePermissionType)) {
} else if (oneself.getCode().equals(rolePermissionType)) {
List<User> list = permissionStrategy.permissionUsers();
log.info(String.valueOf(list.size()));
} else if (subordinate.getCode().equals(rolePermissionType)) {
List<User> list = permissionStrategy.permissionUsers();
log.info(String.valueOf(list.size()));
} else if (selfDepartment.getCode().equals(rolePermissionType)) {
List<Department> list = permissionStrategy.permissionDepartments();
log.info(String.valueOf(list.size()));
} else if (subDepartment.getCode().equals(rolePermissionType)) {
List<Department> list = permissionStrategy.permissionDepartments();
log.info(String.valueOf(list.size()));
}
List<DepartmentDTO> dtoList = permissionStrategy.orgSimpleList(search.getOrgId());
log.info("dtoList:{}", JSON.toJSONString(dtoList, true));
List list = permissionStrategy.orgTree(search);
log.info("treeList:{}", JSON.toJSONString(list, true));
return dtoList;
}
public List orgTree(OrgTreeSearch search) {
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
String beanName = getBeanNameByCode(rolePermissionType);
if (StringUtils.isBlank(beanName)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色权限类型未知");
}
PermissionStrategy permissionStrategy = permissionStrategyMap.get(beanName);
List<? extends TreeModel> treeModels = permissionStrategy.orgTree(search);
return treeModels;
}
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.converter.RoleConverter;
import cn.com.glsx.neshield.modules.entity.Role;
import cn.com.glsx.neshield.modules.entity.RoleMenu;
import cn.com.glsx.neshield.modules.entity.RoleTenant;
import cn.com.glsx.neshield.modules.entity.UserRoleRelation;
import cn.com.glsx.neshield.modules.mapper.RoleMapper;
import cn.com.glsx.neshield.modules.mapper.RoleMenuMapper;
import cn.com.glsx.neshield.modules.mapper.RoleTenantMapper;
import cn.com.glsx.neshield.modules.mapper.UserRoleRelationMapper;
import cn.com.glsx.neshield.modules.model.param.RoleBO;
import cn.com.glsx.neshield.modules.model.param.RoleSearch;
import cn.com.glsx.neshield.modules.model.view.RoleDTO;
import cn.com.glsx.neshield.modules.model.view.SimpleRoleDTO;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.exception.SystemMessage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import static cn.com.glsx.admin.common.constant.UserConstants.RoleVisibility.*;
/**
* @author: taoyr
**/
@Slf4j
@Service
public class RoleService {
@Resource
private RoleMapper roleMapper;
@Resource
private UserRoleRelationMapper userRoleRelationMapper;
@Resource
private RoleMenuMapper roleMenuMapper;
@Resource
private RoleTenantMapper roleTenantMapper;
public PageInfo<RoleDTO> search(RoleSearch search) {
List<Role> list = Lists.newArrayList();
Integer roleVisibility = ShieldContextHolder.getRoleVisibility();
Page page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
if (onlyAdmin.getCode().equals(roleVisibility)) {
//全部
list = roleMapper.selectList(search);
} else if (share.getCode().equals(roleVisibility)) {
//共享
list = roleMapper.selectList(search.setRoleVisibility(roleVisibility));
} else if (specifyTenants.getCode().equals(roleVisibility)) {
//指定租户+共享
list = roleMapper.selectVisibilityList(search.setTenantId(ShieldContextHolder.getTenantId()));
}
List<RoleDTO> roleDTOList = getRoleListAssembled(list);
PageInfo<RoleDTO> pageInfo = new PageInfo<>(roleDTOList);
pageInfo.setPages(page.getPages());//总页数
pageInfo.setTotal(page.getTotal());//总条数
return pageInfo;
}
private List<RoleDTO> getRoleListAssembled(List<Role> list) {
List<RoleDTO> roleDtoList = list.stream().map(role -> {
RoleDTO roleDTO = new RoleDTO();
BeanUtils.copyProperties(role, roleDTO);
return roleDTO;
}).collect(Collectors.toList());
return roleDtoList;
}
public List<Role> getUserRoleList(Long userId) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setUserId(userId);
List<UserRoleRelation> userRoleRelationList = userRoleRelationMapper.selectUserRoleRelationList(userRoleRelation);
List<Long> roleIds = userRoleRelationList.stream().map(UserRoleRelation::getRoleId).collect(Collectors.toList());
if (CollectionUtil.isEmpty(roleIds)) {
return Lists.newArrayList();
}
List<Role> roleList = roleMapper.selectRoleListByIds(roleIds);
return roleList;
}
public Role getRoleById(Long roleId) {
return roleMapper.selectById(roleId);
}
/**
* 根据角色权限范围获取角色列表
*
* @return
*/
public List<SimpleRoleDTO> simpleList() {
List<SimpleRoleDTO> list;
List<Role> roleList;
if (ShieldContextHolder.isSuperAdmin()) {
//假设当前登陆的A账号(角色:系统管理员),则该账号创建账号的时候角色的选择范围可以覆盖系统所有角色
roleList = roleMapper.selectList(new RoleSearch().setEnableStatus(EnableStatus.enable.getCode()));
} else {
//假设当前登陆的B账号(角色:租户B管理员),则该账号创建账号的时候角色的选择范围可以覆盖共享角色+对该租户开放的角色
roleList = Lists.newLinkedList();
Integer roleVisibility = ShieldContextHolder.getRoleVisibility();
if (onlyAdmin.getCode().equals(roleVisibility)) {
roleList = roleMapper.selectList(new RoleSearch());
} else if (share.getCode().equals(roleVisibility)) {
roleList = roleMapper.selectByVisibilityType(roleVisibility);
} else if (specifyTenants.getCode().equals(roleVisibility)) {
List<Role> shareRoleList = roleMapper.selectByVisibilityType(share.getCode());
List<Long> roleTenantIdList = roleTenantMapper.selectTenantIdsByRoleId(ShieldContextHolder.getRoleId());
roleList = roleMapper.selectByTenantIds(roleTenantIdList);
roleList.addAll(shareRoleList);
}
}
list = roleList.stream().map(role -> new SimpleRoleDTO().setRoleId(role.getId()).setRoleName(role.getRoleName())).collect(Collectors.toList());
return list;
}
@Transactional(rollbackFor = Exception.class)
public void addRole(RoleBO roleBO) {
checkRole(roleBO);
Role role = RoleConverter.INSTANCE.bo2do(roleBO);
role.setContextInfo(true);
role.setTenantId(ShieldContextHolder.getTenantId());
roleMapper.insertUseGeneratedKeys(role);
List<Long> menuIdList = roleBO.getMenuIdList();
menuIdList = getFixMenuIds(menuIdList);
List<RoleMenu> roleMenuList = menuIdList.stream().map(menuNo -> new RoleMenu(true)
.setMenuNo(menuNo)
.setRoleId(role.getId()))
.collect(Collectors.toList());
roleMenuMapper.insertList(roleMenuList);
if (specifyTenants.getCode().equals(roleBO.getRoleVisibility())) {
String[] tenantIds = roleBO.getRoleTenants().split(",");
List<RoleTenant> roleTenantList = new ArrayList<>(tenantIds.length);
Arrays.asList(tenantIds).forEach(item -> {
roleTenantList.add(new RoleTenant().setRoleId(role.getId()).setTenantId(Long.valueOf(item)));
});
roleTenantMapper.insertList(roleTenantList);
}
}
@Transactional(rollbackFor = Exception.class)
public void editRole(RoleBO roleBO) {
checkRole(roleBO);
Role role = RoleConverter.INSTANCE.bo2do(roleBO);
role.setContextInfo(false);
roleMapper.updateByPrimaryKeySelective(role);
Long id = role.getId();
roleMenuMapper.logicDelByRoleId(id);
List<Long> menuIdList = roleBO.getMenuIdList();
menuIdList = getFixMenuIds(menuIdList);
List<RoleMenu> roleMenuList = menuIdList.stream().map(menuNo -> new RoleMenu(true)
.setMenuNo(menuNo)
.setRoleId(id)).collect(Collectors.toList());
roleMenuMapper.insertList(roleMenuList);
roleTenantMapper.logicDeleteByRoleId(role.getId());
if (specifyTenants.getCode().equals(roleBO.getRoleVisibility())) {
String[] tenantIds = roleBO.getRoleTenants().split(",");
List<RoleTenant> roleTenantList = new ArrayList<>(tenantIds.length);
Arrays.asList(tenantIds).forEach(item -> {
roleTenantList.add(new RoleTenant().setRoleId(role.getId()).setTenantId(Long.valueOf(item)));
});
roleTenantMapper.insertList(roleTenantList);
}
}
/**
* 将缺失的夫级id补全
*
* @param menuIdList 页面传递的id集合
*/
private List<Long> getFixMenuIds(List<Long> menuIdList) {
//把已有的子菜单id转为Set
HashSet<Long> parentids = new HashSet<>(menuIdList);
//Long转String,根据01判断一级父id,每多一级长度加2,截取下一级父id,添加set
menuIdList.stream().map(String::valueOf).forEach(menuId -> {
int length = menuId.length();
int rootIndex = menuId.indexOf("01") + 2;
if (rootIndex != -1) {
for (int i = rootIndex; i < length; i += 2) {
String parentIdStr = menuId.substring(0, i);
parentids.add(Long.parseLong(parentIdStr));
}
}
});
return new ArrayList<>(parentids);
}
/**
* 检查角色关键信息
*
* @param roleBO
*/
private void checkRole(RoleBO roleBO) {
if (roleBO.getRoleId() == null) {
int cnt = roleMapper.selectCntByName(roleBO.getRoleName());
if (cnt > 0) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "相同角色已存在");
}
} else {
Role dbRole = roleMapper.selectByName(roleBO.getRoleName());
if (dbRole != null && !dbRole.getId().equals(roleBO.getRoleId())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "相同角色已存在");
}
}
if (!ShieldContextHolder.isSuperAdmin() && onlyAdmin.getCode().equals(roleBO.getRoleVisibility())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "非管理员账号不能创建管理员角色");
}
}
public RoleDTO roleInfo(Long id) {
RoleDTO roleDTO = null;
Role role = roleMapper.selectById(id);
if (role != null) {
roleDTO = new RoleDTO();
BeanUtils.copyProperties(role, roleDTO);
if (specifyTenants.getCode().equals(role.getRoleVisibility())) {
List<Long> roleTenantIdList = roleTenantMapper.selectTenantIdsByRoleId(id);
String roleTenants = StringUtils.join(roleTenantIdList, ',');
roleDTO.setRoleTenants(roleTenants);
}
}
return roleDTO;
}
public void deleteRole(Long id) {
List<UserRoleRelation> relations = userRoleRelationMapper.selectUserRoleRelationList(new UserRoleRelation().setRoleId(id));
if (CollectionUtils.isNotEmpty(relations)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "请取消相关账号与该角色的关联后再删除");
}
roleMapper.logicDeleteById(id);
}
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.neshield.modules.entity.Tenant;
import cn.com.glsx.neshield.modules.mapper.TenantMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author: taoyr
**/
@Service
public class TenantService {
@Resource
private TenantMapper tenantMapper;
public Tenant getTenantById(Long tenantId){
return tenantMapper.selectById(tenantId);
}
}
package cn.com.glsx.neshield.modules.service;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.converter.AuthDepartmentConverter;
import cn.com.glsx.neshield.modules.converter.AuthMenuPermissionConverter;
import cn.com.glsx.neshield.modules.converter.AuthRoleConverter;
import cn.com.glsx.neshield.modules.converter.AuthTenantConverter;
import cn.com.glsx.neshield.modules.entity.*;
import cn.com.glsx.neshield.modules.mapper.*;
import cn.com.glsx.neshield.modules.model.export.UserExport;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.SuperTreeModel;
import cn.com.glsx.neshield.modules.model.view.UserDTO;
import cn.hutool.core.lang.UUID;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.ObjectUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils;
import com.glsx.plat.web.utils.SessionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import static cn.com.glsx.admin.common.constant.UserConstants.RolePermitCastType.*;
import static cn.com.glsx.admin.common.constant.UserConstants.RoleVisibility.*;
/**
* @author liuyf
* @desc 用户信息
* @date 2019年10月24日 下午2:37:40
*/
@Slf4j
@Service
public class UserService {
@Resource
private HashedCredentialsMatcher hcm;
@Resource
private JwtUtils<ComJwtUser> jwtUtils;
@Resource
private UserMapper userMapper;
@Resource
private TenantMapper tenantMapper;
@Resource
private DepartmentMapper departmentMapper;
@Autowired
private RoleService roleService;
@Autowired
private MenuService menuService;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private UserPathMapper userPathMapper;
@Resource
private UserRoleRelationMapper userRoleRelationMapper;
@Resource
private RoleMapper roleMapper;
@Resource
private RoleMenuMapper roleMenuMapper;
@Resource
private RoleTenantMapper roleTenantMapper;
@Resource
@Lazy
private DepartmentService departmentService;
public User getById(Long id) {
return userMapper.selectById(id);
}
public User findByAccount(String username) {
return userMapper.selectByAccount(username);
}
public UserDTO userInfo(Long userId) {
UserDTO userDTO = null;
User user = userMapper.selectById(userId);
if (user != null) {
userDTO = new UserDTO();
BeanUtils.copyProperties(user, userDTO);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectUserRoleRelationList(new UserRoleRelation().setUserId(userId));
if (CollectionUtils.isNotEmpty(userRoleRelations)) {
Long roleId = userRoleRelations.get(0).getRoleId();
userDTO.setRoleId(roleId);
Role role = roleMapper.selectById(roleId);
userDTO.setRoleName(role != null ? role.getRoleName() : "");
}
Long departmentId = userDTO.getDepartmentId();
Department department = departmentMapper.selectById(departmentId);
if (department != null) {
userDTO.setDepartmentName(department.getDepartmentName());
userDTO.setDeptDepth(department.getIsRoot() == Constants.IS_ROOT_DEPARTMENT ? 0 : 1);
}
Long superiorId = userDTO.getSuperiorId();
User superiorUser = userMapper.selectById(superiorId);
userDTO.setSuperiorName(superiorUser != null ? superiorUser.getUsername() : "");
}
return userDTO;
}
public int logicDeleteById(Long id) {
return userMapper.logicDeleteById(id);
}
public PageInfo<UserDTO> search(UserSearch search) {
Page page = null;
Integer rolePermissionType = ShieldContextHolder.getRolePermissionType();
Long userDeptId = ShieldContextHolder.getDepartment().getDeptId();
List<Long> selectDeptIdList = Lists.newArrayList();
if (search.getDepartmentId() != null) {
//当前选中部门
selectDeptIdList.add(search.getDepartmentId());
}
List<User> userList;
if (oneself.getCode().equals(rolePermissionType)) {
search.setUserId(ShieldContextHolder.getUserId());
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
userList = userMapper.selectList(search);
} else if (selfDepartment.getCode().equals(rolePermissionType)) {
selectDeptIdList.add(userDeptId);
search.setDepartmentIdList(selectDeptIdList);
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
userList = userMapper.selectList(search);
} else if (subordinate.getCode().equals(rolePermissionType)) {
//所有子部门的下属员工
List<Organization> subList = organizationMapper.selectSubList(Lists.newArrayList(userDeptId), null);
List<Long> departmentIds = subList.stream().map(Organization::getSubId).collect(Collectors.toList());
departmentIds.add(userDeptId);
departmentIds.addAll(selectDeptIdList);
search.setDepartmentIdList(departmentIds);
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
userList = userMapper.selectDepartmentsSubordinate(search);
} else if (subDepartment.getCode().equals(rolePermissionType)) {
//所有属于用户下属部门的当前部门的子部门
List<Organization> subDepartmentList = organizationMapper.selectSubList(Lists.newArrayList(userDeptId), null);
List<Long> subDepartmentIdList = subDepartmentList.stream().map(Organization::getSubId).collect(Collectors.toList());
List<Long> departmentIds = Lists.newArrayList();
if (CollectionUtils.isEmpty(selectDeptIdList)) {
//当前用户所有下属部门
List<Organization> subList = organizationMapper.selectSubList(subDepartmentIdList, null);
departmentIds = subList.stream().filter(dep -> subDepartmentIdList.contains(dep.getSubId())).map(Organization::getSubId).collect(Collectors.toList());
//加上自己当前部门
departmentIds.add(userDeptId);
} else {
//选中部门下属部门
List<Organization> subList = organizationMapper.selectSubList(selectDeptIdList, null);
departmentIds = subList.stream().filter(dep -> subDepartmentIdList.contains(dep.getSubId())).map(Organization::getSubId).collect(Collectors.toList());
//加上当前选中部门
departmentIds.addAll(selectDeptIdList);
}
search.setDepartmentIdList(departmentIds);
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
userList = userMapper.selectList(search);
} else if (all.getCode().equals(rolePermissionType)) {
//部门id
if (CollectionUtils.isNotEmpty(selectDeptIdList)) {
List<Organization> subList = organizationMapper.selectSubList(selectDeptIdList, null);
List<Long> departmentIds = subList.stream().map(Organization::getSubId).collect(Collectors.toList());
departmentIds.addAll(selectDeptIdList);
search.setDepartmentIdList(departmentIds);
}
page = PageHelper.startPage(search.getPageNumber(), search.getPageSize());
userList = userMapper.selectList(search);
} else {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "未知的角色权限范围类型");
}
List<UserDTO> userDTOList = Lists.newLinkedList();
if (CollectionUtils.isNotEmpty(userList)) {
userDTOList = userListAssembled(userList);
}
PageInfo<UserDTO> pageInfo = new PageInfo<>(userDTOList);
pageInfo.setPages(page.getPages());//总页数
pageInfo.setTotal(page.getTotal());//总条数
return pageInfo;
}
public List<UserDTO> userListAssembled(List<User> userList) {
List<UserDTO> userDTOList = Lists.newArrayList();
List<Long> departmentIdList = userList.stream().map(User::getDepartmentId).collect(Collectors.toList());
List<Department> departmentList = departmentMapper.selectByIds(departmentIdList);
Map<Long, Department> departmentMap = departmentList.stream().collect(Collectors.toMap(Department::getId, d -> d));
for (User user : userList) {
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(user, userDTO);
Department department = departmentMap.get(user.getDepartmentId());
if (department != null) {
userDTO.setDepartmentName(department.getDepartmentName());
}
userDTOList.add(userDTO);
}
return userDTOList;
}
public List<UserExport> export(UserSearch search) {
return Lists.newArrayList();
}
@Transactional(rollbackFor = Exception.class)
public void addUser(UserBO userBO) {
//检查用户关键信息
checkUser(userBO);
//校验部门范围
checkUserDepartment(userBO);
//校验上级范围
checkUserSuperior(userBO);
//校验角色
checkUserRole(userBO);
User user = new User(true);
BeanUtils.copyProperties(userBO, user);
generateAndSetPassword(user);
userMapper.insertUseGeneratedKeys(user);
Long userId = user.getId();
if (userBO.getSuperiorId() == null) {
UserPath userPath = new UserPath(true);
userPath.setSuperiorId(userId);
userPath.setSubId(userId);
userPath.setTenantId(user.getTenantId());
userPathMapper.insertRootPath(userPath);
log.info("新增根用户关系{}", userPath.toString());
} else {
UserPath userPath = new UserPath(true);
userPath.setSuperiorId(userBO.getSuperiorId());
userPath.setSubId(userId);
userPath.setTenantId(user.getTenantId());
int insertCnt = userPathMapper.insertUserPath(userPath);
log.info("新增用户{}关系{}条", userId, insertCnt);
}
userRoleRelationMapper.insert(new UserRoleRelation(true).setUserId(userId).setRoleId(userBO.getRoleId()));
}
@Transactional(rollbackFor = Exception.class)
public void editUser(UserBO userBO) {
//检查用户关键信息
checkUser(userBO);
//校验部门范围
checkUserDepartment(userBO);
//校验上级范围
checkUserSuperior(userBO);
//校验角色
checkUserRole(userBO);
boolean changePwd = StringUtils.isNotEmpty(userBO.getPassword());
User user = userMapper.selectById(userBO.getId());
userBO.setPassword(user.getPassword());
BeanUtils.copyProperties(userBO, user);
//如果填了密码,修改密码
if (changePwd) {
generateAndSetPassword(user);
}
userMapper.updateByPrimaryKey(user);
//重建用户上下级关系
rebuildUserPath(user);
//更新角色关系
List<UserRoleRelation> relationList = userRoleRelationMapper.selectUserRoleRelationList(new UserRoleRelation().setUserId(user.getId()));
if (CollectionUtils.isNotEmpty(relationList)) {
UserRoleRelation relation = relationList.get(0);
if (!relation.getRoleId().equals(userBO.getRoleId())) {
relation.setRoleId(userBO.getRoleId());
relation.setUpdatedBy(ShieldContextHolder.getUserId());
relation.setUpdatedDate(new Date());
userRoleRelationMapper.updateByPrimaryKeySelective(relation);
}
}
}
/**
* 重建用户上下级关系
*
* @param user
*/
private void rebuildUserPath(User user) {
}
/**
* 检查用户关键信息
*
* @param userBO
*/
private void checkUser(UserBO userBO) {
if (userBO.getId() == null) {
int cnt = userMapper.selectCntByAccount(userBO.getAccount());
if (cnt > 0) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "相同账号已存在");
}
} else {
User dbUser = userMapper.selectByAccount(userBO.getAccount());
if (dbUser != null && !dbUser.getId().equals(userBO.getId())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "相同账号已存在");
}
}
}
/**
* 检查用户部门权限
*
* @param userBO
*/
private void checkUserDepartment(UserBO userBO) {
Long departmentId = userBO.getDepartmentId();
List<Department> userDepartmentList = departmentService.getCurrentUserDepartment();
List<Long> departmentIdList = userDepartmentList.stream().map(Department::getId).collect(Collectors.toList());
if (!departmentIdList.contains(departmentId)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "当前用户不具备该部门权限");
}
}
/**
* 检查用户上级部门
*
* @param userBO
*/
private void checkUserSuperior(UserBO userBO) {
if (userBO.getId() != null && userBO.getId().equals(userBO.getSuperiorId())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "不能选择当前编辑用户为其上级");
}
//上一级组织
Organization superiorOrg = organizationMapper.selectSuperiorOrganization(userBO.getDepartmentId());
if (superiorOrg != null) {
User superiorUser = userMapper.selectById(userBO.getSuperiorId());
if (superiorUser != null) {
Long superiorUserDeptId = superiorUser.getDepartmentId();
if (org.apache.commons.lang.ObjectUtils.notEqual(superiorUserDeptId, userBO.getDepartmentId()) &&
org.apache.commons.lang.ObjectUtils.notEqual(superiorUserDeptId, superiorOrg.getSuperiorId())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "上级用户范围不在本部门或上级部门");
}
}
userBO.setTenantId(superiorOrg.getTenantId());
} else {
//根组织
Department department = departmentMapper.selectById(userBO.getDepartmentId());
userBO.setTenantId(department.getTenantId());
}
}
/**
* 检查用户角色权限
*
* @param userBO
*/
private void checkUserRole(UserBO userBO) {
if (!ShieldContextHolder.isRoleAdmin()) {
Long roleId = userBO.getRoleId();
Role role = roleMapper.selectById(roleId);
if (onlyAdmin.getCode().equals(role.getRoleVisibility())) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "该角色不可选");
} else if (share.getCode().equals(role.getRoleVisibility())) {
//共享角色
List<Long> shareRoleIdList = roleMapper.selectRoleIdsByVisibilityType(share.getCode());
if (!shareRoleIdList.contains(roleId)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色不可选");
}
} else if (specifyTenants.getCode().equals(role.getRoleVisibility())) {
//共享角色
List<Long> shareRoleIdList = roleMapper.selectRoleIdsByVisibilityType(share.getCode());
//租户下面角色
List<Long> tenantRoleIdList = roleTenantMapper.selectRoleIdsByTenantId(ShieldContextHolder.getTenantId());
if (!shareRoleIdList.contains(roleId) && !tenantRoleIdList.contains(roleId)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色不可选");
}
}
}
}
/**
* 生成密码
*
* @param user
*/
private void generateAndSetPassword(User user) {
String salt = StringUtils.generateRandomCode(false, 4);
SimpleHash hash = new SimpleHash(hcm.getHashAlgorithmName(), user.getPassword(), salt, hcm.getHashIterations());
user.setSalt(salt);
user.setPassword(hash.toString());
}
/**
* 验证密码
*
* @param user
* @param inputPassword
* @return
*/
public boolean verifyPassword(User user, String inputPassword) {
String dbPassword = user.getPassword();
String salt = user.getSalt();
SimpleHash hash = new SimpleHash(hcm.getHashAlgorithmName(), inputPassword, salt, hcm.getHashIterations());
return dbPassword.equals(hash.toString());
}
/**
* 修改密码
*
* @param userId
* @param password
*/
public void changePassword(Long userId, String password) {
}
/**
* 重置密码
*
* @param userId
*/
public void resetPassword(Long userId) {
}
/**
* 生成带用户信息的token
*
* @param user
* @return
*/
public String createToken(User user) {
String uuid = UUID.randomUUID().toString(); //JWT 随机ID,做为验证的key
String jwtId = jwtUtils.getApplication() + ":" + uuid + "_" + jwtUtils.JWT_SESSION_PREFIX + user.getId();
ComJwtUser jwtUser = new ComJwtUser();
jwtUser.setApplication(jwtUtils.getApplication());
jwtUser.setJwtId(jwtId);
jwtUser.setUserId(String.valueOf(user.getId()));
jwtUser.setAccount(user.getAccount());
jwtUser.setTenant(String.valueOf(user.getTenantId()));
Department department = departmentMapper.selectById(user.getDepartmentId());
jwtUser.setBelong(Optional.ofNullable(department).map(d -> department.getDepartmentName()).orElse(""));
Map<String, Object> userMap = (Map<String, Object>) ObjectUtils.objectToMap(jwtUser);
return jwtUtils.createToken(userMap);
}
/**
* 根据Token获取Customer
*/
public User getByToken() {
String token = SessionUtils.request().getHeader(HttpHeaders.AUTHORIZATION);
if (StringUtils.isNullOrEmpty(token)) {
throw new UserCenterException(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg());
}
Map<String, Object> userMap = jwtUtils.parseClaim(token);
Object userId = userMap.get("userId");
if (Objects.isNull(userId)) {
throw new UserCenterException(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg());
}
User user = this.getById(Long.valueOf(userId.toString()));
if (user == null) {
throw new UserCenterException(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg());
}
return user;
}
/**
* 从redis删除token缓存
*/
public void removeToken() {
String token = SessionUtils.request().getHeader(HttpHeaders.AUTHORIZATION);
jwtUtils.destroyToken(token);
}
/**
* 获取综合用户信息
*
* @return
*/
public SyntheticUser getSyntheticUser() {
User user = this.getByToken();
SyntheticUser authUser = new SyntheticUser();
authUser.setUserId(user.getId());
authUser.setAccount(user.getAccount());
authUser.setAdmin(user.isAdmin());
// TODO: 2020/9/24 缓存数据
//租户
Tenant tenant = tenantMapper.selectById(user.getTenantId());
authUser.setTenant(AuthTenantConverter.INSTANCE.toAuthTenant(tenant));
//部门
Department department = departmentMapper.selectById(user.getDepartmentId());
authUser.setDepartment(AuthDepartmentConverter.INSTANCE.toAuthDepartment(department));
//角色
List<Role> roleList = roleService.getUserRoleList(user.getId());
if (CollectionUtils.isNotEmpty(roleList)) {
List<cn.com.glsx.auth.model.Role> list = new ArrayList<>(roleList.size());
roleList.forEach(role -> {
list.add(AuthRoleConverter.INSTANCE.toAuthRole(role));
});
authUser.setRoles(list);
}
Set<Long> deptIds = this.getRelationAuthDeptIds(authUser);
log.info("可见部门IDs:{}", deptIds.toString());
Set<Long> userIds = this.getRelationAuthUserIds(authUser);
log.info("可见用户IDs:{}", userIds.toString());
return authUser;
}
public Set<Long> getRelationAuthDeptIds(SyntheticUser authUser) {
Set<Long> deptIds = Sets.newHashSet();
Long departmentId = authUser.getDepartment().getDeptId();
Integer rolePermissionType = authUser.getRoles().get(0).getRolePermissionType();
if (oneself.getCode().equals(rolePermissionType)) {
// do nothing
} else if (selfDepartment.getCode().equals(rolePermissionType)) {
//自己部门id
deptIds.add(departmentId);
} else if (subDepartment.getCode().equals(rolePermissionType)) {
List<Organization> subOrgList = organizationMapper.selectSubList(Lists.newArrayList(departmentId), null);
//下级部门id
Set<Long> departmentIds = subOrgList.stream().map(Organization::getSubId).collect(Collectors.toSet());
//自己部门id
departmentIds.add(departmentId);
deptIds.addAll(departmentIds);
} else if (subordinate.getCode().equals(rolePermissionType)) {
// do nothing
} else if (all.getCode().equals(rolePermissionType)) {
// do nothing
} else {
throw new UserCenterException("未知角色权限查询类型");
}
//可见用户
authUser.setVisibleDeptIds(deptIds);
return deptIds;
}
/**
* 获取用户根据数据权限范围内的可见用户id
*
* @param authUser
* @return
*/
public Set<Long> getRelationAuthUserIds(SyntheticUser authUser) {
Set<Long> userIds = Sets.newHashSet();
Long userId = authUser.getUserId();
Long departmentId = authUser.getDepartment().getDeptId();
Integer rolePermissionType = authUser.getRoles().get(0).getRolePermissionType();
String beanName = getBeanNameByCode(rolePermissionType);
if (StringUtils.isBlank(beanName)) {
throw new UserCenterException(SystemMessage.FAILURE.getCode(), "角色权限类型未知");
}
if (oneself.getCode().equals(rolePermissionType)) {
userIds.add(userId);
} else if (selfDepartment.getCode().equals(rolePermissionType)) {
List<User> userList = userMapper.selectList(new UserSearch().setDepartmentIdList(Lists.newArrayList(departmentId)));
userIds = userList.stream().map(User::getId).collect(Collectors.toSet());
} else if (subDepartment.getCode().equals(rolePermissionType)) {
List<Organization> subOrgList = organizationMapper.selectSubList(Lists.newArrayList(departmentId), null);
List<Long> departmentIds = subOrgList.stream().map(Organization::getSubId).collect(Collectors.toList());
departmentIds.add(departmentId);
List<User> userList = userMapper.selectList(new UserSearch().setDepartmentIdList(departmentIds));
userIds = userList.stream().map(User::getId).collect(Collectors.toSet());
} else if (subordinate.getCode().equals(rolePermissionType)) {
List<UserPath> userPaths = userPathMapper.selectUserSubordinateList(userId);
userIds = userPaths.stream().map(UserPath::getSubId).collect(Collectors.toSet());
userIds.add(userId);
} else if (all.getCode().equals(rolePermissionType)) {
// do nothing
} else {
throw new UserCenterException("未知角色权限查询类型");
}
//可见用户
authUser.setVisibleCreatorIds(userIds);
return userIds;
}
/**
* 获取用户角色分配的功能菜单标识
*
* @param authUser
* @return
*/
public List<cn.com.glsx.auth.model.MenuPermission> getPermissionMenus(SyntheticUser authUser) {
//菜单
if (CollectionUtils.isNotEmpty(authUser.getRoles())) {
List<Long> roleIds = authUser.getRoles().stream().map(cn.com.glsx.auth.model.Role::getRoleId).collect(Collectors.toList());
// List<Menu> menuList = menuService.getMenuList(roleIds);
// List<cn.com.glsx.auth.model.Menu> list = new ArrayList<>(roleList.size());
// menuList.forEach(menu -> {
// list.add(AuthMenuConverter.INSTANCE.toAuthMentu(menu));
// });
List<Long> menuIdList = roleMenuMapper.selectMenuIdsByRoleIds(roleIds);
List<MenuPermission> permissionList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(menuIdList)) {
permissionList = menuService.getMenuPermissions(menuIdList);
}
List<cn.com.glsx.auth.model.MenuPermission> list = new ArrayList<>(permissionList.size());
permissionList.forEach(mp -> {
list.add(AuthMenuPermissionConverter.INSTANCE.toAuthMenuPermission(mp));
});
return list;
}
return Lists.newArrayList();
}
public List<SuperTreeModel> suitableSuperUsers(Long departmentId) {
Department department = departmentMapper.selectById(departmentId);
if (department == null) {
throw new UserCenterException("部门不存在");
}
List<User> departmentUserList = userMapper.select(new User().setDepartmentId(departmentId));
Organization superiorOrganization = organizationMapper.selectSuperiorOrganization(departmentId);
if (superiorOrganization == null) {
//无上级
SuperTreeModel superTreeModel = new SuperTreeModel();
superTreeModel.setId(departmentId);
superTreeModel.setLabel(department.getDepartmentName());
superTreeModel.setOrder(department.getOrderNum());
superTreeModel.setRoot(true);
superTreeModel.setDisabled(true);
List<SuperTreeModel> children = departmentUserList.stream().map(UserService::applySuperTreeModel).collect(Collectors.toList());
superTreeModel.setChildren(children);
return Lists.newArrayList(superTreeModel);
}
Long superiorId = superiorOrganization.getSuperiorId();
Department superiorDepartment = departmentMapper.selectById(superiorId);
SuperTreeModel superTreeModel = new SuperTreeModel();
superTreeModel.setId(superiorDepartment.getId());
superTreeModel.setLabel(superiorDepartment.getDepartmentName());
superTreeModel.setOrder(superiorDepartment.getOrderNum());
List<User> superiorUserList = userMapper.select(new User().setDepartmentId(superiorId));
List<SuperTreeModel> children = superiorUserList.stream().map(UserService::applySuperTreeModel).collect(Collectors.toList());
SuperTreeModel departmentModel = new SuperTreeModel();
departmentModel.setId(departmentId);
departmentModel.setLabel(department.getDepartmentName());
departmentModel.setOrder(department.getOrderNum());
superTreeModel.setDisabled(true);
children.add(departmentModel);
superTreeModel.setChildren(children);
List<SuperTreeModel> departmentUserModels = departmentUserList.stream().map(UserService::applySuperTreeModel).collect(Collectors.toList());
departmentModel.setChildren(departmentUserModels);
return Lists.newArrayList(superTreeModel);
}
private static SuperTreeModel applySuperTreeModel(User du) {
SuperTreeModel model = new SuperTreeModel();
model.setId(du.getId());
model.setLabel(du.getUsername());
return model;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgSuperiorModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.OrganizationSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author taoyr
*/
@Slf4j
@Component
public class AllStrategy extends PermissionStrategy {
@Resource
private OrganizationMapper organizationMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private DepartmentService departmentService;
@Override
public List<Department> permissionDepartments() {
throw new UserCenterException("权限错误调用,请检查");
}
@Override
public List<User> permissionUsers() {
throw new UserCenterException("权限错误调用,请检查");
}
/**
* 1 all
* * 1.1 root 找所有根部门
* * 1.2 非root 根据rootId找子部门list
* * 封装-不过滤-返回
*
* @param rootId
* @return
*/
@Override
public List<DepartmentDTO> orgSimpleList(Long rootId) {
List<Department> departmentParamList;
if (rootId == null) {
departmentParamList = departmentMapper.selectDepartmentList(new Department().setIsRoot(Constants.IS_ROOT_DEPARTMENT));
} else {
departmentParamList = organizationMapper.selectChildrenList(new OrganizationSearch().setRootId(rootId));
}
return departmentService.getDepartmentAssembled(departmentParamList, true, true);
}
/**
* 1.查询符合条件的部门nameDepartmentList
* 2.找出idList所有向上的路径经过的所有部门allDepartmentIdList
* 3.找出所有组织链organizationList
* 4.找出根节点rootList
* 5.封装-调用TreeModelUtil组装树
*
* @param search
* @return
*/
@Override
public List<? extends TreeModel> orgTree(OrgTreeSearch search) {
if (StringUtils.isNotEmpty(search.getOrgName())) {
List<OrgSuperiorModel> superiorModelList = organizationMapper.selectSuperiorIdsByOrg(search);
if (CollectionUtils.isEmpty(superiorModelList)) {
return Lists.newArrayList();
}
Set<Long> superiorIds = getSuperiorIds(superiorModelList);
search.setOrgIds(superiorIds);
}
List<OrgModel> modelList = organizationMapper.selectOrgList(search);
List<Long> departmentIdList = modelList.stream().map(OrgModel::getOrgId).collect(Collectors.toList());
//计算用户数
Map<Long, Integer> recursiveDepartmentUserMap = departmentService.countRecursiveDepartmentUser(departmentIdList);
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
orgTreeModelList.forEach(otm -> {
Integer number = recursiveDepartmentUserMap.get(otm.getId());
otm.setUserNumber(number == null ? 0 : number);
});
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
return orgTree;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.mapper.UserMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgSuperiorModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author taoyr
*/
@Component
public class OneselfStrategy extends PermissionStrategy {
@Resource
private UserMapper userMapper;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private DepartmentService departmentService;
@Override
public List<Department> permissionDepartments() {
throw new UserCenterException("权限错误调用,请检查");
}
@Override
public List<User> permissionUsers() {
List<User> list = Lists.newArrayList();
User user = userMapper.selectById(ShieldContextHolder.getUserId());
CollectionUtils.addAll(list, user);
return list;
}
/**
* 2 self 或 selfDepartment
* * 2.1 root 找自己根部门
* * 2.2 非root
* * 先用rootId找到与自己部门的深度,看是上级还是下级(包括用户本部门)
* * 2.2.1 上级
* * 找确定深度的上级部门 先用rootId找到与自己部门的深度,-1得到确定深度,从t_org得到department_id(单个)
* * 2.2.2 下级(本部门)
* * 返回空
* * 封装(false,false)-设置userNum为1(self)或设置userNum为自己部门人数(selfDepartment)-如果是本部门设置hasChild为false,非本部门设置hasChild为true
*
* @param rootId
* @return
*/
@Override
public List<DepartmentDTO> orgSimpleList(Long rootId) {
Long userDeptId = ShieldContextHolder.getDepartmentId();
List<Department> departmentParamList = Lists.newArrayList();
Department department = departmentMapper.selectById(userDeptId);
//只能看他本人的部门
departmentParamList.add(department);
List<DepartmentDTO> departmentDTOList = departmentService.getDepartmentAssembled(departmentParamList, false, false);
departmentDTOList.forEach(dep -> dep.setUserNumber(1));
departmentDTOList.forEach(dep -> {
if (!dep.getId().equals(userDeptId)) {
dep.setHasChildren(true);
}
});
return departmentDTOList;
}
@Override
public List<? extends TreeModel> orgTree(OrgTreeSearch search) {
Long tenantId = ShieldContextHolder.getTenantId();
Long deptId = ShieldContextHolder.getDepartmentId();
search.setTenantId(tenantId);
search.setOrgId(deptId);
List<OrgSuperiorModel> superiorModelList = organizationMapper.selectSuperiorIdsByOrg(search);
Set<Long> ids = getSuperiorIds(superiorModelList);
search.setOrgIds(ids);
List<OrgModel> modelList = organizationMapper.selectOrgList(search);
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
orgTreeModelList.stream().filter(otm -> otm.getId().equals(deptId)).forEach(otm -> {
otm.setUserNumber(1);
});
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
return orgTree;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.model.OrgSuperiorModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.StringUtils;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author taoyr
*/
public abstract class PermissionStrategy {
/**
* 根据角色数据权限范围获取对应的部门(组织)
*
* @return
*/
public abstract List<Department> permissionDepartments();
/**
* 根据角色数据权限范围获取对应的人
*
* @return
*/
public abstract List<User> permissionUsers();
/**
* 获取组织机构列表,需求特殊处理(比如本人角色数据权限为本人,但是要求能看的他自己的(包含自己建和非自己建)上级组织结构数据)
*
* @param rootId
* @return
*/
public abstract List<DepartmentDTO> orgSimpleList(Long rootId);
/**
* 获取组织树
*
* @param search
* @return
*/
public abstract List<? extends TreeModel> orgTree(OrgTreeSearch search);
/**
* 获取上级组织id
*
* @param superiorModelList
* @return
*/
public Set<Long> getSuperiorIds(List<OrgSuperiorModel> superiorModelList) {
Set<Long> superiorIds = Sets.newHashSet();
superiorModelList.forEach(osm -> {
if (StringUtils.isNotEmpty(osm.getSuperiorIds())) {
String[] ids = osm.getSuperiorIds().split(",");
for (String id : ids) {
superiorIds.add(Long.valueOf(id));
}
}
});
return superiorIds;
}
public Set<Long> getSuperiorIds(Long deptId, Map<Long, String> idsStrMap) {
String idsStr = idsStrMap.get(deptId);
Set<Long> superiorIds = Sets.newHashSet();
if (StringUtils.isNotEmpty(idsStr)) {
String[] ids = idsStr.split(",");
for (String id : ids) {
superiorIds.add(Long.valueOf(id));
}
}
return superiorIds;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.admin.common.constant.UserConstants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.mapper.UserMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgSuperiorModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author taoyr
*/
@Slf4j
@Component
public class SelfDepartmentStrategy extends PermissionStrategy {
@Resource
private OrganizationMapper organizationMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private UserMapper userMapper;
@Resource
private DepartmentService departmentService;
@Override
public List<Department> permissionDepartments() {
Department department = departmentMapper.selectById(ShieldContextHolder.getDepartmentId());
log.info("用户{} {}部门为{}", ShieldContextHolder.getAccount(), UserConstants.RolePermitCastType.selfDepartment.getValue(), department.getDepartmentName());
return Lists.newArrayList(department);
}
@Override
public List<User> permissionUsers() {
throw new UserCenterException("权限错误调用,请检查");
}
/**
* 2 self 或 selfDepartment
* * 2.1 root 找自己根部门
* * 2.2 非root
* * 先用rootId找到与自己部门的深度,看是上级还是下级(包括用户本部门)
* * 2.2.1 上级
* * 找确定深度的上级部门 先用rootId找到与自己部门的深度,-1得到确定深度,从t_org得到department_id(单个)
* * 2.2.2 下级(本部门)
* * 返回空
* * 封装(false,false)-设置userNum为1(self)或设置userNum为自己部门人数(selfDepartment)-如果是本部门设置hasChild为false,非本部门设置hasChild为true
*
* @param rootId
* @return
*/
@Override
public List<DepartmentDTO> orgSimpleList(Long rootId) {
Long userDeptId = ShieldContextHolder.getDepartmentId();
List<Department> departmentParamList = Lists.newArrayList();
Department department = departmentMapper.selectById(userDeptId);
departmentParamList.add(department);
List<DepartmentDTO> departmentDTOList = departmentService.getDepartmentAssembled(departmentParamList, false, false);
Integer userNumber = userMapper.countByCriterial(new UserBO().setDepartmentId(userDeptId));
departmentDTOList.forEach(dep -> dep.setUserNumber(userNumber == null ? 0 : userNumber));
departmentDTOList.forEach(dep -> {
if (!dep.getId().equals(userDeptId)) {
dep.setHasChildren(true);
}
});
return departmentDTOList;
}
@Override
public List<? extends TreeModel> orgTree(OrgTreeSearch search) {
Long tenantId = ShieldContextHolder.getTenantId();
Long deptId = ShieldContextHolder.getDepartmentId();
search.setTenantId(tenantId);
search.setOrgId(deptId);
List<OrgSuperiorModel> superiorModelList = organizationMapper.selectSuperiorIdsByOrg(search);
Set<Long> ids = getSuperiorIds(superiorModelList);
search.setOrgIds(ids);
List<OrgModel> modelList = organizationMapper.selectOrgList(search);
List<Long> departmentIdList = modelList.stream().map(OrgModel::getOrgId).collect(Collectors.toList());
//计算用户数
Map<Long, Integer> recursiveDepartmentUserMap = departmentService.countRecursiveDepartmentUser(departmentIdList);
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
orgTreeModelList.stream().filter(otm -> otm.getId().equals(deptId)).forEach(otm -> {
Integer number = recursiveDepartmentUserMap.get(otm.getId());
otm.setUserNumber(number == null ? 0 : number);
});
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
return orgTree;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.admin.common.constant.UserConstants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.Organization;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author taoyr
*/
@Slf4j
@Component
public class SubDepartmentStrategy extends PermissionStrategy {
@Resource
private OrganizationMapper organizationMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private DepartmentService departmentService;
@Override
public List<Department> permissionDepartments() {
Long departmentId = ShieldContextHolder.getDepartmentId();
//获取下属部门
List<OrgModel> modelList = organizationMapper.selectOrgList(new OrgTreeSearch().setTenantId(ShieldContextHolder.getTenantId()));
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
List<Long> subOrgIdList = Lists.newArrayList();
TreeModelUtil.findChildrenIds(departmentId, orgTree, subOrgIdList);
List<Department> list = departmentMapper.selectByIds(subOrgIdList);
log.info("用户{} {}部门数为{}", ShieldContextHolder.getAccount(), UserConstants.RolePermitCastType.subDepartment.getValue(), list.size());
return list;
}
@Override
public List<User> permissionUsers() {
throw new UserCenterException("权限错误调用,请检查");
}
/**
* 3 subDepartment
* * 3.1 root找自己根部门
* * 3.2 非root
* * 先用rootId找到与自己部门的深度,看是上级还是下级(包括用户本部门)
* * 3.2.1 上级
* * 找深度-1的上级部门 从t_org得到department_id(单个)
* * 3.2.2 下级(本部门)
* * 找深度+1的下级部门 从t_org得到department_id列表
* * subDepartment 封装(true,false)-设置userNum为用户部门和用户所有与下级部门userNum(用户部门或用户上级部门)
* * -设置userNum为当前部门和所有下级部门的userNum(用户下级部门)
*
* @param rootId
* @return
*/
@Override
public List<DepartmentDTO> orgSimpleList(Long rootId) {
Long userDeptId = ShieldContextHolder.getDepartmentId();
List<DepartmentDTO> departmentDTOList;
List<Department> departmentParamList = Lists.newArrayList();
if (rootId == null) {
Department department = departmentMapper.selectById(userDeptId);
departmentParamList.add(department);
} else {
List<Organization> organizationList = organizationMapper.selectSubList(Lists.newArrayList(rootId), 1);
if (CollectionUtils.isNotEmpty(organizationList)) {
List<Long> departmentIdList = organizationList.stream().map(Organization::getSubId).collect(Collectors.toList());
List<Department> departmentList = departmentMapper.selectByIds(departmentIdList);
departmentParamList.addAll(departmentList);
}
}
departmentDTOList = departmentService.getDepartmentAssembled(departmentParamList, true, true);
return departmentDTOList;
}
@Override
public List<? extends TreeModel> orgTree(OrgTreeSearch search) {
Long tenantId = ShieldContextHolder.getTenantId();
Long deptId = ShieldContextHolder.getDepartmentId();
search.setTenantId(tenantId);
List<Department> subDepartmentList = this.permissionDepartments();
List<Long> subDepartmentIdList = subDepartmentList.stream().map(Department::getId).collect(Collectors.toList());
search.setOrgIds(subDepartmentIdList);
List<OrgModel> modelList = organizationMapper.selectOrgList(search);
List<Long> departmentIdList = modelList.stream().map(OrgModel::getOrgId).collect(Collectors.toList());
//计算用户数
Map<Long, Integer> recursiveDepartmentUserMap = departmentService.countRecursiveDepartmentUser(departmentIdList);
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
List<Long> subOrgIdList = Lists.newArrayList();
TreeModelUtil.findChildrenIds(deptId, orgTreeModelList, subOrgIdList);
subOrgIdList.add(deptId);
orgTreeModelList.forEach(otm -> {
if (subOrgIdList.contains(otm.getId())) {
Integer number = recursiveDepartmentUserMap.get(otm.getId());
otm.setUserNumber(number == null ? 0 : number);
}
});
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
return orgTree;
}
}
package cn.com.glsx.neshield.modules.service.permissionStrategy;
import cn.com.glsx.admin.common.constant.UserConstants;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.neshield.common.exception.UserCenterException;
import cn.com.glsx.neshield.modules.entity.Department;
import cn.com.glsx.neshield.modules.entity.Organization;
import cn.com.glsx.neshield.modules.entity.User;
import cn.com.glsx.neshield.modules.mapper.DepartmentMapper;
import cn.com.glsx.neshield.modules.mapper.OrganizationMapper;
import cn.com.glsx.neshield.modules.mapper.UserMapper;
import cn.com.glsx.neshield.modules.mapper.UserPathMapper;
import cn.com.glsx.neshield.modules.model.OrgModel;
import cn.com.glsx.neshield.modules.model.OrgTreeModel;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.OrganizationBO;
import cn.com.glsx.neshield.modules.model.param.UserSearch;
import cn.com.glsx.neshield.modules.model.view.DepartmentDTO;
import cn.com.glsx.neshield.modules.model.view.DepartmentUserCount;
import cn.com.glsx.neshield.modules.service.DepartmentService;
import com.glsx.plat.common.model.TreeModel;
import com.glsx.plat.common.utils.TreeModelUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author taoyr
*/
@Slf4j
@Component
public class SubOrdinateStrategy extends PermissionStrategy {
@Resource
private OrganizationMapper organizationMapper;
@Resource
private DepartmentMapper departmentMapper;
@Resource
private DepartmentService departmentService;
@Resource
private UserMapper userMapper;
@Resource
private UserPathMapper userPathMapper;
@Override
public List<Department> permissionDepartments() {
throw new UserCenterException("权限错误调用,请检查");
}
@Override
public List<User> permissionUsers() {
Long departmentId = ShieldContextHolder.getDepartmentId();
Long userId = ShieldContextHolder.getUserId();
//获取下属部门
List<OrgModel> modelList = organizationMapper.selectOrgList(new OrgTreeSearch().setTenantId(ShieldContextHolder.getTenantId()));
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).collect(Collectors.toList());
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertByDepth(orgTreeModelList, 0);
List<Long> subOrgIdList = Lists.newArrayList();
TreeModelUtil.findChildrenIds(departmentId, orgTree, subOrgIdList);
List<User> list = userMapper.selectDepartmentsSubordinate(new UserSearch().setUserId(userId).setDepartmentIdList(subOrgIdList));
//本人
User user = userMapper.selectById(userId);
list.add(user);
log.info("用户{} {}用户数为{}", ShieldContextHolder.getAccount(), UserConstants.RolePermitCastType.subordinate.getValue(), list.size());
return list;
}
/**
* 4 subordinate
* * 4.1 root找自己根部门
* * 4.2 非root
* * 找到rootId的下级部门alist
* * 连表查出所有下级用户(及本人)所在所有部门blist
* * t_organization查询blist是当前alist下级的,存在关系,则为最终部门列表clist
* * -设置userNum 据前面查出的map
* * -设置hasChild clist有depth>=1且在blist集合中的下级部门,则为true
*
* @param rootId
* @return
*/
@Override
public List<DepartmentDTO> orgSimpleList(Long rootId) {
Long userId = ShieldContextHolder.getUserId();
Long userDeptId = ShieldContextHolder.getDepartmentId();
List<Department> departmentParamList = Lists.newArrayList();
if (rootId == null) {
Department department = departmentMapper.selectById(userDeptId);
departmentParamList.add(department);
} else {
//所有下级
List<Organization> childrenOrgList = organizationMapper.selectList(new OrganizationBO()
.setSuperiorIdList(Lists.newArrayList(userDeptId))
.setBiggerDepth(1));
List<Long> subIdList = childrenOrgList.stream().map(Organization::getSubId).collect(Collectors.toList());
//加入用户部门
subIdList.add(userDeptId);
if (subIdList.contains(rootId)) {
List<Organization> subOrganizationList = organizationMapper.selectSubList(Lists.newArrayList(rootId), 1);
List<Long> departmentIdList = subOrganizationList.stream().map(Organization::getSubId).collect(Collectors.toList());
List<Department> departmentList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(departmentIdList)) {
departmentList = departmentMapper.selectByIds(departmentIdList);
}
departmentParamList.addAll(departmentList);
}
}
//存在用户的下级部门
List<DepartmentUserCount> departmentUserCountList = userPathMapper.selectSubordinateDepartmentList(userId);
List<Long> hasUserDeptIdList = departmentUserCountList.stream()
.filter(duc -> duc.getDepartmentId() != null)
.map(DepartmentUserCount::getDepartmentId)
.collect(Collectors.toList());
List<DepartmentDTO> departmentDTOList = departmentService.getDepartmentAssembled(departmentParamList, false, false);
for (DepartmentDTO departmentDTO : departmentDTOList) {
if (rootId == null) {
departmentDTO.setHasChildren(CollectionUtils.isNotEmpty(hasUserDeptIdList));
} else {
departmentDTO.setHasChildren(hasUserDeptIdList.contains(departmentDTO.getId()));
}
}
return departmentDTOList;
}
@Override
public List<? extends TreeModel> orgTree(OrgTreeSearch search) {
Long tenantId = ShieldContextHolder.getTenantId();
Long userId = ShieldContextHolder.getUserId();
List<DepartmentUserCount> departmentUserCountList = userPathMapper.selectSubordinateDepartmentList(userId);
//下级部门id
List<Long> subDepartmentIdList = departmentUserCountList.stream()
.filter(duc -> duc.getDepartmentId() != null)
.map(DepartmentUserCount::getDepartmentId)
.collect(Collectors.toList());
//模糊搜索得到的部门
List<Department> namedDepartmentList = departmentMapper.selectDepartmentList(new Department()
.setTenantId(tenantId)
.setDepartmentName(search.getOrgName()));
//提取符合搜索条件的部门
List<Department> finalNamedDepartmentList = namedDepartmentList.stream().filter(department -> subDepartmentIdList.contains(department.getId())).collect(Collectors.toList());
//符合条件的部门idList
List<Long> nameDepartmentIdList = finalNamedDepartmentList.stream().map(Department::getId).collect(Collectors.toList());
List<Organization> superiorOrgList = organizationMapper.selectList(new OrganizationBO().setSubIdList(nameDepartmentIdList));
//所有部门id
List<Long> allDepartmentIdList = superiorOrgList.stream().map(Organization::getSuperiorId).collect(Collectors.toList());
allDepartmentIdList.addAll(nameDepartmentIdList);
List<Department> allDepartmentList = departmentMapper.selectByIds(allDepartmentIdList);
//所有组织链
List<Organization> organizationList = organizationMapper.selectList(new OrganizationBO().setSubIdList(allDepartmentIdList).setSuperiorIdList(allDepartmentIdList));
//根节点
List<Organization> rootList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(nameDepartmentIdList)) {
rootList = organizationMapper.selectRootIdList(nameDepartmentIdList);
}
Set<Long> rootIds = rootList.stream().map(Organization::getSuperiorId).collect(Collectors.toSet());
Map<Long, Organization> organizationMap = organizationList.stream().filter(m -> m.getDepth() == 0 || m.getDepth() == 1).
collect(Collectors.toMap(Organization::getSubId, treeModel -> treeModel));
Map<Long, Integer> subordinateDepartmentUserCountMap = departmentUserCountList.stream().collect(Collectors.toMap(DepartmentUserCount::getDepartmentId, DepartmentUserCount::getUserNumber));
List<OrgModel> modelList = allDepartmentList.stream().map(dep -> {
OrgModel orgModel = new OrgModel();
Organization org = organizationMap.get(dep.getId());
if (org != null) {
orgModel.setParentId(org.getSuperiorId());
}
orgModel.setOrgId(dep.getId());
orgModel.setOrgName(dep.getDepartmentName());
orgModel.setTenantId(dep.getTenantId());
Integer userNumber = subordinateDepartmentUserCountMap.get(dep.getId());
orgModel.setUserNumber(userNumber);
orgModel.setOrderNum(dep.getOrderNum());
return orgModel;
}).collect(Collectors.toList());
List<OrgTreeModel> orgTreeModelList = modelList.stream().map(OrgTreeModel::new).sorted(Comparator.comparing(OrgTreeModel::getOrder)).collect(Collectors.toList());
List<? extends TreeModel> orgTree = TreeModelUtil.fastConvertClosure(orgTreeModelList, Lists.newArrayList(rootIds));
return orgTree;
}
}
#项目名称
spring.application.name=glsx-ne-shield-usercenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.0.39:3306/neshield?serverTimeZone=Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
userId="root"
password="123456">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.glsx.neshield.modules.entity" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.glsx.neshield.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="t_user_path" domainObjectName="UserPath" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.DepartmentMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.Department">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="department_name" jdbcType="VARCHAR" property="departmentName"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="is_root" jdbcType="TINYINT" property="isRoot"/>
<result column="order_num" jdbcType="INTEGER" property="orderNum"/>
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, department_name, tenant_id,is_root, del_flag, order_num, enable_status,created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_department
where del_flag = 0
and id = #{id}
</select>
<update id="logicDeleteByIdList">
update t_department set del_flag = -1 where
id in
<foreach collection="ids" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</update>
<select id="selectDepartmentList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_department
where del_flag = 0
<if test="tenantId != null">
and tenant_id = #{tenantId}
</if>
<if test="departmentName != null">
and department_name like CONCAT('%',#{departmentName},'%')
</if>
<if test="enableStatus != null">
and enable_status = #{enableStatus}
</if>
<if test="isRoot != null">
and is_root = #{isRoot}
</if>
order by order_num
</select>
<select id="selectByIds" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_department where del_flag = 0
and id in
<foreach collection="ids" separator="," open="(" close=")" item="id">
#{id}
</foreach>
</select>
<select id="selectAllNotDel" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_department where del_flag = 0
</select>
<select id="selectRootDepartmentByTenantId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_department
where del_flag = 0
and is_root = 1
and tenant_id = #{tenantId}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.MenuMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.Menu">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="menu_no" jdbcType="INTEGER" property="menuNo"/>
<result column="menu_name" jdbcType="VARCHAR" property="menuName"/>
<result column="front_route" jdbcType="VARCHAR" property="frontRoute"/>
<result column="permission_tag" jdbcType="VARCHAR" property="permissionTag"/>
<result column="parent_id" jdbcType="INTEGER" property="parentId"/>
<result column="type" jdbcType="TINYINT" property="type"/>
<result column="icon" jdbcType="VARCHAR" property="icon"/>
<result column="order_num" jdbcType="INTEGER" property="orderNum"/>
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<resultMap id="DTOResultMap" type="cn.com.glsx.neshield.modules.model.view.MenuDTO">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="menu_no" jdbcType="INTEGER" property="menuNo"/>
<result column="menu_name" jdbcType="VARCHAR" property="menuName"/>
<result column="front_route" jdbcType="VARCHAR" property="frontRoute"/>
<result column="permission_tag" jdbcType="VARCHAR" property="permissionTag"/>
<result column="parent_id" jdbcType="INTEGER" property="parentId"/>
<result column="type" jdbcType="TINYINT" property="type"/>
<result column="icon" jdbcType="VARCHAR" property="icon"/>
<result column="order_num" jdbcType="INTEGER" property="orderNum"/>
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
</resultMap>
<sql id="Base_Column_List">
id, menu_no, menu_name, front_route, permission_tag, parent_id, `type`, icon, order_num, enable_status,
del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_menu
where id = #{id}
and del_flag = 0
</select>
<select id="selectByMenuNo" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_menu
where menu_no = #{menuNo}
and del_flag = 0
</select>
<update id="logicDeleteById">
update t_menu set del_flag = -1 where id = #{id}
</update>
<select id="selectDTOList" resultMap="DTOResultMap">
select
<include refid="Base_Column_List"/>
from t_menu
where del_flag = 0
<if test="name != null and name != ''">
and menu_name LIKE CONCAT('%',#{name},'%')
</if>
<if test="enableStatus != null">
and enable_status = #{enableStatus}
</if>
<choose>
<when test="parentId !=null">
and parent_id LIKE CONCAT(#{parentId},'%')
</when>
<otherwise>
and type = 1
</otherwise>
</choose>
order by order_num
</select>
<select id="selectMenuFullTree" resultType="cn.com.glsx.neshield.modules.model.MenuModel">
select m.menu_no menuNo,m.parent_id parentId,m.menu_name menuName,m.order_num orderNum,m.type,m.icon
from t_menu m
where m.del_flag = 0
and m.enable_status = 1
</select>
<select id="selectMenuPermTree" resultType="cn.com.glsx.neshield.modules.model.MenuModel">
select m.menu_no menuNo,m.parent_id parentId,m.menu_name menuName,m.order_num orderNum,
m.type,m.front_route frontRoute,m.icon
from t_menu m,t_role_menu rm
where m.menu_no = rm.menu_id
and m.del_flag = 0
and rm.del_flag = 0
and m.enable_status = 1
<if test="roleIds != null and roleIds.size() > 0">
and rm.role_id in
<foreach collection="roleIds" item="roleId" open="(" close=")" separator=",">
#{roleId}
</foreach>
</if>
<if test="menuIds != null and menuIds.size() > 0">
and m.id in
<foreach collection="menuIds" item="menuId" open="(" close=")" separator=",">
#{menuId}
</foreach>
</if>
<if test="menuTypes != null and menuTypes.size() > 0">
and m.type in
<foreach collection="menuTypes" item="type" open="(" close=")" separator=",">
#{type}
</foreach>
</if>
</select>
<select id="selectMenuTreeByParentId" resultType="cn.com.glsx.neshield.modules.model.MenuModel">
select m.menu_no menuNo,m.parent_id parentId,m.menu_name menuName,m.order_num orderNum,m.type,m.icon
from t_menu m,t_role_menu rm
where m.id = rm.menu_id
and m.del_flag = 0
and rm.del_flag = 0
and m.enable_status = 1
<if test="roleIds != null and roleIds.size() > 0">
and rm.role_id in
<foreach collection="roleIds" item="roleId" open="(" close=")" separator=",">
#{roleId}
</foreach>
</if>
and m.parent_id = #{parentNo}
</select>
<select id="selectList" resultMap="BaseResultMap">
select
m.id,
m.menu_no,
m.menu_name,
m.front_route,
m.permission_tag,
m.parent_id,
m.`type`,
m.icon,
m.order_num,
m.enable_status,
m.del_flag,
m.created_date,
m.created_by,
m.updated_date,
m.updated_by
from t_menu m,t_role_menu rm
where m.id = rm.menu_id
and m.del_flag = 0
and rm.del_flag = 0
and m.enable_status = 1
<if test="roleIds != null and roleIds.size() > 0">
and rm.role_id in
<foreach collection="roleIds" item="roleId" open="(" close=")" separator=",">
#{roleId}
</foreach>
</if>
</select>
<select id="selectByParentId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_menu
where parent_id = #{parentNo}
and del_flag = 0
order by order_num
</select>
<select id="selectByLikeParentNo" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_menu
where menu_no like #{parentNo}
and del_flag = 0
order by order_num
</select>
<select id="selectChildrenCntByParentId" resultType="java.lang.Integer">
select
count(1)
from t_menu
where parent_id = #{parentNo}
and del_flag = 0
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.MenuPermissionMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.MenuPermission">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="permission_tag" jdbcType="VARCHAR" property="permissionTag"/>
<result column="interface_url" jdbcType="VARCHAR" property="interfaceUrl"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, permission_tag, interface_url, del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectByMenuIds" resultMap="BaseResultMap">
select tp.* from t_permission tp,t_menu tm
where tp.permission_tag = tm.permission_tag
and tm.id in
<foreach collection="menuIds" separator="," close=")" open="(" item="menuId">
#{menuId}
</foreach>
and tm.del_flag = 0
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.OrganizationMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.Organization">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="superior_id" jdbcType="INTEGER" property="superiorId"/>
<result column="sub_id" jdbcType="INTEGER" property="subId"/>
<result column="depth" jdbcType="INTEGER" property="depth"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, superior_id, sub_id, `depth`, tenant_id, del_flag,
created_date, created_by, updated_date, updated_by
</sql>
<insert id="insertRootPath">
insert into t_organization
(superior_id, sub_id, depth, tenant_id, created_date,created_by)
values
(#{superiorId}, #{subId}, 0, #{tenantId}, #{createdDate}, #{createdBy})
</insert>
<insert id="insertOrganizationPath" useGeneratedKeys="false">
insert into t_organization
(superior_id, sub_id, depth, tenant_id, created_date, created_by)
select tor.superior_id, #{subId}, tor.depth+1, #{tenantId}, #{createdDate}, #{createdBy}
from t_organization as tor
where tor.sub_id = #{superiorId} and tor.depth <![CDATA[ <> ]]> 0
union all
select #{superiorId}, #{subId}, 1, #{tenantId}, #{createdDate}, #{createdBy}
</insert>
<delete id="deleteOrganizationPath">
delete a from t_organization a join t_organization b on (a.sub_id = b.sub_id)
where b.superior_id=#{nodeId};
</delete>
<!-- <select id="getUserDepartmentId" resultType="java.lang.Long">-->
<!-- select superior_id-->
<!-- from t_organization-->
<!-- where sub_id = #{userId} and del_flag = 0-->
<!-- and depth = (-->
<!-- select min(depth)-->
<!-- from t_organization-->
<!-- where sub_id = #{userId} and del_flag = 0-->
<!-- )-->
<!-- </select>-->
<!-- <select id="getUserSubDepartment" resultType="java.lang.Long">-->
<!-- select sub_id-->
<!-- from t_organization-->
<!-- where superior_id = #{userId} and type = 1 and del_flag = 0-->
<!-- and depth = (-->
<!-- select min(depth)-->
<!-- from t_organization-->
<!-- where superior_id = #{userId} and type = 1 and del_flag = 0-->
<!-- )-->
<!-- </select>-->
<!-- <select id="getUserSuperiorUser" resultType="java.lang.Long">-->
<!-- select superior_id-->
<!-- from t_organization-->
<!-- where sub_id = #{userId} and type = 0 and del_flag = 0-->
<!-- and depth = (-->
<!-- select max(depth)-->
<!-- from t_organization-->
<!-- where sub_id = #{userId} and type = 0 and del_flag = 0 order by depth limit 2-->
<!-- )-->
<!-- </select>-->
<select id="selectOrgList" resultType="cn.com.glsx.neshield.modules.model.OrgModel">
select tor.sub_id orgId,max(tor.superior_id) parentId,min(tor2.superior_id) superiorId,max(tor.depth) depth,
tt.id tenantId,tt.tenant_name tenantName,td.department_name orgName
from t_organization tor,t_organization tor2
left join t_department td on tor2.sub_id = td.id
left join t_user tu on tor2.sub_id = tu.id
left join t_tenant tt on tor2.tenant_id = tt.id
where td.del_flag = 0
and td.enable_status = 1
and tor.id = tor2.id
and tt.id = tor.tenant_id
<if test="tenantId != null">
and tt.id = #{tenantId}
</if>
<if test="orgIds != null and orgIds.size() > 0">
and tor.sub_id in
<foreach collection="orgIds" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
group by tor.sub_id
order by max(tor.superior_id),max(tor.depth),tor.sub_id
</select>
<select id="selectSuperiorIdsByOrg" resultType="cn.com.glsx.neshield.modules.model.OrgSuperiorModel">
select td1.id orgId,concat(group_concat(to1.superior_id),',',to1.sub_id) superiorIds
from t_department td1, t_organization to1
where td1.del_flag = 0
and td1.id = to1.sub_id
<if test="tenantId != null">
and td1.tenant_id = #{tenantId}
</if>
<if test="orgId != null">
and td1.id = #{orgId}
</if>
<if test="orgName != null and orgName !=''">
and department_name LIKE CONCAT('%',#{orgName},'%')
</if>
group by to1.sub_id
</select>
<select id="selectByRootId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where del_flag = 0 and superior_id = #{organizationId}
</select>
<select id="selectRootPath" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where tenant_id = #{tenantId}
and depth = 0
and del_flag = 0
</select>
<select id="selectRootPathBySubId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where sub_id = #{subId} and del_flag = 0
and depth = (
select max(depth)
from t_organization
where sub_id = #{subId} and del_flag = 0
)
</select>
<select id="selectRootIdList" resultType="cn.com.glsx.neshield.modules.entity.Organization">
select max(depth) depth, superior_id superiorId, sub_id subId from t_organization
where del_flag = 0 and sub_id in
<foreach collection="subIds" separator="," open="(" close=")" item="subId">
#{subId}
</foreach>
group by sub_id
</select>
<select id="selectSuperiorOrganization" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where sub_id = #{organizationId} and del_flag = 0
and depth = 1
</select>
<select id="selectChildrenList" resultType="cn.com.glsx.neshield.modules.entity.Department"
parameterType="cn.com.glsx.neshield.modules.model.param.OrganizationSearch">
select tde.id id, tde.department_name departmentName, order_num orderNum,
tde.created_date createdDate, tde.enable_status enableStatus
from t_organization tor, t_department tde
where tor.sub_id = tde.id
and tor.del_flag = 0 and tde.del_flag = 0
and tor.superior_id = #{rootId} and tor.depth = 1
<if test="orgName != null">
and tde.department_name like CONCAT('%',#{orgName},'%')
</if>
<if test="enableStatus != null">
and tde.enable_status = #{enableStatus}
</if>
order by tde.order_num
</select>
<select id="selectSubList" resultType="cn.com.glsx.neshield.modules.entity.Organization">
select
distinct(sub_id) subId, superior_id superiorId
from t_organization
where del_flag = 0
and superior_id in
<foreach collection="departmentIds" item="departmentId" open="(" close=")" separator=",">
#{departmentId}
</foreach>
<if test="depth != null">
and depth = #{depth}
</if>
</select>
<select id="selectList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where del_flag = 0
<if test="subIdList != null and subIdList.size() > 0">
and sub_id in
<foreach collection="subIdList" item="subId" open="(" close=")" separator=",">
#{subId}
</foreach>
</if>
<if test="superiorIdList != null">
and superior_id in
<foreach collection="superiorIdList" item="superiorId" open="(" close=")" separator=",">
#{superiorId}
</foreach>
</if>
<if test="biggerDepth != null">
and depth >= #{biggerDepth}
</if>
</select>
<select id="selectRootByRootIdAndSubId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where del_flag = 0
and superior_id = #{rootId}
and sub_id = #{subId}
</select>
<select id="selectAllSuperiorBySubId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_organization
where del_flag = 0
and sub_id = #{subId}
</select>
<update id="logicDeleteSelfBySubId">
update t_organization set del_flag = -1 where sub_id = #{subId}
</update>
<update id="logicDeleteAllSubOrganization">
update t_organization set del_flag = -1 where superior_id=#{organizationId}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.RoleMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.Role">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="role_name" jdbcType="VARCHAR" property="roleName"/>
<result column="role_permission_type" jdbcType="TINYINT" property="rolePermissionType"/>
<result column="max_user" jdbcType="INTEGER" property="maxUser"/>
<result column="repel_roles" jdbcType="VARCHAR" property="repelRoles"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="role_visibility" jdbcType="INTEGER" property="roleVisibility"/>
<!-- <result column="role_tenants" jdbcType="VARCHAR" property="roleTenants"/>-->
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, role_name, role_permission_type, max_user, repel_roles,
remark, tenant_id, role_visibility, enable_status, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role
where del_flag = 0
and id = #{id}
</select>
<update id="logicDeleteById">
update t_role set del_flag = -1 where id = #{id}
</update>
<select id="selectList" resultMap="BaseResultMap"
parameterType="cn.com.glsx.neshield.modules.model.param.RoleSearch">
select
<include refid="Base_Column_List"/>
from t_role
where del_flag = 0
<if test="roleName != null and roleName != ''">
and role_name like concat('%',#{roleName},'%')
</if>
<if test="enableStatus != null">
and enable_status = #{enableStatus}
</if>
<if test="roleVisibility != null">
and role_visibility = #{roleVisibility}
</if>
order by id desc
</select>
<select id="selectVisibilityList" resultMap="BaseResultMap"
parameterType="cn.com.glsx.neshield.modules.model.param.RoleSearch">
select * from (
select tr1.*
from t_role tr1
where tr1.del_flag = 0
and tr1.role_visibility = 0
union
select tr.*
from t_role tr,
t_role_tenant trt
where tr.del_flag = 0
and trt.del_flag = 0
and tr.role_visibility = 2
and tr.id = trt.role_id
and trt.tenant_id = #{tenantId}
) tall where 1=1
<if test="roleName != null and roleName != ''">
and role_name like concat('%',#{roleName},'%')
</if>
<if test="enableStatus != null">
and enable_status = #{enableStatus}
</if>
order by id desc
</select>
<select id="selectRoleListByIds" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role
where del_flag = 0
and id in
<foreach collection="roleIds" open="(" close=")" separator="," item="roleId">
#{roleId}
</foreach>
</select>
<select id="selectUserRoleList" resultType="cn.com.glsx.neshield.modules.entity.Role">
select r.id id, r.role_name roleName, r.role_permission_type rolePermissionType
from t_role r, t_user_role_relation urr
where r.del_flag = 0 and urr.del_flag = 0 and r.role_id = urr.role_id
and urr.user_id = #{userId}
</select>
<select id="selectCntByName" resultType="java.lang.Integer">
select count(role_name) from t_role
where del_flag = 0
and role_name = #{roleName}
</select>
<select id="selectByName" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role
where del_flag = 0
and role_name = #{roleName}
limit 1
</select>
<select id="selectByVisibilityType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role
where del_flag = 0
and enable_status = 1
and role_visibility = #{roleVisibility}
</select>
<select id="selectRoleIdsByVisibilityType" resultMap="BaseResultMap">
select id
from t_role
where del_flag = 0
and enable_status = 1
and role_visibility = #{roleVisibility}
</select>
<select id="selectByTenantIds" resultMap="BaseResultMap">
select tr.*
from t_role tr,t_role_tenant trt
where tr.del_flag = 0
and trt.del_flag = 0
and tr.enable_status = 1
and tr.id = trt.role_id
and trt.tenant_id in
<foreach collection="tenantIds" open="(" close=")" separator="," item="tenantId">
#{tenantId}
</foreach>
order by tr.id
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.RoleMenuMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.RoleMenu">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="role_id" jdbcType="INTEGER" property="roleId"/>
<result column="menu_id" jdbcType="INTEGER" property="menuNo"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, role_id, menu_id, del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectByRoleId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role_menu
where del_flag = 0
and role_id = #{roleId}
</select>
<select id="selectByMenuId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role_menu
where del_flag = 0
and menu_id = #{menuId}
</select>
<select id="selectMenuIdsByRoleId" resultType="java.lang.Long">
select menu_id
from t_role_menu
where del_flag = 0
and role_id = #{roleId}
</select>
<select id="selectMenuIdsByRoleIds" resultType="java.lang.Long">
select menu_id
from t_role_menu
where del_flag = 0
and role_id in
<foreach collection="roleIds" separator="," close=")" open="(" item="roleId">
#{roleId}
</foreach>
</select>
<select id="selectRoleIdsByMenuId" resultType="java.lang.Long">
select role_id
from t_role_menu
where del_flag = 0
and menu_id = #{menuId}
</select>
<update id="logicDelByRoleId">
update t_role_menu set del_flag = -1 where role_id = #{roleId}
</update>
<delete id="deleteByMenuNo">
delete from t_role_menu where menu_id = #{menuNo}
</delete>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.RoleTenantMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.RoleTenant">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="role_id" jdbcType="INTEGER" property="roleId"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, role_id, tenant_id, del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectByRoleId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role_tenant
where role_id = #{roleId}
and del_flag = 0
</select>
<select id="selectTenantIdsByRoleId" resultType="java.lang.Long">
select
tenant_id
from t_role_tenant
where role_id = #{roleId}
and del_flag = 0
</select>
<select id="selectByTenantId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_role_tenant
where tenant_id = #{tenantId}
and del_flag = 0
</select>
<select id="selectRoleIdsByTenantId" resultType="java.lang.Long">
select
role_id
from t_role_tenant
where tenant_id = #{roleId}
and del_flag = 0
</select>
<update id="logicDeleteByRoleId">
update t_role_tenant set del_flag = -1 where role_id = #{roleId}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.TenantMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.Tenant">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="tenant_name" jdbcType="VARCHAR" property="tenantName"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, tenant_name, del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_tenant
where del_flag = 0
and id = #{id}
</select>
<update id="logicDeleteById">
update t_tenant set del_flag = -1 where id = #{id}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserGroupMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.UserGroup">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_group_name" jdbcType="INTEGER" property="userGroupName" />
<result column="tenant_id" jdbcType="INTEGER" property="tenantId" />
<result column="enable_status" jdbcType="TINYINT" property="enableStatus" />
<result column="del_flag" jdbcType="TINYINT" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
id, user_group_name, tenant_id, enable_status, del_flag, created_date, created_by, updated_date,
updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserGroupRelationMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.UserGroupRelation">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_id" jdbcType="INTEGER" property="userId" />
<result column="user_group_id" jdbcType="INTEGER" property="userGroupId" />
<result column="del_flag" jdbcType="TINYINT" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
id, user_id, user_group_id, del_flag, created_date, created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserGroupRoleRelationMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.UserGroupRoleRelation">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_group_id" jdbcType="INTEGER" property="userGroupId" />
<result column="role_id" jdbcType="INTEGER" property="roleId" />
<result column="del_flag" jdbcType="TINYINT" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
id, user_group_id, role_id, del_flag, created_date,
created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="account" jdbcType="VARCHAR" property="account"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="phone_number" jdbcType="VARCHAR" property="phoneNumber"/>
<result column="portrait" jdbcType="VARCHAR" property="portrait"/>
<result column="email" jdbcType="VARCHAR" property="email"/>
<result column="gender" jdbcType="INTEGER" property="gender"/>
<result column="position_" jdbcType="VARCHAR" property="position"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="department_id" jdbcType="INTEGER" property="departmentId"/>
<result column="superior_id" jdbcType="INTEGER" property="superiorId"/>
<result column="salt" jdbcType="VARCHAR" property="salt"/>
<result column="enable_status" jdbcType="INTEGER" property="enableStatus"/>
<result column="is_admin" jdbcType="TINYINT" property="admin"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, username, account, `password`, phone_number,
portrait, email, gender, position, salt, tenant_id, department_id,
superior_id, is_admin, del_flag, enable_status,
created_date, created_by, updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select * from t_user
where id = #{id}
and del_flag = 0
</select>
<select id="selectByDepartmentId" resultMap="BaseResultMap">
select * from t_user
where department_id = #{departmentId}
and del_flag = 0
</select>
<select id="selectExcludeUserIdByDepartmentId" resultMap="BaseResultMap">
select * from t_user
where del_flag = 0
and department_id = #{departmentId}
and id <![CDATA[ <> ]]> #{userId}
</select>
<select id="selectCntByAccount" parameterType="java.lang.String" resultType="java.lang.Integer">
select count(account) from t_user
where account = #{account}
and del_flag = 0
</select>
<select id="selectByAccount" parameterType="java.lang.String" resultMap="BaseResultMap">
select * from t_user
where account = #{account}
and del_flag = 0
limit 1
</select>
<select id="selectList" resultMap="BaseResultMap"
parameterType="cn.com.glsx.neshield.modules.model.param.UserSearch">
select
<include refid="Base_Column_List"/>
from t_user where del_flag = 0
<if test="searchField != null and searchField !=''">
and (
account like CONCAT('%',#{searchField},'%')
or
phone_number like CONCAT('%',#{searchField},'%')
or
username like CONCAT('%',#{searchField},'%')
or
id = #{searchField}
)
</if>
<if test="userId != null">
and user_id = #{userId}
</if>
<if test="userStatus != null">
and enable_status = #{userStatus}
</if>
<if test="departmentIdList != null and departmentIdList.size() > 0">
and department_id in
<foreach collection="departmentIdList" item="departmentId" open="(" close=")" separator=",">
#{departmentId}
</foreach>
</if>
order by id desc
</select>
<update id="logicDeleteById">
update t_user set del_flag = -1 where id = #{id}
</update>
<select id="countByCriterial" parameterType="cn.com.glsx.neshield.modules.model.param.UserBO"
resultType="java.lang.Integer">
select count(*) from t_user
where del_flag = 0
<if test="departmentId != null">
and department_id = #{departmentId}
</if>
<if test="departmentIds != null and departmentIds.size() > 0">
and department_id in
<foreach collection="departmentIds" item="departmentId" open="(" close=")" separator=",">
#{departmentId}
</foreach>
</if>
</select>
<select id="countDepartmentsUser" resultType="cn.com.glsx.neshield.modules.model.view.DepartmentCount">
select department_id as departmentId, count(*) as userNumber from t_user
where del_flag = 0
<if test="departmentIds != null and departmentIds.size() > 0">
and department_id in
<foreach collection="departmentIds" item="departmentId" open="(" close=")" separator=",">
#{departmentId}
</foreach>
</if>
group by department_id
</select>
<select id="selectDepartmentsSubordinate" resultType="cn.com.glsx.neshield.modules.entity.User">
select tu.id id, tu.account account, tu.username username, tu.department_id departmentId,
tu.phone_number phoneNumber, tu.enable_status enableStatus, tu.created_date createdDate
from t_user tu, t_user_path tup
where tu.del_flag = 0 and tup.del_flag = 0
and tu.id = tup.sub_id
and tup.superior_id = #{userId}
<if test="userStatus != null">
and tu.enable_status = #{userStatus}
</if>
<if test="searchField != null">
and (
tu.account like CONCAT('%',#{searchField},'%')
or
tu.phone_number like CONCAT('%',#{searchField},'%')
or
tu.username like CONCAT('%',#{searchField},'%')
)
</if>
<if test="departmentIdList != null and departmentIdList.size() > 0">
and tu.department_id in
<foreach collection="departmentIdList" separator="," close=")" open="(" item="departmentId">
#{departmentId}
</foreach>
</if>
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserPathMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.UserPath">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="superior_id" jdbcType="INTEGER" property="superiorId"/>
<result column="sub_id" jdbcType="INTEGER" property="subId"/>
<result column="depth" jdbcType="INTEGER" property="depth"/>
<result column="tenant_id" jdbcType="INTEGER" property="tenantId"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, superior_id, sub_id, `depth`, tenant_id, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<insert id="insertRootPath">
insert into t_user_path
(superior_id, sub_id, depth, tenant_id, created_date,created_by)
values
(#{superiorId}, #{subId}, 0, #{tenantId}, #{createdDate}, #{createdBy})
</insert>
<insert id="insertUserPath" useGeneratedKeys="false">
insert into t_user_path
(superior_id, sub_id, depth, tenant_id, created_date, created_by)
select tor.superior_id, #{subId}, tor.depth+1, #{tenantId}, #{createdDate}, #{createdBy}
from t_user_path as tor
where tor.sub_id = #{superiorId}
union all
select #{superiorId}, #{subId}, 1, #{tenantId}, #{createdDate}, #{createdBy}
</insert>
<select id="selectRootPath" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_path
where tenant_id = #{tenantId}
and depth = 0
and del_flag = 0
</select>
<select id="selectRootPathBySubId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_path
where sub_id = #{subId} and del_flag = 0
and depth = (
select max(depth)
from t_organization
where sub_id = #{subId} and del_flag = 0
)
</select>
<select id="selectSubordinateDepartmentList"
resultType="cn.com.glsx.neshield.modules.model.view.DepartmentUserCount">
select
tu.department_id departmentId,count(*) userNumber
from t_user tu, t_user_path tup
where tu.del_flag = 0 and tup.del_flag = 0
and tup.sub_id = tu.id
and tup.superior_id = #{userId}
</select>
<select id="selectUserSubordinateList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_path
where del_flag = 0
and superior_id = #{userId}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.neshield.modules.mapper.UserRoleRelationMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.neshield.modules.entity.UserRoleRelation">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="role_id" jdbcType="INTEGER" property="roleId"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
id, user_id, role_id, del_flag, created_date, created_by, updated_date, updated_by
</sql>
<select id="selectUserRoleRelationList" resultMap="BaseResultMap">
select turr.*
from t_user_role_relation turr,t_user tu
where turr.del_flag = 0 and tu.del_flag = 0
and turr.user_id = tu.id
<if test="userId != null">
and turr.user_id = #{userId}
</if>
<if test="roleId != null">
and turr.role_id = #{roleId}
</if>
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8883"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-ne-shield-usercenter"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-ne-shield-usercenter"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.test;
import cn.com.glsx.Application;
import cn.com.glsx.neshield.modules.entity.Menu;
import cn.com.glsx.neshield.modules.entity.Role;
import cn.com.glsx.neshield.modules.model.param.OrgTreeSearch;
import cn.com.glsx.neshield.modules.model.param.UserBO;
import cn.com.glsx.neshield.modules.service.MenuService;
import cn.com.glsx.neshield.modules.service.OrganizationService;
import cn.com.glsx.neshield.modules.service.RoleService;
import cn.com.glsx.neshield.modules.service.UserService;
import cn.com.glsx.neshield.modules.service.permissionStrategy.PermissionStrategy;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserApplicationTests {
@Autowired
private OrganizationService organizationService;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private MenuService menuService;
@Resource
private HashedCredentialsMatcher hcm;
@Autowired
private Map<String, PermissionStrategy> permissionStrategyMap;
@Test
public void testOrg() {
OrgTreeSearch search = new OrgTreeSearch();
search.setOrgName("部");
// List<Long> superiorIds = organizationService.getSuperiorIdsByName(search.getOrgName());
// search.setOrgIds(superiorIds);
List list1 = organizationService.fullOrgTree(search);
System.out.println(JSON.toJSONString(list1));
List list2 = organizationService.orgTree(search);
System.out.println(JSON.toJSONString(list2));
}
@Test
public void testRole() {
List<Role> list = roleService.getUserRoleList(1L);
System.out.println(JSON.toJSONString(list));
}
@Test
public void testMenu() {
List<Long> ids = new ArrayList<>();
ids.add(1L);
List list = menuService.getMenuTree(ids);
System.out.println(JSON.toJSONString(list));
}
@Test
public void testMenuNo() {
Long no = menuService.generateMenuNo(null);
System.out.println(no);
}
@Test
public void testUser() {
// SyntheticUser user = userService.getSyntheticUser();
// System.out.println(JSON.toJSONString(user));
// R r = userService.suitableSuperUsers(5L);
// System.out.println(JSON.toJSON(r));
userService.addUser(new UserBO().setAccount("rrew").setUsername("桃桃桃").setDepartmentId(1L).setRoleId(1L).setPassword("123456"));
}
@Test
public void testPassword() {
String password = "123456";
String salt = StringUtils.generateRandomCode(false, 4);
SimpleHash hash = new SimpleHash(hcm.getHashAlgorithmName(), password, salt, hcm.getHashIterations());
//加密入库的密码
String epassword = hash.toString();
System.out.println(salt);
System.out.println(epassword);
String account = "admin";
UsernamePasswordToken token = new UsernamePasswordToken(account, password);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(account, epassword, ByteSource.Util.bytes(salt), account);
boolean matchFlag = hcm.doCredentialsMatch(token, authenticationInfo);
System.out.println(matchFlag);
}
@Test
public void testMenuDept() {
Integer depth = menuService.getMenuDepth(new Menu().setParentId(701010201L), 0);
System.out.println(depth);
}
@Test
public void testCheckedMenus() {
Set<Long> list = menuService.getMenuCheckedIds(19L);
log.info(list.toString());
}
}
\ No newline at end of file \ No newline at end of file
{
"code": 200,
"data": [
{
"children": [
{
"children": [],
"id": 10101,
"origin": {
"menuNo": 10101,
"menuName": "用户管理",
"parentId": 101,
"orderNum": 1
},
"order": 1,
"depth": null,
"parentId": 101,
"label": "用户管理"
},
{
"children": [],
"id": 10102,
"origin": {
"menuNo": 10102,
"menuName": "用户管理",
"parentId": 101,
"orderNum": 2
},
"order": 2,
"depth": null,
"parentId": 101,
"label": "用户管理"
},
{
"children": [],
"id": 10103,
"origin": {
"menuNo": 10103,
"menuName": "角色管理",
"parentId": 101,
"orderNum": 3
},
"order": 3,
"depth": null,
"parentId": 101,
"label": "角色管理"
},
{
"children": [],
"id": 10104,
"origin": {
"menuNo": 10104,
"menuName": "菜单管理",
"parentId": 101,
"orderNum": 4
},
"order": 4,
"depth": null,
"parentId": 101,
"label": "菜单管理"
},
{
"children": [],
"id": 10105,
"origin": {
"menuNo": 10105,
"menuName": "组织管理",
"parentId": 101,
"orderNum": 5
},
"order": 5,
"depth": null,
"parentId": 101,
"label": "组织管理"
},
{
"children": [],
"id": 10106,
"origin": {
"menuNo": 10106,
"menuName": "字典管理",
"parentId": 101,
"orderNum": 6
},
"order": 6,
"depth": null,
"parentId": 101,
"label": "字典管理"
},
{
"children": [],
"id": 10107,
"origin": {
"menuNo": 10107,
"menuName": "操作日志",
"parentId": 101,
"orderNum": 7
},
"order": 7,
"depth": null,
"parentId": 101,
"label": "操作日志"
}
],
"id": 101,
"origin": {
"menuNo": 101,
"menuName": "系统管理",
"parentId": 0,
"orderNum": 1
},
"order": 1,
"depth": null,
"parentId": 0,
"label": "系统管理"
},
{
"children": [
{
"children": [],
"id": 20101,
"origin": {
"menuNo": 20101,
"menuName": "ODB管理",
"parentId": 201,
"orderNum": 1
},
"order": 1,
"depth": null,
"parentId": 201,
"label": "ODB管理"
}
],
"id": 201,
"origin": {
"menuNo": 201,
"menuName": "设备管理",
"parentId": 0,
"orderNum": 2
},
"order": 2,
"depth": null,
"parentId": 0,
"label": "设备管理"
}
],
"message": "success"
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>rest-framework-admin</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>glsx-ne-shield</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<description>Microservice Scaffolding project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.2.RELEASE</spring-cloud-alibaba.version>
<!-- <repo.internal.snapshots.url>https://repo1.maven.org/maven2</repo.internal.snapshots.url>-->
<!-- <repo.internal.releases.url>https://repo1.maven.org/maven2</repo.internal.releases.url>-->
<!-- <repo.proxy.url>https://repo1.maven.org/maven2</repo.proxy.url>-->
<!-- <repo.external.url>https://repo1.maven.org/maven2</repo.external.url>-->
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-archetype-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
<useDefaultDelimiters>false</useDefaultDelimiters>
<delimiters>
<delimiter>${*}</delimiter>
</delimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Local Nexus Releases Repository</name>
<url>http://192.168.3.233/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Local Nexus Snapshots Repository</name>
<url>http://192.168.3.233/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profile.active>prod</profile.active>
</properties>
</profile>
</profiles>
<modules>
<module>glsx-ne-shield-api</module>
<module>glsx-ne-shield-auth-client</module>
<module>glsx-ne-shield-common</module>
<module>glsx-ne-shield-usercenter</module>
<module>glsx-ne-shield-ordercenter</module>
<module>glsx-ne-shield-reportcenter</module>
<module>glsx-ne-shield-notifycenter</module>
<module>glsx-ne-shield-publiccenter</module>
<module>glsx-ne-shield-admin</module>
<module>glsx-ne-shield-alarmcenter</module>
<module>glsx-ne-shield-loggincenter</module>
<module>glsx-ne-shield-assetscenter</module>
</modules>
</project>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!