提交 75006bbe authored 作者: 许志图's avatar 许志图

Initial commit

上级
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
-- ----------------------------
-- Table structure for `美食表`
-- ----------------------------
DROP TABLE IF EXISTS `t_food`;
CREATE TABLE `t_food`
(
`food_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '食品ID',
`food_name` varchar(32) NOT NULL COMMENT '食品名称',
`favorite` int(11) DEFAULT NULL COMMENT '喜欢',
`sort` int(11) DEFAULT '1' COMMENT '排序值',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`del_flag` char(1) DEFAULT '0' COMMENT '逻辑删除标记(0--正常 1--删除)',
PRIMARY KEY (`food_id`) USING BTREE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8
ROW_FORMAT = DYNAMIC COMMENT ='美食表';
差异被折叠。
This source diff could not be displayed because it is too large. You can view the blob instead.
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.elephant.framework.galaxy</groupId>
<artifactId>aroad</artifactId>
<version>0.0.1</version>
<name>aroad</name>
<description>智慧公路项目</description>
<properties>
<java.version>1.8</java.version>
<hutool.version>4.3.2</hutool.version>
<ttl.version>2.10.1</ttl.version>
<spring.security.oauth2.version>2.3.5.RELEASE</spring.security.oauth2.version>
</properties>
<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-amqp</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring.security.oauth2.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.0.7.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!--TTL-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>${ttl.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.elephant.framework.galaxy.aroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Description
* @auther wangjian
* @create 2019-02-18 15:19
*/
@SpringBootApplication
public class ARoadApplication {
public static void main(String[] args) {
SpringApplication.run(ARoadApplication.class, args);
}
}
package com.elephant.framework.galaxy.aroad.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Description
* @auther wangjian
* @create 2019-02-20 21:49
*/
@EnableTransactionManagement
@Configuration
@MapperScan("com.elephant.framework.galaxy.aroad.module.*.mapper*")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
package com.elephant.framework.galaxy.aroad.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* RedisTemplate 配置
*
* @author wangjian
*/
@EnableCaching
@Configuration
public class RedisTemplateConfig extends CachingConfigurerSupport {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public KeyGenerator KeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
}
@Bean
public RedisCacheManager cacheManager() {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
package com.elephant.framework.galaxy.aroad.constant;
/**
* @Description
* @auther wangjian
* @create 2019-02-21 23:20
*/
public interface CommonConstants {
/**
* header 中租户ID
*/
String TENANT_ID = "TENANT_ID";
/**
* 删除
*/
String STATUS_DEL = "1";
/**
* 正常
*/
String STATUS_NORMAL = "0";
/**
* 锁定
*/
String STATUS_LOCK = "9";
/**
* 菜单
*/
String MENU = "0";
/**
* 编码
*/
String UTF8 = "UTF-8";
/**
* 前端工程名
*/
String FRONT_END_PROJECT = "galaxy-ui";
/**
* 后端工程名
*/
String BACK_END_PROJECT = "galaxy";
/**
* 路由存放
*/
String ROUTE_KEY = "gateway_route_key";
/**
* spring boot admin 事件key
*/
String EVENT_KEY = "event_key";
/**
* 验证码前缀
*/
String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY_";
/**
* 成功标记
*/
Integer SUCCESS = 0;
/**
* 失败标记
*/
Integer FAIL = 1;
/**
* 默认存储bucket
*/
String BUCKET_NAME = "galaxy";
}
package com.elephant.framework.galaxy.aroad.constant;
/**
* 分页相关的参数
* @author wangjian
* @date 2018/11/22
*/
public interface PaginationConstants {
/**
* 当前页
*/
String CURRENT="current";
/**
* 每页大小
*/
String SIZE="size";
}
package com.elephant.framework.galaxy.aroad.constant;
/**
* @Description
* @auther wangjian
* @create 2019-02-21 21:43
*/
public interface SecurityConstants {
/**
* 刷新
*/
String REFRESH_TOKEN = "refresh_token";
/**
* 验证码有效期
*/
int CODE_TIME = 60;
/**
* 验证码长度
*/
String CODE_SIZE = "4";
/**
* 角色前缀
*/
String ROLE = "ROLE_";
/**
* 前缀
*/
String GALAXY_PREFIX = "galaxy_";
/**
* oauth 相关前缀
*/
String OAUTH_PREFIX = "oauth:";
/**
* 项目的license
*/
String GALAXY_LICENSE = "EP-Galaxy";
/**
* 内部
*/
String FROM_IN = "Y";
/**
* 标志
*/
String FROM = "from";
/**
* OAUTH URL
*/
String OAUTH_TOKEN_URL = "/oauth/token";
/**
* 手机号登录URL
*/
String SMS_TOKEN_URL = "/mobile/token/sms";
/**
* 社交登录URL
*/
String SOCIAL_TOKEN_URL = "/mobile/token/social";
/**
* 自定义登录URL
*/
String MOBILE_TOKEN_URL = "/mobile/token/*";
/**
* oauth 客户端信息
*/
String CLIENT_DETAILS_KEY = "galaxy_oauth:client:details";
/**
* 微信获取OPENID
*/
String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
/**
* {bcrypt} 加密的特征码
*/
String BCRYPT = "{bcrypt}";
/**
* sys_oauth_client_details 表的字段,不包括client_id、client_secret
*/
String CLIENT_FIELDS = "client_id, CONCAT('{noop}',client_secret) as client_secret, resource_ids, scope, "
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
+ "refresh_token_validity, additional_information, autoapprove";
/**
* JdbcClientDetailsService 查询语句
*/
String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS
+ " from sys_oauth_client_details";
/**
* 默认的查询语句
*/
String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";
/**
* 按条件client_id 查询
*/
String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";
/**
* 资源服务器默认bean名称
*/
String RESOURCE_SERVER_CONFIGURER = "resourceServerConfigurerAdapter";
/**
* 客户端模式
*/
String CLIENT_CREDENTIALS = "client_credentials";
}
package com.elephant.framework.galaxy.aroad.exception;
import lombok.NoArgsConstructor;
/**
* @author wangjian
* @date 😴2018年06月22日16:21:57
*/
@NoArgsConstructor
public class CheckedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CheckedException(String message) {
super(message);
}
public CheckedException(Throwable cause) {
super(cause);
}
public CheckedException(String message, Throwable cause) {
super(message, cause);
}
public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.elephant.framework.galaxy.aroad.exception;
/**
* @Description
* @auther wangjian
* @create 2019-02-18 15:45
*/
public interface CommonError {
public int getErrorCode();
public String getErrorMessage();
public CommonError setErrorMessage(String errorMessage);
}
package com.elephant.framework.galaxy.aroad.exception;
/**
* @Description 全局异常类实现(包装器模式)
* @auther wangjian
* @create 2019-02-18 15:56
*/
public class GlobalException extends Exception implements CommonError {
private CommonError commonError;
public GlobalException(CommonError commonError) {
super();
this.commonError = commonError;
}
public GlobalException(CommonError commonError, String errorMessage) {
super();
this.commonError = commonError;
this.commonError.setErrorMessage(errorMessage);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrorMessage() {
return this.commonError.getErrorMessage();
}
@Override
public CommonError setErrorMessage(String errorMessage) {
this.commonError.setErrorMessage(errorMessage);
return this;
}
}
package com.elephant.framework.galaxy.aroad.exception;
/**
* @Description
* @auther wangjian
* @create 2019-02-18 15:48
*/
public enum GlobalExceptionEnum implements CommonError {
// 通用错误码定义
UNKNOWN_ERROR(10001, "未知错误"),
PARAMETER_VALIDATION_ERROR(10002, "非法参数"),
// 20000 用户相关错误码定义
USER_NOT_EXIST(20001, "用户不存在"),
MENU_HAS_CHILD(20002, "菜单含有下级不能删除"),
;
private int errorCode;
private String errorMessage;
private GlobalExceptionEnum(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
@Override
public int getErrorCode() {
return this.errorCode;
}
@Override
public String getErrorMessage() {
return this.errorMessage;
}
@Override
public CommonError setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}}
package com.elephant.framework.galaxy.aroad.generator;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @Description
* @auther wangjian
* @create 2019-02-21 14:52
*/
public class MysqlGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");//生成文件的输出目录
gc.setAuthor("wangjian");//开发人员
gc.setOpen(false);//是否打开输出目录
gc.setServiceName("%sService");// service 命名方式去掉service接口名中I开头
gc.setServiceImplName("%sServiceImpl");//service impl 命名方式
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML Column List
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/aroad?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));//父包模块名
pc.setParent("com.elephant.framework.galaxy.aroad.module");//父包名
// pc.setEntity("pojo");
// pc.setService("service");
// pc.setServiceImpl("service.impl");
// pc.setController("controller");//设置控制器包名
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");//自定义继承的Entity类全称,带包名
// strategy.setEntityLombokModel(true); //【实体】是否为lombok模型(默认 false)
strategy.setRestControllerStyle(true);//生成 @RestController 控制器
strategy.setSuperControllerClass("BaseController");//自定义继承的Controller类全称,带包名
strategy.setInclude(scanner("表名"));//需要包含的表名,允许正则表达式
// strategy.setSuperEntityColumns("id");//自定义基础的Entity类,公共字段
strategy.setControllerMappingHyphenStyle(true);//驼峰转连字符
// strategy.setTablePrefix(pc.getModuleName() + "_");
strategy.setTablePrefix(scanner("表前缀"));//表前缀
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
package com.elephant.framework.galaxy.aroad.module.codegen.controller;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.codegen.response.R;
import com.elephant.framework.galaxy.aroad.module.codegen.service.SysGeneratorService;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.GenConfig;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
/**
* 代码生成器
*
* @author wangjian
* @date 2018-07-30
*/
@RestController
@AllArgsConstructor
@RequestMapping("/gen/generator")
public class SysGeneratorController {
private final SysGeneratorService sysGeneratorService;
/**
* 列表
*
* @param tableName 参数集
* @return 数据库表
*/
@GetMapping("/page")
public R getPage(Page page, String tableName) {
return new R<>(sysGeneratorService.getPage(page, tableName));
}
/**
* 生成代码
*/
@SneakyThrows
@PostMapping("/code")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
byte[] data = sysGeneratorService.generatorCode(genConfig);
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
}
package com.elephant.framework.galaxy.aroad.module.codegen.entity;
import lombok.Data;
/**
* @author wangjian
* @date 2018/07/29
* 列属性: https://blog.csdn.net/lkforce/article/details/79557482
*/
@Data
public class ColumnEntity {
/**
* 列表
*/
private String columnName;
/**
* 数据类型
*/
private String dataType;
/**
* 备注
*/
private String comments;
/**
* 驼峰属性
*/
private String caseAttrName;
/**
* 普通属性
*/
private String lowerAttrName;
/**
* 属性类型
*/
private String attrType;
/**
* 其他信息
*/
private String extra;
}
package com.elephant.framework.galaxy.aroad.module.codegen.entity;
import lombok.Data;
/**
* @author wangjian
* @date 2018/8/2
* 生成配置
*/
@Data
public class GenConfig {
/**
* 包名
*/
private String packageName;
/**
* 作者
*/
private String author;
/**
* 模块名称
*/
private String moduleName;
/**
* 表前缀
*/
private String tablePrefix;
/**
* 表名称
*/
private String tableName;
/**
* 表备注
*/
private String comments;
}
package com.elephant.framework.galaxy.aroad.module.codegen.entity;
import lombok.Data;
import java.util.List;
/**
* @author wangjian
* @date 2018/07/29
* 表属性: https://blog.csdn.net/lkforce/article/details/79557482
*/
@Data
public class TableEntity {
/**
* 名称
*/
private String tableName;
/**
* 备注
*/
private String comments;
/**
* 主键
*/
private ColumnEntity pk;
/**
* 列名
*/
private List<ColumnEntity> columns;
/**
* 驼峰类型
*/
private String caseClassName;
/**
* 普通类型
*/
private String lowerClassName;
}
package com.elephant.framework.galaxy.aroad.module.codegen.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 代码生成器
*
* @author wangjian
* @date 2018-07-30
*/
public interface SysGeneratorMapper {
/**
* 分页查询表格
*
* @param page
* @param tableName
* @return
*/
IPage<List<Map<String, Object>>> queryList(Page page, @Param("tableName") String tableName);
/**
* 查询表信息
*
* @param tableName 表名称
* @return
*/
Map<String, String> queryTable(String tableName);
/**
* 查询表列信息
*
* @param tableName 表名称
* @return
*/
List<Map<String, String>> queryColumns(String tableName);
}
package com.elephant.framework.galaxy.aroad.module.codegen.response;
import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 响应信息主体
*
* @param <T>
* @author wangjian
*/
@Builder
@ToString
@Accessors(chain = true)
@AllArgsConstructor
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private int code = CommonConstants.SUCCESS;
@Getter
@Setter
private String msg = "success";
@Getter
@Setter
private T data;
public R() {
super();
}
public R(T data) {
super();
this.data = data;
}
public R(T data, String msg) {
super();
this.data = data;
this.msg = msg;
}
public R(Throwable e) {
super();
this.msg = e.getMessage();
this.code = CommonConstants.FAIL;
}
}
package com.elephant.framework.galaxy.aroad.module.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.GenConfig;
import java.util.List;
import java.util.Map;
/**
* @author wangjian
* @date 2018/7/29
*/
public interface SysGeneratorService {
/**
* 生成代码
*
* @param tableNames 表名称
* @return
*/
byte[] generatorCode(GenConfig tableNames);
/**
* 分页查询表
* @param tableName 表名
* @return
*/
IPage<List<Map<String, Object>>> getPage(Page page, String tableName);
}
package com.elephant.framework.galaxy.aroad.module.codegen.service.impl;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.codegen.service.SysGeneratorService;
import com.elephant.framework.galaxy.aroad.module.codegen.util.GenUtils;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.GenConfig;
import com.elephant.framework.galaxy.aroad.module.codegen.mapper.SysGeneratorMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器
*
* @author wangjian
* @date 2018-07-30
*/
@Service
@AllArgsConstructor
public class SysGeneratorServiceImpl implements SysGeneratorService {
private final SysGeneratorMapper sysGeneratorMapper;
/**
* 分页查询表
*
* @param tableName 查询条件
* @return
*/
@Override
public IPage<List<Map<String, Object>>> getPage(Page page, String tableName) {
return sysGeneratorMapper.queryList(page,tableName);
}
/**
* 生成代码
*
* @param genConfig 生成配置
* @return
*/
@Override
public byte[] generatorCode(GenConfig genConfig) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//查询表信息
Map<String, String> table = queryTable(genConfig.getTableName());
//查询列信息
List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
//生成代码
GenUtils.generatorCode(genConfig, table, columns, zip);
IoUtil.close(zip);
return outputStream.toByteArray();
}
private Map<String, String> queryTable(String tableName) {
return sysGeneratorMapper.queryTable(tableName);
}
private List<Map<String, String>> queryColumns(String tableName) {
return sysGeneratorMapper.queryColumns(tableName);
}
}
package com.elephant.framework.galaxy.aroad.module.codegen.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import com.elephant.framework.galaxy.aroad.exception.CheckedException;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.ColumnEntity;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.GenConfig;
import com.elephant.framework.galaxy.aroad.module.codegen.entity.TableEntity;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器 工具类
*
* @author lengleng
* @date 2018-07-30
*/
@Slf4j
@UtilityClass
public class GenUtils {
private final String ENTITY_JAVA_VM = "Entity.java.vm";
private final String MAPPER_JAVA_VM = "Mapper.java.vm";
private final String SERVICE_JAVA_VM = "Service.java.vm";
private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
private final String CONTROLLER_JAVA_VM = "Controller.java.vm";
private final String MAPPER_XML_VM = "Mapper.xml.vm";
private final String MENU_SQL_VM = "menu.sql.vm";
private final String INDEX_VUE_VM = "index.vue.vm";
private final String API_JS_VM = "api.js.vm";
private final String CRUD_JS_VM = "crud.js.vm";
private List<String> getTemplates() {
List<String> templates = new ArrayList<>();
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
templates.add("template/Mapper.xml.vm");
templates.add("template/Service.java.vm");
templates.add("template/ServiceImpl.java.vm");
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
templates.add("template/index.vue.vm");
templates.add("template/api.js.vm");
templates.add("template/crud.js.vm");
return templates;
}
/**
* 生成代码
*/
public void generatorCode(GenConfig genConfig, Map<String, String> table,
List<Map<String, String>> columns, ZipOutputStream zip) {
//配置信息
Configuration config = getConfig();
boolean hasBigDecimal = false;
//表信息
TableEntity tableEntity = new TableEntity();
tableEntity.setTableName(table.get("tableName"));
if (StrUtil.isNotBlank(genConfig.getComments())) {
tableEntity.setComments(genConfig.getComments());
} else {
tableEntity.setComments(table.get("tableComment"));
}
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
} else {
tablePrefix = config.getString("tablePrefix");
}
//表名转换成Java类名
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
//列信息
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setComments(column.get("columnComment"));
columnEntity.setExtra(column.get("extra"));
//列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName());
columnEntity.setCaseAttrName(attrName);
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
//列的数据类型,转换成Java类型
String attrType = config.getString(columnEntity.getDataType(), "unknowType");
columnEntity.setAttrType(attrType);
if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true;
}
//是否主键
if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
tableEntity.setPk(columnEntity);
}
columnList.add(columnEntity);
}
tableEntity.setColumns(columnList);
//没主键,则第一个字段为主键
if (tableEntity.getPk() == null) {
tableEntity.setPk(tableEntity.getColumns().get(0));
}
//设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
//封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("tableName", tableEntity.getTableName());
map.put("pk", tableEntity.getPk());
map.put("className", tableEntity.getCaseClassName());
map.put("classname", tableEntity.getLowerClassName());
map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
map.put("columns", tableEntity.getColumns());
map.put("hasBigDecimal", hasBigDecimal);
map.put("datetime", DateUtil.now());
if (StrUtil.isNotBlank(genConfig.getComments())) {
map.put("comments", genConfig.getComments());
} else {
map.put("comments", tableEntity.getComments());
}
if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor());
} else {
map.put("author", config.getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
} else {
map.put("moduleName", config.getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName());
} else {
map.put("package", config.getString("package"));
map.put("mainPath", config.getString("mainPath"));
}
VelocityContext context = new VelocityContext(map);
//获取模板列表
List<String> templates = getTemplates();
for (String template : templates) {
//渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
try {
//添加到zip
zip.putNextEntry(new ZipEntry(Objects
.requireNonNull(getFileName(template, tableEntity.getCaseClassName()
, map.get("package").toString(), map.get("moduleName").toString()))));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
zip.closeEntry();
} catch (IOException e) {
throw new CheckedException("渲染模板失败,表名:" + tableEntity.getTableName(), e);
}
}
}
/**
* 列名转换成Java属性名
*/
private String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
}
/**
* 表名转换成Java类名
*/
private String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replace(tablePrefix, "");
}
return columnToJava(tableName);
}
/**
* 获取配置信息
*/
private Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties");
} catch (ConfigurationException e) {
throw new CheckedException("获取配置文件失败,", e);
}
}
/**
* 获取文件名
*/
private String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains(ENTITY_JAVA_VM)) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains(MAPPER_JAVA_VM)) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains(SERVICE_JAVA_VM)) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains(SERVICE_IMPL_JAVA_VM)) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains(CONTROLLER_JAVA_VM)) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains(MAPPER_XML_VM)) {
return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains(MENU_SQL_VM)) {
return className.toLowerCase() + "_menu.sql";
}
if (template.contains(INDEX_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" +
File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + "index.vue";
}
if (template.contains(API_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator + className.toLowerCase() + ".js";
}
if (template.contains(CRUD_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const" +
File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
return null;
}
}
package com.elephant.framework.galaxy.aroad.module.common.annotation;
import java.lang.annotation.*;
/**
* @author wangjian
* @date 2018/6/28
* 操作日志注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
/**
* 描述
*
* @return {String}
*/
String value();
}
package com.elephant.framework.galaxy.aroad.module.common.controller;
import com.elephant.framework.galaxy.aroad.exception.GlobalException;
import com.elephant.framework.galaxy.aroad.exception.GlobalExceptionEnum;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
/**
* @Description
* @auther wangjian
* @create 2019-02-18 16:07
*/
@Slf4j
public class BaseController {
/**
* 解决所有未被Controller层处理的异常,不会反应的客户端
*
* @param request
* @param exception
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request, Exception exception) {
exception.printStackTrace();
if (exception instanceof GlobalException) {
GlobalException globalException = (GlobalException) exception;
return new R(globalException.getErrorCode(),globalException.getErrorMessage());
} else if (exception instanceof AccessDeniedException) {
AccessDeniedException accessDeniedException = (AccessDeniedException) exception;
return new R(accessDeniedException);
} else {
return new R(GlobalExceptionEnum.UNKNOWN_ERROR.getErrorCode(), GlobalExceptionEnum.UNKNOWN_ERROR.getErrorMessage());
}
}
}
package com.elephant.framework.galaxy.aroad.module.common.data;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.experimental.UtilityClass;
/**
* @author lengleng
* @date 2018/10/4
* 租户工具类
*/
@UtilityClass
public class TenantContextHolder {
private final ThreadLocal<Integer> THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();
/**
* TTL 设置租户ID
*
* @param tenantId
*/
void setTenantId(Integer tenantId) {
THREAD_LOCAL_TENANT.set(tenantId);
}
/**
* 获取TTL中的租户ID
*
* @return
*/
public Integer getTenantId() {
return THREAD_LOCAL_TENANT.get();
}
public void clear() {
THREAD_LOCAL_TENANT.remove();
}
}
package com.elephant.framework.galaxy.aroad.module.common.datascope;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author wangjian
* @date 2018/8/30
* 数据权限查询参数
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class DataScope extends HashMap {
/**
* 限制范围的字段名称
*/
private String scopeName = "deptId";
/**
* 具体的数据范围
*/
private List<Integer> deptIds = new ArrayList<>();
/**
* 是否只查询本部门
*/
private Boolean isOnly = false;
}
package com.elephant.framework.galaxy.aroad.module.common.datascope;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.elephant.framework.galaxy.aroad.util.SecurityUtils;
import com.elephant.framework.galaxy.aroad.constant.SecurityConstants;
import com.elephant.framework.galaxy.aroad.exception.CheckedException;
import com.elephant.framework.galaxy.aroad.security.entity.GalaxyUser;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.security.core.GrantedAuthority;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author wangjian
* @date 2018/12/26
* <p>
* mybatis 数据权限拦截器
*/
@Slf4j
@AllArgsConstructor
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {
private final DataSource dataSource;
@Override
@SneakyThrows
public Object intercept(Invocation invocation) {
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
this.sqlParser(metaObject);
// 先判断是不是SELECT操作
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
return invocation.proceed();
}
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
//查找参数中包含DataScope类型的参数
DataScope dataScope = findDataScopeObject(parameterObject);
if (dataScope == null) {
return invocation.proceed();
}
String scopeName = dataScope.getScopeName();
List<Integer> deptIds = dataScope.getDeptIds();
// 优先获取赋值数据
if (CollUtil.isEmpty(deptIds)) {
GalaxyUser user = SecurityUtils.getUser();
if (user == null) {
throw new CheckedException("auto datascope, set up security details true");
}
List<String> roleIdList = user.getAuthorities()
.stream().map(GrantedAuthority::getAuthority)
.filter(authority -> authority.startsWith(SecurityConstants.ROLE))
.map(authority -> authority.split("_")[1])
.collect(Collectors.toList());
Entity query = Db.use(dataSource)
.query("SELECT * FROM sys_role where role_id IN (" + CollUtil.join(roleIdList, ",") + ")")
.stream().min(Comparator.comparingInt(o -> o.getInt("ds_type"))).get();
Integer dsType = query.getInt("ds_type");
// 查询全部
if (DataScopeTypeEnum.ALL.getType() == dsType) {
return invocation.proceed();
}
// 自定义
if (DataScopeTypeEnum.CUSTOM.getType() == dsType) {
String dsScope = query.getStr("ds_scope");
deptIds.addAll(Arrays.stream(dsScope.split(","))
.map(Integer::parseInt).collect(Collectors.toList()));
}
// 查询本级及其下级
if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
List<Integer> deptIdList = Db.use(dataSource)
.findBy("sys_dept_relation", "ancestor", user.getDeptId())
.stream().map(entity -> entity.getInt("descendant"))
.collect(Collectors.toList());
deptIds.addAll(deptIdList);
}
// 只查询本级
if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
deptIds.add(user.getDeptId());
}
}
String join = CollectionUtil.join(deptIds, ",");
originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
metaObject.setValue("delegate.boundSql.sql", originalSql);
return invocation.proceed();
}
/**
* 生成拦截对象的代理
*
* @param target 目标对象
* @return 代理对象
*/
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
}
return target;
}
/**
* mybatis配置的属性
*
* @param properties mybatis配置的属性
*/
@Override
public void setProperties(Properties properties) {
}
/**
* 查找参数是否包括DataScope对象
*
* @param parameterObj 参数列表
* @return DataScope
*/
private DataScope findDataScopeObject(Object parameterObj) {
if (parameterObj instanceof DataScope) {
return (DataScope) parameterObj;
} else if (parameterObj instanceof Map) {
for (Object val : ((Map<?, ?>) parameterObj).values()) {
if (val instanceof DataScope) {
return (DataScope) val;
}
}
}
return null;
}
}
package com.elephant.framework.galaxy.aroad.module.common.datascope;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author wangjian
* @date 2018/12/26
* <p>
* 数据权限类型
*/
@Getter
@AllArgsConstructor
public enum DataScopeTypeEnum {
/**
* 查询全部数据
*/
ALL(0, "全部"),
/**
* 自定义
*/
CUSTOM(1, "自定义"),
/**
* 本级及子级
*/
OWN_CHILD_LEVEL(2, "本级及子级"),
/**
* 本级
*/
OWN_LEVEL(3, "本级");
/**
* 类型
*/
private final int type;
/**
* 描述
*/
private final String description;
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.entity.Dept;
import com.elephant.framework.galaxy.aroad.module.system.service.DeptService;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.LocalDateTime;
/**
* <p>
* 部门管理 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/dept")
public class DeptController extends BaseController {
private final DeptService deptService;
/**
* 通过ID查询
*
* @param id ID
* @return SysDept
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(deptService.getById(id));
}
/**
* 返回树形菜单集合
*
* @return 树形菜单
*/
@GetMapping(value = "/tree")
public R getTree() {
return new R(deptService.selectTree());
}
/**
* 返回当前用户树形菜单集合
*
* @return 树形菜单
*/
@GetMapping(value = "/user-tree")
public R getUserTree() {
return new R(deptService.getUserTree());
}
/**
* 添加
*
* @param dept 实体
* @return success/false
*/
@SysLog("添加部门")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_dept_add')")
public R save(@Valid @RequestBody Dept dept) {
return new R(deptService.saveDept(dept));
}
/**
* 删除
*
* @param id ID
* @return success/false
*/
@SysLog("删除部门")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_dept_del')")
public R removeById(@PathVariable Integer id) {
return new R(deptService.removeDeptById(id));
}
/**
* 编辑
*
* @param dept 实体
* @return success/false
*/
@SysLog("编辑部门")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
public R update(@Valid @RequestBody Dept dept) {
dept.setUpdateTime(LocalDateTime.now());
return new R(deptService.updateDeptById(dept));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 部门关系表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/system/dept-relation")
public class DeptRelationController extends BaseController {
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.entity.Dict;
import com.elephant.framework.galaxy.aroad.module.system.service.DictService;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* <p>
* 字典表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/dict")
public class DictController extends BaseController {
private final DictService dictService;
/**
* 通过ID查询字典信息
*
* @param id ID
* @return 字典信息
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(dictService.getById(id));
}
/**
* 分页查询字典信息
*
* @param page 分页对象
* @return 分页对象
*/
@GetMapping("/page")
public R<IPage> getDictPage(Page page, Dict dict) {
return new R(dictService.page(page, Wrappers.query(dict)));
}
/**
* 通过字典类型查找字典
*
* @param type 类型
* @return 同类型字典
*/
@GetMapping("/type/{type}")
@Cacheable(value = "dict_details", key = "#type")
public R getDictByType(@PathVariable String type) {
return new R(dictService.list(Wrappers
.<Dict>query().lambda()
.eq(Dict::getType, type)));
}
/**
* 添加字典
*
* @param dict 字典信息
* @return success、false
*/
@SysLog("添加字典")
@PostMapping
@CacheEvict(value = "dict_details", key = "#dict.type")
@PreAuthorize("@pms.hasPermission('sys_dict_add')")
public R save(@Valid @RequestBody Dict dict) {
return new R(dictService.save(dict));
}
/**
* 删除字典,并且清除字典缓存
*
* @param id ID
* @param type 类型
* @return R
*/
@SysLog("删除字典")
@DeleteMapping("/{id}/{type}")
@CacheEvict(value = "dict_details", key = "#type")
@PreAuthorize("@pms.hasPermission('sys_dict_del')")
public R removeById(@PathVariable Integer id, @PathVariable String type) {
return new R(dictService.removeById(id));
}
/**
* 修改字典
*
* @param dict 字典信息
* @return success/false
*/
@PutMapping
@SysLog("修改字典")
@CacheEvict(value = "dict_details", key = "#dict.type")
@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
public R updateById(@Valid @RequestBody Dict dict) {
return new R(dictService.updateById(dict));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.data.TenantContextHolder;
import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import com.elephant.framework.galaxy.aroad.constant.PaginationConstants;
import com.elephant.framework.galaxy.aroad.constant.SecurityConstants;
import com.elephant.framework.galaxy.aroad.module.codegen.response.R;
import lombok.AllArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author wangjian
* @date 2018/6/24
* 删除token端点
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/token")
public class GalaxyTokenEndpoint {
private static final String GALAXY_OAUTH_ACCESS = SecurityConstants.GALAXY_PREFIX + SecurityConstants.OAUTH_PREFIX + "auth_to_access:";
private static final String GALAXY__ACCESS = SecurityConstants.GALAXY_PREFIX + SecurityConstants.OAUTH_PREFIX + "access:";
private final TokenStore tokenStore;
private final RedisTemplate redisTemplate;
private final CacheManager cacheManager;
/**
* 认证页面
*
* @return ModelAndView
*/
@GetMapping("/login")
public ModelAndView require() {
return new ModelAndView("ftl/login");
}
/**
* 退出token
*
* @param authHeader Authorization
*/
@DeleteMapping("/logout")
public R logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
if (StrUtil.isBlank(authHeader)) {
return R.builder()
.code(CommonConstants.FAIL)
.data(Boolean.FALSE)
.msg("退出失败,token 为空").build();
}
String tokenValue = authHeader.replace("Bearer", "").trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
return R.builder()
.code(CommonConstants.FAIL)
.data(Boolean.FALSE)
.msg("退出失败,token 无效").build();
}
OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
cacheManager.getCache("user_details")
.evict(auth2Authentication.getName());
tokenStore.removeAccessToken(accessToken);
return new R<>(Boolean.TRUE);
}
/**
* 令牌管理调用
*
* @param token token
* @return
*/
@DeleteMapping("/{token}")
public R<Boolean> delToken(@PathVariable("token") String token) {
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
tokenStore.removeAccessToken(oAuth2AccessToken);
return new R<>();
}
/**
* 查询token
*
* @param params 分页参数
* @return
*/
@PostMapping("/page")
public R<Page> tokenList(@RequestBody Map<String, Object> params) {
//根据分页参数获取对应数据
String key = String.format("%s*:%s", GALAXY_OAUTH_ACCESS, TenantContextHolder.getTenantId());
List<String> pages = findKeysForPage(key, MapUtil.getInt(params, PaginationConstants.CURRENT)
, MapUtil.getInt(params, PaginationConstants.SIZE));
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
Page result = new Page(MapUtil.getInt(params, PaginationConstants.CURRENT), MapUtil.getInt(params, PaginationConstants.SIZE));
result.setRecords(redisTemplate.opsForValue().multiGet(pages));
result.setTotal(Long.valueOf(redisTemplate.keys(key).size()));
return new R<>(result);
}
private List<String> findKeysForPage(String patternKey, int pageNum, int pageSize) {
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
List<String> result = new ArrayList<>();
int tmpIndex = 0;
int startIndex = (pageNum - 1) * pageSize;
int end = pageNum * pageSize;
assert cursor != null;
while (cursor.hasNext()) {
if (tmpIndex >= startIndex && tmpIndex < end) {
result.add(cursor.next().toString());
tmpIndex++;
continue;
}
if (tmpIndex >= end) {
break;
}
tmpIndex++;
cursor.next();
}
return result;
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.entity.Log;
import com.elephant.framework.galaxy.aroad.module.system.service.LogService;
import com.elephant.framework.galaxy.aroad.module.system.vo.PreLogVO;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* <p>
* 日志表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/log")
public class LogController extends BaseController {
private final LogService logService;
/**
* 简单分页查询
*
* @param page 分页对象
* @param log 系统日志
* @return
*/
@GetMapping("/page")
public R getLogPage(Page page, Log log) {
return new R(logService.page(page, Wrappers.query(log)));
}
/**
* 删除日志
*
* @param id ID
* @return success/false
*/
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_log_del')")
public R removeById(@PathVariable Long id) {
return new R(logService.removeById(id));
}
/**
* 插入日志
*
* @param log 日志实体
* @return success/false
*/
@PostMapping("/save")
public R save(@Valid @RequestBody Log log) {
return new R(logService.save(log));
}
/**
* 批量插入前端异常日志
*
* @param preLogVoList 日志实体
* @return success/false
*/
@PostMapping("/logs")
public R saveBatchLogs(@RequestBody List<PreLogVO> preLogVoList) {
return new R(logService.saveBatchLogs(preLogVoList));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.dto.MenuTree;
import com.elephant.framework.galaxy.aroad.module.system.entity.Menu;
import com.elephant.framework.galaxy.aroad.module.system.service.MenuService;
import com.elephant.framework.galaxy.aroad.module.system.vo.MenuVO;
import com.elephant.framework.galaxy.aroad.util.SecurityUtils;
import com.elephant.framework.galaxy.aroad.util.TreeUtil;
import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <p>
* 菜单权限表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/admin/menu")
@AllArgsConstructor
public class MenuController extends BaseController {
private final MenuService menuService;
/**
* 返回当前用户的树形菜单集合
*
* @return 当前用户的树形菜单
*/
@GetMapping
public R getUserMenu() {
// 获取符合条件的菜单
Set<MenuVO> all = new HashSet<>();
SecurityUtils.getRoles()
.forEach(roleId -> all.addAll(menuService.findMenuByRoleId(roleId)));
List<MenuTree> menuTreeList = all.stream()
.filter(menuVo -> CommonConstants.MENU.equals(menuVo.getType()))
.map(MenuTree::new)
.sorted(Comparator.comparingInt(MenuTree::getSort))
.collect(Collectors.toList());
return new R(TreeUtil.bulid(menuTreeList, -1));
}
/**
* 返回树形菜单集合
*
* @return 树形菜单
*/
@GetMapping(value = "/tree")
public R getTree() {
return new R(TreeUtil.bulidTree(menuService.list(Wrappers.emptyWrapper()), -1));
}
/**
* 返回角色的菜单集合
*
* @param roleId 角色ID
* @return 属性集合
*/
@GetMapping("/tree/{roleId}")
public List getRoleTree(@PathVariable Integer roleId) {
return menuService.findMenuByRoleId(roleId)
.stream()
.map(MenuVO::getMenuId)
.collect(Collectors.toList());
}
/**
* 通过ID查询菜单的详细信息
*
* @param id 菜单ID
* @return 菜单详细信息
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(menuService.getById(id));
}
/**
* 新增菜单
*
* @param menu 菜单信息
* @return success/false
*/
@SysLog("新增菜单")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_menu_add')")
public R save(@Valid @RequestBody Menu menu) {
return new R(menuService.save(menu));
}
/**
* 删除菜单
*
* @param id 菜单ID
* @return success/false
*/
@SysLog("删除菜单")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_menu_del')")
public R removeById(@PathVariable Integer id) {
return menuService.removeMenuById(id);
}
/**
* 更新菜单
*
* @param menu
* @return
*/
@SysLog("更新菜单")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_menu_edit')")
public R update(@Valid @RequestBody Menu menu) {
return new R(menuService.updateMenuById(menu));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.entity.OauthClientDetails;
import com.elephant.framework.galaxy.aroad.module.system.service.OauthClientDetailsService;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* <p>
* 终端信息表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/client")
public class OauthClientDetailsController extends BaseController {
private final OauthClientDetailsService oauthClientDetailsService;
/**
* 通过ID查询
*
* @param id ID
* @return SysOauthClientDetails
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(oauthClientDetailsService.getById(id));
}
/**
* 简单分页查询
*
* @param page 分页对象
* @param oauthClientDetails 系统终端
* @return
*/
@GetMapping("/page")
public R getOauthClientDetailsPage(Page page, OauthClientDetails oauthClientDetails) {
return new R(oauthClientDetailsService.page(page, Wrappers.query(oauthClientDetails)));
}
/**
* 添加
*
* @param oauthClientDetails 实体
* @return success/false
*/
@SysLog("添加终端")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_client_add')")
public R add(@Valid @RequestBody OauthClientDetails oauthClientDetails) {
return new R(oauthClientDetailsService.save(oauthClientDetails));
}
/**
* 删除
*
* @param id ID
* @return success/false
*/
@SysLog("删除终端")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_client_del')")
public R removeById(@PathVariable String id) {
return new R(oauthClientDetailsService.removeClientDetailsById(id));
}
/**
* 编辑
*
* @param oauthClientDetails 实体
* @return success/false
*/
@SysLog("编辑终端")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_client_edit')")
public R update(@Valid @RequestBody OauthClientDetails oauthClientDetails) {
return new R(oauthClientDetailsService.updateClientDetailsById(oauthClientDetails));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.entity.Role;
import com.elephant.framework.galaxy.aroad.module.system.service.RoleMenuService;
import com.elephant.framework.galaxy.aroad.module.system.service.RoleService;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* <p>
* 系统角色表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/role")
public class RoleController extends BaseController {
private final RoleService roleService;
private final RoleMenuService roleMenuService;
/**
* 通过ID查询角色信息
*
* @param id ID
* @return 角色信息
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(roleService.getById(id));
}
/**
* 添加角色
*
* @param role 角色信息
* @return success、false
*/
@SysLog("添加角色")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_role_add')")
public R save(@Valid @RequestBody Role role) {
return new R(roleService.save(role));
}
/**
* 修改角色
*
* @param role 角色信息
* @return success/false
*/
@SysLog("修改角色")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_role_edit')")
public R update(@Valid @RequestBody Role role) {
return new R(roleService.updateById(role));
}
/**
* 删除角色
*
* @param id
* @return
*/
@SysLog("删除角色")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_role_del')")
public R removeById(@PathVariable Integer id) {
return new R(roleService.removeRoleById(id));
}
/**
* 获取角色列表
*
* @return 角色列表
*/
@GetMapping("/list")
public R listRoles() {
return new R(roleService.list(Wrappers.emptyWrapper()));
}
/**
* 分页查询角色信息
*
* @param page 分页对象
* @return 分页对象
*/
@GetMapping("/page")
public R getRolePage(Page page) {
return new R(roleService.page(page, Wrappers.emptyWrapper()));
}
/**
* 更新角色菜单
*
* @param roleId 角色ID
* @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔
* @return success、false
*/
@SysLog("更新角色菜单")
@PutMapping("/menu")
@PreAuthorize("@pms.hasPermission('sys_role_perm')")
public R saveRoleMenus(Integer roleId, @RequestParam(value = "menuIds", required = false) String menuIds) {
Role sysRole = roleService.getById(roleId);
return new R(roleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleId, menuIds));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 角色菜单表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/system/role-menu")
public class RoleMenuController extends BaseController {
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 系统社交登录账号表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/system/social-details")
public class SocialDetailsController extends BaseController {
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elephant.framework.galaxy.aroad.module.common.annotation.SysLog;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import com.elephant.framework.galaxy.aroad.module.system.dto.UserDTO;
import com.elephant.framework.galaxy.aroad.module.system.entity.User;
import com.elephant.framework.galaxy.aroad.module.system.service.UserService;
import com.elephant.framework.galaxy.aroad.util.SecurityUtils;
import com.elephant.framework.galaxy.aroad.exception.GlobalExceptionEnum;
import com.elephant.framework.galaxy.aroad.response.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* <p>
* 用户表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/admin/user")
public class UserController extends BaseController {
@Autowired
private UserService userService;
/**
* 获取当前用户全部信息
*
* @return 用户信息
*/
@GetMapping(value = {"/info"})
public R info() {
String username = SecurityUtils.getUser().getUsername();
return info(username);
}
/**
* 获取指定用户全部信息
*
* @return 用户信息
*/
@GetMapping("/info/{username}")
public R info(@PathVariable String username) {
User user = userService.getOne(Wrappers.<User>query()
.lambda().eq(User::getUsername, username));
if (user == null) {
return new R(GlobalExceptionEnum.USER_NOT_EXIST);
}
return new R(userService.findUserInfo(user));
}
/**
* 通过ID查询用户信息
*
* @param id ID
* @return 用户信息
*/
@GetMapping("/{id}")
public R user(@PathVariable Integer id) {
return new R(userService.selectUserVoById(id));
}
/**
* 根据用户名查询用户信息
*
* @param username 用户名
* @return
*/
@GetMapping("/details/{username}")
public R user(@PathVariable String username) {
User condition = new User();
condition.setUsername(username);
return new R(userService.getOne(new QueryWrapper<>(condition)));
}
/**
* 删除用户信息
*
* @param id ID
* @return R
*/
@SysLog("删除用户信息")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_user_del')")
public R userDel(@PathVariable Integer id) {
User sysUser = userService.getById(id);
return new R(userService.deleteUserById(sysUser));
}
/**
* 添加用户
*
* @param userDto 用户信息
* @return success/false
*/
@SysLog("添加用户")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_user_add')")
public R user(@RequestBody UserDTO userDto) {
return new R(userService.saveUser(userDto));
}
/**
* 更新用户信息
*
* @param userDto 用户信息
* @return R
*/
@SysLog("更新用户信息")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_user_edit')")
public R updateUser(@Valid @RequestBody UserDTO userDto) {
return new R(userService.updateUser(userDto));
}
/**
* 分页查询用户
*
* @param page 参数集
* @param userDTO 查询参数列表
* @return 用户集合
*/
@GetMapping("/page")
public R getUserPage(Page page, UserDTO userDTO) {
return new R(userService.getUsersWithRolePage(page, userDTO));
}
/**
* 修改个人信息
*
* @param userDto userDto
* @return success/false
*/
@SysLog("修改个人信息")
@PutMapping("/edit")
public R updateUserInfo(@Valid @RequestBody UserDTO userDto) {
return userService.updateUserInfo(userDto);
}
/**
* @param username 用户名称
* @return 上级部门用户列表
*/
@GetMapping("/ancestor/{username}")
public R listAncestorUsers(@PathVariable String username) {
return new R(userService.listAncestorUsers(username));
}
}
package com.elephant.framework.galaxy.aroad.module.system.controller;
import com.elephant.framework.galaxy.aroad.module.common.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 用户角色表 前端控制器
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@RestController
@RequestMapping("/system/user-role")
public class UserRoleController extends BaseController {
}
package com.elephant.framework.galaxy.aroad.module.system.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author wangjian
* @date 2018/1/20
* 部门树
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class DeptTree extends TreeNode {
private String name;
}
package com.elephant.framework.galaxy.aroad.module.system.dto;
import com.elephant.framework.galaxy.aroad.module.system.vo.MenuVO;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author wangjian
* @date 2017年11月9日23:33:27
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class MenuTree extends TreeNode {
private String icon;
private String name;
private boolean spread = false;
private String path;
private String component;
private String authority;
private String redirect;
private String keepAlive;
private String code;
private String type;
private String label;
private Integer sort;
public MenuTree() {
}
public MenuTree(int id, String name, int parentId) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.label = name;
}
public MenuTree(int id, String name, MenuTree parent) {
this.id = id;
this.parentId = parent.getId();
this.name = name;
this.label = name;
}
public MenuTree(MenuVO menuVo) {
this.id = menuVo.getMenuId();
this.parentId = menuVo.getParentId();
this.icon = menuVo.getIcon();
this.name = menuVo.getName();
this.path = menuVo.getPath();
this.component = menuVo.getComponent();
this.type = menuVo.getType();
this.label = menuVo.getName();
this.sort = menuVo.getSort();
this.keepAlive = menuVo.getKeepAlive();
}
}
package com.elephant.framework.galaxy.aroad.module.system.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author wangjian
* @date 2017年11月9日23:33:45
*/
@Data
public class TreeNode {
protected int id;
protected int parentId;
protected List<TreeNode> children = new ArrayList<TreeNode>();
public void add(TreeNode node) {
children.add(node);
}
}
package com.elephant.framework.galaxy.aroad.module.system.dto;
import com.elephant.framework.galaxy.aroad.module.system.entity.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* @author wangjian
* @date 2017/11/5
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class UserDTO extends User {
/**
* 角色ID
*/
private List<Integer> role;
private Integer deptId;
/**
* 新密码
*/
private String newpassword1;
}
package com.elephant.framework.galaxy.aroad.module.system.dto;
import com.elephant.framework.galaxy.aroad.module.system.entity.User;
import lombok.Data;
import java.io.Serializable;
/**
* @Description
* @auther wangjian
* @create 2019-02-21 22:38
*/
@Data
public class UserInfo implements Serializable {
/**
* 用户基本信息
*/
private User user;
/**
* 权限标识集合
*/
private String[] permissions;
/**
* 角色集合
*/
private Integer[] roles;
}
package com.elephant.framework.galaxy.aroad.module.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
/**
* <p>
* 部门管理
* </p>
*
* @author wangjian
* @since 2019-02-21
*/
@TableName("sys_dept")
public class Dept extends Model<Dept> {
private static final long serialVersionUID = 1L;
@TableId(value = "dept_id", type = IdType.AUTO)
private Integer deptId;
/**
* 部门名称
*/
private String name;
/**
* 排序
*/
private Integer sort;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 修改时间
*/
private LocalDateTime updateTime;
/**
* 是否删除 -1:已删除 0:正常
*/
private String delFlag;
private Integer parentId;
private Integer tenantId;
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getTenantId() {
return tenantId;
}
public void setTenantId(Integer tenantId) {
this.tenantId = tenantId;
}
@Override
protected Serializable pkVal() {
return this.deptId;
}
@Override
public String toString() {
return "Dept{" +
"deptId=" + deptId +
", name=" + name +
", sort=" + sort +
", createTime=" + createTime +
", updateTime=" + updateTime +
", delFlag=" + delFlag +
", parentId=" + parentId +
", tenantId=" + tenantId +
"}";
}
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论