From 481fc0bd3c9bb278e70092ae0d66ff3273675095 Mon Sep 17 00:00:00 2001 From: fengyan <2316696377@qq.com> Date: Thu, 21 Nov 2019 18:19:09 +0800 Subject: [PATCH 01/52] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Flyway=EF=BC=8C?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E7=AE=A1=E7=90=86=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=EF=BC=9Aresources:/db/migration/mysql;=20?= =?UTF-8?q?=E5=8D=87=E7=BA=A7springboot=E5=88=B02.2.1=EF=BC=8C=E8=A7=A3?= =?UTF-8?q?=E5=86=B3quartz=E5=9C=A8flyway=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E4=B9=8B=E5=89=8D=E5=B0=B1=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E6=95=B0=E6=8D=AE=E5=BA=93=E7=9A=84=E9=97=AE=E9=A2=98?= =?UTF-8?q?=EF=BC=9B=20=E6=89=93WAR=E5=8C=85=E7=9B=B8=E5=85=B3=EF=BC=9A?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E5=90=8E=E6=B2=A1=E6=9C=89=E6=88=90=E5=8A=9F?= =?UTF-8?q?=E7=9A=84=E4=BF=A1=E6=81=AF=EF=BC=8Cwar=E5=8C=85=E4=B8=AD?= =?UTF-8?q?=E5=8C=85=E5=90=ABtomcat-jar=E5=8C=85=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- ruoyi-admin/pom.xml | 7 +- .../main/java/com/ruoyi/RuoYiApplication.java | 44 +- .../com/ruoyi/RuoYiServletInitializer.java | 18 - .../src/main/resources/application-druid.yml | 34 +- .../src/main/resources/application.yml | 2 +- .../migration/mysql/V001__init_sys_tables.sql | 695 ++++++++++++++++++ .../mysql/V002__init_quartz_tables.sql | 170 +++++ ruoyi-framework/pom.xml | 7 + .../service/impl/SysJobServiceImpl.java | 3 +- 10 files changed, 941 insertions(+), 41 deletions(-) delete mode 100644 ruoyi-admin/src/main/java/com/ruoyi/RuoYiServletInitializer.java create mode 100644 ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql create mode 100644 ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql diff --git a/pom.xml b/pom.xml index 401b07def..bc8ac248d 100644 --- a/pom.xml +++ b/pom.xml @@ -41,7 +41,7 @@ org.springframework.boot spring-boot-dependencies - 2.1.1.RELEASE + 2.2.1.RELEASE pom import diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 0e5ebb834..19b0f1da7 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -72,7 +72,12 @@ com.ruoyi ruoyi-generator - + + + + org.flywaydb + flyway-core + diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java index a0e726bd4..03b2765e4 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java @@ -1,8 +1,12 @@ package com.ruoyi; +import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; /** * 启动程序 @@ -10,21 +14,33 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; * @author ruoyi */ @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) -public class RuoYiApplication -{ - public static void main(String[] args) - { +public class RuoYiApplication extends SpringBootServletInitializer { + public static void main(String[] args) { // System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(RuoYiApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + - " .-------. ____ __ \n" + - " | _ _ \\ \\ \\ / / \n" + - " | ( ' ) | \\ _. / ' \n" + - " |(_ o _) / _( )_ .' \n" + - " | (_,_).' __ ___(_ o _)' \n" + - " | |\\ \\ | || |(_,_)' \n" + - " | | \\ `' /| `-' / \n" + - " | | \\ / \\ / \n" + - " ''-' `'-' `-..-' "); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(RuoYiApplication.class); + } + + @Bean + public CommandLineRunner startupCommandLineRunner(){ + return new CommandLineRunner() { + @Override + public void run(String... args) throws Exception { + System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + + " .-------. ____ __ \n" + + " | _ _ \\ \\ \\ / / \n" + + " | ( ' ) | \\ _. / ' \n" + + " |(_ o _) / _( )_ .' \n" + + " | (_,_).' __ ___(_ o _)' \n" + + " | |\\ \\ | || |(_,_)' \n" + + " | | \\ `' /| `-' / \n" + + " | | \\ / \\ / \n" + + " ''-' `'-' `-..-' "); + } + }; } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiServletInitializer.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiServletInitializer.java deleted file mode 100644 index 9d82a2378..000000000 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiServletInitializer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ruoyi; - -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - -/** - * web容器中进行部署 - * - * @author ruoyi - */ -public class RuoYiServletInitializer extends SpringBootServletInitializer -{ - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) - { - return application.sources(RuoYiApplication.class); - } -} diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index d69c66d27..1df30d82c 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -1,3 +1,10 @@ +#flyway会自动建立该数据库 +db: + # mysql, oracle, sqlserver + type: mysql + name: ry + username: root + password: root # 数据源配置 spring: datasource: @@ -6,9 +13,9 @@ spring: druid: # 主库数据源 master: - url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 - username: root - password: password + url: jdbc:mysql://localhost:3306/${db.name}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: ${db.username} + password: ${db.password} # 从库数据源 slave: # 从数据源开关/默认关闭 @@ -54,4 +61,23 @@ spring: merge-sql: true wall: config: - multi-statement-allow: true \ No newline at end of file + multi-statement-allow: true + + flyway: + enabled: true + url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + user: ${db.username} + password: ${db.password} + #需要目标数据库已经存在,不自动升级 + baseline-on-migrate: false + encoding: utf-8 + clean-on-validation-error: false + clean-disabled: true + #数据库自动迁移的位置 + locations: classpath:db/migration/${db.type} + # 需要管理的数据库 + schemas: ${db.name} + quartz: + job-store-type: jdbc + jdbc: + initialize-schema: never \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 26361c6f8..e9460a605 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -31,8 +31,8 @@ server: # 日志配置 logging: level: + root: warn com.ruoyi: debug - org.springframework: warn # 用户配置 user: diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql new file mode 100644 index 000000000..293c38404 --- /dev/null +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql @@ -0,0 +1,695 @@ +-- ---------------------------- +-- 1、部门表 +-- ---------------------------- +drop table if exists sys_dept; +create table sys_dept ( + dept_id bigint(20) not null auto_increment comment '部门id', + parent_id bigint(20) default 0 comment '父部门id', + ancestors varchar(50) default '' comment '祖级列表', + dept_name varchar(30) default '' comment '部门名称', + order_num int(4) default 0 comment '显示顺序', + leader varchar(20) default null comment '负责人', + phone varchar(11) default null comment '联系电话', + email varchar(50) default null comment '邮箱', + status char(1) default '0' comment '部门状态(0正常 1停用)', + del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + primary key (dept_id) +) engine=innodb auto_increment=200 comment = '部门表'; + +-- ---------------------------- +-- 初始化-部门表数据 +-- ---------------------------- +insert into sys_dept values(100, 0, '0', '若依科技', 0, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(101, 100, '0,100', '深圳总公司', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(102, 100, '0,100', '长沙分公司', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(103, 101, '0,100,101', '研发部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(104, 101, '0,100,101', '市场部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(105, 101, '0,100,101', '测试部门', 3, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(106, 101, '0,100,101', '财务部门', 4, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(107, 101, '0,100,101', '运维部门', 5, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(108, 102, '0,100,102', '市场部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(109, 102, '0,100,102', '财务部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); + + +-- ---------------------------- +-- 2、用户信息表 +-- ---------------------------- +drop table if exists sys_user; +create table sys_user ( + user_id bigint(20) not null auto_increment comment '用户ID', + dept_id bigint(20) default null comment '部门ID', + login_name varchar(30) not null comment '登录账号', + user_name varchar(30) not null comment '用户昵称', + user_type varchar(2) default '00' comment '用户类型(00系统用户)', + email varchar(50) default '' comment '用户邮箱', + phonenumber varchar(11) default '' comment '手机号码', + sex char(1) default '0' comment '用户性别(0男 1女 2未知)', + avatar varchar(100) default '' comment '头像路径', + password varchar(50) default '' comment '密码', + salt varchar(20) default '' comment '盐加密', + status char(1) default '0' comment '帐号状态(0正常 1停用)', + del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', + login_ip varchar(50) default '' comment '最后登陆IP', + login_date datetime comment '最后登陆时间', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (user_id) +) engine=innodb auto_increment=100 comment = '用户信息表'; + +-- ---------------------------- +-- 初始化-用户信息表数据 +-- ---------------------------- +insert into sys_user values(1, 103, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', '29c67a30398638269fe600f73a054934', '111111', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); +insert into sys_user values(2, 105, 'ry', '若依', '00', 'ry@qq.com', '15666666666', '1', '', '8e6d98b90472783cc73c17047ddccf36', '222222', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '测试员'); + + +-- ---------------------------- +-- 3、岗位信息表 +-- ---------------------------- +drop table if exists sys_post; +create table sys_post +( + post_id bigint(20) not null auto_increment comment '岗位ID', + post_code varchar(64) not null comment '岗位编码', + post_name varchar(50) not null comment '岗位名称', + post_sort int(4) not null comment '显示顺序', + status char(1) not null comment '状态(0正常 1停用)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (post_id) +) engine=innodb comment = '岗位信息表'; + +-- ---------------------------- +-- 初始化-岗位信息表数据 +-- ---------------------------- +insert into sys_post values(1, 'ceo', '董事长', 1, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_post values(2, 'se', '项目经理', 2, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_post values(3, 'hr', '人力资源', 3, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_post values(4, 'user', '普通员工', 4, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); + + +-- ---------------------------- +-- 4、角色信息表 +-- ---------------------------- +drop table if exists sys_role; +create table sys_role ( + role_id bigint(20) not null auto_increment comment '角色ID', + role_name varchar(30) not null comment '角色名称', + role_key varchar(100) not null comment '角色权限字符串', + role_sort int(4) not null comment '显示顺序', + data_scope char(1) default '1' comment '数据范围(1:全部数据权限 2:自定数据权限 3:本部门数据权限 4:本部门及以下数据权限)', + status char(1) not null comment '角色状态(0正常 1停用)', + del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (role_id) +) engine=innodb auto_increment=100 comment = '角色信息表'; + +-- ---------------------------- +-- 初始化-角色信息表数据 +-- ---------------------------- +insert into sys_role values('1', '管理员', 'admin', 1, 1, '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); +insert into sys_role values('2', '普通角色', 'common', 2, 2, '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '普通角色'); + + +-- ---------------------------- +-- 5、菜单权限表 +-- ---------------------------- +drop table if exists sys_menu; +create table sys_menu ( + menu_id bigint(20) not null auto_increment comment '菜单ID', + menu_name varchar(50) not null comment '菜单名称', + parent_id bigint(20) default 0 comment '父菜单ID', + order_num int(4) default 0 comment '显示顺序', + url varchar(200) default '#' comment '请求地址', + target varchar(20) default '' comment '打开方式(menuItem页签 menuBlank新窗口)', + menu_type char(1) default '' comment '菜单类型(M目录 C菜单 F按钮)', + visible char(1) default 0 comment '菜单状态(0显示 1隐藏)', + perms varchar(100) default null comment '权限标识', + icon varchar(100) default '#' comment '菜单图标', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default '' comment '备注', + primary key (menu_id) +) engine=innodb auto_increment=2000 comment = '菜单权限表'; + +-- ---------------------------- +-- 初始化-菜单信息表数据 +-- ---------------------------- +-- 一级菜单 +insert into sys_menu values('1', '系统管理', '0', '1', '#', '', 'M', '0', '', 'fa fa-gear', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统管理目录'); +insert into sys_menu values('2', '系统监控', '0', '2', '#', '', 'M', '0', '', 'fa fa-video-camera', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统监控目录'); +insert into sys_menu values('3', '系统工具', '0', '3', '#', '', 'M', '0', '', 'fa fa-bars', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统工具目录'); +-- 二级菜单 +insert into sys_menu values('100', '用户管理', '1', '1', '/system/user', '', 'C', '0', 'system:user:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '用户管理菜单'); +insert into sys_menu values('101', '角色管理', '1', '2', '/system/role', '', 'C', '0', 'system:role:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '角色管理菜单'); +insert into sys_menu values('102', '菜单管理', '1', '3', '/system/menu', '', 'C', '0', 'system:menu:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '菜单管理菜单'); +insert into sys_menu values('103', '部门管理', '1', '4', '/system/dept', '', 'C', '0', 'system:dept:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '部门管理菜单'); +insert into sys_menu values('104', '岗位管理', '1', '5', '/system/post', '', 'C', '0', 'system:post:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '岗位管理菜单'); +insert into sys_menu values('105', '字典管理', '1', '6', '/system/dict', '', 'C', '0', 'system:dict:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '字典管理菜单'); +insert into sys_menu values('106', '参数设置', '1', '7', '/system/config', '', 'C', '0', 'system:config:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '参数设置菜单'); +insert into sys_menu values('107', '通知公告', '1', '8', '/system/notice', '', 'C', '0', 'system:notice:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知公告菜单'); +insert into sys_menu values('108', '日志管理', '1', '9', '#', '', 'M', '0', '', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '日志管理菜单'); +insert into sys_menu values('109', '在线用户', '2', '1', '/monitor/online', '', 'C', '0', 'monitor:online:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '在线用户菜单'); +insert into sys_menu values('110', '定时任务', '2', '2', '/monitor/job', '', 'C', '0', 'monitor:job:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '定时任务菜单'); +insert into sys_menu values('111', '数据监控', '2', '3', '/monitor/data', '', 'C', '0', 'monitor:data:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '数据监控菜单'); +insert into sys_menu values('112', '服务监控', '2', '3', '/monitor/server', '', 'C', '0', 'monitor:server:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '服务监控菜单'); +insert into sys_menu values('113', '表单构建', '3', '1', '/tool/build', '', 'C', '0', 'tool:build:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '表单构建菜单'); +insert into sys_menu values('114', '代码生成', '3', '2', '/tool/gen', '', 'C', '0', 'tool:gen:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '代码生成菜单'); +insert into sys_menu values('115', '系统接口', '3', '3', '/tool/swagger', '', 'C', '0', 'tool:swagger:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统接口菜单'); +-- 三级菜单 +insert into sys_menu values('500', '操作日志', '108', '1', '/monitor/operlog', '', 'C', '0', 'monitor:operlog:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '操作日志菜单'); +insert into sys_menu values('501', '登录日志', '108', '2', '/monitor/logininfor', '', 'C', '0', 'monitor:logininfor:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '登录日志菜单'); +-- 用户管理按钮 +insert into sys_menu values('1000', '用户查询', '100', '1', '#', '', 'F', '0', 'system:user:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1001', '用户新增', '100', '2', '#', '', 'F', '0', 'system:user:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1002', '用户修改', '100', '3', '#', '', 'F', '0', 'system:user:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1003', '用户删除', '100', '4', '#', '', 'F', '0', 'system:user:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1004', '用户导出', '100', '5', '#', '', 'F', '0', 'system:user:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1005', '用户导入', '100', '6', '#', '', 'F', '0', 'system:user:import', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1006', '重置密码', '100', '7', '#', '', 'F', '0', 'system:user:resetPwd', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 角色管理按钮 +insert into sys_menu values('1007', '角色查询', '101', '1', '#', '', 'F', '0', 'system:role:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1008', '角色新增', '101', '2', '#', '', 'F', '0', 'system:role:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1009', '角色修改', '101', '3', '#', '', 'F', '0', 'system:role:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1010', '角色删除', '101', '4', '#', '', 'F', '0', 'system:role:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1011', '角色导出', '101', '5', '#', '', 'F', '0', 'system:role:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 菜单管理按钮 +insert into sys_menu values('1012', '菜单查询', '102', '1', '#', '', 'F', '0', 'system:menu:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1013', '菜单新增', '102', '2', '#', '', 'F', '0', 'system:menu:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1014', '菜单修改', '102', '3', '#', '', 'F', '0', 'system:menu:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1015', '菜单删除', '102', '4', '#', '', 'F', '0', 'system:menu:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 部门管理按钮 +insert into sys_menu values('1016', '部门查询', '103', '1', '#', '', 'F', '0', 'system:dept:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1017', '部门新增', '103', '2', '#', '', 'F', '0', 'system:dept:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1018', '部门修改', '103', '3', '#', '', 'F', '0', 'system:dept:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1019', '部门删除', '103', '4', '#', '', 'F', '0', 'system:dept:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 岗位管理按钮 +insert into sys_menu values('1020', '岗位查询', '104', '1', '#', '', 'F', '0', 'system:post:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1021', '岗位新增', '104', '2', '#', '', 'F', '0', 'system:post:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1022', '岗位修改', '104', '3', '#', '', 'F', '0', 'system:post:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1023', '岗位删除', '104', '4', '#', '', 'F', '0', 'system:post:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1024', '岗位导出', '104', '5', '#', '', 'F', '0', 'system:post:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 字典管理按钮 +insert into sys_menu values('1025', '字典查询', '105', '1', '#', '', 'F', '0', 'system:dict:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1026', '字典新增', '105', '2', '#', '', 'F', '0', 'system:dict:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1027', '字典修改', '105', '3', '#', '', 'F', '0', 'system:dict:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1028', '字典删除', '105', '4', '#', '', 'F', '0', 'system:dict:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1029', '字典导出', '105', '5', '#', '', 'F', '0', 'system:dict:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 参数设置按钮 +insert into sys_menu values('1030', '参数查询', '106', '1', '#', '', 'F', '0', 'system:config:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1031', '参数新增', '106', '2', '#', '', 'F', '0', 'system:config:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1032', '参数修改', '106', '3', '#', '', 'F', '0', 'system:config:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1033', '参数删除', '106', '4', '#', '', 'F', '0', 'system:config:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1034', '参数导出', '106', '5', '#', '', 'F', '0', 'system:config:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 通知公告按钮 +insert into sys_menu values('1035', '公告查询', '107', '1', '#', '', 'F', '0', 'system:notice:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1036', '公告新增', '107', '2', '#', '', 'F', '0', 'system:notice:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1037', '公告修改', '107', '3', '#', '', 'F', '0', 'system:notice:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1038', '公告删除', '107', '4', '#', '', 'F', '0', 'system:notice:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 操作日志按钮 +insert into sys_menu values('1039', '操作查询', '500', '1', '#', '', 'F', '0', 'monitor:operlog:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1040', '操作删除', '500', '2', '#', '', 'F', '0', 'monitor:operlog:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1041', '详细信息', '500', '3', '#', '', 'F', '0', 'monitor:operlog:detail', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1042', '日志导出', '500', '4', '#', '', 'F', '0', 'monitor:operlog:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 登录日志按钮 +insert into sys_menu values('1043', '登录查询', '501', '1', '#', '', 'F', '0', 'monitor:logininfor:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1044', '登录删除', '501', '2', '#', '', 'F', '0', 'monitor:logininfor:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1045', '日志导出', '501', '3', '#', '', 'F', '0', 'monitor:logininfor:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1046', '账户解锁', '501', '4', '#', '', 'F', '0', 'monitor:logininfor:unlock', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 在线用户按钮 +insert into sys_menu values('1047', '在线查询', '109', '1', '#', '', 'F', '0', 'monitor:online:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1048', '批量强退', '109', '2', '#', '', 'F', '0', 'monitor:online:batchForceLogout', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1049', '单条强退', '109', '3', '#', '', 'F', '0', 'monitor:online:forceLogout', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 定时任务按钮 +insert into sys_menu values('1050', '任务查询', '110', '1', '#', '', 'F', '0', 'monitor:job:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1051', '任务新增', '110', '2', '#', '', 'F', '0', 'monitor:job:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1052', '任务修改', '110', '3', '#', '', 'F', '0', 'monitor:job:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1053', '任务删除', '110', '4', '#', '', 'F', '0', 'monitor:job:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1054', '状态修改', '110', '5', '#', '', 'F', '0', 'monitor:job:changeStatus', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1055', '任务详细', '110', '6', '#', '', 'F', '0', 'monitor:job:detail', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1056', '任务导出', '110', '7', '#', '', 'F', '0', 'monitor:job:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +-- 代码生成按钮 +insert into sys_menu values('1057', '生成查询', '114', '1', '#', '', 'F', '0', 'tool:gen:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1058', '生成修改', '114', '2', '#', '', 'F', '0', 'tool:gen:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1059', '生成删除', '114', '3', '#', '', 'F', '0', 'tool:gen:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1060', '预览代码', '114', '4', '#', '', 'F', '0', 'tool:gen:preview', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_menu values('1061', '生成代码', '114', '5', '#', '', 'F', '0', 'tool:gen:code', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); + + +-- ---------------------------- +-- 6、用户和角色关联表 用户N-1角色 +-- ---------------------------- +drop table if exists sys_user_role; +create table sys_user_role ( + user_id bigint(20) not null comment '用户ID', + role_id bigint(20) not null comment '角色ID', + primary key(user_id, role_id) +) engine=innodb comment = '用户和角色关联表'; + +-- ---------------------------- +-- 初始化-用户和角色关联表数据 +-- ---------------------------- +insert into sys_user_role values ('1', '1'); +insert into sys_user_role values ('2', '2'); + + +-- ---------------------------- +-- 7、角色和菜单关联表 角色1-N菜单 +-- ---------------------------- +drop table if exists sys_role_menu; +create table sys_role_menu ( + role_id bigint(20) not null comment '角色ID', + menu_id bigint(20) not null comment '菜单ID', + primary key(role_id, menu_id) +) engine=innodb comment = '角色和菜单关联表'; + +-- ---------------------------- +-- 初始化-角色和菜单关联表数据 +-- ---------------------------- +insert into sys_role_menu values ('2', '1'); +insert into sys_role_menu values ('2', '2'); +insert into sys_role_menu values ('2', '3'); +insert into sys_role_menu values ('2', '100'); +insert into sys_role_menu values ('2', '101'); +insert into sys_role_menu values ('2', '102'); +insert into sys_role_menu values ('2', '103'); +insert into sys_role_menu values ('2', '104'); +insert into sys_role_menu values ('2', '105'); +insert into sys_role_menu values ('2', '106'); +insert into sys_role_menu values ('2', '107'); +insert into sys_role_menu values ('2', '108'); +insert into sys_role_menu values ('2', '109'); +insert into sys_role_menu values ('2', '110'); +insert into sys_role_menu values ('2', '111'); +insert into sys_role_menu values ('2', '112'); +insert into sys_role_menu values ('2', '113'); +insert into sys_role_menu values ('2', '114'); +insert into sys_role_menu values ('2', '115'); +insert into sys_role_menu values ('2', '500'); +insert into sys_role_menu values ('2', '501'); +insert into sys_role_menu values ('2', '1000'); +insert into sys_role_menu values ('2', '1001'); +insert into sys_role_menu values ('2', '1002'); +insert into sys_role_menu values ('2', '1003'); +insert into sys_role_menu values ('2', '1004'); +insert into sys_role_menu values ('2', '1005'); +insert into sys_role_menu values ('2', '1006'); +insert into sys_role_menu values ('2', '1007'); +insert into sys_role_menu values ('2', '1008'); +insert into sys_role_menu values ('2', '1009'); +insert into sys_role_menu values ('2', '1010'); +insert into sys_role_menu values ('2', '1011'); +insert into sys_role_menu values ('2', '1012'); +insert into sys_role_menu values ('2', '1013'); +insert into sys_role_menu values ('2', '1014'); +insert into sys_role_menu values ('2', '1015'); +insert into sys_role_menu values ('2', '1016'); +insert into sys_role_menu values ('2', '1017'); +insert into sys_role_menu values ('2', '1018'); +insert into sys_role_menu values ('2', '1019'); +insert into sys_role_menu values ('2', '1020'); +insert into sys_role_menu values ('2', '1021'); +insert into sys_role_menu values ('2', '1022'); +insert into sys_role_menu values ('2', '1023'); +insert into sys_role_menu values ('2', '1024'); +insert into sys_role_menu values ('2', '1025'); +insert into sys_role_menu values ('2', '1026'); +insert into sys_role_menu values ('2', '1027'); +insert into sys_role_menu values ('2', '1028'); +insert into sys_role_menu values ('2', '1029'); +insert into sys_role_menu values ('2', '1030'); +insert into sys_role_menu values ('2', '1031'); +insert into sys_role_menu values ('2', '1032'); +insert into sys_role_menu values ('2', '1033'); +insert into sys_role_menu values ('2', '1034'); +insert into sys_role_menu values ('2', '1035'); +insert into sys_role_menu values ('2', '1036'); +insert into sys_role_menu values ('2', '1037'); +insert into sys_role_menu values ('2', '1038'); +insert into sys_role_menu values ('2', '1039'); +insert into sys_role_menu values ('2', '1040'); +insert into sys_role_menu values ('2', '1041'); +insert into sys_role_menu values ('2', '1042'); +insert into sys_role_menu values ('2', '1043'); +insert into sys_role_menu values ('2', '1044'); +insert into sys_role_menu values ('2', '1045'); +insert into sys_role_menu values ('2', '1046'); +insert into sys_role_menu values ('2', '1047'); +insert into sys_role_menu values ('2', '1048'); +insert into sys_role_menu values ('2', '1049'); +insert into sys_role_menu values ('2', '1050'); +insert into sys_role_menu values ('2', '1051'); +insert into sys_role_menu values ('2', '1052'); +insert into sys_role_menu values ('2', '1053'); +insert into sys_role_menu values ('2', '1054'); +insert into sys_role_menu values ('2', '1055'); +insert into sys_role_menu values ('2', '1056'); +insert into sys_role_menu values ('2', '1057'); +insert into sys_role_menu values ('2', '1058'); +insert into sys_role_menu values ('2', '1059'); +insert into sys_role_menu values ('2', '1060'); +insert into sys_role_menu values ('2', '1061'); + +-- ---------------------------- +-- 8、角色和部门关联表 角色1-N部门 +-- ---------------------------- +drop table if exists sys_role_dept; +create table sys_role_dept ( + role_id bigint(20) not null comment '角色ID', + dept_id bigint(20) not null comment '部门ID', + primary key(role_id, dept_id) +) engine=innodb comment = '角色和部门关联表'; + +-- ---------------------------- +-- 初始化-角色和部门关联表数据 +-- ---------------------------- +insert into sys_role_dept values ('2', '100'); +insert into sys_role_dept values ('2', '101'); +insert into sys_role_dept values ('2', '105'); + +-- ---------------------------- +-- 9、用户与岗位关联表 用户1-N岗位 +-- ---------------------------- +drop table if exists sys_user_post; +create table sys_user_post +( + user_id bigint(20) not null comment '用户ID', + post_id bigint(20) not null comment '岗位ID', + primary key (user_id, post_id) +) engine=innodb comment = '用户与岗位关联表'; + +-- ---------------------------- +-- 初始化-用户与岗位关联表数据 +-- ---------------------------- +insert into sys_user_post values ('1', '1'); +insert into sys_user_post values ('2', '2'); + + +-- ---------------------------- +-- 10、操作日志记录 +-- ---------------------------- +drop table if exists sys_oper_log; +create table sys_oper_log ( + oper_id bigint(20) not null auto_increment comment '日志主键', + title varchar(50) default '' comment '模块标题', + business_type int(2) default 0 comment '业务类型(0其它 1新增 2修改 3删除)', + method varchar(100) default '' comment '方法名称', + request_method varchar(10) default '' comment '请求方式', + operator_type int(1) default 0 comment '操作类别(0其它 1后台用户 2手机端用户)', + oper_name varchar(50) default '' comment '操作人员', + dept_name varchar(50) default '' comment '部门名称', + oper_url varchar(255) default '' comment '请求URL', + oper_ip varchar(50) default '' comment '主机地址', + oper_location varchar(255) default '' comment '操作地点', + oper_param varchar(2000) default '' comment '请求参数', + json_result varchar(2000) default '' comment '返回参数', + status int(1) default 0 comment '操作状态(0正常 1异常)', + error_msg varchar(2000) default '' comment '错误消息', + oper_time datetime comment '操作时间', + primary key (oper_id) +) engine=innodb auto_increment=100 comment = '操作日志记录'; + + +-- ---------------------------- +-- 11、字典类型表 +-- ---------------------------- +drop table if exists sys_dict_type; +create table sys_dict_type +( + dict_id bigint(20) not null auto_increment comment '字典主键', + dict_name varchar(100) default '' comment '字典名称', + dict_type varchar(100) default '' comment '字典类型', + status char(1) default '0' comment '状态(0正常 1停用)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (dict_id), + unique (dict_type) +) engine=innodb auto_increment=100 comment = '字典类型表'; + +insert into sys_dict_type values(1, '用户性别', 'sys_user_sex', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '用户性别列表'); +insert into sys_dict_type values(2, '菜单状态', 'sys_show_hide', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '菜单状态列表'); +insert into sys_dict_type values(3, '系统开关', 'sys_normal_disable', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统开关列表'); +insert into sys_dict_type values(4, '任务状态', 'sys_job_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '任务状态列表'); +insert into sys_dict_type values(5, '任务分组', 'sys_job_group', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '任务分组列表'); +insert into sys_dict_type values(6, '系统是否', 'sys_yes_no', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统是否列表'); +insert into sys_dict_type values(7, '通知类型', 'sys_notice_type', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知类型列表'); +insert into sys_dict_type values(8, '通知状态', 'sys_notice_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知状态列表'); +insert into sys_dict_type values(9, '操作类型', 'sys_oper_type', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '操作类型列表'); +insert into sys_dict_type values(10, '系统状态', 'sys_common_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '登录状态列表'); + + +-- ---------------------------- +-- 12、字典数据表 +-- ---------------------------- +drop table if exists sys_dict_data; +create table sys_dict_data +( + dict_code bigint(20) not null auto_increment comment '字典编码', + dict_sort int(4) default 0 comment '字典排序', + dict_label varchar(100) default '' comment '字典标签', + dict_value varchar(100) default '' comment '字典键值', + dict_type varchar(100) default '' comment '字典类型', + css_class varchar(100) default null comment '样式属性(其他样式扩展)', + list_class varchar(100) default null comment '表格回显样式', + is_default char(1) default 'N' comment '是否默认(Y是 N否)', + status char(1) default '0' comment '状态(0正常 1停用)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (dict_code) +) engine=innodb auto_increment=100 comment = '字典数据表'; + +insert into sys_dict_data values(1, 1, '男', '0', 'sys_user_sex', '', '', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别男'); +insert into sys_dict_data values(2, 2, '女', '1', 'sys_user_sex', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别女'); +insert into sys_dict_data values(3, 3, '未知', '2', 'sys_user_sex', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别未知'); +insert into sys_dict_data values(4, 1, '显示', '0', 'sys_show_hide', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '显示菜单'); +insert into sys_dict_data values(5, 2, '隐藏', '1', 'sys_show_hide', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '隐藏菜单'); +insert into sys_dict_data values(6, 1, '正常', '0', 'sys_normal_disable', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); +insert into sys_dict_data values(7, 2, '停用', '1', 'sys_normal_disable', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); +insert into sys_dict_data values(8, 1, '正常', '0', 'sys_job_status', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); +insert into sys_dict_data values(9, 2, '暂停', '1', 'sys_job_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); +insert into sys_dict_data values(10, 1, '默认', 'DEFAULT', 'sys_job_group', '', '', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '默认分组'); +insert into sys_dict_data values(11, 2, '系统', 'SYSTEM', 'sys_job_group', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统分组'); +insert into sys_dict_data values(12, 1, '是', 'Y', 'sys_yes_no', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统默认是'); +insert into sys_dict_data values(13, 2, '否', 'N', 'sys_yes_no', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统默认否'); +insert into sys_dict_data values(14, 1, '通知', '1', 'sys_notice_type', '', 'warning', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知'); +insert into sys_dict_data values(15, 2, '公告', '2', 'sys_notice_type', '', 'success', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '公告'); +insert into sys_dict_data values(16, 1, '正常', '0', 'sys_notice_status', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); +insert into sys_dict_data values(17, 2, '关闭', '1', 'sys_notice_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '关闭状态'); +insert into sys_dict_data values(18, 1, '新增', '1', 'sys_oper_type', '', 'info', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '新增操作'); +insert into sys_dict_data values(19, 2, '修改', '2', 'sys_oper_type', '', 'info', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '修改操作'); +insert into sys_dict_data values(20, 3, '删除', '3', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '删除操作'); +insert into sys_dict_data values(21, 4, '授权', '4', 'sys_oper_type', '', 'primary', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '授权操作'); +insert into sys_dict_data values(22, 5, '导出', '5', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '导出操作'); +insert into sys_dict_data values(23, 6, '导入', '6', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '导入操作'); +insert into sys_dict_data values(24, 7, '强退', '7', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '强退操作'); +insert into sys_dict_data values(25, 8, '生成代码', '8', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '生成操作'); +insert into sys_dict_data values(26, 9, '清空数据', '9', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '清空操作'); +insert into sys_dict_data values(27, 1, '成功', '0', 'sys_common_status', '', 'primary', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); +insert into sys_dict_data values(28, 2, '失败', '1', 'sys_common_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); + + +-- ---------------------------- +-- 13、参数配置表 +-- ---------------------------- +drop table if exists sys_config; +create table sys_config ( + config_id int(5) not null auto_increment comment '参数主键', + config_name varchar(100) default '' comment '参数名称', + config_key varchar(100) default '' comment '参数键名', + config_value varchar(500) default '' comment '参数键值', + config_type char(1) default 'N' comment '系统内置(Y是 N否)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (config_id) +) engine=innodb auto_increment=100 comment = '参数配置表'; + +insert into sys_config values(1, '主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-blue', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow' ); +insert into sys_config values(2, '用户管理-账号初始密码', 'sys.user.initPassword', '123456', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '初始化密码 123456' ); +insert into sys_config values(3, '主框架页-侧边栏主题', 'sys.index.sideTheme', 'theme-dark', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '深色主题theme-dark,浅色主题theme-light' ); + + +-- ---------------------------- +-- 14、系统访问记录 +-- ---------------------------- +drop table if exists sys_logininfor; +create table sys_logininfor ( + info_id bigint(20) not null auto_increment comment '访问ID', + login_name varchar(50) default '' comment '登录账号', + ipaddr varchar(50) default '' comment '登录IP地址', + login_location varchar(255) default '' comment '登录地点', + browser varchar(50) default '' comment '浏览器类型', + os varchar(50) default '' comment '操作系统', + status char(1) default '0' comment '登录状态(0成功 1失败)', + msg varchar(255) default '' comment '提示消息', + login_time datetime comment '访问时间', + primary key (info_id) +) engine=innodb auto_increment=100 comment = '系统访问记录'; + + +-- ---------------------------- +-- 15、在线用户记录 +-- ---------------------------- +drop table if exists sys_user_online; +create table sys_user_online ( + sessionId varchar(50) default '' comment '用户会话id', + login_name varchar(50) default '' comment '登录账号', + dept_name varchar(50) default '' comment '部门名称', + ipaddr varchar(50) default '' comment '登录IP地址', + login_location varchar(255) default '' comment '登录地点', + browser varchar(50) default '' comment '浏览器类型', + os varchar(50) default '' comment '操作系统', + status varchar(10) default '' comment '在线状态on_line在线off_line离线', + start_timestamp datetime comment 'session创建时间', + last_access_time datetime comment 'session最后访问时间', + expire_time int(5) default 0 comment '超时时间,单位为分钟', + primary key (sessionId) +) engine=innodb comment = '在线用户记录'; + + +-- ---------------------------- +-- 16、定时任务调度表 +-- ---------------------------- +drop table if exists sys_job; +create table sys_job ( + job_id bigint(20) not null auto_increment comment '任务ID', + job_name varchar(64) default '' comment '任务名称', + job_group varchar(64) default 'DEFAULT' comment '任务组名', + invoke_target varchar(500) not null comment '调用目标字符串', + cron_expression varchar(255) default '' comment 'cron执行表达式', + misfire_policy varchar(20) default '3' comment '计划执行错误策略(1立即执行 2执行一次 3放弃执行)', + concurrent char(1) default '1' comment '是否并发执行(0允许 1禁止)', + status char(1) default '0' comment '状态(0正常 1暂停)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default '' comment '备注信息', + primary key (job_id, job_name, job_group) +) engine=innodb auto_increment=100 comment = '定时任务调度表'; + +insert into sys_job values(1, '系统默认(无参)', 'DEFAULT', 'ryTask.ryNoParams', '0/10 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_job values(2, '系统默认(有参)', 'DEFAULT', 'ryTask.ryParams(\'ry\')', '0/15 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); +insert into sys_job values(3, '系统默认(多参)', 'DEFAULT', 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)', '0/20 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); + + +-- ---------------------------- +-- 17、定时任务调度日志表 +-- ---------------------------- +drop table if exists sys_job_log; +create table sys_job_log ( + job_log_id bigint(20) not null auto_increment comment '任务日志ID', + job_name varchar(64) not null comment '任务名称', + job_group varchar(64) not null comment '任务组名', + invoke_target varchar(500) not null comment '调用目标字符串', + job_message varchar(500) comment '日志信息', + status char(1) default '0' comment '执行状态(0正常 1失败)', + exception_info varchar(2000) default '' comment '异常信息', + create_time datetime comment '创建时间', + primary key (job_log_id) +) engine=innodb comment = '定时任务调度日志表'; + + +-- ---------------------------- +-- 18、通知公告表 +-- ---------------------------- +drop table if exists sys_notice; +create table sys_notice ( + notice_id int(4) not null auto_increment comment '公告ID', + notice_title varchar(50) not null comment '公告标题', + notice_type char(1) not null comment '公告类型(1通知 2公告)', + notice_content varchar(2000) default null comment '公告内容', + status char(1) default '0' comment '公告状态(0正常 1关闭)', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(255) default null comment '备注', + primary key (notice_id) +) engine=innodb auto_increment=10 comment = '通知公告表'; + +-- ---------------------------- +-- 初始化-公告信息表数据 +-- ---------------------------- +insert into sys_notice values('1', '温馨提醒:2018-07-01 若依新版本发布啦', '2', '新版本内容', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); +insert into sys_notice values('2', '维护通知:2018-07-01 若依系统凌晨维护', '1', '维护内容', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); + + +-- ---------------------------- +-- 19、代码生成业务表 +-- ---------------------------- +drop table if exists gen_table; +create table gen_table ( + table_id bigint(20) not null auto_increment comment '编号', + table_name varchar(200) default '' comment '表名称', + table_comment varchar(500) default '' comment '表描述', + class_name varchar(100) default '' comment '实体类名称', + tpl_category varchar(200) default 'crud' comment '使用的模板(crud单表操作 tree树表操作)', + package_name varchar(100) comment '生成包路径', + module_name varchar(30) comment '生成模块名', + business_name varchar(30) comment '生成业务名', + function_name varchar(50) comment '生成功能名', + function_author varchar(50) comment '生成功能作者', + options varchar(1000) comment '其它生成选项', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + remark varchar(500) default null comment '备注', + primary key (table_id) +) engine=innodb auto_increment=1 comment = '代码生成业务表'; + + +-- ---------------------------- +-- 20、代码生成业务表字段 +-- ---------------------------- +drop table if exists gen_table_column; +create table gen_table_column ( + column_id bigint(20) not null auto_increment comment '编号', + table_id varchar(64) comment '归属表编号', + column_name varchar(200) comment '列名称', + column_comment varchar(500) comment '列描述', + column_type varchar(100) comment '列类型', + java_type varchar(500) comment 'JAVA类型', + java_field varchar(200) comment 'JAVA字段名', + is_pk char(1) comment '是否主键(1是)', + is_increment char(1) comment '是否自增(1是)', + is_required char(1) comment '是否必填(1是)', + is_insert char(1) comment '是否为插入字段(1是)', + is_edit char(1) comment '是否编辑字段(1是)', + is_list char(1) comment '是否列表字段(1是)', + is_query char(1) comment '是否查询字段(1是)', + query_type varchar(200) default 'EQ' comment '查询方式(等于、不等于、大于、小于、范围)', + html_type varchar(200) comment '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)', + dict_type varchar(200) default '' comment '字典类型', + sort int comment '排序', + create_by varchar(64) default '' comment '创建者', + create_time datetime comment '创建时间', + update_by varchar(64) default '' comment '更新者', + update_time datetime comment '更新时间', + primary key (column_id) +) engine=innodb auto_increment=1 comment = '代码生成业务表字段'; \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql new file mode 100644 index 000000000..55665e2b9 --- /dev/null +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql @@ -0,0 +1,170 @@ +-- ---------------------------- +-- 1、存储每一个已配置的 jobDetail 的详细信息 +-- ---------------------------- +drop table if exists QRTZ_JOB_DETAILS; +create table QRTZ_JOB_DETAILS ( + sched_name varchar(120) not null, + job_name varchar(200) not null, + job_group varchar(200) not null, + description varchar(250) null, + job_class_name varchar(250) not null, + is_durable varchar(1) not null, + is_nonconcurrent varchar(1) not null, + is_update_data varchar(1) not null, + requests_recovery varchar(1) not null, + job_data blob null, + primary key (sched_name,job_name,job_group) +) engine=innodb; + +-- ---------------------------- +-- 2、 存储已配置的 Trigger 的信息 +-- ---------------------------- +drop table if exists QRTZ_TRIGGERS; +create table QRTZ_TRIGGERS ( + sched_name varchar(120) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + job_name varchar(200) not null, + job_group varchar(200) not null, + description varchar(250) null, + next_fire_time bigint(13) null, + prev_fire_time bigint(13) null, + priority integer null, + trigger_state varchar(16) not null, + trigger_type varchar(8) not null, + start_time bigint(13) not null, + end_time bigint(13) null, + calendar_name varchar(200) null, + misfire_instr smallint(2) null, + job_data blob null, + primary key (sched_name,trigger_name,trigger_group), + foreign key (sched_name,job_name,job_group) references QRTZ_JOB_DETAILS(sched_name,job_name,job_group) +) engine=innodb; + +-- ---------------------------- +-- 3、 存储简单的 Trigger,包括重复次数,间隔,以及已触发的次数 +-- ---------------------------- +drop table if exists QRTZ_SIMPLE_TRIGGERS; +create table QRTZ_SIMPLE_TRIGGERS ( + sched_name varchar(120) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + repeat_count bigint(7) not null, + repeat_interval bigint(12) not null, + times_triggered bigint(10) not null, + primary key (sched_name,trigger_name,trigger_group), + foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) +) engine=innodb; + +-- ---------------------------- +-- 4、 存储 Cron Trigger,包括 Cron 表达式和时区信息 +-- ---------------------------- +drop table if exists QRTZ_CRON_TRIGGERS; +create table QRTZ_CRON_TRIGGERS ( + sched_name varchar(120) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + cron_expression varchar(200) not null, + time_zone_id varchar(80), + primary key (sched_name,trigger_name,trigger_group), + foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) +) engine=innodb; + +-- ---------------------------- +-- 5、 Trigger 作为 Blob 类型存储(用于 Quartz 用户用 JDBC 创建他们自己定制的 Trigger 类型,JobStore 并不知道如何存储实例的时候) +-- ---------------------------- +drop table if exists QRTZ_BLOB_TRIGGERS; +create table QRTZ_BLOB_TRIGGERS ( + sched_name varchar(120) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + blob_data blob null, + primary key (sched_name,trigger_name,trigger_group), + foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) +) engine=innodb; + +-- ---------------------------- +-- 6、 以 Blob 类型存储存放日历信息, quartz可配置一个日历来指定一个时间范围 +-- ---------------------------- +drop table if exists QRTZ_CALENDARS; +create table QRTZ_CALENDARS ( + sched_name varchar(120) not null, + calendar_name varchar(200) not null, + calendar blob not null, + primary key (sched_name,calendar_name) +) engine=innodb; + +-- ---------------------------- +-- 7、 存储已暂停的 Trigger 组的信息 +-- ---------------------------- +drop table if exists QRTZ_PAUSED_TRIGGER_GRPS; +create table QRTZ_PAUSED_TRIGGER_GRPS ( + sched_name varchar(120) not null, + trigger_group varchar(200) not null, + primary key (sched_name,trigger_group) +) engine=innodb; + +-- ---------------------------- +-- 8、 存储与已触发的 Trigger 相关的状态信息,以及相联 Job 的执行信息 +-- ---------------------------- +drop table if exists QRTZ_FIRED_TRIGGERS; +create table QRTZ_FIRED_TRIGGERS ( + sched_name varchar(120) not null, + entry_id varchar(95) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + instance_name varchar(200) not null, + fired_time bigint(13) not null, + sched_time bigint(13) not null, + priority integer not null, + state varchar(16) not null, + job_name varchar(200) null, + job_group varchar(200) null, + is_nonconcurrent varchar(1) null, + requests_recovery varchar(1) null, + primary key (sched_name,entry_id) +) engine=innodb; + +-- ---------------------------- +-- 9、 存储少量的有关 Scheduler 的状态信息,假如是用于集群中,可以看到其他的 Scheduler 实例 +-- ---------------------------- +drop table if exists QRTZ_SCHEDULER_STATE; +create table QRTZ_SCHEDULER_STATE ( + sched_name varchar(120) not null, + instance_name varchar(200) not null, + last_checkin_time bigint(13) not null, + checkin_interval bigint(13) not null, + primary key (sched_name,instance_name) +) engine=innodb; + +-- ---------------------------- +-- 10、 存储程序的悲观锁的信息(假如使用了悲观锁) +-- ---------------------------- +drop table if exists QRTZ_LOCKS; +create table QRTZ_LOCKS ( + sched_name varchar(120) not null, + lock_name varchar(40) not null, + primary key (sched_name,lock_name) +) engine=innodb; + +drop table if exists QRTZ_SIMPROP_TRIGGERS; +create table QRTZ_SIMPROP_TRIGGERS ( + sched_name varchar(120) not null, + trigger_name varchar(200) not null, + trigger_group varchar(200) not null, + str_prop_1 varchar(512) null, + str_prop_2 varchar(512) null, + str_prop_3 varchar(512) null, + int_prop_1 int null, + int_prop_2 int null, + long_prop_1 bigint null, + long_prop_2 bigint null, + dec_prop_1 numeric(13,4) null, + dec_prop_2 numeric(13,4) null, + bool_prop_1 varchar(1) null, + bool_prop_2 varchar(1) null, + primary key (sched_name,trigger_name,trigger_group), + foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) +) engine=innodb; + +commit; \ No newline at end of file diff --git a/ruoyi-framework/pom.xml b/ruoyi-framework/pom.xml index 1156bc378..540ecb592 100644 --- a/ruoyi-framework/pom.xml +++ b/ruoyi-framework/pom.xml @@ -23,6 +23,13 @@ spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + org.springframework.boot diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java index 29a9eb540..95e3623a0 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java @@ -37,8 +37,7 @@ public class SysJobServiceImpl implements ISysJobService * 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据) */ @PostConstruct - public void init() throws SchedulerException, TaskException - { + public void init() throws SchedulerException, TaskException { List jobList = jobMapper.selectJobAll(); for (SysJob job : jobList) { From 56c150e981136ec6ddd8fc656713d80c644824cf Mon Sep 17 00:00:00 2001 From: fengyan <2316696377@qq.com> Date: Thu, 21 Nov 2019 18:20:37 +0800 Subject: [PATCH 02/52] =?UTF-8?q?=E6=B7=BB=E5=8A=A0flyway=E5=90=8E?= =?UTF-8?q?=EF=BC=8C=E6=97=A0=E9=9C=80=E6=89=8B=E5=8A=A8=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=EF=BC=9B=E7=A7=BB=E9=99=A4=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E8=84=9A=E6=9C=AC=EF=BC=8C=E4=BB=A5=E5=85=8D=E8=AF=AF?= =?UTF-8?q?=E5=AF=BC=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sql/quartz.sql | 170 ----------- sql/ry_20191008.sql | 695 -------------------------------------------- 2 files changed, 865 deletions(-) delete mode 100644 sql/quartz.sql delete mode 100644 sql/ry_20191008.sql diff --git a/sql/quartz.sql b/sql/quartz.sql deleted file mode 100644 index 52b6a0926..000000000 --- a/sql/quartz.sql +++ /dev/null @@ -1,170 +0,0 @@ --- ---------------------------- --- 1、存储每一个已配置的 jobDetail 的详细信息 --- ---------------------------- -drop table if exists QRTZ_JOB_DETAILS; -create table QRTZ_JOB_DETAILS ( - sched_name varchar(120) not null, - job_name varchar(200) not null, - job_group varchar(200) not null, - description varchar(250) null, - job_class_name varchar(250) not null, - is_durable varchar(1) not null, - is_nonconcurrent varchar(1) not null, - is_update_data varchar(1) not null, - requests_recovery varchar(1) not null, - job_data blob null, - primary key (sched_name,job_name,job_group) -) engine=innodb; - --- ---------------------------- --- 2、 存储已配置的 Trigger 的信息 --- ---------------------------- -drop table if exists QRTZ_TRIGGERS; -create table QRTZ_TRIGGERS ( - sched_name varchar(120) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - job_name varchar(200) not null, - job_group varchar(200) not null, - description varchar(250) null, - next_fire_time bigint(13) null, - prev_fire_time bigint(13) null, - priority integer null, - trigger_state varchar(16) not null, - trigger_type varchar(8) not null, - start_time bigint(13) not null, - end_time bigint(13) null, - calendar_name varchar(200) null, - misfire_instr smallint(2) null, - job_data blob null, - primary key (sched_name,trigger_name,trigger_group), - foreign key (sched_name,job_name,job_group) references QRTZ_JOB_DETAILS(sched_name,job_name,job_group) -) engine=innodb; - --- ---------------------------- --- 3、 存储简单的 Trigger,包括重复次数,间隔,以及已触发的次数 --- ---------------------------- -drop table if exists QRTZ_SIMPLE_TRIGGERS; -create table QRTZ_SIMPLE_TRIGGERS ( - sched_name varchar(120) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - repeat_count bigint(7) not null, - repeat_interval bigint(12) not null, - times_triggered bigint(10) not null, - primary key (sched_name,trigger_name,trigger_group), - foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) -) engine=innodb; - --- ---------------------------- --- 4、 存储 Cron Trigger,包括 Cron 表达式和时区信息 --- ---------------------------- -drop table if exists QRTZ_CRON_TRIGGERS; -create table QRTZ_CRON_TRIGGERS ( - sched_name varchar(120) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - cron_expression varchar(200) not null, - time_zone_id varchar(80), - primary key (sched_name,trigger_name,trigger_group), - foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) -) engine=innodb; - --- ---------------------------- --- 5、 Trigger 作为 Blob 类型存储(用于 Quartz 用户用 JDBC 创建他们自己定制的 Trigger 类型,JobStore 并不知道如何存储实例的时候) --- ---------------------------- -drop table if exists QRTZ_BLOB_TRIGGERS; -create table QRTZ_BLOB_TRIGGERS ( - sched_name varchar(120) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - blob_data blob null, - primary key (sched_name,trigger_name,trigger_group), - foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) -) engine=innodb; - --- ---------------------------- --- 6、 以 Blob 类型存储存放日历信息, quartz可配置一个日历来指定一个时间范围 --- ---------------------------- -drop table if exists QRTZ_CALENDARS; -create table QRTZ_CALENDARS ( - sched_name varchar(120) not null, - calendar_name varchar(200) not null, - calendar blob not null, - primary key (sched_name,calendar_name) -) engine=innodb; - --- ---------------------------- --- 7、 存储已暂停的 Trigger 组的信息 --- ---------------------------- -drop table if exists QRTZ_PAUSED_TRIGGER_GRPS; -create table QRTZ_PAUSED_TRIGGER_GRPS ( - sched_name varchar(120) not null, - trigger_group varchar(200) not null, - primary key (sched_name,trigger_group) -) engine=innodb; - --- ---------------------------- --- 8、 存储与已触发的 Trigger 相关的状态信息,以及相联 Job 的执行信息 --- ---------------------------- -drop table if exists QRTZ_FIRED_TRIGGERS; -create table QRTZ_FIRED_TRIGGERS ( - sched_name varchar(120) not null, - entry_id varchar(95) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - instance_name varchar(200) not null, - fired_time bigint(13) not null, - sched_time bigint(13) not null, - priority integer not null, - state varchar(16) not null, - job_name varchar(200) null, - job_group varchar(200) null, - is_nonconcurrent varchar(1) null, - requests_recovery varchar(1) null, - primary key (sched_name,entry_id) -) engine=innodb; - --- ---------------------------- --- 9、 存储少量的有关 Scheduler 的状态信息,假如是用于集群中,可以看到其他的 Scheduler 实例 --- ---------------------------- -drop table if exists QRTZ_SCHEDULER_STATE; -create table QRTZ_SCHEDULER_STATE ( - sched_name varchar(120) not null, - instance_name varchar(200) not null, - last_checkin_time bigint(13) not null, - checkin_interval bigint(13) not null, - primary key (sched_name,instance_name) -) engine=innodb; - --- ---------------------------- --- 10、 存储程序的悲观锁的信息(假如使用了悲观锁) --- ---------------------------- -drop table if exists QRTZ_LOCKS; -create table QRTZ_LOCKS ( - sched_name varchar(120) not null, - lock_name varchar(40) not null, - primary key (sched_name,lock_name) -) engine=innodb; - -drop table if exists QRTZ_SIMPROP_TRIGGERS; -create table QRTZ_SIMPROP_TRIGGERS ( - sched_name varchar(120) not null, - trigger_name varchar(200) not null, - trigger_group varchar(200) not null, - str_prop_1 varchar(512) null, - str_prop_2 varchar(512) null, - str_prop_3 varchar(512) null, - int_prop_1 int null, - int_prop_2 int null, - long_prop_1 bigint null, - long_prop_2 bigint null, - dec_prop_1 numeric(13,4) null, - dec_prop_2 numeric(13,4) null, - bool_prop_1 varchar(1) null, - bool_prop_2 varchar(1) null, - primary key (sched_name,trigger_name,trigger_group), - foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) -) engine=innodb; - -commit; \ No newline at end of file diff --git a/sql/ry_20191008.sql b/sql/ry_20191008.sql deleted file mode 100644 index 293c38404..000000000 --- a/sql/ry_20191008.sql +++ /dev/null @@ -1,695 +0,0 @@ --- ---------------------------- --- 1、部门表 --- ---------------------------- -drop table if exists sys_dept; -create table sys_dept ( - dept_id bigint(20) not null auto_increment comment '部门id', - parent_id bigint(20) default 0 comment '父部门id', - ancestors varchar(50) default '' comment '祖级列表', - dept_name varchar(30) default '' comment '部门名称', - order_num int(4) default 0 comment '显示顺序', - leader varchar(20) default null comment '负责人', - phone varchar(11) default null comment '联系电话', - email varchar(50) default null comment '邮箱', - status char(1) default '0' comment '部门状态(0正常 1停用)', - del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - primary key (dept_id) -) engine=innodb auto_increment=200 comment = '部门表'; - --- ---------------------------- --- 初始化-部门表数据 --- ---------------------------- -insert into sys_dept values(100, 0, '0', '若依科技', 0, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(101, 100, '0,100', '深圳总公司', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(102, 100, '0,100', '长沙分公司', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(103, 101, '0,100,101', '研发部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(104, 101, '0,100,101', '市场部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(105, 101, '0,100,101', '测试部门', 3, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(106, 101, '0,100,101', '财务部门', 4, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(107, 101, '0,100,101', '运维部门', 5, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(108, 102, '0,100,102', '市场部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(109, 102, '0,100,102', '财务部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); - - --- ---------------------------- --- 2、用户信息表 --- ---------------------------- -drop table if exists sys_user; -create table sys_user ( - user_id bigint(20) not null auto_increment comment '用户ID', - dept_id bigint(20) default null comment '部门ID', - login_name varchar(30) not null comment '登录账号', - user_name varchar(30) not null comment '用户昵称', - user_type varchar(2) default '00' comment '用户类型(00系统用户)', - email varchar(50) default '' comment '用户邮箱', - phonenumber varchar(11) default '' comment '手机号码', - sex char(1) default '0' comment '用户性别(0男 1女 2未知)', - avatar varchar(100) default '' comment '头像路径', - password varchar(50) default '' comment '密码', - salt varchar(20) default '' comment '盐加密', - status char(1) default '0' comment '帐号状态(0正常 1停用)', - del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', - login_ip varchar(50) default '' comment '最后登陆IP', - login_date datetime comment '最后登陆时间', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (user_id) -) engine=innodb auto_increment=100 comment = '用户信息表'; - --- ---------------------------- --- 初始化-用户信息表数据 --- ---------------------------- -insert into sys_user values(1, 103, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', '29c67a30398638269fe600f73a054934', '111111', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); -insert into sys_user values(2, 105, 'ry', '若依', '00', 'ry@qq.com', '15666666666', '1', '', '8e6d98b90472783cc73c17047ddccf36', '222222', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '测试员'); - - --- ---------------------------- --- 3、岗位信息表 --- ---------------------------- -drop table if exists sys_post; -create table sys_post -( - post_id bigint(20) not null auto_increment comment '岗位ID', - post_code varchar(64) not null comment '岗位编码', - post_name varchar(50) not null comment '岗位名称', - post_sort int(4) not null comment '显示顺序', - status char(1) not null comment '状态(0正常 1停用)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (post_id) -) engine=innodb comment = '岗位信息表'; - --- ---------------------------- --- 初始化-岗位信息表数据 --- ---------------------------- -insert into sys_post values(1, 'ceo', '董事长', 1, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_post values(2, 'se', '项目经理', 2, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_post values(3, 'hr', '人力资源', 3, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_post values(4, 'user', '普通员工', 4, '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); - - --- ---------------------------- --- 4、角色信息表 --- ---------------------------- -drop table if exists sys_role; -create table sys_role ( - role_id bigint(20) not null auto_increment comment '角色ID', - role_name varchar(30) not null comment '角色名称', - role_key varchar(100) not null comment '角色权限字符串', - role_sort int(4) not null comment '显示顺序', - data_scope char(1) default '1' comment '数据范围(1:全部数据权限 2:自定数据权限 3:本部门数据权限 4:本部门及以下数据权限)', - status char(1) not null comment '角色状态(0正常 1停用)', - del_flag char(1) default '0' comment '删除标志(0代表存在 2代表删除)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (role_id) -) engine=innodb auto_increment=100 comment = '角色信息表'; - --- ---------------------------- --- 初始化-角色信息表数据 --- ---------------------------- -insert into sys_role values('1', '管理员', 'admin', 1, 1, '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); -insert into sys_role values('2', '普通角色', 'common', 2, 2, '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '普通角色'); - - --- ---------------------------- --- 5、菜单权限表 --- ---------------------------- -drop table if exists sys_menu; -create table sys_menu ( - menu_id bigint(20) not null auto_increment comment '菜单ID', - menu_name varchar(50) not null comment '菜单名称', - parent_id bigint(20) default 0 comment '父菜单ID', - order_num int(4) default 0 comment '显示顺序', - url varchar(200) default '#' comment '请求地址', - target varchar(20) default '' comment '打开方式(menuItem页签 menuBlank新窗口)', - menu_type char(1) default '' comment '菜单类型(M目录 C菜单 F按钮)', - visible char(1) default 0 comment '菜单状态(0显示 1隐藏)', - perms varchar(100) default null comment '权限标识', - icon varchar(100) default '#' comment '菜单图标', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default '' comment '备注', - primary key (menu_id) -) engine=innodb auto_increment=2000 comment = '菜单权限表'; - --- ---------------------------- --- 初始化-菜单信息表数据 --- ---------------------------- --- 一级菜单 -insert into sys_menu values('1', '系统管理', '0', '1', '#', '', 'M', '0', '', 'fa fa-gear', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统管理目录'); -insert into sys_menu values('2', '系统监控', '0', '2', '#', '', 'M', '0', '', 'fa fa-video-camera', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统监控目录'); -insert into sys_menu values('3', '系统工具', '0', '3', '#', '', 'M', '0', '', 'fa fa-bars', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统工具目录'); --- 二级菜单 -insert into sys_menu values('100', '用户管理', '1', '1', '/system/user', '', 'C', '0', 'system:user:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '用户管理菜单'); -insert into sys_menu values('101', '角色管理', '1', '2', '/system/role', '', 'C', '0', 'system:role:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '角色管理菜单'); -insert into sys_menu values('102', '菜单管理', '1', '3', '/system/menu', '', 'C', '0', 'system:menu:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '菜单管理菜单'); -insert into sys_menu values('103', '部门管理', '1', '4', '/system/dept', '', 'C', '0', 'system:dept:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '部门管理菜单'); -insert into sys_menu values('104', '岗位管理', '1', '5', '/system/post', '', 'C', '0', 'system:post:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '岗位管理菜单'); -insert into sys_menu values('105', '字典管理', '1', '6', '/system/dict', '', 'C', '0', 'system:dict:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '字典管理菜单'); -insert into sys_menu values('106', '参数设置', '1', '7', '/system/config', '', 'C', '0', 'system:config:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '参数设置菜单'); -insert into sys_menu values('107', '通知公告', '1', '8', '/system/notice', '', 'C', '0', 'system:notice:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知公告菜单'); -insert into sys_menu values('108', '日志管理', '1', '9', '#', '', 'M', '0', '', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '日志管理菜单'); -insert into sys_menu values('109', '在线用户', '2', '1', '/monitor/online', '', 'C', '0', 'monitor:online:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '在线用户菜单'); -insert into sys_menu values('110', '定时任务', '2', '2', '/monitor/job', '', 'C', '0', 'monitor:job:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '定时任务菜单'); -insert into sys_menu values('111', '数据监控', '2', '3', '/monitor/data', '', 'C', '0', 'monitor:data:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '数据监控菜单'); -insert into sys_menu values('112', '服务监控', '2', '3', '/monitor/server', '', 'C', '0', 'monitor:server:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '服务监控菜单'); -insert into sys_menu values('113', '表单构建', '3', '1', '/tool/build', '', 'C', '0', 'tool:build:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '表单构建菜单'); -insert into sys_menu values('114', '代码生成', '3', '2', '/tool/gen', '', 'C', '0', 'tool:gen:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '代码生成菜单'); -insert into sys_menu values('115', '系统接口', '3', '3', '/tool/swagger', '', 'C', '0', 'tool:swagger:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统接口菜单'); --- 三级菜单 -insert into sys_menu values('500', '操作日志', '108', '1', '/monitor/operlog', '', 'C', '0', 'monitor:operlog:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '操作日志菜单'); -insert into sys_menu values('501', '登录日志', '108', '2', '/monitor/logininfor', '', 'C', '0', 'monitor:logininfor:view', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '登录日志菜单'); --- 用户管理按钮 -insert into sys_menu values('1000', '用户查询', '100', '1', '#', '', 'F', '0', 'system:user:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1001', '用户新增', '100', '2', '#', '', 'F', '0', 'system:user:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1002', '用户修改', '100', '3', '#', '', 'F', '0', 'system:user:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1003', '用户删除', '100', '4', '#', '', 'F', '0', 'system:user:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1004', '用户导出', '100', '5', '#', '', 'F', '0', 'system:user:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1005', '用户导入', '100', '6', '#', '', 'F', '0', 'system:user:import', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1006', '重置密码', '100', '7', '#', '', 'F', '0', 'system:user:resetPwd', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 角色管理按钮 -insert into sys_menu values('1007', '角色查询', '101', '1', '#', '', 'F', '0', 'system:role:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1008', '角色新增', '101', '2', '#', '', 'F', '0', 'system:role:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1009', '角色修改', '101', '3', '#', '', 'F', '0', 'system:role:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1010', '角色删除', '101', '4', '#', '', 'F', '0', 'system:role:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1011', '角色导出', '101', '5', '#', '', 'F', '0', 'system:role:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 菜单管理按钮 -insert into sys_menu values('1012', '菜单查询', '102', '1', '#', '', 'F', '0', 'system:menu:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1013', '菜单新增', '102', '2', '#', '', 'F', '0', 'system:menu:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1014', '菜单修改', '102', '3', '#', '', 'F', '0', 'system:menu:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1015', '菜单删除', '102', '4', '#', '', 'F', '0', 'system:menu:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 部门管理按钮 -insert into sys_menu values('1016', '部门查询', '103', '1', '#', '', 'F', '0', 'system:dept:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1017', '部门新增', '103', '2', '#', '', 'F', '0', 'system:dept:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1018', '部门修改', '103', '3', '#', '', 'F', '0', 'system:dept:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1019', '部门删除', '103', '4', '#', '', 'F', '0', 'system:dept:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 岗位管理按钮 -insert into sys_menu values('1020', '岗位查询', '104', '1', '#', '', 'F', '0', 'system:post:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1021', '岗位新增', '104', '2', '#', '', 'F', '0', 'system:post:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1022', '岗位修改', '104', '3', '#', '', 'F', '0', 'system:post:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1023', '岗位删除', '104', '4', '#', '', 'F', '0', 'system:post:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1024', '岗位导出', '104', '5', '#', '', 'F', '0', 'system:post:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 字典管理按钮 -insert into sys_menu values('1025', '字典查询', '105', '1', '#', '', 'F', '0', 'system:dict:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1026', '字典新增', '105', '2', '#', '', 'F', '0', 'system:dict:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1027', '字典修改', '105', '3', '#', '', 'F', '0', 'system:dict:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1028', '字典删除', '105', '4', '#', '', 'F', '0', 'system:dict:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1029', '字典导出', '105', '5', '#', '', 'F', '0', 'system:dict:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 参数设置按钮 -insert into sys_menu values('1030', '参数查询', '106', '1', '#', '', 'F', '0', 'system:config:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1031', '参数新增', '106', '2', '#', '', 'F', '0', 'system:config:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1032', '参数修改', '106', '3', '#', '', 'F', '0', 'system:config:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1033', '参数删除', '106', '4', '#', '', 'F', '0', 'system:config:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1034', '参数导出', '106', '5', '#', '', 'F', '0', 'system:config:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 通知公告按钮 -insert into sys_menu values('1035', '公告查询', '107', '1', '#', '', 'F', '0', 'system:notice:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1036', '公告新增', '107', '2', '#', '', 'F', '0', 'system:notice:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1037', '公告修改', '107', '3', '#', '', 'F', '0', 'system:notice:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1038', '公告删除', '107', '4', '#', '', 'F', '0', 'system:notice:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 操作日志按钮 -insert into sys_menu values('1039', '操作查询', '500', '1', '#', '', 'F', '0', 'monitor:operlog:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1040', '操作删除', '500', '2', '#', '', 'F', '0', 'monitor:operlog:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1041', '详细信息', '500', '3', '#', '', 'F', '0', 'monitor:operlog:detail', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1042', '日志导出', '500', '4', '#', '', 'F', '0', 'monitor:operlog:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 登录日志按钮 -insert into sys_menu values('1043', '登录查询', '501', '1', '#', '', 'F', '0', 'monitor:logininfor:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1044', '登录删除', '501', '2', '#', '', 'F', '0', 'monitor:logininfor:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1045', '日志导出', '501', '3', '#', '', 'F', '0', 'monitor:logininfor:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1046', '账户解锁', '501', '4', '#', '', 'F', '0', 'monitor:logininfor:unlock', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 在线用户按钮 -insert into sys_menu values('1047', '在线查询', '109', '1', '#', '', 'F', '0', 'monitor:online:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1048', '批量强退', '109', '2', '#', '', 'F', '0', 'monitor:online:batchForceLogout', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1049', '单条强退', '109', '3', '#', '', 'F', '0', 'monitor:online:forceLogout', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 定时任务按钮 -insert into sys_menu values('1050', '任务查询', '110', '1', '#', '', 'F', '0', 'monitor:job:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1051', '任务新增', '110', '2', '#', '', 'F', '0', 'monitor:job:add', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1052', '任务修改', '110', '3', '#', '', 'F', '0', 'monitor:job:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1053', '任务删除', '110', '4', '#', '', 'F', '0', 'monitor:job:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1054', '状态修改', '110', '5', '#', '', 'F', '0', 'monitor:job:changeStatus', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1055', '任务详细', '110', '6', '#', '', 'F', '0', 'monitor:job:detail', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1056', '任务导出', '110', '7', '#', '', 'F', '0', 'monitor:job:export', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); --- 代码生成按钮 -insert into sys_menu values('1057', '生成查询', '114', '1', '#', '', 'F', '0', 'tool:gen:list', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1058', '生成修改', '114', '2', '#', '', 'F', '0', 'tool:gen:edit', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1059', '生成删除', '114', '3', '#', '', 'F', '0', 'tool:gen:remove', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1060', '预览代码', '114', '4', '#', '', 'F', '0', 'tool:gen:preview', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_menu values('1061', '生成代码', '114', '5', '#', '', 'F', '0', 'tool:gen:code', '#', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); - - --- ---------------------------- --- 6、用户和角色关联表 用户N-1角色 --- ---------------------------- -drop table if exists sys_user_role; -create table sys_user_role ( - user_id bigint(20) not null comment '用户ID', - role_id bigint(20) not null comment '角色ID', - primary key(user_id, role_id) -) engine=innodb comment = '用户和角色关联表'; - --- ---------------------------- --- 初始化-用户和角色关联表数据 --- ---------------------------- -insert into sys_user_role values ('1', '1'); -insert into sys_user_role values ('2', '2'); - - --- ---------------------------- --- 7、角色和菜单关联表 角色1-N菜单 --- ---------------------------- -drop table if exists sys_role_menu; -create table sys_role_menu ( - role_id bigint(20) not null comment '角色ID', - menu_id bigint(20) not null comment '菜单ID', - primary key(role_id, menu_id) -) engine=innodb comment = '角色和菜单关联表'; - --- ---------------------------- --- 初始化-角色和菜单关联表数据 --- ---------------------------- -insert into sys_role_menu values ('2', '1'); -insert into sys_role_menu values ('2', '2'); -insert into sys_role_menu values ('2', '3'); -insert into sys_role_menu values ('2', '100'); -insert into sys_role_menu values ('2', '101'); -insert into sys_role_menu values ('2', '102'); -insert into sys_role_menu values ('2', '103'); -insert into sys_role_menu values ('2', '104'); -insert into sys_role_menu values ('2', '105'); -insert into sys_role_menu values ('2', '106'); -insert into sys_role_menu values ('2', '107'); -insert into sys_role_menu values ('2', '108'); -insert into sys_role_menu values ('2', '109'); -insert into sys_role_menu values ('2', '110'); -insert into sys_role_menu values ('2', '111'); -insert into sys_role_menu values ('2', '112'); -insert into sys_role_menu values ('2', '113'); -insert into sys_role_menu values ('2', '114'); -insert into sys_role_menu values ('2', '115'); -insert into sys_role_menu values ('2', '500'); -insert into sys_role_menu values ('2', '501'); -insert into sys_role_menu values ('2', '1000'); -insert into sys_role_menu values ('2', '1001'); -insert into sys_role_menu values ('2', '1002'); -insert into sys_role_menu values ('2', '1003'); -insert into sys_role_menu values ('2', '1004'); -insert into sys_role_menu values ('2', '1005'); -insert into sys_role_menu values ('2', '1006'); -insert into sys_role_menu values ('2', '1007'); -insert into sys_role_menu values ('2', '1008'); -insert into sys_role_menu values ('2', '1009'); -insert into sys_role_menu values ('2', '1010'); -insert into sys_role_menu values ('2', '1011'); -insert into sys_role_menu values ('2', '1012'); -insert into sys_role_menu values ('2', '1013'); -insert into sys_role_menu values ('2', '1014'); -insert into sys_role_menu values ('2', '1015'); -insert into sys_role_menu values ('2', '1016'); -insert into sys_role_menu values ('2', '1017'); -insert into sys_role_menu values ('2', '1018'); -insert into sys_role_menu values ('2', '1019'); -insert into sys_role_menu values ('2', '1020'); -insert into sys_role_menu values ('2', '1021'); -insert into sys_role_menu values ('2', '1022'); -insert into sys_role_menu values ('2', '1023'); -insert into sys_role_menu values ('2', '1024'); -insert into sys_role_menu values ('2', '1025'); -insert into sys_role_menu values ('2', '1026'); -insert into sys_role_menu values ('2', '1027'); -insert into sys_role_menu values ('2', '1028'); -insert into sys_role_menu values ('2', '1029'); -insert into sys_role_menu values ('2', '1030'); -insert into sys_role_menu values ('2', '1031'); -insert into sys_role_menu values ('2', '1032'); -insert into sys_role_menu values ('2', '1033'); -insert into sys_role_menu values ('2', '1034'); -insert into sys_role_menu values ('2', '1035'); -insert into sys_role_menu values ('2', '1036'); -insert into sys_role_menu values ('2', '1037'); -insert into sys_role_menu values ('2', '1038'); -insert into sys_role_menu values ('2', '1039'); -insert into sys_role_menu values ('2', '1040'); -insert into sys_role_menu values ('2', '1041'); -insert into sys_role_menu values ('2', '1042'); -insert into sys_role_menu values ('2', '1043'); -insert into sys_role_menu values ('2', '1044'); -insert into sys_role_menu values ('2', '1045'); -insert into sys_role_menu values ('2', '1046'); -insert into sys_role_menu values ('2', '1047'); -insert into sys_role_menu values ('2', '1048'); -insert into sys_role_menu values ('2', '1049'); -insert into sys_role_menu values ('2', '1050'); -insert into sys_role_menu values ('2', '1051'); -insert into sys_role_menu values ('2', '1052'); -insert into sys_role_menu values ('2', '1053'); -insert into sys_role_menu values ('2', '1054'); -insert into sys_role_menu values ('2', '1055'); -insert into sys_role_menu values ('2', '1056'); -insert into sys_role_menu values ('2', '1057'); -insert into sys_role_menu values ('2', '1058'); -insert into sys_role_menu values ('2', '1059'); -insert into sys_role_menu values ('2', '1060'); -insert into sys_role_menu values ('2', '1061'); - --- ---------------------------- --- 8、角色和部门关联表 角色1-N部门 --- ---------------------------- -drop table if exists sys_role_dept; -create table sys_role_dept ( - role_id bigint(20) not null comment '角色ID', - dept_id bigint(20) not null comment '部门ID', - primary key(role_id, dept_id) -) engine=innodb comment = '角色和部门关联表'; - --- ---------------------------- --- 初始化-角色和部门关联表数据 --- ---------------------------- -insert into sys_role_dept values ('2', '100'); -insert into sys_role_dept values ('2', '101'); -insert into sys_role_dept values ('2', '105'); - --- ---------------------------- --- 9、用户与岗位关联表 用户1-N岗位 --- ---------------------------- -drop table if exists sys_user_post; -create table sys_user_post -( - user_id bigint(20) not null comment '用户ID', - post_id bigint(20) not null comment '岗位ID', - primary key (user_id, post_id) -) engine=innodb comment = '用户与岗位关联表'; - --- ---------------------------- --- 初始化-用户与岗位关联表数据 --- ---------------------------- -insert into sys_user_post values ('1', '1'); -insert into sys_user_post values ('2', '2'); - - --- ---------------------------- --- 10、操作日志记录 --- ---------------------------- -drop table if exists sys_oper_log; -create table sys_oper_log ( - oper_id bigint(20) not null auto_increment comment '日志主键', - title varchar(50) default '' comment '模块标题', - business_type int(2) default 0 comment '业务类型(0其它 1新增 2修改 3删除)', - method varchar(100) default '' comment '方法名称', - request_method varchar(10) default '' comment '请求方式', - operator_type int(1) default 0 comment '操作类别(0其它 1后台用户 2手机端用户)', - oper_name varchar(50) default '' comment '操作人员', - dept_name varchar(50) default '' comment '部门名称', - oper_url varchar(255) default '' comment '请求URL', - oper_ip varchar(50) default '' comment '主机地址', - oper_location varchar(255) default '' comment '操作地点', - oper_param varchar(2000) default '' comment '请求参数', - json_result varchar(2000) default '' comment '返回参数', - status int(1) default 0 comment '操作状态(0正常 1异常)', - error_msg varchar(2000) default '' comment '错误消息', - oper_time datetime comment '操作时间', - primary key (oper_id) -) engine=innodb auto_increment=100 comment = '操作日志记录'; - - --- ---------------------------- --- 11、字典类型表 --- ---------------------------- -drop table if exists sys_dict_type; -create table sys_dict_type -( - dict_id bigint(20) not null auto_increment comment '字典主键', - dict_name varchar(100) default '' comment '字典名称', - dict_type varchar(100) default '' comment '字典类型', - status char(1) default '0' comment '状态(0正常 1停用)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (dict_id), - unique (dict_type) -) engine=innodb auto_increment=100 comment = '字典类型表'; - -insert into sys_dict_type values(1, '用户性别', 'sys_user_sex', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '用户性别列表'); -insert into sys_dict_type values(2, '菜单状态', 'sys_show_hide', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '菜单状态列表'); -insert into sys_dict_type values(3, '系统开关', 'sys_normal_disable', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统开关列表'); -insert into sys_dict_type values(4, '任务状态', 'sys_job_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '任务状态列表'); -insert into sys_dict_type values(5, '任务分组', 'sys_job_group', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '任务分组列表'); -insert into sys_dict_type values(6, '系统是否', 'sys_yes_no', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统是否列表'); -insert into sys_dict_type values(7, '通知类型', 'sys_notice_type', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知类型列表'); -insert into sys_dict_type values(8, '通知状态', 'sys_notice_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知状态列表'); -insert into sys_dict_type values(9, '操作类型', 'sys_oper_type', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '操作类型列表'); -insert into sys_dict_type values(10, '系统状态', 'sys_common_status', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '登录状态列表'); - - --- ---------------------------- --- 12、字典数据表 --- ---------------------------- -drop table if exists sys_dict_data; -create table sys_dict_data -( - dict_code bigint(20) not null auto_increment comment '字典编码', - dict_sort int(4) default 0 comment '字典排序', - dict_label varchar(100) default '' comment '字典标签', - dict_value varchar(100) default '' comment '字典键值', - dict_type varchar(100) default '' comment '字典类型', - css_class varchar(100) default null comment '样式属性(其他样式扩展)', - list_class varchar(100) default null comment '表格回显样式', - is_default char(1) default 'N' comment '是否默认(Y是 N否)', - status char(1) default '0' comment '状态(0正常 1停用)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (dict_code) -) engine=innodb auto_increment=100 comment = '字典数据表'; - -insert into sys_dict_data values(1, 1, '男', '0', 'sys_user_sex', '', '', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别男'); -insert into sys_dict_data values(2, 2, '女', '1', 'sys_user_sex', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别女'); -insert into sys_dict_data values(3, 3, '未知', '2', 'sys_user_sex', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '性别未知'); -insert into sys_dict_data values(4, 1, '显示', '0', 'sys_show_hide', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '显示菜单'); -insert into sys_dict_data values(5, 2, '隐藏', '1', 'sys_show_hide', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '隐藏菜单'); -insert into sys_dict_data values(6, 1, '正常', '0', 'sys_normal_disable', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); -insert into sys_dict_data values(7, 2, '停用', '1', 'sys_normal_disable', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); -insert into sys_dict_data values(8, 1, '正常', '0', 'sys_job_status', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); -insert into sys_dict_data values(9, 2, '暂停', '1', 'sys_job_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); -insert into sys_dict_data values(10, 1, '默认', 'DEFAULT', 'sys_job_group', '', '', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '默认分组'); -insert into sys_dict_data values(11, 2, '系统', 'SYSTEM', 'sys_job_group', '', '', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统分组'); -insert into sys_dict_data values(12, 1, '是', 'Y', 'sys_yes_no', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统默认是'); -insert into sys_dict_data values(13, 2, '否', 'N', 'sys_yes_no', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '系统默认否'); -insert into sys_dict_data values(14, 1, '通知', '1', 'sys_notice_type', '', 'warning', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '通知'); -insert into sys_dict_data values(15, 2, '公告', '2', 'sys_notice_type', '', 'success', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '公告'); -insert into sys_dict_data values(16, 1, '正常', '0', 'sys_notice_status', '', 'primary', 'Y', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); -insert into sys_dict_data values(17, 2, '关闭', '1', 'sys_notice_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '关闭状态'); -insert into sys_dict_data values(18, 1, '新增', '1', 'sys_oper_type', '', 'info', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '新增操作'); -insert into sys_dict_data values(19, 2, '修改', '2', 'sys_oper_type', '', 'info', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '修改操作'); -insert into sys_dict_data values(20, 3, '删除', '3', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '删除操作'); -insert into sys_dict_data values(21, 4, '授权', '4', 'sys_oper_type', '', 'primary', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '授权操作'); -insert into sys_dict_data values(22, 5, '导出', '5', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '导出操作'); -insert into sys_dict_data values(23, 6, '导入', '6', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '导入操作'); -insert into sys_dict_data values(24, 7, '强退', '7', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '强退操作'); -insert into sys_dict_data values(25, 8, '生成代码', '8', 'sys_oper_type', '', 'warning', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '生成操作'); -insert into sys_dict_data values(26, 9, '清空数据', '9', 'sys_oper_type', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '清空操作'); -insert into sys_dict_data values(27, 1, '成功', '0', 'sys_common_status', '', 'primary', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '正常状态'); -insert into sys_dict_data values(28, 2, '失败', '1', 'sys_common_status', '', 'danger', 'N', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '停用状态'); - - --- ---------------------------- --- 13、参数配置表 --- ---------------------------- -drop table if exists sys_config; -create table sys_config ( - config_id int(5) not null auto_increment comment '参数主键', - config_name varchar(100) default '' comment '参数名称', - config_key varchar(100) default '' comment '参数键名', - config_value varchar(500) default '' comment '参数键值', - config_type char(1) default 'N' comment '系统内置(Y是 N否)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (config_id) -) engine=innodb auto_increment=100 comment = '参数配置表'; - -insert into sys_config values(1, '主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-blue', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow' ); -insert into sys_config values(2, '用户管理-账号初始密码', 'sys.user.initPassword', '123456', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '初始化密码 123456' ); -insert into sys_config values(3, '主框架页-侧边栏主题', 'sys.index.sideTheme', 'theme-dark', 'Y', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '深色主题theme-dark,浅色主题theme-light' ); - - --- ---------------------------- --- 14、系统访问记录 --- ---------------------------- -drop table if exists sys_logininfor; -create table sys_logininfor ( - info_id bigint(20) not null auto_increment comment '访问ID', - login_name varchar(50) default '' comment '登录账号', - ipaddr varchar(50) default '' comment '登录IP地址', - login_location varchar(255) default '' comment '登录地点', - browser varchar(50) default '' comment '浏览器类型', - os varchar(50) default '' comment '操作系统', - status char(1) default '0' comment '登录状态(0成功 1失败)', - msg varchar(255) default '' comment '提示消息', - login_time datetime comment '访问时间', - primary key (info_id) -) engine=innodb auto_increment=100 comment = '系统访问记录'; - - --- ---------------------------- --- 15、在线用户记录 --- ---------------------------- -drop table if exists sys_user_online; -create table sys_user_online ( - sessionId varchar(50) default '' comment '用户会话id', - login_name varchar(50) default '' comment '登录账号', - dept_name varchar(50) default '' comment '部门名称', - ipaddr varchar(50) default '' comment '登录IP地址', - login_location varchar(255) default '' comment '登录地点', - browser varchar(50) default '' comment '浏览器类型', - os varchar(50) default '' comment '操作系统', - status varchar(10) default '' comment '在线状态on_line在线off_line离线', - start_timestamp datetime comment 'session创建时间', - last_access_time datetime comment 'session最后访问时间', - expire_time int(5) default 0 comment '超时时间,单位为分钟', - primary key (sessionId) -) engine=innodb comment = '在线用户记录'; - - --- ---------------------------- --- 16、定时任务调度表 --- ---------------------------- -drop table if exists sys_job; -create table sys_job ( - job_id bigint(20) not null auto_increment comment '任务ID', - job_name varchar(64) default '' comment '任务名称', - job_group varchar(64) default 'DEFAULT' comment '任务组名', - invoke_target varchar(500) not null comment '调用目标字符串', - cron_expression varchar(255) default '' comment 'cron执行表达式', - misfire_policy varchar(20) default '3' comment '计划执行错误策略(1立即执行 2执行一次 3放弃执行)', - concurrent char(1) default '1' comment '是否并发执行(0允许 1禁止)', - status char(1) default '0' comment '状态(0正常 1暂停)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default '' comment '备注信息', - primary key (job_id, job_name, job_group) -) engine=innodb auto_increment=100 comment = '定时任务调度表'; - -insert into sys_job values(1, '系统默认(无参)', 'DEFAULT', 'ryTask.ryNoParams', '0/10 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_job values(2, '系统默认(有参)', 'DEFAULT', 'ryTask.ryParams(\'ry\')', '0/15 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); -insert into sys_job values(3, '系统默认(多参)', 'DEFAULT', 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)', '0/20 * * * * ?', '3', '1', '1', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', ''); - - --- ---------------------------- --- 17、定时任务调度日志表 --- ---------------------------- -drop table if exists sys_job_log; -create table sys_job_log ( - job_log_id bigint(20) not null auto_increment comment '任务日志ID', - job_name varchar(64) not null comment '任务名称', - job_group varchar(64) not null comment '任务组名', - invoke_target varchar(500) not null comment '调用目标字符串', - job_message varchar(500) comment '日志信息', - status char(1) default '0' comment '执行状态(0正常 1失败)', - exception_info varchar(2000) default '' comment '异常信息', - create_time datetime comment '创建时间', - primary key (job_log_id) -) engine=innodb comment = '定时任务调度日志表'; - - --- ---------------------------- --- 18、通知公告表 --- ---------------------------- -drop table if exists sys_notice; -create table sys_notice ( - notice_id int(4) not null auto_increment comment '公告ID', - notice_title varchar(50) not null comment '公告标题', - notice_type char(1) not null comment '公告类型(1通知 2公告)', - notice_content varchar(2000) default null comment '公告内容', - status char(1) default '0' comment '公告状态(0正常 1关闭)', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(255) default null comment '备注', - primary key (notice_id) -) engine=innodb auto_increment=10 comment = '通知公告表'; - --- ---------------------------- --- 初始化-公告信息表数据 --- ---------------------------- -insert into sys_notice values('1', '温馨提醒:2018-07-01 若依新版本发布啦', '2', '新版本内容', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); -insert into sys_notice values('2', '维护通知:2018-07-01 若依系统凌晨维护', '1', '维护内容', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); - - --- ---------------------------- --- 19、代码生成业务表 --- ---------------------------- -drop table if exists gen_table; -create table gen_table ( - table_id bigint(20) not null auto_increment comment '编号', - table_name varchar(200) default '' comment '表名称', - table_comment varchar(500) default '' comment '表描述', - class_name varchar(100) default '' comment '实体类名称', - tpl_category varchar(200) default 'crud' comment '使用的模板(crud单表操作 tree树表操作)', - package_name varchar(100) comment '生成包路径', - module_name varchar(30) comment '生成模块名', - business_name varchar(30) comment '生成业务名', - function_name varchar(50) comment '生成功能名', - function_author varchar(50) comment '生成功能作者', - options varchar(1000) comment '其它生成选项', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - remark varchar(500) default null comment '备注', - primary key (table_id) -) engine=innodb auto_increment=1 comment = '代码生成业务表'; - - --- ---------------------------- --- 20、代码生成业务表字段 --- ---------------------------- -drop table if exists gen_table_column; -create table gen_table_column ( - column_id bigint(20) not null auto_increment comment '编号', - table_id varchar(64) comment '归属表编号', - column_name varchar(200) comment '列名称', - column_comment varchar(500) comment '列描述', - column_type varchar(100) comment '列类型', - java_type varchar(500) comment 'JAVA类型', - java_field varchar(200) comment 'JAVA字段名', - is_pk char(1) comment '是否主键(1是)', - is_increment char(1) comment '是否自增(1是)', - is_required char(1) comment '是否必填(1是)', - is_insert char(1) comment '是否为插入字段(1是)', - is_edit char(1) comment '是否编辑字段(1是)', - is_list char(1) comment '是否列表字段(1是)', - is_query char(1) comment '是否查询字段(1是)', - query_type varchar(200) default 'EQ' comment '查询方式(等于、不等于、大于、小于、范围)', - html_type varchar(200) comment '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)', - dict_type varchar(200) default '' comment '字典类型', - sort int comment '排序', - create_by varchar(64) default '' comment '创建者', - create_time datetime comment '创建时间', - update_by varchar(64) default '' comment '更新者', - update_time datetime comment '更新时间', - primary key (column_id) -) engine=innodb auto_increment=1 comment = '代码生成业务表字段'; \ No newline at end of file From 9ba75d02e0bb26ad45ba0989734a3d264635624c Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:12:06 +0800 Subject: [PATCH 03/52] format code --- .../ruoyi/common/annotation/DataScope.java | 55 +- .../ruoyi/common/annotation/DataSource.java | 52 +- .../com/ruoyi/common/annotation/Excel.java | 217 +- .../com/ruoyi/common/annotation/Excels.java | 5 +- .../java/com/ruoyi/common/annotation/Log.java | 80 +- .../ruoyi/common/annotation/RepeatSubmit.java | 6 +- .../java/com/ruoyi/common/config/Global.java | 228 +- .../com/ruoyi/common/config/ServerConfig.java | 63 +- .../DynamicDataSourceContextHolder.java | 86 +- .../config/thread/ThreadPoolConfig.java | 120 +- .../com/ruoyi/common/constant/Constants.java | 137 +- .../ruoyi/common/constant/GenConstants.java | 241 ++- .../common/constant/PermissionConstants.java | 65 +- .../common/constant/ScheduleConstants.java | 106 +- .../ruoyi/common/constant/ShiroConstants.java | 147 +- .../ruoyi/common/constant/UserConstants.java | 237 ++- .../core/controller/BaseController.java | 327 ++- .../ruoyi/common/core/domain/AjaxResult.java | 360 ++-- .../ruoyi/common/core/domain/BaseEntity.java | 227 +- .../ruoyi/common/core/domain/TreeEntity.java | 123 +- .../com/ruoyi/common/core/domain/Ztree.java | 207 +- .../ruoyi/common/core/page/PageDomain.java | 135 +- .../ruoyi/common/core/page/TableDataInfo.java | 165 +- .../ruoyi/common/core/page/TableSupport.java | 57 +- .../ruoyi/common/core/text/CharsetKit.java | 177 +- .../com/ruoyi/common/core/text/Convert.java | 1849 ++++++++--------- .../ruoyi/common/core/text/StrFormatter.java | 168 +- .../ruoyi/common/enums/BusinessStatus.java | 37 +- .../com/ruoyi/common/enums/BusinessType.java | 117 +- .../ruoyi/common/enums/DataSourceType.java | 37 +- .../com/ruoyi/common/enums/OnlineStatus.java | 47 +- .../com/ruoyi/common/enums/OperatorType.java | 47 +- .../com/ruoyi/common/enums/UserStatus.java | 56 +- .../common/exception/BusinessException.java | 14 +- .../common/exception/DemoModeException.java | 28 +- .../common/exception/base/BaseException.java | 181 +- .../common/exception/file/FileException.java | 8 +- .../FileNameLengthLimitExceededException.java | 30 +- .../file/FileSizeLimitExceededException.java | 10 +- .../file/InvalidExtensionException.java | 132 +- .../common/exception/job/TaskException.java | 61 +- .../exception/user/CaptchaException.java | 30 +- .../exception/user/RoleBlockedException.java | 30 +- .../exception/user/UserBlockedException.java | 30 +- .../exception/user/UserDeleteException.java | 30 +- .../common/exception/user/UserException.java | 34 +- .../user/UserNotExistsException.java | 30 +- .../user/UserPasswordNotMatchException.java | 30 +- .../UserPasswordRetryLimitCountException.java | 30 +- ...UserPasswordRetryLimitExceedException.java | 30 +- .../main/java/com/ruoyi/common/json/JSON.java | 309 ++- .../com/ruoyi/common/json/JSONObject.java | 1367 ++++++------ .../com/ruoyi/common/utils/AddressUtils.java | 100 +- .../java/com/ruoyi/common/utils/Arith.java | 227 +- .../com/ruoyi/common/utils/DateUtils.java | 290 ++- .../com/ruoyi/common/utils/ExceptionUtil.java | 76 +- .../java/com/ruoyi/common/utils/IpUtils.java | 344 ++- .../com/ruoyi/common/utils/MapDataUtil.java | 91 +- .../com/ruoyi/common/utils/MessageUtils.java | 50 +- .../com/ruoyi/common/utils/ServletUtils.java | 253 ++- .../com/ruoyi/common/utils/StringUtils.java | 742 +++---- .../java/com/ruoyi/common/utils/Threads.java | 62 +- .../java/com/ruoyi/common/utils/YamlUtil.java | 155 +- .../ruoyi/common/utils/bean/BeanUtils.java | 214 +- .../common/utils/file/FileUploadUtils.java | 451 ++-- .../ruoyi/common/utils/file/FileUtils.java | 256 +-- .../common/utils/file/MimeTypeUtils.java | 23 +- .../ruoyi/common/utils/html/EscapeUtil.java | 81 +- .../ruoyi/common/utils/http/HttpUtils.java | 441 ++-- .../com/ruoyi/common/utils/poi/ExcelUtil.java | 457 ++-- .../common/utils/reflect/ReflectUtils.java | 221 +- .../ruoyi/common/utils/security/Md5Utils.java | 120 +- .../utils/security/PermissionUtils.java | 219 +- .../common/utils/spring/SpringUtils.java | 216 +- .../com/ruoyi/common/utils/sql/SqlUtil.java | 14 +- .../java/com/ruoyi/common/xss/XssFilter.java | 180 +- .../xss/XssHttpServletRequestWrapper.java | 72 +- 77 files changed, 6377 insertions(+), 7373 deletions(-) diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java index fe5a01f55..b0d4b7ffc 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java @@ -1,28 +1,27 @@ -package com.ruoyi.common.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 数据权限过滤注解 - * - * @author ruoyi - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface DataScope -{ - /** - * 部门表的别名 - */ - public String deptAlias() default ""; - - /** - * 用户表的别名 - */ - public String userAlias() default ""; -} +package com.ruoyi.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 数据权限过滤注解 + * + * @author ruoyi + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DataScope { + /** + * 部门表的别名 + */ + public String deptAlias() default ""; + + /** + * 用户表的别名 + */ + public String userAlias() default ""; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataSource.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataSource.java index a272a5b7b..53b8c2fae 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataSource.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataSource.java @@ -1,26 +1,26 @@ -package com.ruoyi.common.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import com.ruoyi.common.enums.DataSourceType; - -/** - * 自定义多数据源切换注解 - * - * @author ruoyi - */ -@Target({ ElementType.METHOD, ElementType.TYPE }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface DataSource -{ - /** - * 切换数据源名称 - */ - public DataSourceType value() default DataSourceType.MASTER; -} +package com.ruoyi.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.ruoyi.common.enums.DataSourceType; + +/** + * 自定义多数据源切换注解 + * + * @author ruoyi + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface DataSource { + /** + * 切换数据源名称 + */ + public DataSourceType value() default DataSourceType.MASTER; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excel.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excel.java index 2112128a8..f73eabebe 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excel.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excel.java @@ -1,113 +1,106 @@ -package com.ruoyi.common.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 自定义导出Excel数据注解 - * - * @author ruoyi - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface Excel -{ - /** - * 导出到Excel中的名字. - */ - public String name() default ""; - - /** - * 日期格式, 如: yyyy-MM-dd - */ - public String dateFormat() default ""; - - /** - * 读取内容转表达式 (如: 0=男,1=女,2=未知) - */ - public String readConverterExp() default ""; - - /** - * 导出类型(0数字 1字符串) - */ - public ColumnType cellType() default ColumnType.STRING; - - /** - * 导出时在excel中每个列的高度 单位为字符 - */ - public double height() default 14; - - /** - * 导出时在excel中每个列的宽 单位为字符 - */ - public double width() default 16; - - /** - * 文字后缀,如% 90 变成90% - */ - public String suffix() default ""; - - /** - * 当值为空时,字段的默认值 - */ - public String defaultValue() default ""; - - /** - * 提示信息 - */ - public String prompt() default ""; - - /** - * 设置只能选择不能输入的列内容. - */ - public String[] combo() default {}; - - /** - * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写. - */ - public boolean isExport() default true; - - /** - * 另一个类中的属性名称,支持多级获取,以小数点隔开 - */ - public String targetAttr() default ""; - - /** - * 字段类型(0:导出导入;1:仅导出;2:仅导入) - */ - Type type() default Type.ALL; - - public enum Type - { - ALL(0), EXPORT(1), IMPORT(2); - private final int value; - - Type(int value) - { - this.value = value; - } - - public int value() - { - return this.value; - } - } - - public enum ColumnType - { - NUMERIC(0), STRING(1); - private final int value; - - ColumnType(int value) - { - this.value = value; - } - - public int value() - { - return this.value; - } - } +package com.ruoyi.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 自定义导出Excel数据注解 + * + * @author ruoyi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Excel { + /** + * 导出到Excel中的名字. + */ + public String name() default ""; + + /** + * 日期格式, 如: yyyy-MM-dd + */ + public String dateFormat() default ""; + + /** + * 读取内容转表达式 (如: 0=男,1=女,2=未知) + */ + public String readConverterExp() default ""; + + /** + * 导出类型(0数字 1字符串) + */ + public ColumnType cellType() default ColumnType.STRING; + + /** + * 导出时在excel中每个列的高度 单位为字符 + */ + public double height() default 14; + + /** + * 导出时在excel中每个列的宽 单位为字符 + */ + public double width() default 16; + + /** + * 文字后缀,如% 90 变成90% + */ + public String suffix() default ""; + + /** + * 当值为空时,字段的默认值 + */ + public String defaultValue() default ""; + + /** + * 提示信息 + */ + public String prompt() default ""; + + /** + * 设置只能选择不能输入的列内容. + */ + public String[] combo() default {}; + + /** + * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写. + */ + public boolean isExport() default true; + + /** + * 另一个类中的属性名称,支持多级获取,以小数点隔开 + */ + public String targetAttr() default ""; + + /** + * 字段类型(0:导出导入;1:仅导出;2:仅导入) + */ + Type type() default Type.ALL; + + public enum Type { + ALL(0), EXPORT(1), IMPORT(2); + private final int value; + + Type(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } + + public enum ColumnType { + NUMERIC(0), STRING(1); + private final int value; + + ColumnType(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excels.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excels.java index 8c6870c20..8fb4172de 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excels.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Excels.java @@ -7,12 +7,11 @@ import java.lang.annotation.Target; /** * Excel注解集 - * + * * @author ruoyi */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface Excels -{ +public @interface Excels { Excel[] value(); } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Log.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Log.java index 8982f07be..a8683c8a2 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Log.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/Log.java @@ -1,40 +1,40 @@ -package com.ruoyi.common.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.enums.OperatorType; - -/** - * 自定义操作日志记录注解 - * - * @author ruoyi - */ -@Target({ ElementType.PARAMETER, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Log -{ - /** - * 模块 - */ - public String title() default ""; - - /** - * 功能 - */ - public BusinessType businessType() default BusinessType.OTHER; - - /** - * 操作人类别 - */ - public OperatorType operatorType() default OperatorType.MANAGE; - - /** - * 是否保存请求的参数 - */ - public boolean isSaveRequestData() default true; -} +package com.ruoyi.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.enums.OperatorType; + +/** + * 自定义操作日志记录注解 + * + * @author ruoyi + */ +@Target({ElementType.PARAMETER, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Log { + /** + * 模块 + */ + public String title() default ""; + + /** + * 功能 + */ + public BusinessType businessType() default BusinessType.OTHER; + + /** + * 操作人类别 + */ + public OperatorType operatorType() default OperatorType.MANAGE; + + /** + * 是否保存请求的参数 + */ + public boolean isSaveRequestData() default true; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java index 72ac2ecca..40cb6feb0 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java @@ -9,15 +9,13 @@ import java.lang.annotation.Target; /** * 自定义注解防止表单重复提交 - * - * @author ruoyi * + * @author ruoyi */ @Inherited @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface RepeatSubmit -{ +public @interface RepeatSubmit { } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/Global.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/Global.java index 34a47fa0c..d0aa03a8e 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/config/Global.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/Global.java @@ -1,116 +1,112 @@ -package com.ruoyi.common.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * 全局配置类 - * - * @author ruoyi - */ -@Component -@ConfigurationProperties(prefix = "ruoyi") -public class Global -{ - /** 项目名称 */ - private static String name; - - /** 版本 */ - private static String version; - - /** 版权年份 */ - private static String copyrightYear; - - /** 实例演示开关 */ - private static boolean demoEnabled; - - /** 上传路径 */ - private static String profile; - - /** 获取地址开关 */ - private static boolean addressEnabled; - - public static String getName() - { - return name; - } - - public void setName(String name) - { - Global.name = name; - } - - public static String getVersion() - { - return version; - } - - public void setVersion(String version) - { - Global.version = version; - } - - public static String getCopyrightYear() - { - return copyrightYear; - } - - public void setCopyrightYear(String copyrightYear) - { - Global.copyrightYear = copyrightYear; - } - - public static boolean isDemoEnabled() - { - return demoEnabled; - } - - public void setDemoEnabled(boolean demoEnabled) - { - Global.demoEnabled = demoEnabled; - } - - public static String getProfile() - { - return profile; - } - - public void setProfile(String profile) - { - Global.profile = profile; - } - - public static boolean isAddressEnabled() - { - return addressEnabled; - } - - public void setAddressEnabled(boolean addressEnabled) - { - Global.addressEnabled = addressEnabled; - } - - /** - * 获取头像上传路径 - */ - public static String getAvatarPath() - { - return getProfile() + "/avatar"; - } - - /** - * 获取下载路径 - */ - public static String getDownloadPath() - { - return getProfile() + "/download/"; - } - - /** - * 获取上传路径 - */ - public static String getUploadPath() - { - return getProfile() + "/upload"; - } -} +package com.ruoyi.common.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * 全局配置类 + * + * @author ruoyi + */ +@Component +@ConfigurationProperties(prefix = "ruoyi") +public class Global { + /** + * 项目名称 + */ + private static String name; + + /** + * 版本 + */ + private static String version; + + /** + * 版权年份 + */ + private static String copyrightYear; + + /** + * 实例演示开关 + */ + private static boolean demoEnabled; + + /** + * 上传路径 + */ + private static String profile; + + /** + * 获取地址开关 + */ + private static boolean addressEnabled; + + public static String getName() { + return name; + } + + public void setName(String name) { + Global.name = name; + } + + public static String getVersion() { + return version; + } + + public void setVersion(String version) { + Global.version = version; + } + + public static String getCopyrightYear() { + return copyrightYear; + } + + public void setCopyrightYear(String copyrightYear) { + Global.copyrightYear = copyrightYear; + } + + public static boolean isDemoEnabled() { + return demoEnabled; + } + + public void setDemoEnabled(boolean demoEnabled) { + Global.demoEnabled = demoEnabled; + } + + public static String getProfile() { + return profile; + } + + public void setProfile(String profile) { + Global.profile = profile; + } + + public static boolean isAddressEnabled() { + return addressEnabled; + } + + public void setAddressEnabled(boolean addressEnabled) { + Global.addressEnabled = addressEnabled; + } + + /** + * 获取头像上传路径 + */ + public static String getAvatarPath() { + return getProfile() + "/avatar"; + } + + /** + * 获取下载路径 + */ + public static String getDownloadPath() { + return getProfile() + "/download/"; + } + + /** + * 获取上传路径 + */ + public static String getUploadPath() { + return getProfile() + "/upload"; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/ServerConfig.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/ServerConfig.java index ddb873097..0c5c27231 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/config/ServerConfig.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/ServerConfig.java @@ -1,33 +1,30 @@ -package com.ruoyi.common.config; - -import javax.servlet.http.HttpServletRequest; -import org.springframework.stereotype.Component; -import com.ruoyi.common.utils.ServletUtils; - -/** - * 服务相关配置 - * - * @author ruoyi - * - */ -@Component -public class ServerConfig -{ - /** - * 获取完整的请求路径,包括:域名,端口,上下文访问路径 - * - * @return 服务地址 - */ - public String getUrl() - { - HttpServletRequest request = ServletUtils.getRequest(); - return getDomain(request); - } - - public static String getDomain(HttpServletRequest request) - { - StringBuffer url = request.getRequestURL(); - String contextPath = request.getServletContext().getContextPath(); - return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString(); - } -} +package com.ruoyi.common.config; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Component; +import com.ruoyi.common.utils.ServletUtils; + +/** + * 服务相关配置 + * + * @author ruoyi + */ +@Component +public class ServerConfig { + /** + * 获取完整的请求路径,包括:域名,端口,上下文访问路径 + * + * @return 服务地址 + */ + public String getUrl() { + HttpServletRequest request = ServletUtils.getRequest(); + return getDomain(request); + } + + public static String getDomain(HttpServletRequest request) { + StringBuffer url = request.getRequestURL(); + String contextPath = request.getServletContext().getContextPath(); + return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/datasource/DynamicDataSourceContextHolder.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/datasource/DynamicDataSourceContextHolder.java index 6bc9e6178..f87112226 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/config/datasource/DynamicDataSourceContextHolder.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/datasource/DynamicDataSourceContextHolder.java @@ -1,45 +1,41 @@ -package com.ruoyi.common.config.datasource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 数据源切换处理 - * - * @author ruoyi - */ -public class DynamicDataSourceContextHolder -{ - public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); - - /** - * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, - * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 - */ - private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>(); - - /** - * 设置数据源的变量 - */ - public static void setDataSourceType(String dsType) - { - log.info("切换到{}数据源", dsType); - CONTEXT_HOLDER.set(dsType); - } - - /** - * 获得数据源的变量 - */ - public static String getDataSourceType() - { - return CONTEXT_HOLDER.get(); - } - - /** - * 清空数据源变量 - */ - public static void clearDataSourceType() - { - CONTEXT_HOLDER.remove(); - } -} +package com.ruoyi.common.config.datasource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 数据源切换处理 + * + * @author ruoyi + */ +public class DynamicDataSourceContextHolder { + public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); + + /** + * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, + * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 + */ + private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>(); + + /** + * 设置数据源的变量 + */ + public static void setDataSourceType(String dsType) { + log.info("切换到{}数据源", dsType); + CONTEXT_HOLDER.set(dsType); + } + + /** + * 获得数据源的变量 + */ + public static String getDataSourceType() { + return CONTEXT_HOLDER.get(); + } + + /** + * 清空数据源变量 + */ + public static void clearDataSourceType() { + CONTEXT_HOLDER.remove(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/thread/ThreadPoolConfig.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/thread/ThreadPoolConfig.java index 1ff207552..71089d44b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/config/thread/ThreadPoolConfig.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/thread/ThreadPoolConfig.java @@ -1,62 +1,58 @@ -package com.ruoyi.common.config.thread; - -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import com.ruoyi.common.utils.Threads; - -/** - * 线程池配置 - * - * @author ruoyi - **/ -@Configuration -public class ThreadPoolConfig -{ - // 核心线程池大小 - private int corePoolSize = 50; - - // 最大可创建的线程数 - private int maxPoolSize = 200; - - // 队列最大长度 - private int queueCapacity = 1000; - - // 线程池维护线程所允许的空闲时间 - private int keepAliveSeconds = 300; - - @Bean(name = "threadPoolTaskExecutor") - public ThreadPoolTaskExecutor threadPoolTaskExecutor() - { - ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - executor.setMaxPoolSize(maxPoolSize); - executor.setCorePoolSize(corePoolSize); - executor.setQueueCapacity(queueCapacity); - executor.setKeepAliveSeconds(keepAliveSeconds); - // 线程池对拒绝任务(无线程可用)的处理策略 - executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); - return executor; - } - - /** - * 执行周期性或定时任务 - */ - @Bean(name = "scheduledExecutorService") - protected ScheduledExecutorService scheduledExecutorService() - { - return new ScheduledThreadPoolExecutor(corePoolSize, - new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) - { - @Override - protected void afterExecute(Runnable r, Throwable t) - { - super.afterExecute(r, t); - Threads.printException(r, t); - } - }; - } -} +package com.ruoyi.common.config.thread; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import com.ruoyi.common.utils.Threads; + +/** + * 线程池配置 + * + * @author ruoyi + **/ +@Configuration +public class ThreadPoolConfig { + // 核心线程池大小 + private int corePoolSize = 50; + + // 最大可创建的线程数 + private int maxPoolSize = 200; + + // 队列最大长度 + private int queueCapacity = 1000; + + // 线程池维护线程所允许的空闲时间 + private int keepAliveSeconds = 300; + + @Bean(name = "threadPoolTaskExecutor") + public ThreadPoolTaskExecutor threadPoolTaskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setMaxPoolSize(maxPoolSize); + executor.setCorePoolSize(corePoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setKeepAliveSeconds(keepAliveSeconds); + // 线程池对拒绝任务(无线程可用)的处理策略 + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + return executor; + } + + /** + * 执行周期性或定时任务 + */ + @Bean(name = "scheduledExecutorService") + protected ScheduledExecutorService scheduledExecutorService() { + return new ScheduledThreadPoolExecutor(corePoolSize, + new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) { + @Override + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + Threads.printException(r, t); + } + }; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java index 9cee41d0a..8a8066c1b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java @@ -1,69 +1,68 @@ -package com.ruoyi.common.constant; - -/** - * 通用常量信息 - * - * @author ruoyi - */ -public class Constants -{ - /** - * UTF-8 字符集 - */ - public static final String UTF8 = "UTF-8"; - - /** - * 通用成功标识 - */ - public static final String SUCCESS = "0"; - - /** - * 通用失败标识 - */ - public static final String FAIL = "1"; - - /** - * 登录成功 - */ - public static final String LOGIN_SUCCESS = "Success"; - - /** - * 注销 - */ - public static final String LOGOUT = "Logout"; - - /** - * 登录失败 - */ - public static final String LOGIN_FAIL = "Error"; - - /** - * 自动去除表前缀 - */ - public static final String AUTO_REOMVE_PRE = "true"; - - /** - * 当前记录起始索引 - */ - public static final String PAGE_NUM = "pageNum"; - - /** - * 每页显示记录数 - */ - public static final String PAGE_SIZE = "pageSize"; - - /** - * 排序列 - */ - public static final String ORDER_BY_COLUMN = "orderByColumn"; - - /** - * 排序的方向 "desc" 或者 "asc". - */ - public static final String IS_ASC = "isAsc"; - - /** - * 资源映射路径 前缀 - */ - public static final String RESOURCE_PREFIX = "/profile"; -} +package com.ruoyi.common.constant; + +/** + * 通用常量信息 + * + * @author ruoyi + */ +public class Constants { + /** + * UTF-8 字符集 + */ + public static final String UTF8 = "UTF-8"; + + /** + * 通用成功标识 + */ + public static final String SUCCESS = "0"; + + /** + * 通用失败标识 + */ + public static final String FAIL = "1"; + + /** + * 登录成功 + */ + public static final String LOGIN_SUCCESS = "Success"; + + /** + * 注销 + */ + public static final String LOGOUT = "Logout"; + + /** + * 登录失败 + */ + public static final String LOGIN_FAIL = "Error"; + + /** + * 自动去除表前缀 + */ + public static final String AUTO_REOMVE_PRE = "true"; + + /** + * 当前记录起始索引 + */ + public static final String PAGE_NUM = "pageNum"; + + /** + * 每页显示记录数 + */ + public static final String PAGE_SIZE = "pageSize"; + + /** + * 排序列 + */ + public static final String ORDER_BY_COLUMN = "orderByColumn"; + + /** + * 排序的方向 "desc" 或者 "asc". + */ + public static final String IS_ASC = "isAsc"; + + /** + * 资源映射路径 前缀 + */ + public static final String RESOURCE_PREFIX = "/profile"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/GenConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/GenConstants.java index 068969be7..baba26c09 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/GenConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/GenConstants.java @@ -1,94 +1,147 @@ -package com.ruoyi.common.constant; - -/** - * 代码生成通用常量 - * - * @author ruoyi - */ -public class GenConstants -{ - /** 单表(增删改查) */ - public static final String TPL_CRUD = "crud"; - - /** 树表(增删改查) */ - public static final String TPL_TREE = "tree"; - - /** 树编码字段 */ - public static final String TREE_CODE = "treeCode"; - - /** 树父编码字段 */ - public static final String TREE_PARENT_CODE = "treeParentCode"; - - /** 树名称字段 */ - public static final String TREE_NAME = "treeName"; - - /** 数据库字符串类型 */ - public static final String[] COLUMNTYPE_STR = { "char", "varchar", "narchar", "varchar2", "tinytext", "text", - "mediumtext", "longtext" }; - - /** 数据库时间类型 */ - public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" }; - - /** 数据库数字类型 */ - public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer", - "bigint", "float", "float", "double", "decimal" }; - - /** 页面不需要编辑字段 */ - public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" }; - - /** 页面不需要显示的列表字段 */ - public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by", - "update_time" }; - - /** 页面不需要查询字段 */ - public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by", - "update_time", "remark" }; - - /** Entity基类字段 */ - public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" }; - - /** Tree基类字段 */ - public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors" }; - - /** 文本框 */ - public static final String HTML_INPUT = "input"; - - /** 文本域 */ - public static final String HTML_TEXTAREA = "textarea"; - - /** 下拉框 */ - public static final String HTML_SELECT = "select"; - - /** 单选框 */ - public static final String HTML_RADIO = "radio"; - - /** 复选框 */ - public static final String HTML_CHECKBOX = "checkbox"; - - /** 日期控件 */ - public static final String HTML_DATETIME = "datetime"; - - /** 字符串类型 */ - public static final String TYPE_STRING = "String"; - - /** 整型 */ - public static final String TYPE_INTEGER = "Integer"; - - /** 长整型 */ - public static final String TYPE_LONG = "Long"; - - /** 浮点型 */ - public static final String TYPE_DOUBLE = "Double"; - - /** 高精度计算类型 */ - public static final String TYPE_BIGDECIMAL = "BigDecimal"; - - /** 时间类型 */ - public static final String TYPE_DATE = "Date"; - - /** 模糊查询 */ - public static final String QUERY_LIKE = "LIKE"; - - /** 需要 */ - public static final String REQUIRE = "1"; -} +package com.ruoyi.common.constant; + +/** + * 代码生成通用常量 + * + * @author ruoyi + */ +public class GenConstants { + /** + * 单表(增删改查) + */ + public static final String TPL_CRUD = "crud"; + + /** + * 树表(增删改查) + */ + public static final String TPL_TREE = "tree"; + + /** + * 树编码字段 + */ + public static final String TREE_CODE = "treeCode"; + + /** + * 树父编码字段 + */ + public static final String TREE_PARENT_CODE = "treeParentCode"; + + /** + * 树名称字段 + */ + public static final String TREE_NAME = "treeName"; + + /** + * 数据库字符串类型 + */ + public static final String[] COLUMNTYPE_STR = {"char", "varchar", "narchar", "varchar2", "tinytext", "text", + "mediumtext", "longtext"}; + + /** + * 数据库时间类型 + */ + public static final String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"}; + + /** + * 数据库数字类型 + */ + public static final String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer", + "bigint", "float", "float", "double", "decimal"}; + + /** + * 页面不需要编辑字段 + */ + public static final String[] COLUMNNAME_NOT_EDIT = {"id", "create_by", "create_time", "del_flag"}; + + /** + * 页面不需要显示的列表字段 + */ + public static final String[] COLUMNNAME_NOT_LIST = {"id", "create_by", "create_time", "del_flag", "update_by", + "update_time"}; + + /** + * 页面不需要查询字段 + */ + public static final String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by", + "update_time", "remark"}; + + /** + * Entity基类字段 + */ + public static final String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime", "remark"}; + + /** + * Tree基类字段 + */ + public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors"}; + + /** + * 文本框 + */ + public static final String HTML_INPUT = "input"; + + /** + * 文本域 + */ + public static final String HTML_TEXTAREA = "textarea"; + + /** + * 下拉框 + */ + public static final String HTML_SELECT = "select"; + + /** + * 单选框 + */ + public static final String HTML_RADIO = "radio"; + + /** + * 复选框 + */ + public static final String HTML_CHECKBOX = "checkbox"; + + /** + * 日期控件 + */ + public static final String HTML_DATETIME = "datetime"; + + /** + * 字符串类型 + */ + public static final String TYPE_STRING = "String"; + + /** + * 整型 + */ + public static final String TYPE_INTEGER = "Integer"; + + /** + * 长整型 + */ + public static final String TYPE_LONG = "Long"; + + /** + * 浮点型 + */ + public static final String TYPE_DOUBLE = "Double"; + + /** + * 高精度计算类型 + */ + public static final String TYPE_BIGDECIMAL = "BigDecimal"; + + /** + * 时间类型 + */ + public static final String TYPE_DATE = "Date"; + + /** + * 模糊查询 + */ + public static final String QUERY_LIKE = "LIKE"; + + /** + * 需要 + */ + public static final String REQUIRE = "1"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/PermissionConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/PermissionConstants.java index 7caf18542..69b29afc5 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/PermissionConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/PermissionConstants.java @@ -1,27 +1,38 @@ -package com.ruoyi.common.constant; - -/** - * 权限通用常量 - * - * @author ruoyi - */ -public class PermissionConstants -{ - /** 新增权限 */ - public static final String ADD_PERMISSION = "add"; - - /** 修改权限 */ - public static final String EDIT_PERMISSION = "edit"; - - /** 删除权限 */ - public static final String REMOVE_PERMISSION = "remove"; - - /** 导出权限 */ - public static final String EXPORT_PERMISSION = "export"; - - /** 显示权限 */ - public static final String VIEW_PERMISSION = "view"; - - /** 查询权限 */ - public static final String LIST_PERMISSION = "list"; -} +package com.ruoyi.common.constant; + +/** + * 权限通用常量 + * + * @author ruoyi + */ +public class PermissionConstants { + /** + * 新增权限 + */ + public static final String ADD_PERMISSION = "add"; + + /** + * 修改权限 + */ + public static final String EDIT_PERMISSION = "edit"; + + /** + * 删除权限 + */ + public static final String REMOVE_PERMISSION = "remove"; + + /** + * 导出权限 + */ + public static final String EXPORT_PERMISSION = "export"; + + /** + * 显示权限 + */ + public static final String VIEW_PERMISSION = "view"; + + /** + * 查询权限 + */ + public static final String LIST_PERMISSION = "list"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/ScheduleConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/ScheduleConstants.java index b82036666..c5f9fa0be 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/ScheduleConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/ScheduleConstants.java @@ -1,50 +1,56 @@ -package com.ruoyi.common.constant; - -/** - * 任务调度通用常量 - * - * @author ruoyi - */ -public interface ScheduleConstants -{ - public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; - - /** 执行目标key */ - public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; - - /** 默认 */ - public static final String MISFIRE_DEFAULT = "0"; - - /** 立即触发执行 */ - public static final String MISFIRE_IGNORE_MISFIRES = "1"; - - /** 触发一次执行 */ - public static final String MISFIRE_FIRE_AND_PROCEED = "2"; - - /** 不触发立即执行 */ - public static final String MISFIRE_DO_NOTHING = "3"; - - public enum Status - { - /** - * 正常 - */ - NORMAL("0"), - /** - * 暂停 - */ - PAUSE("1"); - - private String value; - - private Status(String value) - { - this.value = value; - } - - public String getValue() - { - return value; - } - } -} +package com.ruoyi.common.constant; + +/** + * 任务调度通用常量 + * + * @author ruoyi + */ +public interface ScheduleConstants { + public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; + + /** + * 执行目标key + */ + public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; + + /** + * 默认 + */ + public static final String MISFIRE_DEFAULT = "0"; + + /** + * 立即触发执行 + */ + public static final String MISFIRE_IGNORE_MISFIRES = "1"; + + /** + * 触发一次执行 + */ + public static final String MISFIRE_FIRE_AND_PROCEED = "2"; + + /** + * 不触发立即执行 + */ + public static final String MISFIRE_DO_NOTHING = "3"; + + public enum Status { + /** + * 正常 + */ + NORMAL("0"), + /** + * 暂停 + */ + PAUSE("1"); + + private String value; + + private Status(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/ShiroConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/ShiroConstants.java index c5027c240..a5a0c0c79 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/ShiroConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/ShiroConstants.java @@ -1,74 +1,73 @@ -package com.ruoyi.common.constant; - -/** - * Shiro通用常量 - * - * @author ruoyi - */ -public interface ShiroConstants -{ - /** - * 当前登录的用户 - */ - public static final String CURRENT_USER = "currentUser"; - - /** - * 用户名 - */ - public static final String CURRENT_USERNAME = "username"; - - /** - * 消息key - */ - public static String MESSAGE = "message"; - - /** - * 错误key - */ - public static String ERROR = "errorMsg"; - - /** - * 编码格式 - */ - public static String ENCODING = "UTF-8"; - - /** - * 当前在线会话 - */ - public String ONLINE_SESSION = "online_session"; - - /** - * 验证码key - */ - public static final String CURRENT_CAPTCHA = "captcha"; - - /** - * 验证码开关 - */ - public static final String CURRENT_ENABLED = "captchaEnabled"; - - /** - * 验证码类型 - */ - public static final String CURRENT_TYPE = "captchaType"; - - /** - * 验证码 - */ - public static final String CURRENT_VALIDATECODE = "validateCode"; - - /** - * 验证码错误 - */ - public static final String CAPTCHA_ERROR = "captchaError"; - - /** - * 登录记录缓存 - */ - public static final String LOGINRECORDCACHE = "loginRecordCache"; - - /** - * 系统活跃用户缓存 - */ - public static final String SYS_USERCACHE = "sys-userCache"; -} +package com.ruoyi.common.constant; + +/** + * Shiro通用常量 + * + * @author ruoyi + */ +public interface ShiroConstants { + /** + * 当前登录的用户 + */ + public static final String CURRENT_USER = "currentUser"; + + /** + * 用户名 + */ + public static final String CURRENT_USERNAME = "username"; + + /** + * 消息key + */ + public static String MESSAGE = "message"; + + /** + * 错误key + */ + public static String ERROR = "errorMsg"; + + /** + * 编码格式 + */ + public static String ENCODING = "UTF-8"; + + /** + * 当前在线会话 + */ + public String ONLINE_SESSION = "online_session"; + + /** + * 验证码key + */ + public static final String CURRENT_CAPTCHA = "captcha"; + + /** + * 验证码开关 + */ + public static final String CURRENT_ENABLED = "captchaEnabled"; + + /** + * 验证码类型 + */ + public static final String CURRENT_TYPE = "captchaType"; + + /** + * 验证码 + */ + public static final String CURRENT_VALIDATECODE = "validateCode"; + + /** + * 验证码错误 + */ + public static final String CAPTCHA_ERROR = "captchaError"; + + /** + * 登录记录缓存 + */ + public static final String LOGINRECORDCACHE = "loginRecordCache"; + + /** + * 系统活跃用户缓存 + */ + public static final String SYS_USERCACHE = "sys-userCache"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java index a51ba3bfd..27ce76cde 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java @@ -1,101 +1,136 @@ -package com.ruoyi.common.constant; - -/** - * 用户常量信息 - * - * @author ruoyi - */ -public class UserConstants -{ - /** - * 平台内系统用户的唯一标志 - */ - public static final String SYS_USER = "SYS_USER"; - - /** 正常状态 */ - public static final String NORMAL = "0"; - - /** 异常状态 */ - public static final String EXCEPTION = "1"; - - /** 用户封禁状态 */ - public static final String USER_BLOCKED = "1"; - - /** 角色封禁状态 */ - public static final String ROLE_BLOCKED = "1"; - - /** 部门正常状态 */ - public static final String DEPT_NORMAL = "0"; - - /** 字典正常状态 */ - public static final String DICT_NORMAL = "0"; - - /** 是否为系统默认(是) */ - public static final String YES = "Y"; - - /** - * 用户名长度限制 - */ - public static final int USERNAME_MIN_LENGTH = 2; - public static final int USERNAME_MAX_LENGTH = 20; - - /** 登录名称是否唯一的返回结果码 */ - public final static String USER_NAME_UNIQUE = "0"; - public final static String USER_NAME_NOT_UNIQUE = "1"; - - /** 手机号码是否唯一的返回结果 */ - public final static String USER_PHONE_UNIQUE = "0"; - public final static String USER_PHONE_NOT_UNIQUE = "1"; - - /** e-mail 是否唯一的返回结果 */ - public final static String USER_EMAIL_UNIQUE = "0"; - public final static String USER_EMAIL_NOT_UNIQUE = "1"; - - /** 部门名称是否唯一的返回结果码 */ - public final static String DEPT_NAME_UNIQUE = "0"; - public final static String DEPT_NAME_NOT_UNIQUE = "1"; - - /** 角色名称是否唯一的返回结果码 */ - public final static String ROLE_NAME_UNIQUE = "0"; - public final static String ROLE_NAME_NOT_UNIQUE = "1"; - - /** 岗位名称是否唯一的返回结果码 */ - public final static String POST_NAME_UNIQUE = "0"; - public final static String POST_NAME_NOT_UNIQUE = "1"; - - /** 角色权限是否唯一的返回结果码 */ - public final static String ROLE_KEY_UNIQUE = "0"; - public final static String ROLE_KEY_NOT_UNIQUE = "1"; - - /** 岗位编码是否唯一的返回结果码 */ - public final static String POST_CODE_UNIQUE = "0"; - public final static String POST_CODE_NOT_UNIQUE = "1"; - - /** 菜单名称是否唯一的返回结果码 */ - public final static String MENU_NAME_UNIQUE = "0"; - public final static String MENU_NAME_NOT_UNIQUE = "1"; - - /** 字典类型是否唯一的返回结果码 */ - public final static String DICT_TYPE_UNIQUE = "0"; - public final static String DICT_TYPE_NOT_UNIQUE = "1"; - - /** 参数键名是否唯一的返回结果码 */ - public final static String CONFIG_KEY_UNIQUE = "0"; - public final static String CONFIG_KEY_NOT_UNIQUE = "1"; - - /** - * 密码长度限制 - */ - public static final int PASSWORD_MIN_LENGTH = 5; - public static final int PASSWORD_MAX_LENGTH = 20; - - /** - * 手机号码格式限制 - */ - public static final String MOBILE_PHONE_NUMBER_PATTERN = "^0{0,1}(13[0-9]|15[0-9]|14[0-9]|18[0-9])[0-9]{8}$"; - - /** - * 邮箱格式限制 - */ - public static final String EMAIL_PATTERN = "^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?"; -} +package com.ruoyi.common.constant; + +/** + * 用户常量信息 + * + * @author ruoyi + */ +public class UserConstants { + /** + * 平台内系统用户的唯一标志 + */ + public static final String SYS_USER = "SYS_USER"; + + /** + * 正常状态 + */ + public static final String NORMAL = "0"; + + /** + * 异常状态 + */ + public static final String EXCEPTION = "1"; + + /** + * 用户封禁状态 + */ + public static final String USER_BLOCKED = "1"; + + /** + * 角色封禁状态 + */ + public static final String ROLE_BLOCKED = "1"; + + /** + * 部门正常状态 + */ + public static final String DEPT_NORMAL = "0"; + + /** + * 字典正常状态 + */ + public static final String DICT_NORMAL = "0"; + + /** + * 是否为系统默认(是) + */ + public static final String YES = "Y"; + + /** + * 用户名长度限制 + */ + public static final int USERNAME_MIN_LENGTH = 2; + public static final int USERNAME_MAX_LENGTH = 20; + + /** + * 登录名称是否唯一的返回结果码 + */ + public final static String USER_NAME_UNIQUE = "0"; + public final static String USER_NAME_NOT_UNIQUE = "1"; + + /** + * 手机号码是否唯一的返回结果 + */ + public final static String USER_PHONE_UNIQUE = "0"; + public final static String USER_PHONE_NOT_UNIQUE = "1"; + + /** + * e-mail 是否唯一的返回结果 + */ + public final static String USER_EMAIL_UNIQUE = "0"; + public final static String USER_EMAIL_NOT_UNIQUE = "1"; + + /** + * 部门名称是否唯一的返回结果码 + */ + public final static String DEPT_NAME_UNIQUE = "0"; + public final static String DEPT_NAME_NOT_UNIQUE = "1"; + + /** + * 角色名称是否唯一的返回结果码 + */ + public final static String ROLE_NAME_UNIQUE = "0"; + public final static String ROLE_NAME_NOT_UNIQUE = "1"; + + /** + * 岗位名称是否唯一的返回结果码 + */ + public final static String POST_NAME_UNIQUE = "0"; + public final static String POST_NAME_NOT_UNIQUE = "1"; + + /** + * 角色权限是否唯一的返回结果码 + */ + public final static String ROLE_KEY_UNIQUE = "0"; + public final static String ROLE_KEY_NOT_UNIQUE = "1"; + + /** + * 岗位编码是否唯一的返回结果码 + */ + public final static String POST_CODE_UNIQUE = "0"; + public final static String POST_CODE_NOT_UNIQUE = "1"; + + /** + * 菜单名称是否唯一的返回结果码 + */ + public final static String MENU_NAME_UNIQUE = "0"; + public final static String MENU_NAME_NOT_UNIQUE = "1"; + + /** + * 字典类型是否唯一的返回结果码 + */ + public final static String DICT_TYPE_UNIQUE = "0"; + public final static String DICT_TYPE_NOT_UNIQUE = "1"; + + /** + * 参数键名是否唯一的返回结果码 + */ + public final static String CONFIG_KEY_UNIQUE = "0"; + public final static String CONFIG_KEY_NOT_UNIQUE = "1"; + + /** + * 密码长度限制 + */ + public static final int PASSWORD_MIN_LENGTH = 5; + public static final int PASSWORD_MAX_LENGTH = 20; + + /** + * 手机号码格式限制 + */ + public static final String MOBILE_PHONE_NUMBER_PATTERN = "^0{0,1}(13[0-9]|15[0-9]|14[0-9]|18[0-9])[0-9]{8}$"; + + /** + * 邮箱格式限制 + */ + public static final String EMAIL_PATTERN = "^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java index 149ac01d1..a25558746 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java @@ -1,172 +1,155 @@ -package com.ruoyi.common.core.controller; - -import java.beans.PropertyEditorSupport; -import java.util.Date; -import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.AjaxResult.Type; -import com.ruoyi.common.core.page.PageDomain; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.core.page.TableSupport; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.ServletUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.sql.SqlUtil; - -/** - * web层通用数据处理 - * - * @author ruoyi - */ -public class BaseController -{ - protected final Logger logger = LoggerFactory.getLogger(BaseController.class); - - /** - * 将前台传递过来的日期格式的字符串,自动转化为Date类型 - */ - @InitBinder - public void initBinder(WebDataBinder binder) - { - // Date 类型转换 - binder.registerCustomEditor(Date.class, new PropertyEditorSupport() - { - @Override - public void setAsText(String text) - { - setValue(DateUtils.parseDate(text)); - } - }); - } - - /** - * 设置请求分页数据 - */ - protected void startPage() - { - PageDomain pageDomain = TableSupport.buildPageRequest(); - Integer pageNum = pageDomain.getPageNum(); - Integer pageSize = pageDomain.getPageSize(); - if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) - { - String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); - PageHelper.startPage(pageNum, pageSize, orderBy); - } - } - - /** - * 获取request - */ - public HttpServletRequest getRequest() - { - return ServletUtils.getRequest(); - } - - /** - * 获取response - */ - public HttpServletResponse getResponse() - { - return ServletUtils.getResponse(); - } - - /** - * 获取session - */ - public HttpSession getSession() - { - return getRequest().getSession(); - } - - /** - * 响应请求分页数据 - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected TableDataInfo getDataTable(List list) - { - TableDataInfo rspData = new TableDataInfo(); - rspData.setCode(0); - rspData.setRows(list); - rspData.setTotal(new PageInfo(list).getTotal()); - return rspData; - } - - /** - * 响应返回结果 - * - * @param rows 影响行数 - * @return 操作结果 - */ - protected AjaxResult toAjax(int rows) - { - return rows > 0 ? success() : error(); - } - - /** - * 响应返回结果 - * - * @param result 结果 - * @return 操作结果 - */ - protected AjaxResult toAjax(boolean result) - { - return result ? success() : error(); - } - - /** - * 返回成功 - */ - public AjaxResult success() - { - return AjaxResult.success(); - } - - /** - * 返回失败消息 - */ - public AjaxResult error() - { - return AjaxResult.error(); - } - - /** - * 返回成功消息 - */ - public AjaxResult success(String message) - { - return AjaxResult.success(message); - } - - /** - * 返回失败消息 - */ - public AjaxResult error(String message) - { - return AjaxResult.error(message); - } - - /** - * 返回错误码消息 - */ - public AjaxResult error(Type type, String message) - { - return new AjaxResult(type, message); - } - - /** - * 页面跳转 - */ - public String redirect(String url) - { - return StringUtils.format("redirect:{}", url); - } -} +package com.ruoyi.common.core.controller; + +import java.beans.PropertyEditorSupport; +import java.util.Date; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.AjaxResult.Type; +import com.ruoyi.common.core.page.PageDomain; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.core.page.TableSupport; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.sql.SqlUtil; + +/** + * web层通用数据处理 + * + * @author ruoyi + */ +public class BaseController { + protected final Logger logger = LoggerFactory.getLogger(BaseController.class); + + /** + * 将前台传递过来的日期格式的字符串,自动转化为Date类型 + */ + @InitBinder + public void initBinder(WebDataBinder binder) { + // Date 类型转换 + binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { + @Override + public void setAsText(String text) { + setValue(DateUtils.parseDate(text)); + } + }); + } + + /** + * 设置请求分页数据 + */ + protected void startPage() { + PageDomain pageDomain = TableSupport.buildPageRequest(); + Integer pageNum = pageDomain.getPageNum(); + Integer pageSize = pageDomain.getPageSize(); + if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { + String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); + PageHelper.startPage(pageNum, pageSize, orderBy); + } + } + + /** + * 获取request + */ + public HttpServletRequest getRequest() { + return ServletUtils.getRequest(); + } + + /** + * 获取response + */ + public HttpServletResponse getResponse() { + return ServletUtils.getResponse(); + } + + /** + * 获取session + */ + public HttpSession getSession() { + return getRequest().getSession(); + } + + /** + * 响应请求分页数据 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + protected TableDataInfo getDataTable(List list) { + TableDataInfo rspData = new TableDataInfo(); + rspData.setCode(0); + rspData.setRows(list); + rspData.setTotal(new PageInfo(list).getTotal()); + return rspData; + } + + /** + * 响应返回结果 + * + * @param rows 影响行数 + * @return 操作结果 + */ + protected AjaxResult toAjax(int rows) { + return rows > 0 ? success() : error(); + } + + /** + * 响应返回结果 + * + * @param result 结果 + * @return 操作结果 + */ + protected AjaxResult toAjax(boolean result) { + return result ? success() : error(); + } + + /** + * 返回成功 + */ + public AjaxResult success() { + return AjaxResult.success(); + } + + /** + * 返回失败消息 + */ + public AjaxResult error() { + return AjaxResult.error(); + } + + /** + * 返回成功消息 + */ + public AjaxResult success(String message) { + return AjaxResult.success(message); + } + + /** + * 返回失败消息 + */ + public AjaxResult error(String message) { + return AjaxResult.error(message); + } + + /** + * 返回错误码消息 + */ + public AjaxResult error(Type type, String message) { + return new AjaxResult(type, message); + } + + /** + * 页面跳转 + */ + public String redirect(String url) { + return StringUtils.format("redirect:{}", url); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/AjaxResult.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/AjaxResult.java index ef89f5c84..3102b9186 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/AjaxResult.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/AjaxResult.java @@ -1,182 +1,178 @@ -package com.ruoyi.common.core.domain; - -import java.util.HashMap; -import com.ruoyi.common.utils.StringUtils; - -/** - * 操作消息提醒 - * - * @author ruoyi - */ -public class AjaxResult extends HashMap -{ - private static final long serialVersionUID = 1L; - - /** 状态码 */ - public static final String CODE_TAG = "code"; - - /** 返回内容 */ - public static final String MSG_TAG = "msg"; - - /** 数据对象 */ - public static final String DATA_TAG = "data"; - - /** - * 状态类型 - */ - public enum Type - { - /** 成功 */ - SUCCESS(0), - /** 警告 */ - WARN(301), - /** 错误 */ - ERROR(500); - private final int value; - - Type(int value) - { - this.value = value; - } - - public int value() - { - return this.value; - } - } - - /** - * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 - */ - public AjaxResult() - { - } - - /** - * 初始化一个新创建的 AjaxResult 对象 - * - * @param type 状态类型 - * @param msg 返回内容 - */ - public AjaxResult(Type type, String msg) - { - super.put(CODE_TAG, type.value); - super.put(MSG_TAG, msg); - } - - /** - * 初始化一个新创建的 AjaxResult 对象 - * - * @param type 状态类型 - * @param msg 返回内容 - * @param data 数据对象 - */ - public AjaxResult(Type type, String msg, Object data) - { - super.put(CODE_TAG, type.value); - super.put(MSG_TAG, msg); - if (StringUtils.isNotNull(data)) - { - super.put(DATA_TAG, data); - } - } - - /** - * 返回成功消息 - * - * @return 成功消息 - */ - public static AjaxResult success() - { - return AjaxResult.success("操作成功"); - } - - /** - * 返回成功数据 - * - * @return 成功消息 - */ - public static AjaxResult success(Object data) - { - return AjaxResult.success("操作成功", data); - } - - /** - * 返回成功消息 - * - * @param msg 返回内容 - * @return 成功消息 - */ - public static AjaxResult success(String msg) - { - return AjaxResult.success(msg, null); - } - - /** - * 返回成功消息 - * - * @param msg 返回内容 - * @param data 数据对象 - * @return 成功消息 - */ - public static AjaxResult success(String msg, Object data) - { - return new AjaxResult(Type.SUCCESS, msg, data); - } - - /** - * 返回警告消息 - * - * @param msg 返回内容 - * @return 警告消息 - */ - public static AjaxResult warn(String msg) - { - return AjaxResult.warn(msg, null); - } - - /** - * 返回警告消息 - * - * @param msg 返回内容 - * @param data 数据对象 - * @return 警告消息 - */ - public static AjaxResult warn(String msg, Object data) - { - return new AjaxResult(Type.WARN, msg, data); - } - - /** - * 返回错误消息 - * - * @return - */ - public static AjaxResult error() - { - return AjaxResult.error("操作失败"); - } - - /** - * 返回错误消息 - * - * @param msg 返回内容 - * @return 警告消息 - */ - public static AjaxResult error(String msg) - { - return AjaxResult.error(msg, null); - } - - /** - * 返回错误消息 - * - * @param msg 返回内容 - * @param data 数据对象 - * @return 警告消息 - */ - public static AjaxResult error(String msg, Object data) - { - return new AjaxResult(Type.ERROR, msg, data); - } -} +package com.ruoyi.common.core.domain; + +import java.util.HashMap; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 操作消息提醒 + * + * @author ruoyi + */ +public class AjaxResult extends HashMap { + private static final long serialVersionUID = 1L; + + /** + * 状态码 + */ + public static final String CODE_TAG = "code"; + + /** + * 返回内容 + */ + public static final String MSG_TAG = "msg"; + + /** + * 数据对象 + */ + public static final String DATA_TAG = "data"; + + /** + * 状态类型 + */ + public enum Type { + /** + * 成功 + */ + SUCCESS(0), + /** + * 警告 + */ + WARN(301), + /** + * 错误 + */ + ERROR(500); + private final int value; + + Type(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } + + /** + * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 + */ + public AjaxResult() { + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param type 状态类型 + * @param msg 返回内容 + */ + public AjaxResult(Type type, String msg) { + super.put(CODE_TAG, type.value); + super.put(MSG_TAG, msg); + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param type 状态类型 + * @param msg 返回内容 + * @param data 数据对象 + */ + public AjaxResult(Type type, String msg, Object data) { + super.put(CODE_TAG, type.value); + super.put(MSG_TAG, msg); + if (StringUtils.isNotNull(data)) { + super.put(DATA_TAG, data); + } + } + + /** + * 返回成功消息 + * + * @return 成功消息 + */ + public static AjaxResult success() { + return AjaxResult.success("操作成功"); + } + + /** + * 返回成功数据 + * + * @return 成功消息 + */ + public static AjaxResult success(Object data) { + return AjaxResult.success("操作成功", data); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @return 成功消息 + */ + public static AjaxResult success(String msg) { + return AjaxResult.success(msg, null); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 成功消息 + */ + public static AjaxResult success(String msg, Object data) { + return new AjaxResult(Type.SUCCESS, msg, data); + } + + /** + * 返回警告消息 + * + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult warn(String msg) { + return AjaxResult.warn(msg, null); + } + + /** + * 返回警告消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 警告消息 + */ + public static AjaxResult warn(String msg, Object data) { + return new AjaxResult(Type.WARN, msg, data); + } + + /** + * 返回错误消息 + * + * @return + */ + public static AjaxResult error() { + return AjaxResult.error("操作失败"); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult error(String msg) { + return AjaxResult.error(msg, null); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 警告消息 + */ + public static AjaxResult error(String msg, Object data) { + return new AjaxResult(Type.ERROR, msg, data); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java index 0fc68beb5..093fee410 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java @@ -1,114 +1,113 @@ -package com.ruoyi.common.core.domain; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonFormat; - -/** - * Entity基类 - * - * @author ruoyi - */ -public class BaseEntity implements Serializable -{ - private static final long serialVersionUID = 1L; - - /** 搜索值 */ - private String searchValue; - - /** 创建者 */ - private String createBy; - - /** 创建时间 */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; - - /** 更新者 */ - private String updateBy; - - /** 更新时间 */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date updateTime; - - /** 备注 */ - private String remark; - - /** 请求参数 */ - private Map params; - - public String getSearchValue() - { - return searchValue; - } - - public void setSearchValue(String searchValue) - { - this.searchValue = searchValue; - } - - public String getCreateBy() - { - return createBy; - } - - public void setCreateBy(String createBy) - { - this.createBy = createBy; - } - - public Date getCreateTime() - { - return createTime; - } - - public void setCreateTime(Date createTime) - { - this.createTime = createTime; - } - - public String getUpdateBy() - { - return updateBy; - } - - public void setUpdateBy(String updateBy) - { - this.updateBy = updateBy; - } - - public Date getUpdateTime() - { - return updateTime; - } - - public void setUpdateTime(Date updateTime) - { - this.updateTime = updateTime; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark; - } - - public Map getParams() - { - if (params == null) - { - params = new HashMap<>(); - } - return params; - } - - public void setParams(Map params) - { - this.params = params; - } -} +package com.ruoyi.common.core.domain; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonFormat; + +/** + * Entity基类 + * + * @author ruoyi + */ +public class BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 搜索值 + */ + private String searchValue; + + /** + * 创建者 + */ + private String createBy; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; + + /** + * 更新者 + */ + private String updateBy; + + /** + * 更新时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTime; + + /** + * 备注 + */ + private String remark; + + /** + * 请求参数 + */ + private Map params; + + public String getSearchValue() { + return searchValue; + } + + public void setSearchValue(String searchValue) { + this.searchValue = searchValue; + } + + public String getCreateBy() { + return createBy; + } + + public void setCreateBy(String createBy) { + this.createBy = createBy; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(String updateBy) { + this.updateBy = updateBy; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public Map getParams() { + if (params == null) { + params = new HashMap<>(); + } + return params; + } + + public void setParams(Map params) { + this.params = params; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/TreeEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/TreeEntity.java index 7a0efe62a..66011a52e 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/TreeEntity.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/TreeEntity.java @@ -1,63 +1,62 @@ -package com.ruoyi.common.core.domain; - -/** - * Tree基类 - * - * @author ruoyi - */ -public class TreeEntity extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 父菜单名称 */ - private String parentName; - - /** 父菜单ID */ - private Long parentId; - - /** 显示顺序 */ - private Integer orderNum; - - /** 祖级列表 */ - private String ancestors; - - public String getParentName() - { - return parentName; - } - - public void setParentName(String parentName) - { - this.parentName = parentName; - } - - public Long getParentId() - { - return parentId; - } - - public void setParentId(Long parentId) - { - this.parentId = parentId; - } - - public Integer getOrderNum() - { - return orderNum; - } - - public void setOrderNum(Integer orderNum) - { - this.orderNum = orderNum; - } - - public String getAncestors() - { - return ancestors; - } - - public void setAncestors(String ancestors) - { - this.ancestors = ancestors; - } +package com.ruoyi.common.core.domain; + +/** + * Tree基类 + * + * @author ruoyi + */ +public class TreeEntity extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 父菜单名称 + */ + private String parentName; + + /** + * 父菜单ID + */ + private Long parentId; + + /** + * 显示顺序 + */ + private Integer orderNum; + + /** + * 祖级列表 + */ + private String ancestors; + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public Integer getOrderNum() { + return orderNum; + } + + public void setOrderNum(Integer orderNum) { + this.orderNum = orderNum; + } + + public String getAncestors() { + return ancestors; + } + + public void setAncestors(String ancestors) { + this.ancestors = ancestors; + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/Ztree.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/Ztree.java index e7fe780e4..6385eadb2 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/Ztree.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/Ztree.java @@ -1,104 +1,103 @@ -package com.ruoyi.common.core.domain; - -import java.io.Serializable; - -/** - * Ztree树结构实体类 - * - * @author ruoyi - */ -public class Ztree implements Serializable -{ - private static final long serialVersionUID = 1L; - - /** 节点ID */ - private Long id; - - /** 节点父ID */ - private Long pId; - - /** 节点名称 */ - private String name; - - /** 节点标题 */ - private String title; - - /** 是否勾选 */ - private boolean checked = false; - - /** 是否展开 */ - private boolean open = false; - - /** 是否能勾选 */ - private boolean nocheck = false; - - public Long getId() - { - return id; - } - - public void setId(Long id) - { - this.id = id; - } - - public Long getpId() - { - return pId; - } - - public void setpId(Long pId) - { - this.pId = pId; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getTitle() - { - return title; - } - - public void setTitle(String title) - { - this.title = title; - } - - public boolean isChecked() - { - return checked; - } - - public void setChecked(boolean checked) - { - this.checked = checked; - } - - public boolean isOpen() - { - return open; - } - - public void setOpen(boolean open) - { - this.open = open; - } - - public boolean isNocheck() - { - return nocheck; - } - - public void setNocheck(boolean nocheck) - { - this.nocheck = nocheck; - } -} +package com.ruoyi.common.core.domain; + +import java.io.Serializable; + +/** + * Ztree树结构实体类 + * + * @author ruoyi + */ +public class Ztree implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 节点ID + */ + private Long id; + + /** + * 节点父ID + */ + private Long pId; + + /** + * 节点名称 + */ + private String name; + + /** + * 节点标题 + */ + private String title; + + /** + * 是否勾选 + */ + private boolean checked = false; + + /** + * 是否展开 + */ + private boolean open = false; + + /** + * 是否能勾选 + */ + private boolean nocheck = false; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getpId() { + return pId; + } + + public void setpId(Long pId) { + this.pId = pId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public boolean isChecked() { + return checked; + } + + public void setChecked(boolean checked) { + this.checked = checked; + } + + public boolean isOpen() { + return open; + } + + public void setOpen(boolean open) { + this.open = open; + } + + public boolean isNocheck() { + return nocheck; + } + + public void setNocheck(boolean nocheck) { + this.nocheck = nocheck; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/PageDomain.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/PageDomain.java index 7fccaf46e..a7b8d4052 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/PageDomain.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/PageDomain.java @@ -1,69 +1,66 @@ -package com.ruoyi.common.core.page; - -import com.ruoyi.common.utils.StringUtils; - -/** - * 分页数据 - * - * @author ruoyi - */ -public class PageDomain -{ - /** 当前记录起始索引 */ - private Integer pageNum; - /** 每页显示记录数 */ - private Integer pageSize; - /** 排序列 */ - private String orderByColumn; - /** 排序的方向 "desc" 或者 "asc". */ - private String isAsc; - - public String getOrderBy() - { - if (StringUtils.isEmpty(orderByColumn)) - { - return ""; - } - return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; - } - - public Integer getPageNum() - { - return pageNum; - } - - public void setPageNum(Integer pageNum) - { - this.pageNum = pageNum; - } - - public Integer getPageSize() - { - return pageSize; - } - - public void setPageSize(Integer pageSize) - { - this.pageSize = pageSize; - } - - public String getOrderByColumn() - { - return orderByColumn; - } - - public void setOrderByColumn(String orderByColumn) - { - this.orderByColumn = orderByColumn; - } - - public String getIsAsc() - { - return isAsc; - } - - public void setIsAsc(String isAsc) - { - this.isAsc = isAsc; - } -} +package com.ruoyi.common.core.page; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 分页数据 + * + * @author ruoyi + */ +public class PageDomain { + /** + * 当前记录起始索引 + */ + private Integer pageNum; + /** + * 每页显示记录数 + */ + private Integer pageSize; + /** + * 排序列 + */ + private String orderByColumn; + /** + * 排序的方向 "desc" 或者 "asc". + */ + private String isAsc; + + public String getOrderBy() { + if (StringUtils.isEmpty(orderByColumn)) { + return ""; + } + return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public String getOrderByColumn() { + return orderByColumn; + } + + public void setOrderByColumn(String orderByColumn) { + this.orderByColumn = orderByColumn; + } + + public String getIsAsc() { + return isAsc; + } + + public void setIsAsc(String isAsc) { + this.isAsc = isAsc; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableDataInfo.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableDataInfo.java index 82dca3716..ac74e061e 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableDataInfo.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableDataInfo.java @@ -1,85 +1,82 @@ -package com.ruoyi.common.core.page; - -import java.io.Serializable; -import java.util.List; - -/** - * 表格分页数据对象 - * - * @author ruoyi - */ -public class TableDataInfo implements Serializable -{ - private static final long serialVersionUID = 1L; - - /** 总记录数 */ - private long total; - - /** 列表数据 */ - private List rows; - - /** 消息状态码 */ - private int code; - - /** 消息内容 */ - private int msg; - - /** - * 表格数据对象 - */ - public TableDataInfo() - { - } - - /** - * 分页 - * - * @param list 列表数据 - * @param total 总记录数 - */ - public TableDataInfo(List list, int total) - { - this.rows = list; - this.total = total; - } - - public long getTotal() - { - return total; - } - - public void setTotal(long total) - { - this.total = total; - } - - public List getRows() - { - return rows; - } - - public void setRows(List rows) - { - this.rows = rows; - } - - public int getCode() - { - return code; - } - - public void setCode(int code) - { - this.code = code; - } - - public int getMsg() - { - return msg; - } - - public void setMsg(int msg) - { - this.msg = msg; - } +package com.ruoyi.common.core.page; + +import java.io.Serializable; +import java.util.List; + +/** + * 表格分页数据对象 + * + * @author ruoyi + */ +public class TableDataInfo implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 总记录数 + */ + private long total; + + /** + * 列表数据 + */ + private List rows; + + /** + * 消息状态码 + */ + private int code; + + /** + * 消息内容 + */ + private int msg; + + /** + * 表格数据对象 + */ + public TableDataInfo() { + } + + /** + * 分页 + * + * @param list 列表数据 + * @param total 总记录数 + */ + public TableDataInfo(List list, int total) { + this.rows = list; + this.total = total; + } + + public long getTotal() { + return total; + } + + public void setTotal(long total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public int getMsg() { + return msg; + } + + public void setMsg(int msg) { + this.msg = msg; + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableSupport.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableSupport.java index 0efd82b32..320cbda70 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableSupport.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableSupport.java @@ -1,30 +1,27 @@ -package com.ruoyi.common.core.page; - -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.utils.ServletUtils; - -/** - * 表格数据处理 - * - * @author ruoyi - */ -public class TableSupport -{ - /** - * 封装分页对象 - */ - public static PageDomain getPageDomain() - { - PageDomain pageDomain = new PageDomain(); - pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM)); - pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE)); - pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN)); - pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC)); - return pageDomain; - } - - public static PageDomain buildPageRequest() - { - return getPageDomain(); - } -} +package com.ruoyi.common.core.page; + +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.utils.ServletUtils; + +/** + * 表格数据处理 + * + * @author ruoyi + */ +public class TableSupport { + /** + * 封装分页对象 + */ + public static PageDomain getPageDomain() { + PageDomain pageDomain = new PageDomain(); + pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM)); + pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE)); + pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN)); + pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC)); + return pageDomain; + } + + public static PageDomain buildPageRequest() { + return getPageDomain(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/CharsetKit.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/CharsetKit.java index 8297661af..556ca3e10 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/CharsetKit.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/CharsetKit.java @@ -1,86 +1,91 @@ -package com.ruoyi.common.core.text; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import com.ruoyi.common.utils.StringUtils; - -/** - * 字符集工具类 - * - * @author ruoyi - */ -public class CharsetKit -{ - /** ISO-8859-1 */ - public static final String ISO_8859_1 = "ISO-8859-1"; - /** UTF-8 */ - public static final String UTF_8 = "UTF-8"; - /** GBK */ - public static final String GBK = "GBK"; - - /** ISO-8859-1 */ - public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); - /** UTF-8 */ - public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); - /** GBK */ - public static final Charset CHARSET_GBK = Charset.forName(GBK); - - /** - * 转换为Charset对象 - * - * @param charset 字符集,为空则返回默认字符集 - * @return Charset - */ - public static Charset charset(String charset) - { - return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); - } - - /** - * 转换字符串的字符集编码 - * - * @param source 字符串 - * @param srcCharset 源字符集,默认ISO-8859-1 - * @param destCharset 目标字符集,默认UTF-8 - * @return 转换后的字符集 - */ - public static String convert(String source, String srcCharset, String destCharset) - { - return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); - } - - /** - * 转换字符串的字符集编码 - * - * @param source 字符串 - * @param srcCharset 源字符集,默认ISO-8859-1 - * @param destCharset 目标字符集,默认UTF-8 - * @return 转换后的字符集 - */ - public static String convert(String source, Charset srcCharset, Charset destCharset) - { - if (null == srcCharset) - { - srcCharset = StandardCharsets.ISO_8859_1; - } - - if (null == destCharset) - { - srcCharset = StandardCharsets.UTF_8; - } - - if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) - { - return source; - } - return new String(source.getBytes(srcCharset), destCharset); - } - - /** - * @return 系统字符集编码 - */ - public static String systemCharset() - { - return Charset.defaultCharset().name(); - } -} +package com.ruoyi.common.core.text; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 字符集工具类 + * + * @author ruoyi + */ +public class CharsetKit { + /** + * ISO-8859-1 + */ + public static final String ISO_8859_1 = "ISO-8859-1"; + /** + * UTF-8 + */ + public static final String UTF_8 = "UTF-8"; + /** + * GBK + */ + public static final String GBK = "GBK"; + + /** + * ISO-8859-1 + */ + public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); + /** + * UTF-8 + */ + public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); + /** + * GBK + */ + public static final Charset CHARSET_GBK = Charset.forName(GBK); + + /** + * 转换为Charset对象 + * + * @param charset 字符集,为空则返回默认字符集 + * @return Charset + */ + public static Charset charset(String charset) { + return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, String srcCharset, String destCharset) { + return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, Charset srcCharset, Charset destCharset) { + if (null == srcCharset) { + srcCharset = StandardCharsets.ISO_8859_1; + } + + if (null == destCharset) { + srcCharset = StandardCharsets.UTF_8; + } + + if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) { + return source; + } + return new String(source.getBytes(srcCharset), destCharset); + } + + /** + * @return 系统字符集编码 + */ + public static String systemCharset() { + return Charset.defaultCharset().name(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/Convert.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/Convert.java index 9dd076d04..f9dce907c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/Convert.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/Convert.java @@ -1,999 +1,850 @@ -package com.ruoyi.common.core.text; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.text.NumberFormat; -import java.util.Set; -import com.ruoyi.common.utils.StringUtils; - -/** - * 类型转换器 - * - * @author ruoyi - */ -public class Convert -{ - /** - * 转换为字符串
- * 如果给定的值为null,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static String toStr(Object value, String defaultValue) - { - if (null == value) - { - return defaultValue; - } - if (value instanceof String) - { - return (String) value; - } - return value.toString(); - } - - /** - * 转换为字符串
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static String toStr(Object value) - { - return toStr(value, null); - } - - /** - * 转换为字符
- * 如果给定的值为null,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Character toChar(Object value, Character defaultValue) - { - if (null == value) - { - return defaultValue; - } - if (value instanceof Character) - { - return (Character) value; - } - - final String valueStr = toStr(value, null); - return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); - } - - /** - * 转换为字符
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Character toChar(Object value) - { - return toChar(value, null); - } - - /** - * 转换为byte
- * 如果给定的值为null,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Byte toByte(Object value, Byte defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Byte) - { - return (Byte) value; - } - if (value instanceof Number) - { - return ((Number) value).byteValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return Byte.parseByte(valueStr); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为byte
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Byte toByte(Object value) - { - return toByte(value, null); - } - - /** - * 转换为Short
- * 如果给定的值为null,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Short toShort(Object value, Short defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Short) - { - return (Short) value; - } - if (value instanceof Number) - { - return ((Number) value).shortValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return Short.parseShort(valueStr.trim()); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为Short
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Short toShort(Object value) - { - return toShort(value, null); - } - - /** - * 转换为Number
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Number toNumber(Object value, Number defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Number) - { - return (Number) value; - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return NumberFormat.getInstance().parse(valueStr); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为Number
- * 如果给定的值为空,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Number toNumber(Object value) - { - return toNumber(value, null); - } - - /** - * 转换为int
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Integer toInt(Object value, Integer defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Integer) - { - return (Integer) value; - } - if (value instanceof Number) - { - return ((Number) value).intValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return Integer.parseInt(valueStr.trim()); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为int
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Integer toInt(Object value) - { - return toInt(value, null); - } - - /** - * 转换为Integer数组
- * - * @param str 被转换的值 - * @return 结果 - */ - public static Integer[] toIntArray(String str) - { - return toIntArray(",", str); - } - - /** - * 转换为Long数组
- * - * @param str 被转换的值 - * @return 结果 - */ - public static Long[] toLongArray(String str) - { - return toLongArray(",", str); - } - - /** - * 转换为Integer数组
- * - * @param split 分隔符 - * @param split 被转换的值 - * @return 结果 - */ - public static Integer[] toIntArray(String split, String str) - { - if (StringUtils.isEmpty(str)) - { - return new Integer[] {}; - } - String[] arr = str.split(split); - final Integer[] ints = new Integer[arr.length]; - for (int i = 0; i < arr.length; i++) - { - final Integer v = toInt(arr[i], 0); - ints[i] = v; - } - return ints; - } - - /** - * 转换为Long数组
- * - * @param split 分隔符 - * @param str 被转换的值 - * @return 结果 - */ - public static Long[] toLongArray(String split, String str) - { - if (StringUtils.isEmpty(str)) - { - return new Long[] {}; - } - String[] arr = str.split(split); - final Long[] longs = new Long[arr.length]; - for (int i = 0; i < arr.length; i++) - { - final Long v = toLong(arr[i], null); - longs[i] = v; - } - return longs; - } - - /** - * 转换为String数组
- * - * @param str 被转换的值 - * @return 结果 - */ - public static String[] toStrArray(String str) - { - return toStrArray(",", str); - } - - /** - * 转换为String数组
- * - * @param split 分隔符 - * @param split 被转换的值 - * @return 结果 - */ - public static String[] toStrArray(String split, String str) - { - return str.split(split); - } - - /** - * 转换为long
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Long toLong(Object value, Long defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Long) - { - return (Long) value; - } - if (value instanceof Number) - { - return ((Number) value).longValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - // 支持科学计数法 - return new BigDecimal(valueStr.trim()).longValue(); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为long
- * 如果给定的值为null,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Long toLong(Object value) - { - return toLong(value, null); - } - - /** - * 转换为double
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Double toDouble(Object value, Double defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Double) - { - return (Double) value; - } - if (value instanceof Number) - { - return ((Number) value).doubleValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - // 支持科学计数法 - return new BigDecimal(valueStr.trim()).doubleValue(); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为double
- * 如果给定的值为空,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Double toDouble(Object value) - { - return toDouble(value, null); - } - - /** - * 转换为Float
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Float toFloat(Object value, Float defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Float) - { - return (Float) value; - } - if (value instanceof Number) - { - return ((Number) value).floatValue(); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return Float.parseFloat(valueStr.trim()); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为Float
- * 如果给定的值为空,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Float toFloat(Object value) - { - return toFloat(value, null); - } - - /** - * 转换为boolean
- * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static Boolean toBool(Object value, Boolean defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof Boolean) - { - return (Boolean) value; - } - String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - valueStr = valueStr.trim().toLowerCase(); - switch (valueStr) - { - case "true": - return true; - case "false": - return false; - case "yes": - return true; - case "ok": - return true; - case "no": - return false; - case "1": - return true; - case "0": - return false; - default: - return defaultValue; - } - } - - /** - * 转换为boolean
- * 如果给定的值为空,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static Boolean toBool(Object value) - { - return toBool(value, null); - } - - /** - * 转换为Enum对象
- * 如果给定的值为空,或者转换失败,返回默认值
- * - * @param clazz Enum的Class - * @param value 值 - * @param defaultValue 默认值 - * @return Enum - */ - public static > E toEnum(Class clazz, Object value, E defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (clazz.isAssignableFrom(value.getClass())) - { - @SuppressWarnings("unchecked") - E myE = (E) value; - return myE; - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return Enum.valueOf(clazz, valueStr); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为Enum对象
- * 如果给定的值为空,或者转换失败,返回默认值null
- * - * @param clazz Enum的Class - * @param value 值 - * @return Enum - */ - public static > E toEnum(Class clazz, Object value) - { - return toEnum(clazz, value, null); - } - - /** - * 转换为BigInteger
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static BigInteger toBigInteger(Object value, BigInteger defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof BigInteger) - { - return (BigInteger) value; - } - if (value instanceof Long) - { - return BigInteger.valueOf((Long) value); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return new BigInteger(valueStr); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为BigInteger
- * 如果给定的值为空,或者转换失败,返回默认值null
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static BigInteger toBigInteger(Object value) - { - return toBigInteger(value, null); - } - - /** - * 转换为BigDecimal
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @param defaultValue 转换错误时的默认值 - * @return 结果 - */ - public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) - { - if (value == null) - { - return defaultValue; - } - if (value instanceof BigDecimal) - { - return (BigDecimal) value; - } - if (value instanceof Long) - { - return new BigDecimal((Long) value); - } - if (value instanceof Double) - { - return new BigDecimal((Double) value); - } - if (value instanceof Integer) - { - return new BigDecimal((Integer) value); - } - final String valueStr = toStr(value, null); - if (StringUtils.isEmpty(valueStr)) - { - return defaultValue; - } - try - { - return new BigDecimal(valueStr); - } - catch (Exception e) - { - return defaultValue; - } - } - - /** - * 转换为BigDecimal
- * 如果给定的值为空,或者转换失败,返回默认值
- * 转换失败不会报错 - * - * @param value 被转换的值 - * @return 结果 - */ - public static BigDecimal toBigDecimal(Object value) - { - return toBigDecimal(value, null); - } - - /** - * 将对象转为字符串
- * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * - * @param obj 对象 - * @return 字符串 - */ - public static String utf8Str(Object obj) - { - return str(obj, CharsetKit.CHARSET_UTF_8); - } - - /** - * 将对象转为字符串
- * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * - * @param obj 对象 - * @param charsetName 字符集 - * @return 字符串 - */ - public static String str(Object obj, String charsetName) - { - return str(obj, Charset.forName(charsetName)); - } - - /** - * 将对象转为字符串
- * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * - * @param obj 对象 - * @param charset 字符集 - * @return 字符串 - */ - public static String str(Object obj, Charset charset) - { - if (null == obj) - { - return null; - } - - if (obj instanceof String) - { - return (String) obj; - } - else if (obj instanceof byte[] || obj instanceof Byte[]) - { - return str((Byte[]) obj, charset); - } - else if (obj instanceof ByteBuffer) - { - return str((ByteBuffer) obj, charset); - } - return obj.toString(); - } - - /** - * 将byte数组转为字符串 - * - * @param bytes byte数组 - * @param charset 字符集 - * @return 字符串 - */ - public static String str(byte[] bytes, String charset) - { - return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset)); - } - - /** - * 解码字节码 - * - * @param data 字符串 - * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 - * @return 解码后的字符串 - */ - public static String str(byte[] data, Charset charset) - { - if (data == null) - { - return null; - } - - if (null == charset) - { - return new String(data); - } - return new String(data, charset); - } - - /** - * 将编码的byteBuffer数据转换为字符串 - * - * @param data 数据 - * @param charset 字符集,如果为空使用当前系统字符集 - * @return 字符串 - */ - public static String str(ByteBuffer data, String charset) - { - if (data == null) - { - return null; - } - - return str(data, Charset.forName(charset)); - } - - /** - * 将编码的byteBuffer数据转换为字符串 - * - * @param data 数据 - * @param charset 字符集,如果为空使用当前系统字符集 - * @return 字符串 - */ - public static String str(ByteBuffer data, Charset charset) - { - if (null == charset) - { - charset = Charset.defaultCharset(); - } - return charset.decode(data).toString(); - } - - // ----------------------------------------------------------------------- 全角半角转换 - /** - * 半角转全角 - * - * @param input String. - * @return 全角字符串. - */ - public static String toSBC(String input) - { - return toSBC(input, null); - } - - /** - * 半角转全角 - * - * @param input String - * @param notConvertSet 不替换的字符集合 - * @return 全角字符串. - */ - public static String toSBC(String input, Set notConvertSet) - { - char c[] = input.toCharArray(); - for (int i = 0; i < c.length; i++) - { - if (null != notConvertSet && notConvertSet.contains(c[i])) - { - // 跳过不替换的字符 - continue; - } - - if (c[i] == ' ') - { - c[i] = '\u3000'; - } - else if (c[i] < '\177') - { - c[i] = (char) (c[i] + 65248); - - } - } - return new String(c); - } - - /** - * 全角转半角 - * - * @param input String. - * @return 半角字符串 - */ - public static String toDBC(String input) - { - return toDBC(input, null); - } - - /** - * 替换全角为半角 - * - * @param text 文本 - * @param notConvertSet 不替换的字符集合 - * @return 替换后的字符 - */ - public static String toDBC(String text, Set notConvertSet) - { - char c[] = text.toCharArray(); - for (int i = 0; i < c.length; i++) - { - if (null != notConvertSet && notConvertSet.contains(c[i])) - { - // 跳过不替换的字符 - continue; - } - - if (c[i] == '\u3000') - { - c[i] = ' '; - } - else if (c[i] > '\uFF00' && c[i] < '\uFF5F') - { - c[i] = (char) (c[i] - 65248); - } - } - String returnString = new String(c); - - return returnString; - } - - /** - * 数字金额大写转换 先写个完整的然后将如零拾替换成零 - * - * @param n 数字 - * @return 中文大写数字 - */ - public static String digitUppercase(double n) - { - String[] fraction = { "角", "分" }; - String[] digit = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; - String[][] unit = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } }; - - String head = n < 0 ? "负" : ""; - n = Math.abs(n); - - String s = ""; - for (int i = 0; i < fraction.length; i++) - { - s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); - } - if (s.length() < 1) - { - s = "整"; - } - int integerPart = (int) Math.floor(n); - - for (int i = 0; i < unit[0].length && integerPart > 0; i++) - { - String p = ""; - for (int j = 0; j < unit[1].length && n > 0; j++) - { - p = digit[integerPart % 10] + unit[1][j] + p; - integerPart = integerPart / 10; - } - s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; - } - return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); - } -} +package com.ruoyi.common.core.text; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.text.NumberFormat; +import java.util.Set; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 类型转换器 + * + * @author ruoyi + */ +public class Convert { + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static String toStr(Object value, String defaultValue) { + if (null == value) { + return defaultValue; + } + if (value instanceof String) { + return (String) value; + } + return value.toString(); + } + + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static String toStr(Object value) { + return toStr(value, null); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Character toChar(Object value, Character defaultValue) { + if (null == value) { + return defaultValue; + } + if (value instanceof Character) { + return (Character) value; + } + + final String valueStr = toStr(value, null); + return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Character toChar(Object value) { + return toChar(value, null); + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Byte toByte(Object value, Byte defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Byte) { + return (Byte) value; + } + if (value instanceof Number) { + return ((Number) value).byteValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Byte.parseByte(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Byte toByte(Object value) { + return toByte(value, null); + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Short toShort(Object value, Short defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Short) { + return (Short) value; + } + if (value instanceof Number) { + return ((Number) value).shortValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Short.parseShort(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Short toShort(Object value) { + return toShort(value, null); + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Number toNumber(Object value, Number defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Number) { + return (Number) value; + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return NumberFormat.getInstance().parse(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Number toNumber(Object value) { + return toNumber(value, null); + } + + /** + * 转换为int
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Integer toInt(Object value, Integer defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof Number) { + return ((Number) value).intValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Integer.parseInt(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为int
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Integer toInt(Object value) { + return toInt(value, null); + } + + /** + * 转换为Integer数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String str) { + return toIntArray(",", str); + } + + /** + * 转换为Long数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String str) { + return toLongArray(",", str); + } + + /** + * 转换为Integer数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String split, String str) { + if (StringUtils.isEmpty(str)) { + return new Integer[]{}; + } + String[] arr = str.split(split); + final Integer[] ints = new Integer[arr.length]; + for (int i = 0; i < arr.length; i++) { + final Integer v = toInt(arr[i], 0); + ints[i] = v; + } + return ints; + } + + /** + * 转换为Long数组
+ * + * @param split 分隔符 + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String split, String str) { + if (StringUtils.isEmpty(str)) { + return new Long[]{}; + } + String[] arr = str.split(split); + final Long[] longs = new Long[arr.length]; + for (int i = 0; i < arr.length; i++) { + final Long v = toLong(arr[i], null); + longs[i] = v; + } + return longs; + } + + /** + * 转换为String数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String str) { + return toStrArray(",", str); + } + + /** + * 转换为String数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String split, String str) { + return str.split(split); + } + + /** + * 转换为long
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Long toLong(Object value, Long defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Number) { + return ((Number) value).longValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).longValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为long
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Long toLong(Object value) { + return toLong(value, null); + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Double toDouble(Object value, Double defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Double) { + return (Double) value; + } + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Double toDouble(Object value) { + return toDouble(value, null); + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Float toFloat(Object value, Float defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Float) { + return (Float) value; + } + if (value instanceof Number) { + return ((Number) value).floatValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Float.parseFloat(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Float toFloat(Object value) { + return toFloat(value, null); + } + + /** + * 转换为boolean
+ * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Boolean toBool(Object value, Boolean defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Boolean) { + return (Boolean) value; + } + String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + valueStr = valueStr.trim().toLowerCase(); + switch (valueStr) { + case "true": + return true; + case "false": + return false; + case "yes": + return true; + case "ok": + return true; + case "no": + return false; + case "1": + return true; + case "0": + return false; + default: + return defaultValue; + } + } + + /** + * 转换为boolean
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Boolean toBool(Object value) { + return toBool(value, null); + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * + * @param clazz Enum的Class + * @param value 值 + * @param defaultValue 默认值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value, E defaultValue) { + if (value == null) { + return defaultValue; + } + if (clazz.isAssignableFrom(value.getClass())) { + @SuppressWarnings("unchecked") + E myE = (E) value; + return myE; + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Enum.valueOf(clazz, valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * + * @param clazz Enum的Class + * @param value 值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value) { + return toEnum(clazz, value, null); + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value, BigInteger defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof BigInteger) { + return (BigInteger) value; + } + if (value instanceof Long) { + return BigInteger.valueOf((Long) value); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return new BigInteger(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value) { + return toBigInteger(value, null); + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof BigDecimal) { + return (BigDecimal) value; + } + if (value instanceof Long) { + return new BigDecimal((Long) value); + } + if (value instanceof Double) { + return new BigDecimal((Double) value); + } + if (value instanceof Integer) { + return new BigDecimal((Integer) value); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return new BigDecimal(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value) { + return toBigDecimal(value, null); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @return 字符串 + */ + public static String utf8Str(Object obj) { + return str(obj, CharsetKit.CHARSET_UTF_8); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charsetName 字符集 + * @return 字符串 + */ + public static String str(Object obj, String charsetName) { + return str(obj, Charset.forName(charsetName)); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(Object obj, Charset charset) { + if (null == obj) { + return null; + } + + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof byte[] || obj instanceof Byte[]) { + return str((Byte[]) obj, charset); + } else if (obj instanceof ByteBuffer) { + return str((ByteBuffer) obj, charset); + } + return obj.toString(); + } + + /** + * 将byte数组转为字符串 + * + * @param bytes byte数组 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(byte[] bytes, String charset) { + return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset)); + } + + /** + * 解码字节码 + * + * @param data 字符串 + * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @return 解码后的字符串 + */ + public static String str(byte[] data, Charset charset) { + if (data == null) { + return null; + } + + if (null == charset) { + return new String(data); + } + return new String(data, charset); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, String charset) { + if (data == null) { + return null; + } + + return str(data, Charset.forName(charset)); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, Charset charset) { + if (null == charset) { + charset = Charset.defaultCharset(); + } + return charset.decode(data).toString(); + } + + // ----------------------------------------------------------------------- 全角半角转换 + + /** + * 半角转全角 + * + * @param input String. + * @return 全角字符串. + */ + public static String toSBC(String input) { + return toSBC(input, null); + } + + /** + * 半角转全角 + * + * @param input String + * @param notConvertSet 不替换的字符集合 + * @return 全角字符串. + */ + public static String toSBC(String input, Set notConvertSet) { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == ' ') { + c[i] = '\u3000'; + } else if (c[i] < '\177') { + c[i] = (char) (c[i] + 65248); + + } + } + return new String(c); + } + + /** + * 全角转半角 + * + * @param input String. + * @return 半角字符串 + */ + public static String toDBC(String input) { + return toDBC(input, null); + } + + /** + * 替换全角为半角 + * + * @param text 文本 + * @param notConvertSet 不替换的字符集合 + * @return 替换后的字符 + */ + public static String toDBC(String text, Set notConvertSet) { + char c[] = text.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == '\u3000') { + c[i] = ' '; + } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + + return returnString; + } + + /** + * 数字金额大写转换 先写个完整的然后将如零拾替换成零 + * + * @param n 数字 + * @return 中文大写数字 + */ + public static String digitUppercase(double n) { + String[] fraction = {"角", "分"}; + String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; + String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}}; + + String head = n < 0 ? "负" : ""; + n = Math.abs(n); + + String s = ""; + for (int i = 0; i < fraction.length; i++) { + s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); + } + if (s.length() < 1) { + s = "整"; + } + int integerPart = (int) Math.floor(n); + + for (int i = 0; i < unit[0].length && integerPart > 0; i++) { + String p = ""; + for (int j = 0; j < unit[1].length && n > 0; j++) { + p = digit[integerPart % 10] + unit[1][j] + p; + integerPart = integerPart / 10; + } + s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; + } + return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/StrFormatter.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/StrFormatter.java index dbf3e2375..eec64f994 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/text/StrFormatter.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/text/StrFormatter.java @@ -1,92 +1,76 @@ -package com.ruoyi.common.core.text; - -import com.ruoyi.common.utils.StringUtils; - -/** - * 字符串格式化 - * - * @author ruoyi - */ -public class StrFormatter -{ - public static final String EMPTY_JSON = "{}"; - public static final char C_BACKSLASH = '\\'; - public static final char C_DELIM_START = '{'; - public static final char C_DELIM_END = '}'; - - /** - * 格式化字符串
- * 此方法只是简单将占位符 {} 按照顺序替换为参数
- * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
- * 例:
- * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
- * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
- * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
- * - * @param strPattern 字符串模板 - * @param argArray 参数列表 - * @return 结果 - */ - public static String format(final String strPattern, final Object... argArray) - { - if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) - { - return strPattern; - } - final int strPatternLength = strPattern.length(); - - // 初始化定义好的长度以获得更好的性能 - StringBuilder sbuf = new StringBuilder(strPatternLength + 50); - - int handledPosition = 0; - int delimIndex;// 占位符所在位置 - for (int argIndex = 0; argIndex < argArray.length; argIndex++) - { - delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); - if (delimIndex == -1) - { - if (handledPosition == 0) - { - return strPattern; - } - else - { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 - sbuf.append(strPattern, handledPosition, strPatternLength); - return sbuf.toString(); - } - } - else - { - if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) - { - if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) - { - // 转义符之前还有一个转义符,占位符依旧有效 - sbuf.append(strPattern, handledPosition, delimIndex - 1); - sbuf.append(Convert.utf8Str(argArray[argIndex])); - handledPosition = delimIndex + 2; - } - else - { - // 占位符被转义 - argIndex--; - sbuf.append(strPattern, handledPosition, delimIndex - 1); - sbuf.append(C_DELIM_START); - handledPosition = delimIndex + 1; - } - } - else - { - // 正常占位符 - sbuf.append(strPattern, handledPosition, delimIndex); - sbuf.append(Convert.utf8Str(argArray[argIndex])); - handledPosition = delimIndex + 2; - } - } - } - // 加入最后一个占位符后所有的字符 - sbuf.append(strPattern, handledPosition, strPattern.length()); - - return sbuf.toString(); - } -} +package com.ruoyi.common.core.text; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 字符串格式化 + * + * @author ruoyi + */ +public class StrFormatter { + public static final String EMPTY_JSON = "{}"; + public static final char C_BACKSLASH = '\\'; + public static final char C_DELIM_START = '{'; + public static final char C_DELIM_END = '}'; + + /** + * 格式化字符串
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param strPattern 字符串模板 + * @param argArray 参数列表 + * @return 结果 + */ + public static String format(final String strPattern, final Object... argArray) { + if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) { + return strPattern; + } + final int strPatternLength = strPattern.length(); + + // 初始化定义好的长度以获得更好的性能 + StringBuilder sbuf = new StringBuilder(strPatternLength + 50); + + int handledPosition = 0; + int delimIndex;// 占位符所在位置 + for (int argIndex = 0; argIndex < argArray.length; argIndex++) { + delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); + if (delimIndex == -1) { + if (handledPosition == 0) { + return strPattern; + } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 + sbuf.append(strPattern, handledPosition, strPatternLength); + return sbuf.toString(); + } + } else { + if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) { + if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) { + // 转义符之前还有一个转义符,占位符依旧有效 + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } else { + // 占位符被转义 + argIndex--; + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(C_DELIM_START); + handledPosition = delimIndex + 1; + } + } else { + // 正常占位符 + sbuf.append(strPattern, handledPosition, delimIndex); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } + } + } + // 加入最后一个占位符后所有的字符 + sbuf.append(strPattern, handledPosition, strPattern.length()); + + return sbuf.toString(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessStatus.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessStatus.java index 43612e5d7..ce32cb41c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessStatus.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessStatus.java @@ -1,19 +1,18 @@ -package com.ruoyi.common.enums; - -/** - * 操作状态 - * - * @author ruoyi - */ -public enum BusinessStatus -{ - /** - * 成功 - */ - SUCCESS, - - /** - * 失败 - */ - FAIL, -} +package com.ruoyi.common.enums; + +/** + * 操作状态 + * + * @author ruoyi + */ +public enum BusinessStatus { + /** + * 成功 + */ + SUCCESS, + + /** + * 失败 + */ + FAIL, +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessType.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessType.java index d22bccbd3..b344ad6ea 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessType.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/BusinessType.java @@ -1,59 +1,58 @@ -package com.ruoyi.common.enums; - -/** - * 业务操作类型 - * - * @author ruoyi - */ -public enum BusinessType -{ - /** - * 其它 - */ - OTHER, - - /** - * 新增 - */ - INSERT, - - /** - * 修改 - */ - UPDATE, - - /** - * 删除 - */ - DELETE, - - /** - * 授权 - */ - GRANT, - - /** - * 导出 - */ - EXPORT, - - /** - * 导入 - */ - IMPORT, - - /** - * 强退 - */ - FORCE, - - /** - * 生成代码 - */ - GENCODE, - - /** - * 清空 - */ - CLEAN, -} +package com.ruoyi.common.enums; + +/** + * 业务操作类型 + * + * @author ruoyi + */ +public enum BusinessType { + /** + * 其它 + */ + OTHER, + + /** + * 新增 + */ + INSERT, + + /** + * 修改 + */ + UPDATE, + + /** + * 删除 + */ + DELETE, + + /** + * 授权 + */ + GRANT, + + /** + * 导出 + */ + EXPORT, + + /** + * 导入 + */ + IMPORT, + + /** + * 强退 + */ + FORCE, + + /** + * 生成代码 + */ + GENCODE, + + /** + * 清空 + */ + CLEAN, +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/DataSourceType.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/DataSourceType.java index 4b5341d19..e9ed99af3 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/DataSourceType.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/DataSourceType.java @@ -1,19 +1,18 @@ -package com.ruoyi.common.enums; - -/** - * 数据源 - * - * @author ruoyi - */ -public enum DataSourceType -{ - /** - * 主库 - */ - MASTER, - - /** - * 从库 - */ - SLAVE -} +package com.ruoyi.common.enums; + +/** + * 数据源 + * + * @author ruoyi + */ +public enum DataSourceType { + /** + * 主库 + */ + MASTER, + + /** + * 从库 + */ + SLAVE +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/OnlineStatus.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/OnlineStatus.java index b0bdd1003..a79eb9e03 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/OnlineStatus.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/OnlineStatus.java @@ -1,24 +1,23 @@ -package com.ruoyi.common.enums; - -/** - * 用户会话 - * - * @author ruoyi - */ -public enum OnlineStatus -{ - /** 用户状态 */ - on_line("在线"), off_line("离线"); - - private final String info; - - private OnlineStatus(String info) - { - this.info = info; - } - - public String getInfo() - { - return info; - } -} +package com.ruoyi.common.enums; + +/** + * 用户会话 + * + * @author ruoyi + */ +public enum OnlineStatus { + /** + * 用户状态 + */ + on_line("在线"), off_line("离线"); + + private final String info; + + private OnlineStatus(String info) { + this.info = info; + } + + public String getInfo() { + return info; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/OperatorType.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/OperatorType.java index 06532af8f..3c4127d98 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/OperatorType.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/OperatorType.java @@ -1,24 +1,23 @@ -package com.ruoyi.common.enums; - -/** - * 操作人类别 - * - * @author ruoyi - */ -public enum OperatorType -{ - /** - * 其它 - */ - OTHER, - - /** - * 后台用户 - */ - MANAGE, - - /** - * 手机端用户 - */ - MOBILE -} +package com.ruoyi.common.enums; + +/** + * 操作人类别 + * + * @author ruoyi + */ +public enum OperatorType { + /** + * 其它 + */ + OTHER, + + /** + * 后台用户 + */ + MANAGE, + + /** + * 手机端用户 + */ + MOBILE +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/UserStatus.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/UserStatus.java index a4613ff9c..673ddebd2 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/enums/UserStatus.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/UserStatus.java @@ -1,30 +1,26 @@ -package com.ruoyi.common.enums; - -/** - * 用户状态 - * - * @author ruoyi - */ -public enum UserStatus -{ - OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); - - private final String code; - private final String info; - - UserStatus(String code, String info) - { - this.code = code; - this.info = info; - } - - public String getCode() - { - return code; - } - - public String getInfo() - { - return info; - } -} +package com.ruoyi.common.enums; + +/** + * 用户状态 + * + * @author ruoyi + */ +public enum UserStatus { + OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); + + private final String code; + private final String info; + + UserStatus(String code, String info) { + this.code = code; + this.info = info; + } + + public String getCode() { + return code; + } + + public String getInfo() { + return info; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/BusinessException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/BusinessException.java index d490675e7..8eecc0707 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/BusinessException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/BusinessException.java @@ -2,29 +2,25 @@ package com.ruoyi.common.exception; /** * 业务异常 - * + * * @author ruoyi */ -public class BusinessException extends RuntimeException -{ +public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; protected final String message; - public BusinessException(String message) - { + public BusinessException(String message) { this.message = message; } - public BusinessException(String message, Throwable e) - { + public BusinessException(String message, Throwable e) { super(message, e); this.message = message; } @Override - public String getMessage() - { + public String getMessage() { return message; } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/DemoModeException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/DemoModeException.java index 57bffc47b..9178131d7 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/DemoModeException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/DemoModeException.java @@ -1,15 +1,13 @@ -package com.ruoyi.common.exception; - -/** - * 演示模式异常 - * - * @author ruoyi - */ -public class DemoModeException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public DemoModeException() - { - } -} +package com.ruoyi.common.exception; + +/** + * 演示模式异常 + * + * @author ruoyi + */ +public class DemoModeException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public DemoModeException() { + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/base/BaseException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/base/BaseException.java index 3dd2c1ee7..c4ff125d0 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/base/BaseException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/base/BaseException.java @@ -1,97 +1,84 @@ -package com.ruoyi.common.exception.base; - -import com.ruoyi.common.utils.MessageUtils; -import com.ruoyi.common.utils.StringUtils; - -/** - * 基础异常 - * - * @author ruoyi - */ -public class BaseException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - /** - * 所属模块 - */ - private String module; - - /** - * 错误码 - */ - private String code; - - /** - * 错误码对应的参数 - */ - private Object[] args; - - /** - * 错误消息 - */ - private String defaultMessage; - - public BaseException(String module, String code, Object[] args, String defaultMessage) - { - this.module = module; - this.code = code; - this.args = args; - this.defaultMessage = defaultMessage; - } - - public BaseException(String module, String code, Object[] args) - { - this(module, code, args, null); - } - - public BaseException(String module, String defaultMessage) - { - this(module, null, null, defaultMessage); - } - - public BaseException(String code, Object[] args) - { - this(null, code, args, null); - } - - public BaseException(String defaultMessage) - { - this(null, null, null, defaultMessage); - } - - @Override - public String getMessage() - { - String message = null; - if (!StringUtils.isEmpty(code)) - { - message = MessageUtils.message(code, args); - } - if (message == null) - { - message = defaultMessage; - } - return message; - } - - public String getModule() - { - return module; - } - - public String getCode() - { - return code; - } - - public Object[] getArgs() - { - return args; - } - - public String getDefaultMessage() - { - return defaultMessage; - } -} +package com.ruoyi.common.exception.base; + +import com.ruoyi.common.utils.MessageUtils; +import com.ruoyi.common.utils.StringUtils; + +/** + * 基础异常 + * + * @author ruoyi + */ +public class BaseException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * 所属模块 + */ + private String module; + + /** + * 错误码 + */ + private String code; + + /** + * 错误码对应的参数 + */ + private Object[] args; + + /** + * 错误消息 + */ + private String defaultMessage; + + public BaseException(String module, String code, Object[] args, String defaultMessage) { + this.module = module; + this.code = code; + this.args = args; + this.defaultMessage = defaultMessage; + } + + public BaseException(String module, String code, Object[] args) { + this(module, code, args, null); + } + + public BaseException(String module, String defaultMessage) { + this(module, null, null, defaultMessage); + } + + public BaseException(String code, Object[] args) { + this(null, code, args, null); + } + + public BaseException(String defaultMessage) { + this(null, null, null, defaultMessage); + } + + @Override + public String getMessage() { + String message = null; + if (!StringUtils.isEmpty(code)) { + message = MessageUtils.message(code, args); + } + if (message == null) { + message = defaultMessage; + } + return message; + } + + public String getModule() { + return module; + } + + public String getCode() { + return code; + } + + public Object[] getArgs() { + return args; + } + + public String getDefaultMessage() { + return defaultMessage; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileException.java index 871f09b52..794f4e1a7 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileException.java @@ -4,15 +4,13 @@ import com.ruoyi.common.exception.base.BaseException; /** * 文件信息异常类 - * + * * @author ruoyi */ -public class FileException extends BaseException -{ +public class FileException extends BaseException { private static final long serialVersionUID = 1L; - public FileException(String code, Object[] args) - { + public FileException(String code, Object[] args) { super("file", code, args, null); } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileNameLengthLimitExceededException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileNameLengthLimitExceededException.java index 44941b8bc..64a5020d0 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileNameLengthLimitExceededException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileNameLengthLimitExceededException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.file; - -/** - * 文件名称超长限制异常类 - * - * @author ruoyi - */ -public class FileNameLengthLimitExceededException extends FileException -{ - private static final long serialVersionUID = 1L; - - public FileNameLengthLimitExceededException(int defaultFileNameLength) - { - super("upload.filename.exceed.length", new Object[] { defaultFileNameLength }); - } -} +package com.ruoyi.common.exception.file; + +/** + * 文件名称超长限制异常类 + * + * @author ruoyi + */ +public class FileNameLengthLimitExceededException extends FileException { + private static final long serialVersionUID = 1L; + + public FileNameLengthLimitExceededException(int defaultFileNameLength) { + super("upload.filename.exceed.length", new Object[]{defaultFileNameLength}); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileSizeLimitExceededException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileSizeLimitExceededException.java index ec6ab054d..93e9e1c60 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileSizeLimitExceededException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileSizeLimitExceededException.java @@ -2,15 +2,13 @@ package com.ruoyi.common.exception.file; /** * 文件名大小限制异常类 - * + * * @author ruoyi */ -public class FileSizeLimitExceededException extends FileException -{ +public class FileSizeLimitExceededException extends FileException { private static final long serialVersionUID = 1L; - public FileSizeLimitExceededException(long defaultMaxSize) - { - super("upload.exceed.maxSize", new Object[] { defaultMaxSize }); + public FileSizeLimitExceededException(long defaultMaxSize) { + super("upload.exceed.maxSize", new Object[]{defaultMaxSize}); } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/InvalidExtensionException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/InvalidExtensionException.java index 81cd78b81..ce5c7fdaf 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/InvalidExtensionException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/InvalidExtensionException.java @@ -1,71 +1,61 @@ -package com.ruoyi.common.exception.file; - -import java.util.Arrays; -import org.apache.commons.fileupload.FileUploadException; - -/** - * 文件上传 误异常类 - * - * @author ruoyi - */ -public class InvalidExtensionException extends FileUploadException -{ - private static final long serialVersionUID = 1L; - - private String[] allowedExtension; - private String extension; - private String filename; - - public InvalidExtensionException(String[] allowedExtension, String extension, String filename) - { - super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); - this.allowedExtension = allowedExtension; - this.extension = extension; - this.filename = filename; - } - - public String[] getAllowedExtension() - { - return allowedExtension; - } - - public String getExtension() - { - return extension; - } - - public String getFilename() - { - return filename; - } - - public static class InvalidImageExtensionException extends InvalidExtensionException - { - private static final long serialVersionUID = 1L; - - public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) - { - super(allowedExtension, extension, filename); - } - } - - public static class InvalidFlashExtensionException extends InvalidExtensionException - { - private static final long serialVersionUID = 1L; - - public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) - { - super(allowedExtension, extension, filename); - } - } - - public static class InvalidMediaExtensionException extends InvalidExtensionException - { - private static final long serialVersionUID = 1L; - - public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) - { - super(allowedExtension, extension, filename); - } - } -} +package com.ruoyi.common.exception.file; + +import java.util.Arrays; + +import org.apache.commons.fileupload.FileUploadException; + +/** + * 文件上传 误异常类 + * + * @author ruoyi + */ +public class InvalidExtensionException extends FileUploadException { + private static final long serialVersionUID = 1L; + + private String[] allowedExtension; + private String extension; + private String filename; + + public InvalidExtensionException(String[] allowedExtension, String extension, String filename) { + super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); + this.allowedExtension = allowedExtension; + this.extension = extension; + this.filename = filename; + } + + public String[] getAllowedExtension() { + return allowedExtension; + } + + public String getExtension() { + return extension; + } + + public String getFilename() { + return filename; + } + + public static class InvalidImageExtensionException extends InvalidExtensionException { + private static final long serialVersionUID = 1L; + + public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidFlashExtensionException extends InvalidExtensionException { + private static final long serialVersionUID = 1L; + + public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidMediaExtensionException extends InvalidExtensionException { + private static final long serialVersionUID = 1L; + + public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) { + super(allowedExtension, extension, filename); + } + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/job/TaskException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/job/TaskException.java index 14b2361d0..c9ac31f19 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/job/TaskException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/job/TaskException.java @@ -1,34 +1,29 @@ -package com.ruoyi.common.exception.job; - -/** - * 计划策略异常 - * - * @author ruoyi - */ -public class TaskException extends Exception -{ - private static final long serialVersionUID = 1L; - - private Code code; - - public TaskException(String msg, Code code) - { - this(msg, code, null); - } - - public TaskException(String msg, Code code, Exception nestedEx) - { - super(msg, nestedEx); - this.code = code; - } - - public Code getCode() - { - return code; - } - - public enum Code - { - TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE - } +package com.ruoyi.common.exception.job; + +/** + * 计划策略异常 + * + * @author ruoyi + */ +public class TaskException extends Exception { + private static final long serialVersionUID = 1L; + + private Code code; + + public TaskException(String msg, Code code) { + this(msg, code, null); + } + + public TaskException(String msg, Code code, Exception nestedEx) { + super(msg, nestedEx); + this.code = code; + } + + public Code getCode() { + return code; + } + + public enum Code { + TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/CaptchaException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/CaptchaException.java index e3334ae37..90404854c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/CaptchaException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/CaptchaException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 验证码错误异常类 - * - * @author ruoyi - */ -public class CaptchaException extends UserException -{ - private static final long serialVersionUID = 1L; - - public CaptchaException() - { - super("user.jcaptcha.error", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 验证码错误异常类 + * + * @author ruoyi + */ +public class CaptchaException extends UserException { + private static final long serialVersionUID = 1L; + + public CaptchaException() { + super("user.jcaptcha.error", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/RoleBlockedException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/RoleBlockedException.java index e11624426..e537912e0 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/RoleBlockedException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/RoleBlockedException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 角色锁定异常类 - * - * @author ruoyi - */ -public class RoleBlockedException extends UserException -{ - private static final long serialVersionUID = 1L; - - public RoleBlockedException() - { - super("role.blocked", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 角色锁定异常类 + * + * @author ruoyi + */ +public class RoleBlockedException extends UserException { + private static final long serialVersionUID = 1L; + + public RoleBlockedException() { + super("role.blocked", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserBlockedException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserBlockedException.java index 8feb8493e..edfaf2b65 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserBlockedException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserBlockedException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户锁定异常类 - * - * @author ruoyi - */ -public class UserBlockedException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserBlockedException() - { - super("user.blocked", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户锁定异常类 + * + * @author ruoyi + */ +public class UserBlockedException extends UserException { + private static final long serialVersionUID = 1L; + + public UserBlockedException() { + super("user.blocked", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserDeleteException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserDeleteException.java index cf0724228..7758190e4 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserDeleteException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserDeleteException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户账号已被删除 - * - * @author ruoyi - */ -public class UserDeleteException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserDeleteException() - { - super("user.password.delete", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户账号已被删除 + * + * @author ruoyi + */ +public class UserDeleteException extends UserException { + private static final long serialVersionUID = 1L; + + public UserDeleteException() { + super("user.password.delete", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserException.java index 79160d861..94dbcdd52 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserException.java @@ -1,18 +1,16 @@ -package com.ruoyi.common.exception.user; - -import com.ruoyi.common.exception.base.BaseException; - -/** - * 用户信息异常类 - * - * @author ruoyi - */ -public class UserException extends BaseException -{ - private static final long serialVersionUID = 1L; - - public UserException(String code, Object[] args) - { - super("user", code, args, null); - } -} +package com.ruoyi.common.exception.user; + +import com.ruoyi.common.exception.base.BaseException; + +/** + * 用户信息异常类 + * + * @author ruoyi + */ +public class UserException extends BaseException { + private static final long serialVersionUID = 1L; + + public UserException(String code, Object[] args) { + super("user", code, args, null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserNotExistsException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserNotExistsException.java index ed4bea3ac..9f19b9039 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserNotExistsException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserNotExistsException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户不存在异常类 - * - * @author ruoyi - */ -public class UserNotExistsException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserNotExistsException() - { - super("user.not.exists", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户不存在异常类 + * + * @author ruoyi + */ +public class UserNotExistsException extends UserException { + private static final long serialVersionUID = 1L; + + public UserNotExistsException() { + super("user.not.exists", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordNotMatchException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordNotMatchException.java index 71449e293..0fab11678 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordNotMatchException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordNotMatchException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户密码不正确或不符合规范异常类 - * - * @author ruoyi - */ -public class UserPasswordNotMatchException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserPasswordNotMatchException() - { - super("user.password.not.match", null); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户密码不正确或不符合规范异常类 + * + * @author ruoyi + */ +public class UserPasswordNotMatchException extends UserException { + private static final long serialVersionUID = 1L; + + public UserPasswordNotMatchException() { + super("user.password.not.match", null); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitCountException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitCountException.java index 4222135f5..be3243c79 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitCountException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitCountException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户错误记数异常类 - * - * @author ruoyi - */ -public class UserPasswordRetryLimitCountException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserPasswordRetryLimitCountException(int retryLimitCount) - { - super("user.password.retry.limit.count", new Object[] { retryLimitCount }); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户错误记数异常类 + * + * @author ruoyi + */ +public class UserPasswordRetryLimitCountException extends UserException { + private static final long serialVersionUID = 1L; + + public UserPasswordRetryLimitCountException(int retryLimitCount) { + super("user.password.retry.limit.count", new Object[]{retryLimitCount}); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitExceedException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitExceedException.java index b48c40657..d8412ec9f 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitExceedException.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/user/UserPasswordRetryLimitExceedException.java @@ -1,16 +1,14 @@ -package com.ruoyi.common.exception.user; - -/** - * 用户错误最大次数异常类 - * - * @author ruoyi - */ -public class UserPasswordRetryLimitExceedException extends UserException -{ - private static final long serialVersionUID = 1L; - - public UserPasswordRetryLimitExceedException(int retryLimitCount) - { - super("user.password.retry.limit.exceed", new Object[] { retryLimitCount }); - } -} +package com.ruoyi.common.exception.user; + +/** + * 用户错误最大次数异常类 + * + * @author ruoyi + */ +public class UserPasswordRetryLimitExceedException extends UserException { + private static final long serialVersionUID = 1L; + + public UserPasswordRetryLimitExceedException(int retryLimitCount) { + super("user.password.retry.limit.exceed", new Object[]{retryLimitCount}); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/json/JSON.java b/ruoyi-common/src/main/java/com/ruoyi/common/json/JSON.java index 119147b6a..db4a73da9 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/json/JSON.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/json/JSON.java @@ -1,187 +1,122 @@ -package com.ruoyi.common.json; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -/** - * JSON解析处理 - * - * @author ruoyi - */ -public class JSON -{ - public static final String DEFAULT_FAIL = "\"Parse failed\""; - private static final ObjectMapper objectMapper = new ObjectMapper(); - private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter(); - - public static void marshal(File file, Object value) throws Exception - { - try - { - objectWriter.writeValue(file, value); - } - catch (JsonGenerationException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static void marshal(OutputStream os, Object value) throws Exception - { - try - { - objectWriter.writeValue(os, value); - } - catch (JsonGenerationException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static String marshal(Object value) throws Exception - { - try - { - return objectWriter.writeValueAsString(value); - } - catch (JsonGenerationException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static byte[] marshalBytes(Object value) throws Exception - { - try - { - return objectWriter.writeValueAsBytes(value); - } - catch (JsonGenerationException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static T unmarshal(File file, Class valueType) throws Exception - { - try - { - return objectMapper.readValue(file, valueType); - } - catch (JsonParseException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static T unmarshal(InputStream is, Class valueType) throws Exception - { - try - { - return objectMapper.readValue(is, valueType); - } - catch (JsonParseException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static T unmarshal(String str, Class valueType) throws Exception - { - try - { - return objectMapper.readValue(str, valueType); - } - catch (JsonParseException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } - - public static T unmarshal(byte[] bytes, Class valueType) throws Exception - { - try - { - if (bytes == null) - { - bytes = new byte[0]; - } - return objectMapper.readValue(bytes, 0, bytes.length, valueType); - } - catch (JsonParseException e) - { - throw new Exception(e); - } - catch (JsonMappingException e) - { - throw new Exception(e); - } - catch (IOException e) - { - throw new Exception(e); - } - } -} +package com.ruoyi.common.json; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +/** + * JSON解析处理 + * + * @author ruoyi + */ +public class JSON { + public static final String DEFAULT_FAIL = "\"Parse failed\""; + private static final ObjectMapper objectMapper = new ObjectMapper(); + private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter(); + + public static void marshal(File file, Object value) throws Exception { + try { + objectWriter.writeValue(file, value); + } catch (JsonGenerationException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static void marshal(OutputStream os, Object value) throws Exception { + try { + objectWriter.writeValue(os, value); + } catch (JsonGenerationException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static String marshal(Object value) throws Exception { + try { + return objectWriter.writeValueAsString(value); + } catch (JsonGenerationException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static byte[] marshalBytes(Object value) throws Exception { + try { + return objectWriter.writeValueAsBytes(value); + } catch (JsonGenerationException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static T unmarshal(File file, Class valueType) throws Exception { + try { + return objectMapper.readValue(file, valueType); + } catch (JsonParseException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static T unmarshal(InputStream is, Class valueType) throws Exception { + try { + return objectMapper.readValue(is, valueType); + } catch (JsonParseException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static T unmarshal(String str, Class valueType) throws Exception { + try { + return objectMapper.readValue(str, valueType); + } catch (JsonParseException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } + + public static T unmarshal(byte[] bytes, Class valueType) throws Exception { + try { + if (bytes == null) { + bytes = new byte[0]; + } + return objectMapper.readValue(bytes, 0, bytes.length, valueType); + } catch (JsonParseException e) { + throw new Exception(e); + } catch (JsonMappingException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/json/JSONObject.java b/ruoyi-common/src/main/java/com/ruoyi/common/json/JSONObject.java index 24ef6ccb7..ba09102cf 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/json/JSONObject.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/json/JSONObject.java @@ -1,749 +1,618 @@ -package com.ruoyi.common.json; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.ruoyi.common.utils.StringUtils; - -/** - * 通用消息对象,基于Map实现的可嵌套数据结构。 支持JSON数据结构。 - * - * @author ruoyi - */ -public class JSONObject extends LinkedHashMap -{ - private static final long serialVersionUID = 1L; - private static final Pattern arrayNamePattern = Pattern.compile("(\\w+)((\\[\\d+\\])+)"); - private static final ObjectMapper objectMapper = new ObjectMapper(); - - /** - * 数组结构。 - */ - public static class JSONArray extends ArrayList - { - private static final long serialVersionUID = 1L; - - public JSONArray() - { - super(); - } - - public JSONArray(int size) - { - super(size); - } - - @Override - public String toString() - { - try - { - return JSON.marshal(this); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - @Override - public Object set(int index, Object element) - { - return super.set(index, transfer(element)); - } - - @Override - public boolean add(Object element) - { - return super.add(transfer(element)); - } - - @Override - public void add(int index, Object element) - { - super.add(index, transfer(element)); - } - } - - public JSONObject() - { - super(); - } - - public JSONObject(final JSONObject other) - { - super(other); - } - - @Override - public String toString() - { - try - { - return JSON.marshal(this); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - /** - * 转换为紧凑格式的字符串。 - * - * @return 返回本对象紧凑格式字符串。 - */ - public String toCompactString() - { - try - { - return objectMapper.writeValueAsString(this); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - /** - * 获取指定字段的整数值。如果字段不存在,或者无法转换为整数,返回null。 - * - * @param name 字段名,支持多级。 - * @return 返回指定的整数值,或者null。 - */ - public Integer intValue(final String name) - { - return valueAsInt(value(name)); - } - - /** - * 获取指定字段的整数值。如果字段不存在,或者无法转换为整数,返回defaultValue。 - * - * @param name 字段名,支持多级。 - * @param defaultValue 查询失败时,返回的值。 - * @return 返回指定的整数值,或者defaultValue。 - */ - public Integer intValue(final String name, final Integer defaultValue) - { - return StringUtils.nvl(intValue(name), defaultValue); - } - - /** - * 获取指定字段的长整数值。如果字段不存在,或者无法转换为长整数,返回null。 - * - * @param name 字段名,支持多级。 - * @return 返回指定的长整数值,或者null。 - */ - public Long longValue(final String name) - { - return valueAsLong(value(name)); - } - - /** - * 获取指定字段的长整数值。如果字段不存在,或者无法转换为长整数,返回defaultValue。 - * - * @param name 字段名,支持多级。 - * @param defaultValue 查询失败时,返回的值。 - * @return 返回指定的长整数值,或者defaultValue。 - */ - public Long longValue(final String name, final Long defaultValue) - { - return StringUtils.nvl(longValue(name), defaultValue); - } - - /** - * 获取指定字段的布尔值。如果字段不存在,或者无法转换为布尔型,返回null。 - * - * @param name 字段名,支持多级。 - * @return 返回指定的布尔值,或者null。 - */ - public Boolean boolValue(final String name) - { - return valueAsBool(value(name)); - } - - /** - * 获取指定字段的布尔值。如果字段不存在,或者无法转换为布尔型,返回defaultValue。 - * - * @param name 字段名,支持多级。 - * @param defaultValue 查询失败时,返回的值。 - * @return 返回指定的布尔值,或者defaultValue。 - */ - public Boolean boolValue(final String name, final Boolean defaultValue) - { - return StringUtils.nvl(boolValue(name), defaultValue); - } - - /** - * 获取指定字段的字符串值。如果字段不存在,返回null。 - * - * @param name 字段名,支持多级。 - * @return 返回指定的字符串值,或者null。 - */ - public String strValue(final String name) - { - return valueAsStr(value(name)); - } - - /** - * 获取指定字段的字符串值。如果字段不存在,返回defaultValue。 - * - * @param name 字段名,支持多级。 - * @param defaultValue 查询失败时,返回的值。 - * @return 返回指定的字符串值,或者defaultValue。 - */ - public String strValue(final String name, final String defaultValue) - { - return StringUtils.nvl(strValue(name), defaultValue); - } - - /** - * 获取指定字段的值。 - * - * @param name 字段名,支持多级,支持数组下标。 - * @return 返回指定字段的值。 - */ - public Object value(final String name) - { - final int indexDot = name.indexOf('.'); - if (indexDot >= 0) - { - return obj(name.substring(0, indexDot)).value(name.substring(indexDot + 1)); - } - else - { - final Matcher matcher = arrayNamePattern.matcher(name); - if (matcher.find()) - { - return endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() - { - @Override - public Object callback(JSONArray arr, int index) - { - return elementAt(arr, index); - } - }); - } - else - { - return get(name); - } - } - } - - /** - * 设置指定字段的值。 - * - * @param name 字段名,支持多级,支持数组下标。 - * @param value 字段值。 - * @return 返回本对象。 - */ - public JSONObject value(final String name, final Object value) - { - final int indexDot = name.indexOf('.'); - if (indexDot >= 0) - { - obj(name.substring(0, indexDot)).value(name.substring(indexDot + 1), value); - } - else - { - final Matcher matcher = arrayNamePattern.matcher(name); - if (matcher.find()) - { - endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() - { - @Override - public Void callback(JSONArray arr, int index) - { - elementAt(arr, index, value); - return null; - } - }); - } - else - { - set(name, value); - } - } - return this; - } - - /** - * 获取对象(非标量类型)字段。返回的数据是一个结构体。当不存在指定对象时,则为指定的名字创建一个空的MessageObject对象。 - * - * @param name 字段名。不支持多级名字,支持数组下标。 - * @return 返回指定的对象。如果对象不存在,则为指定的名字创建一个空的MessageObject对象。 - */ - public JSONObject obj(final String name) - { - final Matcher matcher = arrayNamePattern.matcher(name); - if (matcher.find()) - { - return endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() - { - @Override - public JSONObject callback(JSONArray arr, int index) - { - return objAt(arr, index); - } - }); - } - else - { - JSONObject obj = getObj(name); - if (obj == null) - { - obj = new JSONObject(); - put(name, obj); - } - return obj; - } - } - - /** - * 获取数组字段。将名字对应的对象以数组对象返回,当指定的字段不存在时,创建一个空的数组。 - * - * @param name 字段名。不支持多级名字,不支持下标。 - * @return 返回一个数组(List)。 - */ - public JSONArray arr(final String name) - { - JSONArray arr = getArr(name); - if (arr == null) - { - arr = new JSONArray(); - put(name, arr); - } - return arr; - } - - /** - * 获取对象(非标量类型)字段。返回的数据是一个结构体。 - * - * @param name 字段名。 - * @return 返回指定的对象字段。 - */ - public JSONObject getObj(final String name) - { - return (JSONObject) get(name); - } - - /** - * 获取数组类型字段。 - * - * @param name 字段名。 - * @return 返回数组类型字段。 - */ - public JSONArray getArr(final String name) - { - return (JSONArray) get(name); - } - - /** - * 返回字段整数值。如果不存在,返回null。 - * - * @param name 字段名。 - * @return 返回指定字段整数值。 - */ - public Integer getInt(final String name) - { - return valueAsInt(get(name)); - } - - /** - * 返回字段整数值。如果不存在,返回defaultValue。 - * - * @param name 字段名。 - * @param defaultValue 字段不存在时,返回的值。 - * @return 返回指定字段整数值。 - */ - public Integer getInt(final String name, Integer defaultValue) - { - return StringUtils.nvl(getInt(name), defaultValue); - } - - /** - * 返回字段长整数值。如果不存在,返回null。 - * - * @param name 字段名。 - * @return 返回指定字段长整数值。 - */ - public Long getLong(final String name) - { - return valueAsLong(get(name)); - } - - /** - * 返回字段长整数值。如果不存在,返回defaultValue。 - * - * @param name 字段名。 - * @param defaultValue 字段不存在时,返回的值。 - * @return 返回指定字段长整数值。 - */ - public Long getLong(final String name, Long defaultValue) - { - return StringUtils.nvl(getLong(name), defaultValue); - } - - /** - * 返回字段字符串值。如果不存在,返回null。 - * - * @param name 字段名。 - * @return 返回指定字段字符串值。 - */ - public String getStr(final String name) - { - return valueAsStr(get(name)); - } - - /** - * 返回字段字符串值。如果不存在,返回defaultValue。 - * - * @param name 字段名。 - * @param defaultValue 字段不存在时,返回的值。 - * @return 返回指定字段字符串值。 - */ - public String getStr(final String name, final String defaultValue) - { - return StringUtils.nvl(getStr(name), defaultValue); - } - - /** - * 字段值按照布尔类型返回。如果不存在,返回null。 - * - * @param name 字段名。 - * @return 字段值。 - */ - public Boolean getBool(final String name) - { - return valueAsBool(get(name)); - } - - /** - * 字段值按照布尔类型返回。如果不存在,返回defaultValue。 - * - * @param name 字段名。 - * @param defaultValue 字段不存在时,返回的值。 - * @return 字段值。 - */ - public Boolean getBool(final String name, final Boolean defaultValue) - { - return StringUtils.nvl(getBool(name), defaultValue); - } - - /** - * 设置字段值 - * - * @param name 字段名 - * @param value 字段值(标量:数字、字符串、布尔型;结构体:MessageObject)。 如果是Map类型同时非MessageObject类型,则自动转换为MessageObject类型再存入 - * (此时,再修改Map中的数据,将不会体现到本对象中)。 - * @return 返回本对象 - */ - public JSONObject set(final String name, final Object value) - { - put(name, value); - return this; - } - - /** - * 将本对象转换为Java Bean。 - * - * @param beanClass Java Bean的类对象。 - * @return 返回转换后的Java Bean。 - */ - public T asBean(Class beanClass) - { - try - { - return JSON.unmarshal(JSON.marshal(this), beanClass); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - /** - * 重载基类的方法。如果 value 是 Map 类型,但不是 MessageObject 类型,则创建一个包含内容等同于原 Map 的 MessageObject 作为 value(注意:此后再更改 Map 的内容,将不会反映到 - * MessageObject 中)。 重载此方法的目的是为了使JSON能够正确地解析为MessageObject对象。不建议直接调用此方法,请使用 set(name, value)方法设置字段值。 - */ - @Override - public Object put(String key, Object value) - { - return super.put(key, transfer(value)); - } - - public static Integer valueAsInt(Object value) - { - if (value instanceof Integer) - { - return (Integer) value; - } - else if (value instanceof Number) - { - return ((Number) value).intValue(); - } - else if (value instanceof String) - { - return Integer.valueOf((String) value); - } - else if (value instanceof Boolean) - { - return ((Boolean) value) ? 1 : 0; - } - else - { - return null; - } - } - - public static Long valueAsLong(Object value) - { - if (value instanceof Long) - { - return (Long) value; - } - else if (value instanceof Number) - { - return ((Number) value).longValue(); - } - else if (value instanceof String) - { - return Long.valueOf((String) value); - } - else if (value instanceof Boolean) - { - return ((Boolean) value) ? 1L : 0L; - } - else - { - return null; - } - } - - public static String valueAsStr(Object value) - { - if (value instanceof String) - { - return (String) value; - } - else if (value != null) - { - return value.toString(); - } - else - { - return null; - } - } - - public static Boolean valueAsBool(Object value) - { - if (value instanceof Boolean) - { - return (Boolean) value; - } - else if (value instanceof Number) - { - return ((Number) value).doubleValue() != 0.0; - } - else if (value instanceof String) - { - return Boolean.valueOf((String) value); - } - else - { - return null; - } - } - - /** - * 将所有层次中凡是Map类型同时又不是MessageObject的类型,转换为MessageObject类型。 - * - * @param value 值。 - * @return 返回转换后的值。 - */ - @SuppressWarnings("unchecked") - private static Object transfer(final Object value) - { - if (!(value instanceof JSONObject) && value instanceof Map) - { - return toObj((Map) value); - } - else if (!(value instanceof JSONArray) && value instanceof Collection) - { - return toArr((Collection) value); - } - else - { - return value; - } - } - - private static JSONArray toArr(final Collection list) - { - final JSONArray arr = new JSONArray(list.size()); - for (final Object element : list) - { - arr.add(element); - } - return arr; - } - - private static JSONObject toObj(final Map map) - { - final JSONObject obj = new JSONObject(); - for (final Map.Entry ent : map.entrySet()) - { - obj.put(ent.getKey(), transfer(ent.getValue())); - } - return obj; - } - - /** - * 将指定下标元素作为数组返回,如果不存在,则在该位置创建一个空的数组。 - * - * @param arr 当前数组。 - * @param index 下标。 - * @return 返回当前数组指定下标的元素,该元素应该是一个数组。 - */ - private static JSONArray arrayAt(JSONArray arr, int index) - { - expand(arr, index); - if (arr.get(index) == null) - { - arr.set(index, new JSONArray()); - } - return (JSONArray) arr.get(index); - } - - /** - * 将指定下标元素作为结构体返回,如果不存在,则在该位置创建一个空的结构体。 - * - * @param arr 当前数组。 - * @param index 下标。 - * @return 返回当前数组指定下标元素,该元素是一个结构体。 - */ - private static JSONObject objAt(final JSONArray arr, int index) - { - expand(arr, index); - if (arr.get(index) == null) - { - arr.set(index, new JSONObject()); - } - return (JSONObject) arr.get(index); - } - - /** - * 设置数组指定下标位置的值。 - * - * @param arr 数组。 - * @param index 下标。 - * @param value 值。 - */ - private static void elementAt(final JSONArray arr, final int index, final Object value) - { - expand(arr, index).set(index, value); - } - - /** - * 获取数组指定下标元素的值。 - * - * @param arr 数组。 - * @param index 下标。 - * @return 值。 - */ - private static Object elementAt(final JSONArray arr, final int index) - { - return expand(arr, index).get(index); - } - - /** - * 扩展数组到指定下标,以防止访问时下标越界。 - * - * @param arr 数组 - * @param index 下标 - * @return 返回传入的数组 - */ - private static JSONArray expand(final JSONArray arr, final int index) - { - while (arr.size() <= index) - { - arr.add(null); - } - return arr; - } - - /** - * 最后数组回调。 - * - * @author Mike - * - * @param 回调返回数据类型。 - */ - private interface EndArrayCallback - { - /** - * 当定位到最后一级数组,将调用本方法。 - * - * @param arr 最后一级数组对象。 - * @param index 最后一级索引。 - * @return 返回回调的返回值。 - */ - T callback(JSONArray arr, int index); - } - - /** - * 处理多维数组的工具函数(包括一维数组)。多维数组的名字如:arrary[1][2][3], 则name=array,indexStr=[1][2][3],在callback中,endArr将是 - * array[1][2]指定的对象,indexe=3。 - * - * @param name 不带下标的名字,不支持多级名字。 - * @param indexesStr 索引部分的字符串,如:[1][2][3] - * @param callback 回调函数。 - * @return 返回回调函数的返回值。 - */ - private T endArray(final String name, final String indexesStr, final EndArrayCallback callback) - { - JSONArray endArr = arr(name); - final int[] indexes = parseIndexes(indexesStr); - int i = 0; - while (i < indexes.length - 1) - { - endArr = arrayAt(endArr, indexes[i++]); - } - return callback.callback(endArr, indexes[i]); - } - - private static int[] parseIndexes(final String s) - { - int[] indexes = null; - List list = new ArrayList(); - - final StringTokenizer st = new StringTokenizer(s, "[]"); - while (st.hasMoreTokens()) - { - final int index = Integer.valueOf(st.nextToken()); - if (index < 0) - { - throw new RuntimeException(String.format("Illegal index %1$d in \"%2$s\"", index, s)); - } - - list.add(index); - } - - indexes = new int[list.size()]; - int i = 0; - for (Integer tmp : list.toArray(new Integer[list.size()])) - { - indexes[i++] = tmp; - } - - return indexes; - } -} +package com.ruoyi.common.json; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ruoyi.common.utils.StringUtils; + +/** + * 通用消息对象,基于Map实现的可嵌套数据结构。 支持JSON数据结构。 + * + * @author ruoyi + */ +public class JSONObject extends LinkedHashMap { + private static final long serialVersionUID = 1L; + private static final Pattern arrayNamePattern = Pattern.compile("(\\w+)((\\[\\d+\\])+)"); + private static final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * 数组结构。 + */ + public static class JSONArray extends ArrayList { + private static final long serialVersionUID = 1L; + + public JSONArray() { + super(); + } + + public JSONArray(int size) { + super(size); + } + + @Override + public String toString() { + try { + return JSON.marshal(this); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public Object set(int index, Object element) { + return super.set(index, transfer(element)); + } + + @Override + public boolean add(Object element) { + return super.add(transfer(element)); + } + + @Override + public void add(int index, Object element) { + super.add(index, transfer(element)); + } + } + + public JSONObject() { + super(); + } + + public JSONObject(final JSONObject other) { + super(other); + } + + @Override + public String toString() { + try { + return JSON.marshal(this); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * 转换为紧凑格式的字符串。 + * + * @return 返回本对象紧凑格式字符串。 + */ + public String toCompactString() { + try { + return objectMapper.writeValueAsString(this); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * 获取指定字段的整数值。如果字段不存在,或者无法转换为整数,返回null。 + * + * @param name 字段名,支持多级。 + * @return 返回指定的整数值,或者null。 + */ + public Integer intValue(final String name) { + return valueAsInt(value(name)); + } + + /** + * 获取指定字段的整数值。如果字段不存在,或者无法转换为整数,返回defaultValue。 + * + * @param name 字段名,支持多级。 + * @param defaultValue 查询失败时,返回的值。 + * @return 返回指定的整数值,或者defaultValue。 + */ + public Integer intValue(final String name, final Integer defaultValue) { + return StringUtils.nvl(intValue(name), defaultValue); + } + + /** + * 获取指定字段的长整数值。如果字段不存在,或者无法转换为长整数,返回null。 + * + * @param name 字段名,支持多级。 + * @return 返回指定的长整数值,或者null。 + */ + public Long longValue(final String name) { + return valueAsLong(value(name)); + } + + /** + * 获取指定字段的长整数值。如果字段不存在,或者无法转换为长整数,返回defaultValue。 + * + * @param name 字段名,支持多级。 + * @param defaultValue 查询失败时,返回的值。 + * @return 返回指定的长整数值,或者defaultValue。 + */ + public Long longValue(final String name, final Long defaultValue) { + return StringUtils.nvl(longValue(name), defaultValue); + } + + /** + * 获取指定字段的布尔值。如果字段不存在,或者无法转换为布尔型,返回null。 + * + * @param name 字段名,支持多级。 + * @return 返回指定的布尔值,或者null。 + */ + public Boolean boolValue(final String name) { + return valueAsBool(value(name)); + } + + /** + * 获取指定字段的布尔值。如果字段不存在,或者无法转换为布尔型,返回defaultValue。 + * + * @param name 字段名,支持多级。 + * @param defaultValue 查询失败时,返回的值。 + * @return 返回指定的布尔值,或者defaultValue。 + */ + public Boolean boolValue(final String name, final Boolean defaultValue) { + return StringUtils.nvl(boolValue(name), defaultValue); + } + + /** + * 获取指定字段的字符串值。如果字段不存在,返回null。 + * + * @param name 字段名,支持多级。 + * @return 返回指定的字符串值,或者null。 + */ + public String strValue(final String name) { + return valueAsStr(value(name)); + } + + /** + * 获取指定字段的字符串值。如果字段不存在,返回defaultValue。 + * + * @param name 字段名,支持多级。 + * @param defaultValue 查询失败时,返回的值。 + * @return 返回指定的字符串值,或者defaultValue。 + */ + public String strValue(final String name, final String defaultValue) { + return StringUtils.nvl(strValue(name), defaultValue); + } + + /** + * 获取指定字段的值。 + * + * @param name 字段名,支持多级,支持数组下标。 + * @return 返回指定字段的值。 + */ + public Object value(final String name) { + final int indexDot = name.indexOf('.'); + if (indexDot >= 0) { + return obj(name.substring(0, indexDot)).value(name.substring(indexDot + 1)); + } else { + final Matcher matcher = arrayNamePattern.matcher(name); + if (matcher.find()) { + return endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() { + @Override + public Object callback(JSONArray arr, int index) { + return elementAt(arr, index); + } + }); + } else { + return get(name); + } + } + } + + /** + * 设置指定字段的值。 + * + * @param name 字段名,支持多级,支持数组下标。 + * @param value 字段值。 + * @return 返回本对象。 + */ + public JSONObject value(final String name, final Object value) { + final int indexDot = name.indexOf('.'); + if (indexDot >= 0) { + obj(name.substring(0, indexDot)).value(name.substring(indexDot + 1), value); + } else { + final Matcher matcher = arrayNamePattern.matcher(name); + if (matcher.find()) { + endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() { + @Override + public Void callback(JSONArray arr, int index) { + elementAt(arr, index, value); + return null; + } + }); + } else { + set(name, value); + } + } + return this; + } + + /** + * 获取对象(非标量类型)字段。返回的数据是一个结构体。当不存在指定对象时,则为指定的名字创建一个空的MessageObject对象。 + * + * @param name 字段名。不支持多级名字,支持数组下标。 + * @return 返回指定的对象。如果对象不存在,则为指定的名字创建一个空的MessageObject对象。 + */ + public JSONObject obj(final String name) { + final Matcher matcher = arrayNamePattern.matcher(name); + if (matcher.find()) { + return endArray(matcher.group(1), matcher.group(2), new EndArrayCallback() { + @Override + public JSONObject callback(JSONArray arr, int index) { + return objAt(arr, index); + } + }); + } else { + JSONObject obj = getObj(name); + if (obj == null) { + obj = new JSONObject(); + put(name, obj); + } + return obj; + } + } + + /** + * 获取数组字段。将名字对应的对象以数组对象返回,当指定的字段不存在时,创建一个空的数组。 + * + * @param name 字段名。不支持多级名字,不支持下标。 + * @return 返回一个数组(List)。 + */ + public JSONArray arr(final String name) { + JSONArray arr = getArr(name); + if (arr == null) { + arr = new JSONArray(); + put(name, arr); + } + return arr; + } + + /** + * 获取对象(非标量类型)字段。返回的数据是一个结构体。 + * + * @param name 字段名。 + * @return 返回指定的对象字段。 + */ + public JSONObject getObj(final String name) { + return (JSONObject) get(name); + } + + /** + * 获取数组类型字段。 + * + * @param name 字段名。 + * @return 返回数组类型字段。 + */ + public JSONArray getArr(final String name) { + return (JSONArray) get(name); + } + + /** + * 返回字段整数值。如果不存在,返回null。 + * + * @param name 字段名。 + * @return 返回指定字段整数值。 + */ + public Integer getInt(final String name) { + return valueAsInt(get(name)); + } + + /** + * 返回字段整数值。如果不存在,返回defaultValue。 + * + * @param name 字段名。 + * @param defaultValue 字段不存在时,返回的值。 + * @return 返回指定字段整数值。 + */ + public Integer getInt(final String name, Integer defaultValue) { + return StringUtils.nvl(getInt(name), defaultValue); + } + + /** + * 返回字段长整数值。如果不存在,返回null。 + * + * @param name 字段名。 + * @return 返回指定字段长整数值。 + */ + public Long getLong(final String name) { + return valueAsLong(get(name)); + } + + /** + * 返回字段长整数值。如果不存在,返回defaultValue。 + * + * @param name 字段名。 + * @param defaultValue 字段不存在时,返回的值。 + * @return 返回指定字段长整数值。 + */ + public Long getLong(final String name, Long defaultValue) { + return StringUtils.nvl(getLong(name), defaultValue); + } + + /** + * 返回字段字符串值。如果不存在,返回null。 + * + * @param name 字段名。 + * @return 返回指定字段字符串值。 + */ + public String getStr(final String name) { + return valueAsStr(get(name)); + } + + /** + * 返回字段字符串值。如果不存在,返回defaultValue。 + * + * @param name 字段名。 + * @param defaultValue 字段不存在时,返回的值。 + * @return 返回指定字段字符串值。 + */ + public String getStr(final String name, final String defaultValue) { + return StringUtils.nvl(getStr(name), defaultValue); + } + + /** + * 字段值按照布尔类型返回。如果不存在,返回null。 + * + * @param name 字段名。 + * @return 字段值。 + */ + public Boolean getBool(final String name) { + return valueAsBool(get(name)); + } + + /** + * 字段值按照布尔类型返回。如果不存在,返回defaultValue。 + * + * @param name 字段名。 + * @param defaultValue 字段不存在时,返回的值。 + * @return 字段值。 + */ + public Boolean getBool(final String name, final Boolean defaultValue) { + return StringUtils.nvl(getBool(name), defaultValue); + } + + /** + * 设置字段值 + * + * @param name 字段名 + * @param value 字段值(标量:数字、字符串、布尔型;结构体:MessageObject)。 如果是Map类型同时非MessageObject类型,则自动转换为MessageObject类型再存入 + * (此时,再修改Map中的数据,将不会体现到本对象中)。 + * @return 返回本对象 + */ + public JSONObject set(final String name, final Object value) { + put(name, value); + return this; + } + + /** + * 将本对象转换为Java Bean。 + * + * @param beanClass Java Bean的类对象。 + * @return 返回转换后的Java Bean。 + */ + public T asBean(Class beanClass) { + try { + return JSON.unmarshal(JSON.marshal(this), beanClass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * 重载基类的方法。如果 value 是 Map 类型,但不是 MessageObject 类型,则创建一个包含内容等同于原 Map 的 MessageObject 作为 value(注意:此后再更改 Map 的内容,将不会反映到 + * MessageObject 中)。 重载此方法的目的是为了使JSON能够正确地解析为MessageObject对象。不建议直接调用此方法,请使用 set(name, value)方法设置字段值。 + */ + @Override + public Object put(String key, Object value) { + return super.put(key, transfer(value)); + } + + public static Integer valueAsInt(Object value) { + if (value instanceof Integer) { + return (Integer) value; + } else if (value instanceof Number) { + return ((Number) value).intValue(); + } else if (value instanceof String) { + return Integer.valueOf((String) value); + } else if (value instanceof Boolean) { + return ((Boolean) value) ? 1 : 0; + } else { + return null; + } + } + + public static Long valueAsLong(Object value) { + if (value instanceof Long) { + return (Long) value; + } else if (value instanceof Number) { + return ((Number) value).longValue(); + } else if (value instanceof String) { + return Long.valueOf((String) value); + } else if (value instanceof Boolean) { + return ((Boolean) value) ? 1L : 0L; + } else { + return null; + } + } + + public static String valueAsStr(Object value) { + if (value instanceof String) { + return (String) value; + } else if (value != null) { + return value.toString(); + } else { + return null; + } + } + + public static Boolean valueAsBool(Object value) { + if (value instanceof Boolean) { + return (Boolean) value; + } else if (value instanceof Number) { + return ((Number) value).doubleValue() != 0.0; + } else if (value instanceof String) { + return Boolean.valueOf((String) value); + } else { + return null; + } + } + + /** + * 将所有层次中凡是Map类型同时又不是MessageObject的类型,转换为MessageObject类型。 + * + * @param value 值。 + * @return 返回转换后的值。 + */ + @SuppressWarnings("unchecked") + private static Object transfer(final Object value) { + if (!(value instanceof JSONObject) && value instanceof Map) { + return toObj((Map) value); + } else if (!(value instanceof JSONArray) && value instanceof Collection) { + return toArr((Collection) value); + } else { + return value; + } + } + + private static JSONArray toArr(final Collection list) { + final JSONArray arr = new JSONArray(list.size()); + for (final Object element : list) { + arr.add(element); + } + return arr; + } + + private static JSONObject toObj(final Map map) { + final JSONObject obj = new JSONObject(); + for (final Map.Entry ent : map.entrySet()) { + obj.put(ent.getKey(), transfer(ent.getValue())); + } + return obj; + } + + /** + * 将指定下标元素作为数组返回,如果不存在,则在该位置创建一个空的数组。 + * + * @param arr 当前数组。 + * @param index 下标。 + * @return 返回当前数组指定下标的元素,该元素应该是一个数组。 + */ + private static JSONArray arrayAt(JSONArray arr, int index) { + expand(arr, index); + if (arr.get(index) == null) { + arr.set(index, new JSONArray()); + } + return (JSONArray) arr.get(index); + } + + /** + * 将指定下标元素作为结构体返回,如果不存在,则在该位置创建一个空的结构体。 + * + * @param arr 当前数组。 + * @param index 下标。 + * @return 返回当前数组指定下标元素,该元素是一个结构体。 + */ + private static JSONObject objAt(final JSONArray arr, int index) { + expand(arr, index); + if (arr.get(index) == null) { + arr.set(index, new JSONObject()); + } + return (JSONObject) arr.get(index); + } + + /** + * 设置数组指定下标位置的值。 + * + * @param arr 数组。 + * @param index 下标。 + * @param value 值。 + */ + private static void elementAt(final JSONArray arr, final int index, final Object value) { + expand(arr, index).set(index, value); + } + + /** + * 获取数组指定下标元素的值。 + * + * @param arr 数组。 + * @param index 下标。 + * @return 值。 + */ + private static Object elementAt(final JSONArray arr, final int index) { + return expand(arr, index).get(index); + } + + /** + * 扩展数组到指定下标,以防止访问时下标越界。 + * + * @param arr 数组 + * @param index 下标 + * @return 返回传入的数组 + */ + private static JSONArray expand(final JSONArray arr, final int index) { + while (arr.size() <= index) { + arr.add(null); + } + return arr; + } + + /** + * 最后数组回调。 + * + * @param 回调返回数据类型。 + * @author Mike + */ + private interface EndArrayCallback { + /** + * 当定位到最后一级数组,将调用本方法。 + * + * @param arr 最后一级数组对象。 + * @param index 最后一级索引。 + * @return 返回回调的返回值。 + */ + T callback(JSONArray arr, int index); + } + + /** + * 处理多维数组的工具函数(包括一维数组)。多维数组的名字如:arrary[1][2][3], 则name=array,indexStr=[1][2][3],在callback中,endArr将是 + * array[1][2]指定的对象,indexe=3。 + * + * @param name 不带下标的名字,不支持多级名字。 + * @param indexesStr 索引部分的字符串,如:[1][2][3] + * @param callback 回调函数。 + * @return 返回回调函数的返回值。 + */ + private T endArray(final String name, final String indexesStr, final EndArrayCallback callback) { + JSONArray endArr = arr(name); + final int[] indexes = parseIndexes(indexesStr); + int i = 0; + while (i < indexes.length - 1) { + endArr = arrayAt(endArr, indexes[i++]); + } + return callback.callback(endArr, indexes[i]); + } + + private static int[] parseIndexes(final String s) { + int[] indexes = null; + List list = new ArrayList(); + + final StringTokenizer st = new StringTokenizer(s, "[]"); + while (st.hasMoreTokens()) { + final int index = Integer.valueOf(st.nextToken()); + if (index < 0) { + throw new RuntimeException(String.format("Illegal index %1$d in \"%2$s\"", index, s)); + } + + list.add(index); + } + + indexes = new int[list.size()]; + int i = 0; + for (Integer tmp : list.toArray(new Integer[list.size()])) { + indexes[i++] = tmp; + } + + return indexes; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/AddressUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/AddressUtils.java index 437137dea..936247bee 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/AddressUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/AddressUtils.java @@ -1,54 +1,46 @@ -package com.ruoyi.common.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.json.JSON; -import com.ruoyi.common.json.JSONObject; -import com.ruoyi.common.utils.http.HttpUtils; - -/** - * 获取地址类 - * - * @author ruoyi - */ -public class AddressUtils -{ - private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); - - public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php"; - - public static String getRealAddressByIP(String ip) - { - String address = "XX XX"; - - // 内网不查询 - if (IpUtils.internalIp(ip)) - { - return "内网IP"; - } - if (Global.isAddressEnabled()) - { - String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip); - if (StringUtils.isEmpty(rspStr)) - { - log.error("获取地理位置异常 {}", ip); - return address; - } - JSONObject obj; - try - { - obj = JSON.unmarshal(rspStr, JSONObject.class); - JSONObject data = obj.getObj("data"); - String region = data.getStr("region"); - String city = data.getStr("city"); - address = region + " " + city; - } - catch (Exception e) - { - log.error("获取地理位置异常 {}", ip); - } - } - return address; - } -} +package com.ruoyi.common.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.json.JSON; +import com.ruoyi.common.json.JSONObject; +import com.ruoyi.common.utils.http.HttpUtils; + +/** + * 获取地址类 + * + * @author ruoyi + */ +public class AddressUtils { + private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); + + public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php"; + + public static String getRealAddressByIP(String ip) { + String address = "XX XX"; + + // 内网不查询 + if (IpUtils.internalIp(ip)) { + return "内网IP"; + } + if (Global.isAddressEnabled()) { + String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip); + if (StringUtils.isEmpty(rspStr)) { + log.error("获取地理位置异常 {}", ip); + return address; + } + JSONObject obj; + try { + obj = JSON.unmarshal(rspStr, JSONObject.class); + JSONObject data = obj.getObj("data"); + String region = data.getStr("region"); + String city = data.getStr("city"); + address = region + " " + city; + } catch (Exception e) { + log.error("获取地理位置异常 {}", ip); + } + } + return address; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/Arith.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/Arith.java index 866831977..e8abc25e3 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/Arith.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/Arith.java @@ -1,114 +1,113 @@ -package com.ruoyi.common.utils; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -/** - * 精确的浮点数运算 - * - * @author ruoyi - */ -public class Arith -{ - - /** 默认除法运算精度 */ - private static final int DEF_DIV_SCALE = 10; - - /** 这个类不能实例化 */ - private Arith() - { - } - - /** - * 提供精确的加法运算。 - * @param v1 被加数 - * @param v2 加数 - * @return 两个参数的和 - */ - public static double add(double v1, double v2) - { - BigDecimal b1 = new BigDecimal(Double.toString(v1)); - BigDecimal b2 = new BigDecimal(Double.toString(v2)); - return b1.add(b2).doubleValue(); - } - - /** - * 提供精确的减法运算。 - * @param v1 被减数 - * @param v2 减数 - * @return 两个参数的差 - */ - public static double sub(double v1, double v2) - { - BigDecimal b1 = new BigDecimal(Double.toString(v1)); - BigDecimal b2 = new BigDecimal(Double.toString(v2)); - return b1.subtract(b2).doubleValue(); - } - - /** - * 提供精确的乘法运算。 - * @param v1 被乘数 - * @param v2 乘数 - * @return 两个参数的积 - */ - public static double mul(double v1, double v2) - { - BigDecimal b1 = new BigDecimal(Double.toString(v1)); - BigDecimal b2 = new BigDecimal(Double.toString(v2)); - return b1.multiply(b2).doubleValue(); - } - - /** - * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 - * 小数点以后10位,以后的数字四舍五入。 - * @param v1 被除数 - * @param v2 除数 - * @return 两个参数的商 - */ - public static double div(double v1, double v2) - { - return div(v1, v2, DEF_DIV_SCALE); - } - - /** - * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 - * 定精度,以后的数字四舍五入。 - * @param v1 被除数 - * @param v2 除数 - * @param scale 表示表示需要精确到小数点以后几位。 - * @return 两个参数的商 - */ - public static double div(double v1, double v2, int scale) - { - if (scale < 0) - { - throw new IllegalArgumentException( - "The scale must be a positive integer or zero"); - } - BigDecimal b1 = new BigDecimal(Double.toString(v1)); - BigDecimal b2 = new BigDecimal(Double.toString(v2)); - if (b1.compareTo(BigDecimal.ZERO) == 0) - { - return BigDecimal.ZERO.doubleValue(); - } - return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue(); - } - - /** - * 提供精确的小数位四舍五入处理。 - * @param v 需要四舍五入的数字 - * @param scale 小数点后保留几位 - * @return 四舍五入后的结果 - */ - public static double round(double v, int scale) - { - if (scale < 0) - { - throw new IllegalArgumentException( - "The scale must be a positive integer or zero"); - } - BigDecimal b = new BigDecimal(Double.toString(v)); - BigDecimal one = new BigDecimal("1"); - return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue(); - } -} +package com.ruoyi.common.utils; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * 精确的浮点数运算 + * + * @author ruoyi + */ +public class Arith { + + /** + * 默认除法运算精度 + */ + private static final int DEF_DIV_SCALE = 10; + + /** + * 这个类不能实例化 + */ + private Arith() { + } + + /** + * 提供精确的加法运算。 + * + * @param v1 被加数 + * @param v2 加数 + * @return 两个参数的和 + */ + public static double add(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2).doubleValue(); + } + + /** + * 提供精确的减法运算。 + * + * @param v1 被减数 + * @param v2 减数 + * @return 两个参数的差 + */ + public static double sub(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.subtract(b2).doubleValue(); + } + + /** + * 提供精确的乘法运算。 + * + * @param v1 被乘数 + * @param v2 乘数 + * @return 两个参数的积 + */ + public static double mul(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.multiply(b2).doubleValue(); + } + + /** + * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 + * 小数点以后10位,以后的数字四舍五入。 + * + * @param v1 被除数 + * @param v2 除数 + * @return 两个参数的商 + */ + public static double div(double v1, double v2) { + return div(v1, v2, DEF_DIV_SCALE); + } + + /** + * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 + * 定精度,以后的数字四舍五入。 + * + * @param v1 被除数 + * @param v2 除数 + * @param scale 表示表示需要精确到小数点以后几位。 + * @return 两个参数的商 + */ + public static double div(double v1, double v2, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + if (b1.compareTo(BigDecimal.ZERO) == 0) { + return BigDecimal.ZERO.doubleValue(); + } + return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue(); + } + + /** + * 提供精确的小数位四舍五入处理。 + * + * @param v 需要四舍五入的数字 + * @param scale 小数点后保留几位 + * @return 四舍五入后的结果 + */ + public static double round(double v, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java index 8ff95f1b7..0ecacf32b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java @@ -1,155 +1,135 @@ -package com.ruoyi.common.utils; - -import java.lang.management.ManagementFactory; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import org.apache.commons.lang3.time.DateFormatUtils; - -/** - * 时间工具类 - * - * @author ruoyi - */ -public class DateUtils extends org.apache.commons.lang3.time.DateUtils -{ - public static String YYYY = "yyyy"; - - public static String YYYY_MM = "yyyy-MM"; - - public static String YYYY_MM_DD = "yyyy-MM-dd"; - - public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; - - public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; - - private static String[] parsePatterns = { - "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", - "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", - "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; - - /** - * 获取当前Date型日期 - * - * @return Date() 当前日期 - */ - public static Date getNowDate() - { - return new Date(); - } - - /** - * 获取当前日期, 默认格式为yyyy-MM-dd - * - * @return String - */ - public static String getDate() - { - return dateTimeNow(YYYY_MM_DD); - } - - public static final String getTime() - { - return dateTimeNow(YYYY_MM_DD_HH_MM_SS); - } - - public static final String dateTimeNow() - { - return dateTimeNow(YYYYMMDDHHMMSS); - } - - public static final String dateTimeNow(final String format) - { - return parseDateToStr(format, new Date()); - } - - public static final String dateTime(final Date date) - { - return parseDateToStr(YYYY_MM_DD, date); - } - - public static final String parseDateToStr(final String format, final Date date) - { - return new SimpleDateFormat(format).format(date); - } - - public static final Date dateTime(final String format, final String ts) - { - try - { - return new SimpleDateFormat(format).parse(ts); - } - catch (ParseException e) - { - throw new RuntimeException(e); - } - } - - /** - * 日期路径 即年/月/日 如2018/08/08 - */ - public static final String datePath() - { - Date now = new Date(); - return DateFormatUtils.format(now, "yyyy/MM/dd"); - } - - /** - * 日期路径 即年/月/日 如20180808 - */ - public static final String dateTime() - { - Date now = new Date(); - return DateFormatUtils.format(now, "yyyyMMdd"); - } - - /** - * 日期型字符串转化为日期 格式 - */ - public static Date parseDate(Object str) - { - if (str == null) - { - return null; - } - try - { - return parseDate(str.toString(), parsePatterns); - } - catch (ParseException e) - { - return null; - } - } - - /** - * 获取服务器启动时间 - */ - public static Date getServerStartDate() - { - long time = ManagementFactory.getRuntimeMXBean().getStartTime(); - return new Date(time); - } - - /** - * 计算两个时间差 - */ - public static String getDatePoor(Date endDate, Date nowDate) - { - long nd = 1000 * 24 * 60 * 60; - long nh = 1000 * 60 * 60; - long nm = 1000 * 60; - // long ns = 1000; - // 获得两个时间的毫秒时间差异 - long diff = endDate.getTime() - nowDate.getTime(); - // 计算差多少天 - long day = diff / nd; - // 计算差多少小时 - long hour = diff % nd / nh; - // 计算差多少分钟 - long min = diff % nd % nh / nm; - // 计算差多少秒//输出结果 - // long sec = diff % nd % nh % nm / ns; - return day + "天" + hour + "小时" + min + "分钟"; - } -} +package com.ruoyi.common.utils; + +import java.lang.management.ManagementFactory; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.commons.lang3.time.DateFormatUtils; + +/** + * 时间工具类 + * + * @author ruoyi + */ +public class DateUtils extends org.apache.commons.lang3.time.DateUtils { + public static String YYYY = "yyyy"; + + public static String YYYY_MM = "yyyy-MM"; + + public static String YYYY_MM_DD = "yyyy-MM-dd"; + + public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; + + public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + + private static String[] parsePatterns = { + "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", + "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", + "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; + + /** + * 获取当前Date型日期 + * + * @return Date() 当前日期 + */ + public static Date getNowDate() { + return new Date(); + } + + /** + * 获取当前日期, 默认格式为yyyy-MM-dd + * + * @return String + */ + public static String getDate() { + return dateTimeNow(YYYY_MM_DD); + } + + public static final String getTime() { + return dateTimeNow(YYYY_MM_DD_HH_MM_SS); + } + + public static final String dateTimeNow() { + return dateTimeNow(YYYYMMDDHHMMSS); + } + + public static final String dateTimeNow(final String format) { + return parseDateToStr(format, new Date()); + } + + public static final String dateTime(final Date date) { + return parseDateToStr(YYYY_MM_DD, date); + } + + public static final String parseDateToStr(final String format, final Date date) { + return new SimpleDateFormat(format).format(date); + } + + public static final Date dateTime(final String format, final String ts) { + try { + return new SimpleDateFormat(format).parse(ts); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * 日期路径 即年/月/日 如2018/08/08 + */ + public static final String datePath() { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyy/MM/dd"); + } + + /** + * 日期路径 即年/月/日 如20180808 + */ + public static final String dateTime() { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyyMMdd"); + } + + /** + * 日期型字符串转化为日期 格式 + */ + public static Date parseDate(Object str) { + if (str == null) { + return null; + } + try { + return parseDate(str.toString(), parsePatterns); + } catch (ParseException e) { + return null; + } + } + + /** + * 获取服务器启动时间 + */ + public static Date getServerStartDate() { + long time = ManagementFactory.getRuntimeMXBean().getStartTime(); + return new Date(time); + } + + /** + * 计算两个时间差 + */ + public static String getDatePoor(Date endDate, Date nowDate) { + long nd = 1000 * 24 * 60 * 60; + long nh = 1000 * 60 * 60; + long nm = 1000 * 60; + // long ns = 1000; + // 获得两个时间的毫秒时间差异 + long diff = endDate.getTime() - nowDate.getTime(); + // 计算差多少天 + long day = diff / nd; + // 计算差多少小时 + long hour = diff % nd / nh; + // 计算差多少分钟 + long min = diff % nd % nh / nm; + // 计算差多少秒//输出结果 + // long sec = diff % nd % nh % nm / ns; + return day + "天" + hour + "小时" + min + "分钟"; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ExceptionUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ExceptionUtil.java index 4ca52838a..56406fdfb 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ExceptionUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ExceptionUtil.java @@ -1,40 +1,36 @@ -package com.ruoyi.common.utils; - -import java.io.PrintWriter; -import java.io.StringWriter; -import org.apache.commons.lang3.exception.ExceptionUtils; - -/** - * 错误信息处理类。 - * - * @author ruoyi - */ -public class ExceptionUtil -{ - /** - * 获取exception的详细错误信息。 - */ - public static String getExceptionMessage(Throwable e) - { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw, true)); - String str = sw.toString(); - return str; - } - - public static String getRootErrorMseeage(Exception e) - { - Throwable root = ExceptionUtils.getRootCause(e); - root = (root == null ? e : root); - if (root == null) - { - return ""; - } - String msg = root.getMessage(); - if (msg == null) - { - return "null"; - } - return StringUtils.defaultString(msg); - } -} +package com.ruoyi.common.utils; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.apache.commons.lang3.exception.ExceptionUtils; + +/** + * 错误信息处理类。 + * + * @author ruoyi + */ +public class ExceptionUtil { + /** + * 获取exception的详细错误信息。 + */ + public static String getExceptionMessage(Throwable e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw, true)); + String str = sw.toString(); + return str; + } + + public static String getRootErrorMseeage(Exception e) { + Throwable root = ExceptionUtils.getRootCause(e); + root = (root == null ? e : root); + if (root == null) { + return ""; + } + String msg = root.getMessage(); + if (msg == null) { + return "null"; + } + return StringUtils.defaultString(msg); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/IpUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/IpUtils.java index a2a7011b0..f1b35cf13 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/IpUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/IpUtils.java @@ -1,188 +1,158 @@ -package com.ruoyi.common.utils; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import javax.servlet.http.HttpServletRequest; - -/** - * 获取IP方法 - * - * @author ruoyi - */ -public class IpUtils -{ - public static String getIpAddr(HttpServletRequest request) - { - if (request == null) - { - return "unknown"; - } - String ip = request.getHeader("x-forwarded-for"); - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { - ip = request.getHeader("Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { - ip = request.getHeader("X-Forwarded-For"); - } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { - ip = request.getHeader("WL-Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { - ip = request.getHeader("X-Real-IP"); - } - - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { - ip = request.getRemoteAddr(); - } - - return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; - } - - public static boolean internalIp(String ip) - { - byte[] addr = textToNumericFormatV4(ip); - return internalIp(addr) || "127.0.0.1".equals(ip); - } - - private static boolean internalIp(byte[] addr) - { - if (StringUtils.isNull(addr) || addr.length < 2) - { - return true; - } - final byte b0 = addr[0]; - final byte b1 = addr[1]; - // 10.x.x.x/8 - final byte SECTION_1 = 0x0A; - // 172.16.x.x/12 - final byte SECTION_2 = (byte) 0xAC; - final byte SECTION_3 = (byte) 0x10; - final byte SECTION_4 = (byte) 0x1F; - // 192.168.x.x/16 - final byte SECTION_5 = (byte) 0xC0; - final byte SECTION_6 = (byte) 0xA8; - switch (b0) - { - case SECTION_1: - return true; - case SECTION_2: - if (b1 >= SECTION_3 && b1 <= SECTION_4) - { - return true; - } - case SECTION_5: - switch (b1) - { - case SECTION_6: - return true; - } - default: - return false; - } - } - - /** - * 将IPv4地址转换成字节 - * - * @param text IPv4地址 - * @return byte 字节 - */ - public static byte[] textToNumericFormatV4(String text) - { - if (text.length() == 0) - { - return null; - } - - byte[] bytes = new byte[4]; - String[] elements = text.split("\\.", -1); - try - { - long l; - int i; - switch (elements.length) - { - case 1: - l = Long.parseLong(elements[0]); - if ((l < 0L) || (l > 4294967295L)) - return null; - bytes[0] = (byte) (int) (l >> 24 & 0xFF); - bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); - bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); - bytes[3] = (byte) (int) (l & 0xFF); - break; - case 2: - l = Integer.parseInt(elements[0]); - if ((l < 0L) || (l > 255L)) - return null; - bytes[0] = (byte) (int) (l & 0xFF); - l = Integer.parseInt(elements[1]); - if ((l < 0L) || (l > 16777215L)) - return null; - bytes[1] = (byte) (int) (l >> 16 & 0xFF); - bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); - bytes[3] = (byte) (int) (l & 0xFF); - break; - case 3: - for (i = 0; i < 2; ++i) - { - l = Integer.parseInt(elements[i]); - if ((l < 0L) || (l > 255L)) - return null; - bytes[i] = (byte) (int) (l & 0xFF); - } - l = Integer.parseInt(elements[2]); - if ((l < 0L) || (l > 65535L)) - return null; - bytes[2] = (byte) (int) (l >> 8 & 0xFF); - bytes[3] = (byte) (int) (l & 0xFF); - break; - case 4: - for (i = 0; i < 4; ++i) - { - l = Integer.parseInt(elements[i]); - if ((l < 0L) || (l > 255L)) - return null; - bytes[i] = (byte) (int) (l & 0xFF); - } - break; - default: - return null; - } - } - catch (NumberFormatException e) - { - return null; - } - return bytes; - } - - public static String getHostIp() - { - try - { - return InetAddress.getLocalHost().getHostAddress(); - } - catch (UnknownHostException e) - { - } - return "127.0.0.1"; - } - - public static String getHostName() - { - try - { - return InetAddress.getLocalHost().getHostName(); - } - catch (UnknownHostException e) - { - } - return "未知"; - } +package com.ruoyi.common.utils; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import javax.servlet.http.HttpServletRequest; + +/** + * 获取IP方法 + * + * @author ruoyi + */ +public class IpUtils { + public static String getIpAddr(HttpServletRequest request) { + if (request == null) { + return "unknown"; + } + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + + return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; + } + + public static boolean internalIp(String ip) { + byte[] addr = textToNumericFormatV4(ip); + return internalIp(addr) || "127.0.0.1".equals(ip); + } + + private static boolean internalIp(byte[] addr) { + if (StringUtils.isNull(addr) || addr.length < 2) { + return true; + } + final byte b0 = addr[0]; + final byte b1 = addr[1]; + // 10.x.x.x/8 + final byte SECTION_1 = 0x0A; + // 172.16.x.x/12 + final byte SECTION_2 = (byte) 0xAC; + final byte SECTION_3 = (byte) 0x10; + final byte SECTION_4 = (byte) 0x1F; + // 192.168.x.x/16 + final byte SECTION_5 = (byte) 0xC0; + final byte SECTION_6 = (byte) 0xA8; + switch (b0) { + case SECTION_1: + return true; + case SECTION_2: + if (b1 >= SECTION_3 && b1 <= SECTION_4) { + return true; + } + case SECTION_5: + switch (b1) { + case SECTION_6: + return true; + } + default: + return false; + } + } + + /** + * 将IPv4地址转换成字节 + * + * @param text IPv4地址 + * @return byte 字节 + */ + public static byte[] textToNumericFormatV4(String text) { + if (text.length() == 0) { + return null; + } + + byte[] bytes = new byte[4]; + String[] elements = text.split("\\.", -1); + try { + long l; + int i; + switch (elements.length) { + case 1: + l = Long.parseLong(elements[0]); + if ((l < 0L) || (l > 4294967295L)) + return null; + bytes[0] = (byte) (int) (l >> 24 & 0xFF); + bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); + bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); + bytes[3] = (byte) (int) (l & 0xFF); + break; + case 2: + l = Integer.parseInt(elements[0]); + if ((l < 0L) || (l > 255L)) + return null; + bytes[0] = (byte) (int) (l & 0xFF); + l = Integer.parseInt(elements[1]); + if ((l < 0L) || (l > 16777215L)) + return null; + bytes[1] = (byte) (int) (l >> 16 & 0xFF); + bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); + bytes[3] = (byte) (int) (l & 0xFF); + break; + case 3: + for (i = 0; i < 2; ++i) { + l = Integer.parseInt(elements[i]); + if ((l < 0L) || (l > 255L)) + return null; + bytes[i] = (byte) (int) (l & 0xFF); + } + l = Integer.parseInt(elements[2]); + if ((l < 0L) || (l > 65535L)) + return null; + bytes[2] = (byte) (int) (l >> 8 & 0xFF); + bytes[3] = (byte) (int) (l & 0xFF); + break; + case 4: + for (i = 0; i < 4; ++i) { + l = Integer.parseInt(elements[i]); + if ((l < 0L) || (l > 255L)) + return null; + bytes[i] = (byte) (int) (l & 0xFF); + } + break; + default: + return null; + } + } catch (NumberFormatException e) { + return null; + } + return bytes; + } + + public static String getHostIp() { + try { + return InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + } + return "127.0.0.1"; + } + + public static String getHostName() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + } + return "未知"; + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/MapDataUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/MapDataUtil.java index d750df45d..33c58deb8 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/MapDataUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/MapDataUtil.java @@ -1,50 +1,41 @@ -package com.ruoyi.common.utils; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import javax.servlet.http.HttpServletRequest; - -/** - * Map通用处理方法 - * - * @author ruoyi - */ -public class MapDataUtil -{ - public static Map convertDataMap(HttpServletRequest request) - { - Map properties = request.getParameterMap(); - Map returnMap = new HashMap(); - Iterator entries = properties.entrySet().iterator(); - Map.Entry entry; - String name = ""; - String value = ""; - while (entries.hasNext()) - { - entry = (Entry) entries.next(); - name = (String) entry.getKey(); - Object valueObj = entry.getValue(); - if (null == valueObj) - { - value = ""; - } - else if (valueObj instanceof String[]) - { - String[] values = (String[]) valueObj; - for (int i = 0; i < values.length; i++) - { - value = values[i] + ","; - } - value = value.substring(0, value.length() - 1); - } - else - { - value = valueObj.toString(); - } - returnMap.put(name, value); - } - return returnMap; - } -} +package com.ruoyi.common.utils; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import javax.servlet.http.HttpServletRequest; + +/** + * Map通用处理方法 + * + * @author ruoyi + */ +public class MapDataUtil { + public static Map convertDataMap(HttpServletRequest request) { + Map properties = request.getParameterMap(); + Map returnMap = new HashMap(); + Iterator entries = properties.entrySet().iterator(); + Map.Entry entry; + String name = ""; + String value = ""; + while (entries.hasNext()) { + entry = (Entry) entries.next(); + name = (String) entry.getKey(); + Object valueObj = entry.getValue(); + if (null == valueObj) { + value = ""; + } else if (valueObj instanceof String[]) { + String[] values = (String[]) valueObj; + for (int i = 0; i < values.length; i++) { + value = values[i] + ","; + } + value = value.substring(0, value.length() - 1); + } else { + value = valueObj.toString(); + } + returnMap.put(name, value); + } + return returnMap; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/MessageUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/MessageUtils.java index 5f2d9ea24..d9eb4b978 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/MessageUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/MessageUtils.java @@ -1,26 +1,24 @@ -package com.ruoyi.common.utils; - -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import com.ruoyi.common.utils.spring.SpringUtils; - -/** - * 获取i18n资源文件 - * - * @author ruoyi - */ -public class MessageUtils -{ - /** - * 根据消息键和参数 获取消息 委托给spring messageSource - * - * @param code 消息键 - * @param args 参数 - * @return 获取国际化翻译值 - */ - public static String message(String code, Object... args) - { - MessageSource messageSource = SpringUtils.getBean(MessageSource.class); - return messageSource.getMessage(code, args, LocaleContextHolder.getLocale()); - } -} +package com.ruoyi.common.utils; + +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import com.ruoyi.common.utils.spring.SpringUtils; + +/** + * 获取i18n资源文件 + * + * @author ruoyi + */ +public class MessageUtils { + /** + * 根据消息键和参数 获取消息 委托给spring messageSource + * + * @param code 消息键 + * @param args 参数 + * @return 获取国际化翻译值 + */ + public static String message(String code, Object... args) { + MessageSource messageSource = SpringUtils.getBean(MessageSource.class); + return messageSource.getMessage(code, args, LocaleContextHolder.getLocale()); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java index 451b180fe..650b97411 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java @@ -1,135 +1,118 @@ -package com.ruoyi.common.utils; - -import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import com.ruoyi.common.core.text.Convert; - -/** - * 客户端工具类 - * - * @author ruoyi - */ -public class ServletUtils -{ - /** - * 获取String参数 - */ - public static String getParameter(String name) - { - return getRequest().getParameter(name); - } - - /** - * 获取String参数 - */ - public static String getParameter(String name, String defaultValue) - { - return Convert.toStr(getRequest().getParameter(name), defaultValue); - } - - /** - * 获取Integer参数 - */ - public static Integer getParameterToInt(String name) - { - return Convert.toInt(getRequest().getParameter(name)); - } - - /** - * 获取Integer参数 - */ - public static Integer getParameterToInt(String name, Integer defaultValue) - { - return Convert.toInt(getRequest().getParameter(name), defaultValue); - } - - /** - * 获取request - */ - public static HttpServletRequest getRequest() - { - return getRequestAttributes().getRequest(); - } - - /** - * 获取response - */ - public static HttpServletResponse getResponse() - { - return getRequestAttributes().getResponse(); - } - - /** - * 获取session - */ - public static HttpSession getSession() - { - return getRequest().getSession(); - } - - public static ServletRequestAttributes getRequestAttributes() - { - RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); - return (ServletRequestAttributes) attributes; - } - - /** - * 将字符串渲染到客户端 - * - * @param response 渲染对象 - * @param string 待渲染的字符串 - * @return null - */ - public static String renderString(HttpServletResponse response, String string) - { - try - { - response.setContentType("application/json"); - response.setCharacterEncoding("utf-8"); - response.getWriter().print(string); - } - catch (IOException e) - { - e.printStackTrace(); - } - return null; - } - - /** - * 是否是Ajax异步请求 - * - * @param request - */ - public static boolean isAjaxRequest(HttpServletRequest request) - { - String accept = request.getHeader("accept"); - if (accept != null && accept.indexOf("application/json") != -1) - { - return true; - } - - String xRequestedWith = request.getHeader("X-Requested-With"); - if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) - { - return true; - } - - String uri = request.getRequestURI(); - if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) - { - return true; - } - - String ajax = request.getParameter("__ajax"); - if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) - { - return true; - } - return false; - } -} +package com.ruoyi.common.utils; + +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import com.ruoyi.common.core.text.Convert; + +/** + * 客户端工具类 + * + * @author ruoyi + */ +public class ServletUtils { + /** + * 获取String参数 + */ + public static String getParameter(String name) { + return getRequest().getParameter(name); + } + + /** + * 获取String参数 + */ + public static String getParameter(String name, String defaultValue) { + return Convert.toStr(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name) { + return Convert.toInt(getRequest().getParameter(name)); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name, Integer defaultValue) { + return Convert.toInt(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取request + */ + public static HttpServletRequest getRequest() { + return getRequestAttributes().getRequest(); + } + + /** + * 获取response + */ + public static HttpServletResponse getResponse() { + return getRequestAttributes().getResponse(); + } + + /** + * 获取session + */ + public static HttpSession getSession() { + return getRequest().getSession(); + } + + public static ServletRequestAttributes getRequestAttributes() { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + return (ServletRequestAttributes) attributes; + } + + /** + * 将字符串渲染到客户端 + * + * @param response 渲染对象 + * @param string 待渲染的字符串 + * @return null + */ + public static String renderString(HttpServletResponse response, String string) { + try { + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().print(string); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 是否是Ajax异步请求 + * + * @param request + */ + public static boolean isAjaxRequest(HttpServletRequest request) { + String accept = request.getHeader("accept"); + if (accept != null && accept.indexOf("application/json") != -1) { + return true; + } + + String xRequestedWith = request.getHeader("X-Requested-With"); + if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { + return true; + } + + String uri = request.getRequestURI(); + if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) { + return true; + } + + String ajax = request.getParameter("__ajax"); + if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) { + return true; + } + return false; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java index 86dee8a8a..2a9e19830 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java @@ -1,398 +1,346 @@ -package com.ruoyi.common.utils; - -import java.util.Collection; -import java.util.Map; -import com.ruoyi.common.core.text.StrFormatter; - -/** - * 字符串工具类 - * - * @author ruoyi - */ -public class StringUtils extends org.apache.commons.lang3.StringUtils -{ - /** 空字符串 */ - private static final String NULLSTR = ""; - - /** 下划线 */ - private static final char SEPARATOR = '_'; - - /** - * 获取参数不为空值 - * - * @param value defaultValue 要判断的value - * @return value 返回值 - */ - public static T nvl(T value, T defaultValue) - { - return value != null ? value : defaultValue; - } - - /** - * * 判断一个Collection是否为空, 包含List,Set,Queue - * - * @param coll 要判断的Collection - * @return true:为空 false:非空 - */ - public static boolean isEmpty(Collection coll) - { - return isNull(coll) || coll.isEmpty(); - } - - /** - * * 判断一个Collection是否非空,包含List,Set,Queue - * - * @param coll 要判断的Collection - * @return true:非空 false:空 - */ - public static boolean isNotEmpty(Collection coll) - { - return !isEmpty(coll); - } - - /** - * * 判断一个对象数组是否为空 - * - * @param objects 要判断的对象数组 - ** @return true:为空 false:非空 - */ - public static boolean isEmpty(Object[] objects) - { - return isNull(objects) || (objects.length == 0); - } - - /** - * * 判断一个对象数组是否非空 - * - * @param objects 要判断的对象数组 - * @return true:非空 false:空 - */ - public static boolean isNotEmpty(Object[] objects) - { - return !isEmpty(objects); - } - - /** - * * 判断一个Map是否为空 - * - * @param map 要判断的Map - * @return true:为空 false:非空 - */ - public static boolean isEmpty(Map map) - { - return isNull(map) || map.isEmpty(); - } - - /** - * * 判断一个Map是否为空 - * - * @param map 要判断的Map - * @return true:非空 false:空 - */ - public static boolean isNotEmpty(Map map) - { - return !isEmpty(map); - } - - /** - * * 判断一个字符串是否为空串 - * - * @param str String - * @return true:为空 false:非空 - */ - public static boolean isEmpty(String str) - { - return isNull(str) || NULLSTR.equals(str.trim()); - } - - /** - * * 判断一个字符串是否为非空串 - * - * @param str String - * @return true:非空串 false:空串 - */ - public static boolean isNotEmpty(String str) - { - return !isEmpty(str); - } - - /** - * * 判断一个对象是否为空 - * - * @param object Object - * @return true:为空 false:非空 - */ - public static boolean isNull(Object object) - { - return object == null; - } - - /** - * * 判断一个对象是否非空 - * - * @param object Object - * @return true:非空 false:空 - */ - public static boolean isNotNull(Object object) - { - return !isNull(object); - } - - /** - * * 判断一个对象是否是数组类型(Java基本型别的数组) - * - * @param object 对象 - * @return true:是数组 false:不是数组 - */ - public static boolean isArray(Object object) - { - return isNotNull(object) && object.getClass().isArray(); - } - - /** - * 去空格 - */ - public static String trim(String str) - { - return (str == null ? "" : str.trim()); - } - - /** - * 截取字符串 - * - * @param str 字符串 - * @param start 开始 - * @return 结果 - */ - public static String substring(final String str, int start) - { - if (str == null) - { - return NULLSTR; - } - - if (start < 0) - { - start = str.length() + start; - } - - if (start < 0) - { - start = 0; - } - if (start > str.length()) - { - return NULLSTR; - } - - return str.substring(start); - } - - /** - * 截取字符串 - * - * @param str 字符串 - * @param start 开始 - * @param end 结束 - * @return 结果 - */ - public static String substring(final String str, int start, int end) - { - if (str == null) - { - return NULLSTR; - } - - if (end < 0) - { - end = str.length() + end; - } - if (start < 0) - { - start = str.length() + start; - } - - if (end > str.length()) - { - end = str.length(); - } - - if (start > end) - { - return NULLSTR; - } - - if (start < 0) - { - start = 0; - } - if (end < 0) - { - end = 0; - } - - return str.substring(start, end); - } - - /** - * 格式化文本, {} 表示占位符
- * 此方法只是简单将占位符 {} 按照顺序替换为参数
- * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
- * 例:
- * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
- * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
- * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
- * - * @param template 文本模板,被替换的部分用 {} 表示 - * @param params 参数值 - * @return 格式化后的文本 - */ - public static String format(String template, Object... params) - { - if (isEmpty(params) || isEmpty(template)) - { - return template; - } - return StrFormatter.format(template, params); - } - - /** - * 下划线转驼峰命名 - */ - public static String toUnderScoreCase(String str) - { - if (str == null) - { - return null; - } - StringBuilder sb = new StringBuilder(); - // 前置字符是否大写 - boolean preCharIsUpperCase = true; - // 当前字符是否大写 - boolean curreCharIsUpperCase = true; - // 下一字符是否大写 - boolean nexteCharIsUpperCase = true; - for (int i = 0; i < str.length(); i++) - { - char c = str.charAt(i); - if (i > 0) - { - preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); - } - else - { - preCharIsUpperCase = false; - } - - curreCharIsUpperCase = Character.isUpperCase(c); - - if (i < (str.length() - 1)) - { - nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); - } - - if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) - { - sb.append(SEPARATOR); - } - else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) - { - sb.append(SEPARATOR); - } - sb.append(Character.toLowerCase(c)); - } - - return sb.toString(); - } - - /** - * 是否包含字符串 - * - * @param str 验证字符串 - * @param strs 字符串组 - * @return 包含返回true - */ - public static boolean inStringIgnoreCase(String str, String... strs) - { - if (str != null && strs != null) - { - for (String s : strs) - { - if (str.equalsIgnoreCase(trim(s))) - { - return true; - } - } - } - return false; - } - - /** - * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld - * - * @param name 转换前的下划线大写方式命名的字符串 - * @return 转换后的驼峰式命名的字符串 - */ - public static String convertToCamelCase(String name) - { - StringBuilder result = new StringBuilder(); - // 快速检查 - if (name == null || name.isEmpty()) - { - // 没必要转换 - return ""; - } - else if (!name.contains("_")) - { - // 不含下划线,仅将首字母大写 - return name.substring(0, 1).toUpperCase() + name.substring(1); - } - // 用下划线将原始字符串分割 - String[] camels = name.split("_"); - for (String camel : camels) - { - // 跳过原始字符串中开头、结尾的下换线或双重下划线 - if (camel.isEmpty()) - { - continue; - } - // 首字母大写 - result.append(camel.substring(0, 1).toUpperCase()); - result.append(camel.substring(1).toLowerCase()); - } - return result.toString(); - } - - /** - * 驼峰式命名法 例如:user_name->userName - */ - public static String toCamelCase(String s) - { - if (s == null) - { - return null; - } - s = s.toLowerCase(); - StringBuilder sb = new StringBuilder(s.length()); - boolean upperCase = false; - for (int i = 0; i < s.length(); i++) - { - char c = s.charAt(i); - - if (c == SEPARATOR) - { - upperCase = true; - } - else if (upperCase) - { - sb.append(Character.toUpperCase(c)); - upperCase = false; - } - else - { - sb.append(c); - } - } - return sb.toString(); - } +package com.ruoyi.common.utils; + +import java.util.Collection; +import java.util.Map; + +import com.ruoyi.common.core.text.StrFormatter; + +/** + * 字符串工具类 + * + * @author ruoyi + */ +public class StringUtils extends org.apache.commons.lang3.StringUtils { + /** + * 空字符串 + */ + private static final String NULLSTR = ""; + + /** + * 下划线 + */ + private static final char SEPARATOR = '_'; + + /** + * 获取参数不为空值 + * + * @param value defaultValue 要判断的value + * @return value 返回值 + */ + public static T nvl(T value, T defaultValue) { + return value != null ? value : defaultValue; + } + + /** + * * 判断一个Collection是否为空, 包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Collection coll) { + return isNull(coll) || coll.isEmpty(); + } + + /** + * * 判断一个Collection是否非空,包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Collection coll) { + return !isEmpty(coll); + } + + /** + * * 判断一个对象数组是否为空 + * + * @param objects 要判断的对象数组 + * * @return true:为空 false:非空 + */ + public static boolean isEmpty(Object[] objects) { + return isNull(objects) || (objects.length == 0); + } + + /** + * * 判断一个对象数组是否非空 + * + * @param objects 要判断的对象数组 + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Object[] objects) { + return !isEmpty(objects); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Map map) { + return isNull(map) || map.isEmpty(); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Map map) { + return !isEmpty(map); + } + + /** + * * 判断一个字符串是否为空串 + * + * @param str String + * @return true:为空 false:非空 + */ + public static boolean isEmpty(String str) { + return isNull(str) || NULLSTR.equals(str.trim()); + } + + /** + * * 判断一个字符串是否为非空串 + * + * @param str String + * @return true:非空串 false:空串 + */ + public static boolean isNotEmpty(String str) { + return !isEmpty(str); + } + + /** + * * 判断一个对象是否为空 + * + * @param object Object + * @return true:为空 false:非空 + */ + public static boolean isNull(Object object) { + return object == null; + } + + /** + * * 判断一个对象是否非空 + * + * @param object Object + * @return true:非空 false:空 + */ + public static boolean isNotNull(Object object) { + return !isNull(object); + } + + /** + * * 判断一个对象是否是数组类型(Java基本型别的数组) + * + * @param object 对象 + * @return true:是数组 false:不是数组 + */ + public static boolean isArray(Object object) { + return isNotNull(object) && object.getClass().isArray(); + } + + /** + * 去空格 + */ + public static String trim(String str) { + return (str == null ? "" : str.trim()); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @return 结果 + */ + public static String substring(final String str, int start) { + if (str == null) { + return NULLSTR; + } + + if (start < 0) { + start = str.length() + start; + } + + if (start < 0) { + start = 0; + } + if (start > str.length()) { + return NULLSTR; + } + + return str.substring(start); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @param end 结束 + * @return 结果 + */ + public static String substring(final String str, int start, int end) { + if (str == null) { + return NULLSTR; + } + + if (end < 0) { + end = str.length() + end; + } + if (start < 0) { + start = str.length() + start; + } + + if (end > str.length()) { + end = str.length(); + } + + if (start > end) { + return NULLSTR; + } + + if (start < 0) { + start = 0; + } + if (end < 0) { + end = 0; + } + + return str.substring(start, end); + } + + /** + * 格式化文本, {} 表示占位符
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param template 文本模板,被替换的部分用 {} 表示 + * @param params 参数值 + * @return 格式化后的文本 + */ + public static String format(String template, Object... params) { + if (isEmpty(params) || isEmpty(template)) { + return template; + } + return StrFormatter.format(template, params); + } + + /** + * 下划线转驼峰命名 + */ + public static String toUnderScoreCase(String str) { + if (str == null) { + return null; + } + StringBuilder sb = new StringBuilder(); + // 前置字符是否大写 + boolean preCharIsUpperCase = true; + // 当前字符是否大写 + boolean curreCharIsUpperCase = true; + // 下一字符是否大写 + boolean nexteCharIsUpperCase = true; + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (i > 0) { + preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); + } else { + preCharIsUpperCase = false; + } + + curreCharIsUpperCase = Character.isUpperCase(c); + + if (i < (str.length() - 1)) { + nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); + } + + if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) { + sb.append(SEPARATOR); + } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) { + sb.append(SEPARATOR); + } + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + /** + * 是否包含字符串 + * + * @param str 验证字符串 + * @param strs 字符串组 + * @return 包含返回true + */ + public static boolean inStringIgnoreCase(String str, String... strs) { + if (str != null && strs != null) { + for (String s : strs) { + if (str.equalsIgnoreCase(trim(s))) { + return true; + } + } + } + return false; + } + + /** + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld + * + * @param name 转换前的下划线大写方式命名的字符串 + * @return 转换后的驼峰式命名的字符串 + */ + public static String convertToCamelCase(String name) { + StringBuilder result = new StringBuilder(); + // 快速检查 + if (name == null || name.isEmpty()) { + // 没必要转换 + return ""; + } else if (!name.contains("_")) { + // 不含下划线,仅将首字母大写 + return name.substring(0, 1).toUpperCase() + name.substring(1); + } + // 用下划线将原始字符串分割 + String[] camels = name.split("_"); + for (String camel : camels) { + // 跳过原始字符串中开头、结尾的下换线或双重下划线 + if (camel.isEmpty()) { + continue; + } + // 首字母大写 + result.append(camel.substring(0, 1).toUpperCase()); + result.append(camel.substring(1).toLowerCase()); + } + return result.toString(); + } + + /** + * 驼峰式命名法 例如:user_name->userName + */ + public static String toCamelCase(String s) { + if (s == null) { + return null; + } + s = s.toLowerCase(); + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + if (c == SEPARATOR) { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + return sb.toString(); + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/Threads.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/Threads.java index 193419506..f427c314f 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/Threads.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/Threads.java @@ -5,29 +5,25 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 线程相关工具类. - * + * * @author ruoyi */ -public class Threads -{ +public class Threads { private static final Logger logger = LoggerFactory.getLogger(Threads.class); /** * sleep等待,单位为毫秒 */ - public static void sleep(long milliseconds) - { - try - { + public static void sleep(long milliseconds) { + try { Thread.sleep(milliseconds); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { return; } } @@ -39,24 +35,17 @@ public class Threads * 如果仍人超時,則強制退出. * 另对在shutdown时线程本身被调用中断做了处理. */ - public static void shutdownAndAwaitTermination(ExecutorService pool) - { - if (pool != null && !pool.isShutdown()) - { + public static void shutdownAndAwaitTermination(ExecutorService pool) { + if (pool != null && !pool.isShutdown()) { pool.shutdown(); - try - { - if (!pool.awaitTermination(120, TimeUnit.SECONDS)) - { + try { + if (!pool.awaitTermination(120, TimeUnit.SECONDS)) { pool.shutdownNow(); - if (!pool.awaitTermination(120, TimeUnit.SECONDS)) - { + if (!pool.awaitTermination(120, TimeUnit.SECONDS)) { logger.info("Pool did not terminate"); } } - } - catch (InterruptedException ie) - { + } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } @@ -66,33 +55,22 @@ public class Threads /** * 打印线程异常信息 */ - public static void printException(Runnable r, Throwable t) - { - if (t == null && r instanceof Future) - { - try - { + public static void printException(Runnable r, Throwable t) { + if (t == null && r instanceof Future) { + try { Future future = (Future) r; - if (future.isDone()) - { + if (future.isDone()) { future.get(); } - } - catch (CancellationException ce) - { + } catch (CancellationException ce) { t = ce; - } - catch (ExecutionException ee) - { + } catch (ExecutionException ee) { t = ee.getCause(); - } - catch (InterruptedException ie) - { + } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } - if (t != null) - { + if (t != null) { logger.error(t.getMessage(), t); } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/YamlUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/YamlUtil.java index bb8a4ed68..27957858b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/YamlUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/YamlUtil.java @@ -1,87 +1,70 @@ -package com.ruoyi.common.utils; - -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedHashMap; -import java.util.Map; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import com.ruoyi.common.utils.StringUtils; - -/** - * 配置处理工具类 - * - * @author yml - */ -public class YamlUtil -{ - public static Map loadYaml(String fileName) throws FileNotFoundException - { - InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream(fileName); - return StringUtils.isNotEmpty(fileName) ? (LinkedHashMap) new Yaml().load(in) : null; - } - - public static void dumpYaml(String fileName, Map map) throws IOException - { - if (StringUtils.isNotEmpty(fileName)) - { - FileWriter fileWriter = new FileWriter(YamlUtil.class.getResource(fileName).getFile()); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - yaml.dump(map, fileWriter); - } - } - - public static Object getProperty(Map map, Object qualifiedKey) - { - if (map != null && !map.isEmpty() && qualifiedKey != null) - { - String input = String.valueOf(qualifiedKey); - if (!"".equals(input)) - { - if (input.contains(".")) - { - int index = input.indexOf("."); - String left = input.substring(0, index); - String right = input.substring(index + 1, input.length()); - return getProperty((Map) map.get(left), right); - } - else if (map.containsKey(input)) - { - return map.get(input); - } - else - { - return null; - } - } - } - return null; - } - - @SuppressWarnings("unchecked") - public static void setProperty(Map map, Object qualifiedKey, Object value) - { - if (map != null && !map.isEmpty() && qualifiedKey != null) - { - String input = String.valueOf(qualifiedKey); - if (!input.equals("")) - { - if (input.contains(".")) - { - int index = input.indexOf("."); - String left = input.substring(0, index); - String right = input.substring(index + 1, input.length()); - setProperty((Map) map.get(left), right, value); - } - else - { - ((Map) map).put(qualifiedKey, value); - } - } - } - } +package com.ruoyi.common.utils; + +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import com.ruoyi.common.utils.StringUtils; + +/** + * 配置处理工具类 + * + * @author yml + */ +public class YamlUtil { + public static Map loadYaml(String fileName) throws FileNotFoundException { + InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream(fileName); + return StringUtils.isNotEmpty(fileName) ? (LinkedHashMap) new Yaml().load(in) : null; + } + + public static void dumpYaml(String fileName, Map map) throws IOException { + if (StringUtils.isNotEmpty(fileName)) { + FileWriter fileWriter = new FileWriter(YamlUtil.class.getResource(fileName).getFile()); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + yaml.dump(map, fileWriter); + } + } + + public static Object getProperty(Map map, Object qualifiedKey) { + if (map != null && !map.isEmpty() && qualifiedKey != null) { + String input = String.valueOf(qualifiedKey); + if (!"".equals(input)) { + if (input.contains(".")) { + int index = input.indexOf("."); + String left = input.substring(0, index); + String right = input.substring(index + 1, input.length()); + return getProperty((Map) map.get(left), right); + } else if (map.containsKey(input)) { + return map.get(input); + } else { + return null; + } + } + } + return null; + } + + @SuppressWarnings("unchecked") + public static void setProperty(Map map, Object qualifiedKey, Object value) { + if (map != null && !map.isEmpty() && qualifiedKey != null) { + String input = String.valueOf(qualifiedKey); + if (!input.equals("")) { + if (input.contains(".")) { + int index = input.indexOf("."); + String left = input.substring(0, index); + String right = input.substring(index + 1, input.length()); + setProperty((Map) map.get(left), right, value); + } else { + ((Map) map).put(qualifiedKey, value); + } + } + } + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanUtils.java index 51cdc2fb1..43114b308 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanUtils.java @@ -1,110 +1,104 @@ -package com.ruoyi.common.utils.bean; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Bean 工具类 - * - * @author ruoyi - */ -public class BeanUtils extends org.springframework.beans.BeanUtils -{ - /** Bean方法名中属性名开始的下标 */ - private static final int BEAN_METHOD_PROP_INDEX = 3; - - /** * 匹配getter方法的正则表达式 */ - private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)"); - - /** * 匹配setter方法的正则表达式 */ - private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)"); - - /** - * Bean属性复制工具方法。 - * - * @param dest 目标对象 - * @param src 源对象 - */ - public static void copyBeanProp(Object dest, Object src) - { - try - { - copyProperties(src, dest); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - /** - * 获取对象的setter方法。 - * - * @param obj 对象 - * @return 对象的setter方法列表 - */ - public static List getSetterMethods(Object obj) - { - // setter方法列表 - List setterMethods = new ArrayList(); - - // 获取所有方法 - Method[] methods = obj.getClass().getMethods(); - - // 查找setter方法 - - for (Method method : methods) - { - Matcher m = SET_PATTERN.matcher(method.getName()); - if (m.matches() && (method.getParameterTypes().length == 1)) - { - setterMethods.add(method); - } - } - // 返回setter方法列表 - return setterMethods; - } - - /** - * 获取对象的getter方法。 - * - * @param obj 对象 - * @return 对象的getter方法列表 - */ - - public static List getGetterMethods(Object obj) - { - // getter方法列表 - List getterMethods = new ArrayList(); - // 获取所有方法 - Method[] methods = obj.getClass().getMethods(); - // 查找getter方法 - for (Method method : methods) - { - Matcher m = GET_PATTERN.matcher(method.getName()); - if (m.matches() && (method.getParameterTypes().length == 0)) - { - getterMethods.add(method); - } - } - // 返回getter方法列表 - return getterMethods; - } - - /** - * 检查Bean方法名中的属性名是否相等。
- * 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。 - * - * @param m1 方法名1 - * @param m2 方法名2 - * @return 属性名一样返回true,否则返回false - */ - - public static boolean isMethodPropEquals(String m1, String m2) - { - return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX)); - } -} +package com.ruoyi.common.utils.bean; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Bean 工具类 + * + * @author ruoyi + */ +public class BeanUtils extends org.springframework.beans.BeanUtils { + /** + * Bean方法名中属性名开始的下标 + */ + private static final int BEAN_METHOD_PROP_INDEX = 3; + + /** + * 匹配getter方法的正则表达式 + */ + private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)"); + + /** + * 匹配setter方法的正则表达式 + */ + private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)"); + + /** + * Bean属性复制工具方法。 + * + * @param dest 目标对象 + * @param src 源对象 + */ + public static void copyBeanProp(Object dest, Object src) { + try { + copyProperties(src, dest); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 获取对象的setter方法。 + * + * @param obj 对象 + * @return 对象的setter方法列表 + */ + public static List getSetterMethods(Object obj) { + // setter方法列表 + List setterMethods = new ArrayList(); + + // 获取所有方法 + Method[] methods = obj.getClass().getMethods(); + + // 查找setter方法 + + for (Method method : methods) { + Matcher m = SET_PATTERN.matcher(method.getName()); + if (m.matches() && (method.getParameterTypes().length == 1)) { + setterMethods.add(method); + } + } + // 返回setter方法列表 + return setterMethods; + } + + /** + * 获取对象的getter方法。 + * + * @param obj 对象 + * @return 对象的getter方法列表 + */ + + public static List getGetterMethods(Object obj) { + // getter方法列表 + List getterMethods = new ArrayList(); + // 获取所有方法 + Method[] methods = obj.getClass().getMethods(); + // 查找getter方法 + for (Method method : methods) { + Matcher m = GET_PATTERN.matcher(method.getName()); + if (m.matches() && (method.getParameterTypes().length == 0)) { + getterMethods.add(method); + } + } + // 返回getter方法列表 + return getterMethods; + } + + /** + * 检查Bean方法名中的属性名是否相等。
+ * 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。 + * + * @param m1 方法名1 + * @param m2 方法名2 + * @return 属性名一样返回true,否则返回false + */ + + public static boolean isMethodPropEquals(String m1, String m2) { + return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX)); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUploadUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUploadUtils.java index 1503e1559..4d4dfd777 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUploadUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUploadUtils.java @@ -1,243 +1,210 @@ -package com.ruoyi.common.utils.file; - -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FilenameUtils; -import org.springframework.web.multipart.MultipartFile; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException; -import com.ruoyi.common.exception.file.FileSizeLimitExceededException; -import com.ruoyi.common.exception.file.InvalidExtensionException; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.security.Md5Utils; - -/** - * 文件上传工具类 - * - * @author ruoyi - */ -public class FileUploadUtils -{ - /** - * 默认大小 50M - */ - public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; - - /** - * 默认的文件名最大长度 100 - */ - public static final int DEFAULT_FILE_NAME_LENGTH = 100; - - /** - * 默认上传的地址 - */ - private static String defaultBaseDir = Global.getProfile(); - - private static int counter = 0; - - public static void setDefaultBaseDir(String defaultBaseDir) - { - FileUploadUtils.defaultBaseDir = defaultBaseDir; - } - - public static String getDefaultBaseDir() - { - return defaultBaseDir; - } - - /** - * 以默认配置进行文件上传 - * - * @param file 上传的文件 - * @return 文件名称 - * @throws Exception - */ - public static final String upload(MultipartFile file) throws IOException - { - try - { - return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); - } - catch (Exception e) - { - throw new IOException(e.getMessage(), e); - } - } - - /** - * 根据文件路径上传 - * - * @param baseDir 相对应用的基目录 - * @param file 上传的文件 - * @return 文件名称 - * @throws IOException - */ - public static final String upload(String baseDir, MultipartFile file) throws IOException - { - try - { - return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); - } - catch (Exception e) - { - throw new IOException(e.getMessage(), e); - } - } - - /** - * 文件上传 - * - * @param baseDir 相对应用的基目录 - * @param file 上传的文件 - * @param extension 上传文件类型 - * @return 返回上传成功的文件名 - * @throws FileSizeLimitExceededException 如果超出最大大小 - * @throws FileNameLengthLimitExceededException 文件名太长 - * @throws IOException 比如读写文件出错时 - * @throws InvalidExtensionException 文件校验异常 - */ - public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) - throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, - InvalidExtensionException - { - int fileNamelength = file.getOriginalFilename().length(); - if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) - { - throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); - } - - assertAllowed(file, allowedExtension); - - String fileName = extractFilename(file); - - File desc = getAbsoluteFile(baseDir, fileName); - file.transferTo(desc); - String pathFileName = getPathFileName(baseDir, fileName); - return pathFileName; - } - - /** - * 编码文件名 - */ - public static final String extractFilename(MultipartFile file) - { - String fileName = file.getOriginalFilename(); - String extension = getExtension(file); - fileName = DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension; - return fileName; - } - - private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException - { - File desc = new File(uploadDir + File.separator + fileName); - - if (!desc.getParentFile().exists()) - { - desc.getParentFile().mkdirs(); - } - if (!desc.exists()) - { - desc.createNewFile(); - } - return desc; - } - - private static final String getPathFileName(String uploadDir, String fileName) throws IOException - { - int dirLastIndex = Global.getProfile().length() + 1; - String currentDir = StringUtils.substring(uploadDir, dirLastIndex); - String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; - return pathFileName; - } - - /** - * 编码文件名 - */ - private static final String encodingFilename(String fileName) - { - fileName = fileName.replace("_", " "); - fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++); - return fileName; - } - - /** - * 文件大小校验 - * - * @param file 上传的文件 - * @return - * @throws FileSizeLimitExceededException 如果超出最大大小 - * @throws InvalidExtensionException - */ - public static final void assertAllowed(MultipartFile file, String[] allowedExtension) - throws FileSizeLimitExceededException, InvalidExtensionException - { - long size = file.getSize(); - if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) - { - throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); - } - - String fileName = file.getOriginalFilename(); - String extension = getExtension(file); - if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) - { - if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) - { - throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, - fileName); - } - else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) - { - throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, - fileName); - } - else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) - { - throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, - fileName); - } - else - { - throw new InvalidExtensionException(allowedExtension, extension, fileName); - } - } - - } - - /** - * 判断MIME类型是否是允许的MIME类型 - * - * @param extension - * @param allowedExtension - * @return - */ - public static final boolean isAllowedExtension(String extension, String[] allowedExtension) - { - for (String str : allowedExtension) - { - if (str.equalsIgnoreCase(extension)) - { - return true; - } - } - return false; - } - - /** - * 获取文件名的后缀 - * - * @param file 表单文件 - * @return 后缀名 - */ - public static final String getExtension(MultipartFile file) - { - String extension = FilenameUtils.getExtension(file.getOriginalFilename()); - if (StringUtils.isEmpty(extension)) - { - extension = MimeTypeUtils.getExtension(file.getContentType()); - } - return extension; - } +package com.ruoyi.common.utils.file; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FilenameUtils; +import org.springframework.web.multipart.MultipartFile; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException; +import com.ruoyi.common.exception.file.FileSizeLimitExceededException; +import com.ruoyi.common.exception.file.InvalidExtensionException; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.security.Md5Utils; + +/** + * 文件上传工具类 + * + * @author ruoyi + */ +public class FileUploadUtils { + /** + * 默认大小 50M + */ + public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; + + /** + * 默认的文件名最大长度 100 + */ + public static final int DEFAULT_FILE_NAME_LENGTH = 100; + + /** + * 默认上传的地址 + */ + private static String defaultBaseDir = Global.getProfile(); + + private static int counter = 0; + + public static void setDefaultBaseDir(String defaultBaseDir) { + FileUploadUtils.defaultBaseDir = defaultBaseDir; + } + + public static String getDefaultBaseDir() { + return defaultBaseDir; + } + + /** + * 以默认配置进行文件上传 + * + * @param file 上传的文件 + * @return 文件名称 + * @throws Exception + */ + public static final String upload(MultipartFile file) throws IOException { + try { + return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } catch (Exception e) { + throw new IOException(e.getMessage(), e); + } + } + + /** + * 根据文件路径上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @return 文件名称 + * @throws IOException + */ + public static final String upload(String baseDir, MultipartFile file) throws IOException { + try { + return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } catch (Exception e) { + throw new IOException(e.getMessage(), e); + } + } + + /** + * 文件上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @param extension 上传文件类型 + * @return 返回上传成功的文件名 + * @throws FileSizeLimitExceededException 如果超出最大大小 + * @throws FileNameLengthLimitExceededException 文件名太长 + * @throws IOException 比如读写文件出错时 + * @throws InvalidExtensionException 文件校验异常 + */ + public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) + throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, + InvalidExtensionException { + int fileNamelength = file.getOriginalFilename().length(); + if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { + throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); + } + + assertAllowed(file, allowedExtension); + + String fileName = extractFilename(file); + + File desc = getAbsoluteFile(baseDir, fileName); + file.transferTo(desc); + String pathFileName = getPathFileName(baseDir, fileName); + return pathFileName; + } + + /** + * 编码文件名 + */ + public static final String extractFilename(MultipartFile file) { + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + fileName = DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension; + return fileName; + } + + private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { + File desc = new File(uploadDir + File.separator + fileName); + + if (!desc.getParentFile().exists()) { + desc.getParentFile().mkdirs(); + } + if (!desc.exists()) { + desc.createNewFile(); + } + return desc; + } + + private static final String getPathFileName(String uploadDir, String fileName) throws IOException { + int dirLastIndex = Global.getProfile().length() + 1; + String currentDir = StringUtils.substring(uploadDir, dirLastIndex); + String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; + return pathFileName; + } + + /** + * 编码文件名 + */ + private static final String encodingFilename(String fileName) { + fileName = fileName.replace("_", " "); + fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++); + return fileName; + } + + /** + * 文件大小校验 + * + * @param file 上传的文件 + * @return + * @throws FileSizeLimitExceededException 如果超出最大大小 + * @throws InvalidExtensionException + */ + public static final void assertAllowed(MultipartFile file, String[] allowedExtension) + throws FileSizeLimitExceededException, InvalidExtensionException { + long size = file.getSize(); + if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) { + throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); + } + + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) { + if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { + throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, + fileName); + } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { + throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, + fileName); + } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { + throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, + fileName); + } else { + throw new InvalidExtensionException(allowedExtension, extension, fileName); + } + } + + } + + /** + * 判断MIME类型是否是允许的MIME类型 + * + * @param extension + * @param allowedExtension + * @return + */ + public static final boolean isAllowedExtension(String extension, String[] allowedExtension) { + for (String str : allowedExtension) { + if (str.equalsIgnoreCase(extension)) { + return true; + } + } + return false; + } + + /** + * 获取文件名的后缀 + * + * @param file 表单文件 + * @return 后缀名 + */ + public static final String getExtension(MultipartFile file) { + String extension = FilenameUtils.getExtension(file.getOriginalFilename()); + if (StringUtils.isEmpty(extension)) { + extension = MimeTypeUtils.getExtension(file.getContentType()); + } + return extension; + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java index 03f5aa2a2..e26e55446 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java @@ -1,142 +1,114 @@ -package com.ruoyi.common.utils.file; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import javax.servlet.http.HttpServletRequest; - -/** - * 文件处理工具类 - * - * @author ruoyi - */ -public class FileUtils -{ - public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; - - /** - * 输出指定文件的byte数组 - * - * @param filePath 文件路径 - * @param os 输出流 - * @return - */ - public static void writeBytes(String filePath, OutputStream os) throws IOException - { - FileInputStream fis = null; - try - { - File file = new File(filePath); - if (!file.exists()) - { - throw new FileNotFoundException(filePath); - } - fis = new FileInputStream(file); - byte[] b = new byte[1024]; - int length; - while ((length = fis.read(b)) > 0) - { - os.write(b, 0, length); - } - } - catch (IOException e) - { - throw e; - } - finally - { - if (os != null) - { - try - { - os.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } - if (fis != null) - { - try - { - fis.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } - } - } - - /** - * 删除文件 - * - * @param filePath 文件 - * @return - */ - public static boolean deleteFile(String filePath) - { - boolean flag = false; - File file = new File(filePath); - // 路径为文件且不为空则进行删除 - if (file.isFile() && file.exists()) - { - file.delete(); - flag = true; - } - return flag; - } - - /** - * 文件名称验证 - * - * @param filename 文件名称 - * @return true 正常 false 非法 - */ - public static boolean isValidFilename(String filename) - { - return filename.matches(FILENAME_PATTERN); - } - - /** - * 下载文件名重新编码 - * - * @param request 请求对象 - * @param fileName 文件名 - * @return 编码后的文件名 - */ - public static String setFileDownloadHeader(HttpServletRequest request, String fileName) - throws UnsupportedEncodingException - { - final String agent = request.getHeader("USER-AGENT"); - String filename = fileName; - if (agent.contains("MSIE")) - { - // IE浏览器 - filename = URLEncoder.encode(filename, "utf-8"); - filename = filename.replace("+", " "); - } - else if (agent.contains("Firefox")) - { - // 火狐浏览器 - filename = new String(fileName.getBytes(), "ISO8859-1"); - } - else if (agent.contains("Chrome")) - { - // google浏览器 - filename = URLEncoder.encode(filename, "utf-8"); - } - else - { - // 其它浏览器 - filename = URLEncoder.encode(filename, "utf-8"); - } - return filename; - } -} +package com.ruoyi.common.utils.file; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import javax.servlet.http.HttpServletRequest; + +/** + * 文件处理工具类 + * + * @author ruoyi + */ +public class FileUtils { + public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; + + /** + * 输出指定文件的byte数组 + * + * @param filePath 文件路径 + * @param os 输出流 + * @return + */ + public static void writeBytes(String filePath, OutputStream os) throws IOException { + FileInputStream fis = null; + try { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + fis = new FileInputStream(file); + byte[] b = new byte[1024]; + int length; + while ((length = fis.read(b)) > 0) { + os.write(b, 0, length); + } + } catch (IOException e) { + throw e; + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + if (fis != null) { + try { + fis.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + } + + /** + * 删除文件 + * + * @param filePath 文件 + * @return + */ + public static boolean deleteFile(String filePath) { + boolean flag = false; + File file = new File(filePath); + // 路径为文件且不为空则进行删除 + if (file.isFile() && file.exists()) { + file.delete(); + flag = true; + } + return flag; + } + + /** + * 文件名称验证 + * + * @param filename 文件名称 + * @return true 正常 false 非法 + */ + public static boolean isValidFilename(String filename) { + return filename.matches(FILENAME_PATTERN); + } + + /** + * 下载文件名重新编码 + * + * @param request 请求对象 + * @param fileName 文件名 + * @return 编码后的文件名 + */ + public static String setFileDownloadHeader(HttpServletRequest request, String fileName) + throws UnsupportedEncodingException { + final String agent = request.getHeader("USER-AGENT"); + String filename = fileName; + if (agent.contains("MSIE")) { + // IE浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + filename = filename.replace("+", " "); + } else if (agent.contains("Firefox")) { + // 火狐浏览器 + filename = new String(fileName.getBytes(), "ISO8859-1"); + } else if (agent.contains("Chrome")) { + // google浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } else { + // 其它浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } + return filename; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java index 698464128..4369fc654 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java @@ -2,11 +2,10 @@ package com.ruoyi.common.utils.file; /** * 媒体类型工具类 - * + * * @author ruoyi */ -public class MimeTypeUtils -{ +public class MimeTypeUtils { public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_JPG = "image/jpg"; @@ -16,13 +15,13 @@ public class MimeTypeUtils public static final String IMAGE_BMP = "image/bmp"; public static final String IMAGE_GIF = "image/gif"; - - public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; - public static final String[] FLASH_EXTENSION = { "swf", "flv" }; + public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"}; - public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", - "asf", "rm", "rmvb" }; + public static final String[] FLASH_EXTENSION = {"swf", "flv"}; + + public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", + "asf", "rm", "rmvb"}; public static final String[] DEFAULT_ALLOWED_EXTENSION = { // 图片 @@ -32,12 +31,10 @@ public class MimeTypeUtils // 压缩文件 "rar", "zip", "gz", "bz2", // pdf - "pdf" }; + "pdf"}; - public static String getExtension(String prefix) - { - switch (prefix) - { + public static String getExtension(String prefix) { + switch (prefix) { case IMAGE_PNG: return "png"; case IMAGE_JPG: diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/html/EscapeUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/html/EscapeUtil.java index 9b6e1587a..6a042e7bd 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/html/EscapeUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/html/EscapeUtil.java @@ -4,20 +4,17 @@ import com.ruoyi.common.utils.StringUtils; /** * 转义和反转义工具类 - * + * * @author ruoyi */ -public class EscapeUtil -{ +public class EscapeUtil { public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)"; private static final char[][] TEXT = new char[64][]; - static - { - for (int i = 0; i < 64; i++) - { - TEXT[i] = new char[] { (char) i }; + static { + for (int i = 0; i < 64; i++) { + TEXT[i] = new char[]{(char) i}; } // special HTML characters @@ -30,61 +27,52 @@ public class EscapeUtil /** * 转义文本中的HTML字符为安全的字符 - * + * * @param text 被转义的文本 * @return 转义后的文本 */ - public static String escape(String text) - { + public static String escape(String text) { return encode(text); } /** * 还原被转义的HTML特殊字符 - * + * * @param content 包含转义符的HTML内容 * @return 转换后的字符串 */ - public static String unescape(String content) - { + public static String unescape(String content) { return decode(content); } /** * 清除所有HTML标签,但是不删除标签内的内容 - * + * * @param content 文本 * @return 清除标签后的文本 */ - public static String clean(String content) - { + public static String clean(String content) { return content.replaceAll(RE_HTML_MARK, ""); } /** * Escape编码 - * + * * @param text 被编码的文本 * @return 编码后的字符 */ - private static String encode(String text) - { + private static String encode(String text) { int len; - if ((text == null) || ((len = text.length()) == 0)) - { + if ((text == null) || ((len = text.length()) == 0)) { return StringUtils.EMPTY; } StringBuilder buffer = new StringBuilder(len + (len >> 2)); char c; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { c = text.charAt(i); - if (c < 64) - { + if (c < 64) { buffer.append(TEXT[c]); - } - else - { + } else { buffer.append(c); } } @@ -93,47 +81,35 @@ public class EscapeUtil /** * Escape解码 - * + * * @param content 被转义的内容 * @return 解码后的字符串 */ - public static String decode(String content) - { - if (StringUtils.isEmpty(content)) - { + public static String decode(String content) { + if (StringUtils.isEmpty(content)) { return content; } StringBuilder tmp = new StringBuilder(content.length()); int lastPos = 0, pos = 0; char ch; - while (lastPos < content.length()) - { + while (lastPos < content.length()) { pos = content.indexOf("%", lastPos); - if (pos == lastPos) - { - if (content.charAt(pos + 1) == 'u') - { + if (pos == lastPos) { + if (content.charAt(pos + 1) == 'u') { ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16); tmp.append(ch); lastPos = pos + 6; - } - else - { + } else { ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16); tmp.append(ch); lastPos = pos + 3; } - } - else - { - if (pos == -1) - { + } else { + if (pos == -1) { tmp.append(content.substring(lastPos)); lastPos = content.length(); - } - else - { + } else { tmp.append(content.substring(lastPos, pos)); lastPos = pos; } @@ -142,8 +118,7 @@ public class EscapeUtil return tmp.toString(); } - public static void main(String[] args) - { + public static void main(String[] args) { String html = ""; System.out.println(EscapeUtil.clean(html)); System.out.println(EscapeUtil.escape(html)); diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java index 323dbc1a3..0a9321f59 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java @@ -1,248 +1,195 @@ -package com.ruoyi.common.utils.http; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.ConnectException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLConnection; -import java.security.cert.X509Certificate; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 通用http发送方法 - * - * @author ruoyi - */ -public class HttpUtils -{ - private static final Logger log = LoggerFactory.getLogger(HttpUtils.class); - - /** - * 向指定 URL 发送GET方法的请求 - * - * @param url 发送请求的 URL - * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return 所代表远程资源的响应结果 - */ - public static String sendGet(String url, String param) - { - StringBuilder result = new StringBuilder(); - BufferedReader in = null; - try - { - String urlNameString = url + "?" + param; - log.info("sendGet - {}", urlNameString); - URL realUrl = new URL(urlNameString); - URLConnection connection = realUrl.openConnection(); - connection.setRequestProperty("accept", "*/*"); - connection.setRequestProperty("connection", "Keep-Alive"); - connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - connection.connect(); - in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - while ((line = in.readLine()) != null) - { - result.append(line); - } - log.info("recv - {}", result); - } - catch (ConnectException e) - { - log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e); - } - catch (SocketTimeoutException e) - { - log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e); - } - catch (IOException e) - { - log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e); - } - catch (Exception e) - { - log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e); - } - finally - { - try - { - if (in != null) - { - in.close(); - } - } - catch (Exception ex) - { - log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); - } - } - return result.toString(); - } - - /** - * 向指定 URL 发送POST方法的请求 - * - * @param url 发送请求的 URL - * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return 所代表远程资源的响应结果 - */ - public static String sendPost(String url, String param) - { - PrintWriter out = null; - BufferedReader in = null; - StringBuilder result = new StringBuilder(); - try - { - String urlNameString = url + "?" + param; - log.info("sendPost - {}", urlNameString); - URL realUrl = new URL(urlNameString); - URLConnection conn = realUrl.openConnection(); - conn.setRequestProperty("accept", "*/*"); - conn.setRequestProperty("connection", "Keep-Alive"); - conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - conn.setRequestProperty("Accept-Charset", "utf-8"); - conn.setRequestProperty("contentType", "utf-8"); - conn.setDoOutput(true); - conn.setDoInput(true); - out = new PrintWriter(conn.getOutputStream()); - out.print(param); - out.flush(); - in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); - String line; - while ((line = in.readLine()) != null) - { - result.append(line); - } - log.info("recv - {}", result); - } - catch (ConnectException e) - { - log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e); - } - catch (SocketTimeoutException e) - { - log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e); - } - catch (IOException e) - { - log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e); - } - catch (Exception e) - { - log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e); - } - finally - { - try - { - if (out != null) - { - out.close(); - } - if (in != null) - { - in.close(); - } - } - catch (IOException ex) - { - log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); - } - } - return result.toString(); - } - - public static String sendSSLPost(String url, String param) - { - StringBuilder result = new StringBuilder(); - String urlNameString = url + "?" + param; - try - { - log.info("sendSSLPost - {}", urlNameString); - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); - URL console = new URL(urlNameString); - HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); - conn.setRequestProperty("accept", "*/*"); - conn.setRequestProperty("connection", "Keep-Alive"); - conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - conn.setRequestProperty("Accept-Charset", "utf-8"); - conn.setRequestProperty("contentType", "utf-8"); - conn.setDoOutput(true); - conn.setDoInput(true); - - conn.setSSLSocketFactory(sc.getSocketFactory()); - conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); - conn.connect(); - InputStream is = conn.getInputStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - String ret = ""; - while ((ret = br.readLine()) != null) - { - if (ret != null && !ret.trim().equals("")) - { - result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8")); - } - } - log.info("recv - {}", result); - conn.disconnect(); - br.close(); - } - catch (ConnectException e) - { - log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e); - } - catch (SocketTimeoutException e) - { - log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e); - } - catch (IOException e) - { - log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e); - } - catch (Exception e) - { - log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e); - } - return result.toString(); - } - - private static class TrustAnyTrustManager implements X509TrustManager - { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - { - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - { - } - - @Override - public X509Certificate[] getAcceptedIssuers() - { - return new X509Certificate[] {}; - } - } - - private static class TrustAnyHostnameVerifier implements HostnameVerifier - { - @Override - public boolean verify(String hostname, SSLSession session) - { - return true; - } - } +package com.ruoyi.common.utils.http; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; +import java.security.cert.X509Certificate; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 通用http发送方法 + * + * @author ruoyi + */ +public class HttpUtils { + private static final Logger log = LoggerFactory.getLogger(HttpUtils.class); + + /** + * 向指定 URL 发送GET方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendGet(String url, String param) { + StringBuilder result = new StringBuilder(); + BufferedReader in = null; + try { + String urlNameString = url + "?" + param; + log.info("sendGet - {}", urlNameString); + URL realUrl = new URL(urlNameString); + URLConnection connection = realUrl.openConnection(); + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + connection.connect(); + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + log.info("recv - {}", result); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e); + } finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception ex) { + log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); + } + } + return result.toString(); + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendPost(String url, String param) { + PrintWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + try { + String urlNameString = url + "?" + param; + log.info("sendPost - {}", urlNameString); + URL realUrl = new URL(urlNameString); + URLConnection conn = realUrl.openConnection(); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("Accept-Charset", "utf-8"); + conn.setRequestProperty("contentType", "utf-8"); + conn.setDoOutput(true); + conn.setDoInput(true); + out = new PrintWriter(conn.getOutputStream()); + out.print(param); + out.flush(); + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + log.info("recv - {}", result); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); + } + } + return result.toString(); + } + + public static String sendSSLPost(String url, String param) { + StringBuilder result = new StringBuilder(); + String urlNameString = url + "?" + param; + try { + log.info("sendSSLPost - {}", urlNameString); + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); + URL console = new URL(urlNameString); + HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("Accept-Charset", "utf-8"); + conn.setRequestProperty("contentType", "utf-8"); + conn.setDoOutput(true); + conn.setDoInput(true); + + conn.setSSLSocketFactory(sc.getSocketFactory()); + conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); + conn.connect(); + InputStream is = conn.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + String ret = ""; + while ((ret = br.readLine()) != null) { + if (ret != null && !ret.trim().equals("")) { + result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8")); + } + } + log.info("recv - {}", result); + conn.disconnect(); + br.close(); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e); + } + return result.toString(); + } + + private static class TrustAnyTrustManager implements X509TrustManager { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + } + + private static class TrustAnyHostnameVerifier implements HostnameVerifier { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java index f1c98e1ca..44a683f87 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java @@ -16,6 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; + import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; @@ -53,11 +54,10 @@ import com.ruoyi.common.utils.reflect.ReflectUtils; /** * Excel相关处理 - * + * * @author ruoyi */ -public class ExcelUtil -{ +public class ExcelUtil { private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); /** @@ -105,15 +105,12 @@ public class ExcelUtil */ public Class clazz; - public ExcelUtil(Class clazz) - { + public ExcelUtil(Class clazz) { this.clazz = clazz; } - public void init(List list, String sheetName, Type type) - { - if (list == null) - { + public void init(List list, String sheetName, Type type) { + if (list == null) { list = new ArrayList(); } this.list = list; @@ -125,62 +122,51 @@ public class ExcelUtil /** * 对excel表单默认第一个索引名转换成list - * + * * @param is 输入流 * @return 转换后集合 */ - public List importExcel(InputStream is) throws Exception - { + public List importExcel(InputStream is) throws Exception { return importExcel(StringUtils.EMPTY, is); } /** * 对excel表单指定表格索引名转换成list - * + * * @param sheetName 表格索引名 - * @param is 输入流 + * @param is 输入流 * @return 转换后集合 */ - public List importExcel(String sheetName, InputStream is) throws Exception - { + public List importExcel(String sheetName, InputStream is) throws Exception { this.type = Type.IMPORT; this.wb = WorkbookFactory.create(is); List list = new ArrayList(); Sheet sheet = null; - if (StringUtils.isNotEmpty(sheetName)) - { + if (StringUtils.isNotEmpty(sheetName)) { // 如果指定sheet名,则取指定sheet中的内容. sheet = wb.getSheet(sheetName); - } - else - { + } else { // 如果传入的sheet名不存在则默认指向第1个sheet. sheet = wb.getSheetAt(0); } - if (sheet == null) - { + if (sheet == null) { throw new IOException("文件sheet不存在"); } int rows = sheet.getPhysicalNumberOfRows(); - if (rows > 0) - { + if (rows > 0) { // 定义一个map用于存放excel列的序号和field. Map cellMap = new HashMap(); // 获取表头 Row heard = sheet.getRow(0); - for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) - { + for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) { Cell cell = heard.getCell(i); - if (StringUtils.isNotNull(cell != null)) - { + if (StringUtils.isNotNull(cell != null)) { String value = this.getCellValue(heard, i).toString(); cellMap.put(value, i); - } - else - { + } else { cellMap.put(null, i); } } @@ -188,25 +174,21 @@ public class ExcelUtil Field[] allFields = clazz.getDeclaredFields(); // 定义一个map用于存放列的序号和field. Map fieldsMap = new HashMap(); - for (int col = 0; col < allFields.length; col++) - { + for (int col = 0; col < allFields.length; col++) { Field field = allFields[col]; Excel attr = field.getAnnotation(Excel.class); - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) - { + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) { // 设置类的私有字段属性可访问. field.setAccessible(true); Integer column = cellMap.get(attr.name()); fieldsMap.put(column, field); } } - for (int i = 1; i < rows; i++) - { + for (int i = 1; i < rows; i++) { // 从第2行开始取数据,默认第一行是表头. Row row = sheet.getRow(i); T entity = null; - for (Map.Entry entry : fieldsMap.entrySet()) - { + for (Map.Entry entry : fieldsMap.entrySet()) { Object val = this.getCellValue(row, entry.getKey()); // 如果不存在实例则新建. @@ -215,67 +197,41 @@ public class ExcelUtil Field field = fieldsMap.get(entry.getKey()); // 取得类型,并根据对象类型设置值. Class fieldType = field.getType(); - if (String.class == fieldType) - { + if (String.class == fieldType) { String s = Convert.toStr(val); - if (StringUtils.endsWith(s, ".0")) - { + if (StringUtils.endsWith(s, ".0")) { val = StringUtils.substringBefore(s, ".0"); - } - else - { + } else { String dateFormat = field.getAnnotation(Excel.class).dateFormat(); - if (StringUtils.isNotEmpty(dateFormat)) - { + if (StringUtils.isNotEmpty(dateFormat)) { val = DateUtils.parseDateToStr(dateFormat, (Date) val); - } - else - { + } else { val = Convert.toStr(val); } } - } - else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) - { + } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { val = Convert.toInt(val); - } - else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) - { + } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { val = Convert.toLong(val); - } - else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) - { + } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { val = Convert.toDouble(val); - } - else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) - { + } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { val = Convert.toFloat(val); - } - else if (BigDecimal.class == fieldType) - { + } else if (BigDecimal.class == fieldType) { val = Convert.toBigDecimal(val); - } - else if (Date.class == fieldType) - { - if (val instanceof String) - { + } else if (Date.class == fieldType) { + if (val instanceof String) { val = DateUtils.parseDate(val); - } - else if (val instanceof Double) - { + } else if (val instanceof Double) { val = DateUtil.getJavaDate((Double) val); } } - if (StringUtils.isNotNull(fieldType)) - { + if (StringUtils.isNotNull(fieldType)) { Excel attr = field.getAnnotation(Excel.class); String propertyName = field.getName(); - if (StringUtils.isNotEmpty(attr.targetAttr())) - { + if (StringUtils.isNotEmpty(attr.targetAttr())) { propertyName = field.getName() + "." + attr.targetAttr(); - } - else if (StringUtils.isNotEmpty(attr.readConverterExp())) - { + } else if (StringUtils.isNotEmpty(attr.readConverterExp())) { val = reverseByExp(String.valueOf(val), attr.readConverterExp()); } ReflectUtils.invokeSetter(entity, propertyName, val); @@ -289,56 +245,49 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * - * @param list 导出数据集合 + * + * @param list 导出数据集合 * @param sheetName 工作表的名称 * @return 结果 */ - public AjaxResult exportExcel(List list, String sheetName) - { + public AjaxResult exportExcel(List list, String sheetName) { this.init(list, sheetName, Type.EXPORT); return exportExcel(); } /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param sheetName 工作表的名称 * @return 结果 */ - public AjaxResult importTemplateExcel(String sheetName) - { + public AjaxResult importTemplateExcel(String sheetName) { this.init(null, sheetName, Type.IMPORT); return exportExcel(); } /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @return 结果 */ - public AjaxResult exportExcel() - { + public AjaxResult exportExcel() { OutputStream out = null; - try - { + try { // 取出一共有多少个sheet. double sheetNo = Math.ceil(list.size() / sheetSize); - for (int index = 0; index <= sheetNo; index++) - { + for (int index = 0; index <= sheetNo; index++) { createSheet(sheetNo, index); // 产生一行 Row row = sheet.createRow(0); int column = 0; // 写入各个字段的列头名称 - for (Object[] os : fields) - { + for (Object[] os : fields) { Excel excel = (Excel) os[1]; this.createCell(excel, row, column++); } - if (Type.EXPORT.equals(type)) - { + if (Type.EXPORT.equals(type)) { fillExcelData(index, row); } } @@ -346,33 +295,21 @@ public class ExcelUtil out = new FileOutputStream(getAbsoluteFile(filename)); wb.write(out); return AjaxResult.success(filename); - } - catch (Exception e) - { + } catch (Exception e) { log.error("导出Excel异常{}", e.getMessage()); throw new BusinessException("导出Excel失败,请联系网站管理员!"); - } - finally - { - if (wb != null) - { - try - { + } finally { + if (wb != null) { + try { wb.close(); - } - catch (IOException e1) - { + } catch (IOException e1) { e1.printStackTrace(); } } - if (out != null) - { - try - { + if (out != null) { + try { out.close(); - } - catch (IOException e1) - { + } catch (IOException e1) { e1.printStackTrace(); } } @@ -381,22 +318,19 @@ public class ExcelUtil /** * 填充excel数据 - * + * * @param index 序号 - * @param row 单元格行 + * @param row 单元格行 */ - public void fillExcelData(int index, Row row) - { + public void fillExcelData(int index, Row row) { int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, list.size()); - for (int i = startNo; i < endNo; i++) - { + for (int i = startNo; i < endNo; i++) { row = sheet.createRow(i + 1 - startNo); // 得到导出对象. T vo = (T) list.get(i); int column = 0; - for (Object[] os : fields) - { + for (Object[] os : fields) { Field field = (Field) os[0]; Excel excel = (Excel) os[1]; // 设置实体类私有属性可访问 @@ -408,12 +342,11 @@ public class ExcelUtil /** * 创建表格样式 - * + * * @param wb 工作薄对象 * @return 样式列表 */ - private Map createStyles(Workbook wb) - { + private Map createStyles(Workbook wb) { // 写入各条记录,每条记录对应excel表中的一行 Map styles = new HashMap(); CellStyle style = wb.createCellStyle(); @@ -453,8 +386,7 @@ public class ExcelUtil /** * 创建单元格 */ - public Cell createCell(Excel attr, Row row, int column) - { + public Cell createCell(Excel attr, Row row, int column) { // 创建列 Cell cell = row.createCell(column); // 写入列信息 @@ -466,20 +398,16 @@ public class ExcelUtil /** * 设置单元格信息 - * + * * @param value 单元格值 - * @param attr 注解相关 - * @param cell 单元格信息 + * @param attr 注解相关 + * @param cell 单元格信息 */ - public void setCellVo(Object value, Excel attr, Cell cell) - { - if (ColumnType.STRING == attr.cellType()) - { + public void setCellVo(Object value, Excel attr, Cell cell) { + if (ColumnType.STRING == attr.cellType()) { cell.setCellType(CellType.NUMERIC); cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix()); - } - else if (ColumnType.NUMERIC == attr.cellType()) - { + } else if (ColumnType.NUMERIC == attr.cellType()) { cell.setCellType(CellType.NUMERIC); cell.setCellValue(Integer.parseInt(value + "")); } @@ -488,27 +416,21 @@ public class ExcelUtil /** * 创建表格样式 */ - public void setDataValidation(Excel attr, Row row, int column) - { - if (attr.name().indexOf("注:") >= 0) - { + public void setDataValidation(Excel attr, Row row, int column) { + if (attr.name().indexOf("注:") >= 0) { sheet.setColumnWidth(column, 6000); - } - else - { + } else { // 设置列宽 sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); row.setHeight((short) (attr.height() * 20)); } // 如果设置了提示信息则鼠标放上去提示. - if (StringUtils.isNotEmpty(attr.prompt())) - { + if (StringUtils.isNotEmpty(attr.prompt())) { // 这里默认设了2-101列提示. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column); } // 如果设置了combo属性则本列只能选择不能输入 - if (attr.combo().length > 0) - { + if (attr.combo().length > 0) { // 这里默认设了2-101列只能选择不能输入. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column); } @@ -517,16 +439,13 @@ public class ExcelUtil /** * 添加单元格 */ - public Cell addCell(Excel attr, Row row, T vo, Field field, int column) - { + public Cell addCell(Excel attr, Row row, T vo, Field field, int column) { Cell cell = null; - try - { + try { // 设置行高 row.setHeight((short) (attr.height() * 20)); // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. - if (attr.isExport()) - { + if (attr.isExport()) { // 创建cell cell = row.createCell(column); cell.setCellStyle(styles.get("data")); @@ -535,23 +454,16 @@ public class ExcelUtil Object value = getTargetValue(vo, field, attr); String dateFormat = attr.dateFormat(); String readConverterExp = attr.readConverterExp(); - if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) - { + if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) { cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value)); - } - else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) - { + } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) { cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp)); - } - else - { + } else { // 设置列类型 setCellVo(value, attr, cell); } } - } - catch (Exception e) - { + } catch (Exception e) { log.error("导出Excel失败{}", e); } return cell; @@ -559,18 +471,17 @@ public class ExcelUtil /** * 设置 POI XSSFSheet 单元格提示 - * - * @param sheet 表单 - * @param promptTitle 提示标题 + * + * @param sheet 表单 + * @param promptTitle 提示标题 * @param promptContent 提示内容 - * @param firstRow 开始行 - * @param endRow 结束行 - * @param firstCol 开始列 - * @param endCol 结束列 + * @param firstRow 开始行 + * @param endRow 结束行 + * @param firstCol 开始列 + * @param endCol 结束列 */ public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, - int firstCol, int endCol) - { + int firstCol, int endCol) { DataValidationHelper helper = sheet.getDataValidationHelper(); DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); @@ -582,17 +493,16 @@ public class ExcelUtil /** * 设置某些列的值只能输入预制的数据,显示下拉框. - * - * @param sheet 要设置的sheet. + * + * @param sheet 要设置的sheet. * @param textlist 下拉框显示的内容 * @param firstRow 开始行 - * @param endRow 结束行 + * @param endRow 结束行 * @param firstCol 开始列 - * @param endCol 结束列 + * @param endCol 结束列 * @return 设置好的sheet. */ - public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) - { + public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) { DataValidationHelper helper = sheet.getDataValidationHelper(); // 加载下拉列表内容 DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist); @@ -601,13 +511,10 @@ public class ExcelUtil // 数据有效性对象 DataValidation dataValidation = helper.createValidation(constraint, regions); // 处理Excel兼容性问题 - if (dataValidation instanceof XSSFDataValidation) - { + if (dataValidation instanceof XSSFDataValidation) { dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowErrorBox(true); - } - else - { + } else { dataValidation.setSuppressDropDownArrow(false); } @@ -616,28 +523,22 @@ public class ExcelUtil /** * 解析导出值 0=男,1=女,2=未知 - * + * * @param propertyValue 参数值 - * @param converterExp 翻译注解 + * @param converterExp 翻译注解 * @return 解析后值 * @throws Exception */ - public static String convertByExp(String propertyValue, String converterExp) throws Exception - { - try - { + public static String convertByExp(String propertyValue, String converterExp) throws Exception { + try { String[] convertSource = converterExp.split(","); - for (String item : convertSource) - { + for (String item : convertSource) { String[] itemArray = item.split("="); - if (itemArray[0].equals(propertyValue)) - { + if (itemArray[0].equals(propertyValue)) { return itemArray[1]; } } - } - catch (Exception e) - { + } catch (Exception e) { throw e; } return propertyValue; @@ -645,28 +546,22 @@ public class ExcelUtil /** * 反向解析值 男=0,女=1,未知=2 - * + * * @param propertyValue 参数值 - * @param converterExp 翻译注解 + * @param converterExp 翻译注解 * @return 解析后值 * @throws Exception */ - public static String reverseByExp(String propertyValue, String converterExp) throws Exception - { - try - { + public static String reverseByExp(String propertyValue, String converterExp) throws Exception { + try { String[] convertSource = converterExp.split(","); - for (String item : convertSource) - { + for (String item : convertSource) { String[] itemArray = item.split("="); - if (itemArray[1].equals(propertyValue)) - { + if (itemArray[1].equals(propertyValue)) { return itemArray[0]; } } - } - catch (Exception e) - { + } catch (Exception e) { throw e; } return propertyValue; @@ -675,23 +570,20 @@ public class ExcelUtil /** * 编码文件名 */ - public String encodingFilename(String filename) - { + public String encodingFilename(String filename) { filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; return filename; } /** * 获取下载路径 - * + * * @param filename 文件名称 */ - public String getAbsoluteFile(String filename) - { + public String getAbsoluteFile(String filename) { String downloadPath = Global.getDownloadPath() + filename; File desc = new File(downloadPath); - if (!desc.getParentFile().exists()) - { + if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } return downloadPath; @@ -699,29 +591,23 @@ public class ExcelUtil /** * 获取bean中的属性值 - * - * @param vo 实体对象 + * + * @param vo 实体对象 * @param field 字段 * @param excel 注解 * @return 最终的属性值 * @throws Exception */ - private Object getTargetValue(T vo, Field field, Excel excel) throws Exception - { + private Object getTargetValue(T vo, Field field, Excel excel) throws Exception { Object o = field.get(vo); - if (StringUtils.isNotEmpty(excel.targetAttr())) - { + if (StringUtils.isNotEmpty(excel.targetAttr())) { String target = excel.targetAttr(); - if (target.indexOf(".") > -1) - { + if (target.indexOf(".") > -1) { String[] targets = target.split("[.]"); - for (String name : targets) - { + for (String name : targets) { o = getValue(o, name); } - } - else - { + } else { o = getValue(o, target); } } @@ -730,16 +616,14 @@ public class ExcelUtil /** * 以类的属性的get方法方法形式获取值 - * + * * @param o * @param name * @return value * @throws Exception */ - private Object getValue(Object o, String name) throws Exception - { - if (StringUtils.isNotEmpty(name)) - { + private Object getValue(Object o, String name) throws Exception { + if (StringUtils.isNotEmpty(name)) { Class clazz = o.getClass(); String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = clazz.getMethod(methodName); @@ -751,27 +635,22 @@ public class ExcelUtil /** * 得到所有定义字段 */ - private void createExcelField() - { + private void createExcelField() { this.fields = new ArrayList(); List tempFields = new ArrayList<>(); tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); - for (Field field : tempFields) - { + for (Field field : tempFields) { // 单注解 - if (field.isAnnotationPresent(Excel.class)) - { + if (field.isAnnotationPresent(Excel.class)) { putToField(field, field.getAnnotation(Excel.class)); } // 多注解 - if (field.isAnnotationPresent(Excels.class)) - { + if (field.isAnnotationPresent(Excels.class)) { Excels attrs = field.getAnnotation(Excels.class); Excel[] excels = attrs.value(); - for (Excel excel : excels) - { + for (Excel excel : excels) { putToField(field, excel); } } @@ -781,98 +660,72 @@ public class ExcelUtil /** * 放到字段集合中 */ - private void putToField(Field field, Excel attr) - { - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) - { - this.fields.add(new Object[] { field, attr }); + private void putToField(Field field, Excel attr) { + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) { + this.fields.add(new Object[]{field, attr}); } } /** * 创建一个工作簿 */ - public void createWorkbook() - { + public void createWorkbook() { this.wb = new SXSSFWorkbook(500); } /** * 创建工作表 - * + * * @param sheetNo sheet数量 - * @param index 序号 + * @param index 序号 */ - public void createSheet(double sheetNo, int index) - { + public void createSheet(double sheetNo, int index) { this.sheet = wb.createSheet(); this.styles = createStyles(wb); // 设置工作表的名称. - if (sheetNo == 0) - { + if (sheetNo == 0) { wb.setSheetName(index, sheetName); - } - else - { + } else { wb.setSheetName(index, sheetName + index); } } /** * 获取单元格值 - * - * @param row 获取的行 + * + * @param row 获取的行 * @param column 获取单元格列号 * @return 单元格值 */ - public Object getCellValue(Row row, int column) - { - if (row == null) - { + public Object getCellValue(Row row, int column) { + if (row == null) { return row; } Object val = ""; - try - { + try { Cell cell = row.getCell(column); - if (cell != null) - { - if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) - { + if (cell != null) { + if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) { val = cell.getNumericCellValue(); - if (HSSFDateUtil.isCellDateFormatted(cell)) - { + if (HSSFDateUtil.isCellDateFormatted(cell)) { val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 - } - else - { - if ((Double) val % 1 > 0) - { + } else { + if ((Double) val % 1 > 0) { val = new DecimalFormat("0.00").format(val); - } - else - { + } else { val = new DecimalFormat("0").format(val); } } - } - else if (cell.getCellTypeEnum() == CellType.STRING) - { + } else if (cell.getCellTypeEnum() == CellType.STRING) { val = cell.getStringCellValue(); - } - else if (cell.getCellTypeEnum() == CellType.BOOLEAN) - { + } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) { val = cell.getBooleanCellValue(); - } - else if (cell.getCellTypeEnum() == CellType.ERROR) - { + } else if (cell.getCellTypeEnum() == CellType.ERROR) { val = cell.getErrorCellValue(); } } - } - catch (Exception e) - { + } catch (Exception e) { return val; } return val; diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java index b78e53e10..f56cc66b9 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java @@ -7,6 +7,7 @@ import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Date; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.poi.ss.usermodel.DateUtil; @@ -17,12 +18,11 @@ import com.ruoyi.common.utils.DateUtils; /** * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. - * + * * @author ruoyi */ @SuppressWarnings("rawtypes") -public class ReflectUtils -{ +public class ReflectUtils { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; @@ -36,13 +36,11 @@ public class ReflectUtils * 支持多级,如:对象名.对象名.方法 */ @SuppressWarnings("unchecked") - public static E invokeGetter(Object obj, String propertyName) - { + public static E invokeGetter(Object obj, String propertyName) { Object object = obj; - for (String name : StringUtils.split(propertyName, ".")) - { + for (String name : StringUtils.split(propertyName, ".")) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); - object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); + object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{}); } return (E) object; } @@ -51,21 +49,16 @@ public class ReflectUtils * 调用Setter方法, 仅匹配方法名。 * 支持多级,如:对象名.对象名.方法 */ - public static void invokeSetter(Object obj, String propertyName, E value) - { + public static void invokeSetter(Object obj, String propertyName, E value) { Object object = obj; String[] names = StringUtils.split(propertyName, "."); - for (int i = 0; i < names.length; i++) - { - if (i < names.length - 1) - { + for (int i = 0; i < names.length; i++) { + if (i < names.length - 1) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); - object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); - } - else - { + object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{}); + } else { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); - invokeMethodByName(object, setterMethodName, new Object[] { value }); + invokeMethodByName(object, setterMethodName, new Object[]{value}); } } } @@ -74,21 +67,16 @@ public class ReflectUtils * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */ @SuppressWarnings("unchecked") - public static E getFieldValue(final Object obj, final String fieldName) - { + public static E getFieldValue(final Object obj, final String fieldName) { Field field = getAccessibleField(obj, fieldName); - if (field == null) - { + if (field == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return null; } E result = null; - try - { + try { result = (E) field.get(obj); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { logger.error("不可能抛出的异常{}", e.getMessage()); } return result; @@ -97,21 +85,16 @@ public class ReflectUtils /** * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ - public static void setFieldValue(final Object obj, final String fieldName, final E value) - { + public static void setFieldValue(final Object obj, final String fieldName, final E value) { Field field = getAccessibleField(obj, fieldName); - if (field == null) - { + if (field == null) { // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return; } - try - { + try { field.set(obj, value); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { logger.error("不可能抛出的异常: {}", e.getMessage()); } } @@ -123,24 +106,18 @@ public class ReflectUtils */ @SuppressWarnings("unchecked") public static E invokeMethod(final Object obj, final String methodName, final Class[] parameterTypes, - final Object[] args) - { - if (obj == null || methodName == null) - { + final Object[] args) { + if (obj == null || methodName == null) { return null; } Method method = getAccessibleMethod(obj, methodName, parameterTypes); - if (method == null) - { + if (method == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } - try - { + try { return (E) method.invoke(obj, args); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; throw convertReflectionExceptionToUnchecked(msg, e); } @@ -152,64 +129,42 @@ public class ReflectUtils * 只匹配函数名,如果有多个同名函数调用第一个。 */ @SuppressWarnings("unchecked") - public static E invokeMethodByName(final Object obj, final String methodName, final Object[] args) - { + public static E invokeMethodByName(final Object obj, final String methodName, final Object[] args) { Method method = getAccessibleMethodByName(obj, methodName, args.length); - if (method == null) - { + if (method == null) { // 如果为空不报错,直接返回空。 logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } - try - { + try { // 类型转换(将参数数据类型转换为目标方法参数类型) Class[] cs = method.getParameterTypes(); - for (int i = 0; i < cs.length; i++) - { - if (args[i] != null && !args[i].getClass().equals(cs[i])) - { - if (cs[i] == String.class) - { + for (int i = 0; i < cs.length; i++) { + if (args[i] != null && !args[i].getClass().equals(cs[i])) { + if (cs[i] == String.class) { args[i] = Convert.toStr(args[i]); - if (StringUtils.endsWith((String) args[i], ".0")) - { + if (StringUtils.endsWith((String) args[i], ".0")) { args[i] = StringUtils.substringBefore((String) args[i], ".0"); } - } - else if (cs[i] == Integer.class) - { + } else if (cs[i] == Integer.class) { args[i] = Convert.toInt(args[i]); - } - else if (cs[i] == Long.class) - { + } else if (cs[i] == Long.class) { args[i] = Convert.toLong(args[i]); - } - else if (cs[i] == Double.class) - { + } else if (cs[i] == Double.class) { args[i] = Convert.toDouble(args[i]); - } - else if (cs[i] == Float.class) - { + } else if (cs[i] == Float.class) { args[i] = Convert.toFloat(args[i]); - } - else if (cs[i] == Date.class) - { - if (args[i] instanceof String) - { + } else if (cs[i] == Date.class) { + if (args[i] instanceof String) { args[i] = DateUtils.parseDate(args[i]); - } - else - { + } else { args[i] = DateUtil.getJavaDate((Double) args[i]); } } } } return (E) method.invoke(obj, args); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; throw convertReflectionExceptionToUnchecked(msg, e); } @@ -219,24 +174,18 @@ public class ReflectUtils * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. * 如向上转型到Object仍无法找到, 返回null. */ - public static Field getAccessibleField(final Object obj, final String fieldName) - { + public static Field getAccessibleField(final Object obj, final String fieldName) { // 为空不报错。直接返回 null - if (obj == null) - { + if (obj == null) { return null; } Validate.notBlank(fieldName, "fieldName can't be blank"); - for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) - { - try - { + for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { + try { Field field = superClass.getDeclaredField(fieldName); makeAccessible(field); return field; - } - catch (NoSuchFieldException e) - { + } catch (NoSuchFieldException e) { continue; } } @@ -250,24 +199,18 @@ public class ReflectUtils * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, - final Class... parameterTypes) - { + final Class... parameterTypes) { // 为空不报错。直接返回 null - if (obj == null) - { + if (obj == null) { return null; } Validate.notBlank(methodName, "methodName can't be blank"); - for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) - { - try - { + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { + try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { continue; } } @@ -280,21 +223,16 @@ public class ReflectUtils * 只匹配函数名。 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ - public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) - { + public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) { // 为空不报错。直接返回 null - if (obj == null) - { + if (obj == null) { return null; } Validate.notBlank(methodName, "methodName can't be blank"); - for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) - { + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { Method[] methods = searchType.getDeclaredMethods(); - for (Method method : methods) - { - if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) - { + for (Method method : methods) { + if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) { makeAccessible(method); return method; } @@ -306,11 +244,9 @@ public class ReflectUtils /** * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */ - public static void makeAccessible(Method method) - { + public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) - && !method.isAccessible()) - { + && !method.isAccessible()) { method.setAccessible(true); } } @@ -318,11 +254,9 @@ public class ReflectUtils /** * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */ - public static void makeAccessible(Field field) - { + public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) - || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) - { + || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } @@ -332,8 +266,7 @@ public class ReflectUtils * 如无法找到, 返回Object.class. */ @SuppressWarnings("unchecked") - public static Class getClassGenricType(final Class clazz) - { + public static Class getClassGenricType(final Class clazz) { return getClassGenricType(clazz, 0); } @@ -341,26 +274,22 @@ public class ReflectUtils * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. * 如无法找到, 返回Object.class. */ - public static Class getClassGenricType(final Class clazz, final int index) - { + public static Class getClassGenricType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); - if (!(genType instanceof ParameterizedType)) - { + if (!(genType instanceof ParameterizedType)) { logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); - if (index >= params.length || index < 0) - { + if (index >= params.length || index < 0) { logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } - if (!(params[index] instanceof Class)) - { + if (!(params[index] instanceof Class)) { logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } @@ -368,18 +297,14 @@ public class ReflectUtils return (Class) params[index]; } - public static Class getUserClass(Object instance) - { - if (instance == null) - { + public static Class getUserClass(Object instance) { + if (instance == null) { throw new RuntimeException("Instance must not be null"); } Class clazz = instance.getClass(); - if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) - { + if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { Class superClass = clazz.getSuperclass(); - if (superClass != null && !Object.class.equals(superClass)) - { + if (superClass != null && !Object.class.equals(superClass)) { return superClass; } } @@ -390,15 +315,11 @@ public class ReflectUtils /** * 将反射时的checked exception转换为unchecked exception. */ - public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) - { + public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException - || e instanceof NoSuchMethodException) - { + || e instanceof NoSuchMethodException) { return new IllegalArgumentException(msg, e); - } - else if (e instanceof InvocationTargetException) - { + } else if (e instanceof InvocationTargetException) { return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException()); } return new RuntimeException(msg, e); diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/Md5Utils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/Md5Utils.java index 40e80304a..a3d289bac 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/Md5Utils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/Md5Utils.java @@ -1,66 +1,54 @@ -package com.ruoyi.common.utils.security; - -import java.security.MessageDigest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Md5加密方法 - * - * @author ruoyi - */ -public class Md5Utils -{ - private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); - - private static byte[] md5(String s) - { - MessageDigest algorithm; - try - { - algorithm = MessageDigest.getInstance("MD5"); - algorithm.reset(); - algorithm.update(s.getBytes("UTF-8")); - byte[] messageDigest = algorithm.digest(); - return messageDigest; - } - catch (Exception e) - { - log.error("MD5 Error...", e); - } - return null; - } - - private static final String toHex(byte hash[]) - { - if (hash == null) - { - return null; - } - StringBuffer buf = new StringBuffer(hash.length * 2); - int i; - - for (i = 0; i < hash.length; i++) - { - if ((hash[i] & 0xff) < 0x10) - { - buf.append("0"); - } - buf.append(Long.toString(hash[i] & 0xff, 16)); - } - return buf.toString(); - } - - public static String hash(String s) - { - try - { - return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8"); - } - catch (Exception e) - { - log.error("not supported charset...{}", e); - return s; - } - } -} +package com.ruoyi.common.utils.security; + +import java.security.MessageDigest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Md5加密方法 + * + * @author ruoyi + */ +public class Md5Utils { + private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); + + private static byte[] md5(String s) { + MessageDigest algorithm; + try { + algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(s.getBytes("UTF-8")); + byte[] messageDigest = algorithm.digest(); + return messageDigest; + } catch (Exception e) { + log.error("MD5 Error...", e); + } + return null; + } + + private static final String toHex(byte hash[]) { + if (hash == null) { + return null; + } + StringBuffer buf = new StringBuffer(hash.length * 2); + int i; + + for (i = 0; i < hash.length; i++) { + if ((hash[i] & 0xff) < 0x10) { + buf.append("0"); + } + buf.append(Long.toString(hash[i] & 0xff, 16)); + } + return buf.toString(); + } + + public static String hash(String s) { + try { + return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8"); + } catch (Exception e) { + log.error("not supported charset...{}", e); + return s; + } + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/PermissionUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/PermissionUtils.java index 3b6f098ca..4c0a49d0a 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/PermissionUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/security/PermissionUtils.java @@ -1,118 +1,101 @@ -package com.ruoyi.common.utils.security; - -import java.beans.BeanInfo; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import org.apache.commons.lang3.StringUtils; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.subject.Subject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.constant.PermissionConstants; -import com.ruoyi.common.utils.MessageUtils; - -/** - * permission 工具类 - * - * @author ruoyi - */ -public class PermissionUtils -{ - private static final Logger log = LoggerFactory.getLogger(PermissionUtils.class); - - /** - * 查看数据的权限 - */ - public static final String VIEW_PERMISSION = "no.view.permission"; - - /** - * 创建数据的权限 - */ - public static final String CREATE_PERMISSION = "no.create.permission"; - - /** - * 修改数据的权限 - */ - public static final String UPDATE_PERMISSION = "no.update.permission"; - - /** - * 删除数据的权限 - */ - public static final String DELETE_PERMISSION = "no.delete.permission"; - - /** - * 导出数据的权限 - */ - public static final String EXPORT_PERMISSION = "no.export.permission"; - - /** - * 其他数据的权限 - */ - public static final String PERMISSION = "no.permission"; - - /** - * 权限错误消息提醒 - * - * @param permissionsStr 错误信息 - * @return 提示信息 - */ - public static String getMsg(String permissionsStr) - { - String permission = StringUtils.substringBetween(permissionsStr, "[", "]"); - String msg = MessageUtils.message(PERMISSION, permission); - if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.ADD_PERMISSION)) - { - msg = MessageUtils.message(CREATE_PERMISSION, permission); - } - else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.EDIT_PERMISSION)) - { - msg = MessageUtils.message(UPDATE_PERMISSION, permission); - } - else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.REMOVE_PERMISSION)) - { - msg = MessageUtils.message(DELETE_PERMISSION, permission); - } - else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.EXPORT_PERMISSION)) - { - msg = MessageUtils.message(EXPORT_PERMISSION, permission); - } - else if (StringUtils.endsWithAny(permission, - new String[] { PermissionConstants.VIEW_PERMISSION, PermissionConstants.LIST_PERMISSION })) - { - msg = MessageUtils.message(VIEW_PERMISSION, permission); - } - return msg; - } - - /** - * 返回用户属性值 - * - * @param property 属性名称 - * @return 用户属性值 - */ - public static Object getPrincipalProperty(String property) - { - Subject subject = SecurityUtils.getSubject(); - if (subject != null) - { - Object principal = subject.getPrincipal(); - try - { - BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); - for (PropertyDescriptor pd : bi.getPropertyDescriptors()) - { - if (pd.getName().equals(property) == true) - { - return pd.getReadMethod().invoke(principal, (Object[]) null); - } - } - } - catch (Exception e) - { - log.error("Error reading property [{}] from principal of type [{}]", property, - principal.getClass().getName()); - } - } - return null; - } -} +package com.ruoyi.common.utils.security; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; + +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.constant.PermissionConstants; +import com.ruoyi.common.utils.MessageUtils; + +/** + * permission 工具类 + * + * @author ruoyi + */ +public class PermissionUtils { + private static final Logger log = LoggerFactory.getLogger(PermissionUtils.class); + + /** + * 查看数据的权限 + */ + public static final String VIEW_PERMISSION = "no.view.permission"; + + /** + * 创建数据的权限 + */ + public static final String CREATE_PERMISSION = "no.create.permission"; + + /** + * 修改数据的权限 + */ + public static final String UPDATE_PERMISSION = "no.update.permission"; + + /** + * 删除数据的权限 + */ + public static final String DELETE_PERMISSION = "no.delete.permission"; + + /** + * 导出数据的权限 + */ + public static final String EXPORT_PERMISSION = "no.export.permission"; + + /** + * 其他数据的权限 + */ + public static final String PERMISSION = "no.permission"; + + /** + * 权限错误消息提醒 + * + * @param permissionsStr 错误信息 + * @return 提示信息 + */ + public static String getMsg(String permissionsStr) { + String permission = StringUtils.substringBetween(permissionsStr, "[", "]"); + String msg = MessageUtils.message(PERMISSION, permission); + if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.ADD_PERMISSION)) { + msg = MessageUtils.message(CREATE_PERMISSION, permission); + } else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.EDIT_PERMISSION)) { + msg = MessageUtils.message(UPDATE_PERMISSION, permission); + } else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.REMOVE_PERMISSION)) { + msg = MessageUtils.message(DELETE_PERMISSION, permission); + } else if (StringUtils.endsWithIgnoreCase(permission, PermissionConstants.EXPORT_PERMISSION)) { + msg = MessageUtils.message(EXPORT_PERMISSION, permission); + } else if (StringUtils.endsWithAny(permission, + new String[]{PermissionConstants.VIEW_PERMISSION, PermissionConstants.LIST_PERMISSION})) { + msg = MessageUtils.message(VIEW_PERMISSION, permission); + } + return msg; + } + + /** + * 返回用户属性值 + * + * @param property 属性名称 + * @return 用户属性值 + */ + public static Object getPrincipalProperty(String property) { + Subject subject = SecurityUtils.getSubject(); + if (subject != null) { + Object principal = subject.getPrincipal(); + try { + BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); + for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { + if (pd.getName().equals(property) == true) { + return pd.getReadMethod().invoke(principal, (Object[]) null); + } + } + } catch (Exception e) { + log.error("Error reading property [{}] from principal of type [{}]", property, + principal.getClass().getName()); + } + } + return null; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java index e0311595a..4cdbf14ff 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java @@ -1,114 +1,102 @@ -package com.ruoyi.common.utils.spring; - -import org.springframework.aop.framework.AopContext; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.stereotype.Component; - -/** - * spring工具类 方便在非spring管理环境中获取bean - * - * @author ruoyi - */ -@Component -public final class SpringUtils implements BeanFactoryPostProcessor -{ - /** Spring应用上下文环境 */ - private static ConfigurableListableBeanFactory beanFactory; - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException - { - SpringUtils.beanFactory = beanFactory; - } - - /** - * 获取对象 - * - * @param name - * @return Object 一个以所给名字注册的bean的实例 - * @throws org.springframework.beans.BeansException - * - */ - @SuppressWarnings("unchecked") - public static T getBean(String name) throws BeansException - { - return (T) beanFactory.getBean(name); - } - - /** - * 获取类型为requiredType的对象 - * - * @param clz - * @return - * @throws org.springframework.beans.BeansException - * - */ - public static T getBean(Class clz) throws BeansException - { - T result = (T) beanFactory.getBean(clz); - return result; - } - - /** - * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true - * - * @param name - * @return boolean - */ - public static boolean containsBean(String name) - { - return beanFactory.containsBean(name); - } - - /** - * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) - * - * @param name - * @return boolean - * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException - * - */ - public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException - { - return beanFactory.isSingleton(name); - } - - /** - * @param name - * @return Class 注册对象的类型 - * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException - * - */ - public static Class getType(String name) throws NoSuchBeanDefinitionException - { - return beanFactory.getType(name); - } - - /** - * 如果给定的bean名字在bean定义中有别名,则返回这些别名 - * - * @param name - * @return - * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException - * - */ - public static String[] getAliases(String name) throws NoSuchBeanDefinitionException - { - return beanFactory.getAliases(name); - } - - /** - * 获取aop代理对象 - * - * @param invoker - * @return - */ - @SuppressWarnings("unchecked") - public static T getAopProxy(T invoker) - { - return (T) AopContext.currentProxy(); - } -} +package com.ruoyi.common.utils.spring; + +import org.springframework.aop.framework.AopContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.stereotype.Component; + +/** + * spring工具类 方便在非spring管理环境中获取bean + * + * @author ruoyi + */ +@Component +public final class SpringUtils implements BeanFactoryPostProcessor { + /** + * Spring应用上下文环境 + */ + private static ConfigurableListableBeanFactory beanFactory; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + SpringUtils.beanFactory = beanFactory; + } + + /** + * 获取对象 + * + * @param name + * @return Object 一个以所给名字注册的bean的实例 + * @throws org.springframework.beans.BeansException + */ + @SuppressWarnings("unchecked") + public static T getBean(String name) throws BeansException { + return (T) beanFactory.getBean(name); + } + + /** + * 获取类型为requiredType的对象 + * + * @param clz + * @return + * @throws org.springframework.beans.BeansException + */ + public static T getBean(Class clz) throws BeansException { + T result = (T) beanFactory.getBean(clz); + return result; + } + + /** + * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true + * + * @param name + * @return boolean + */ + public static boolean containsBean(String name) { + return beanFactory.containsBean(name); + } + + /** + * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) + * + * @param name + * @return boolean + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + */ + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return beanFactory.isSingleton(name); + } + + /** + * @param name + * @return Class 注册对象的类型 + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + */ + public static Class getType(String name) throws NoSuchBeanDefinitionException { + return beanFactory.getType(name); + } + + /** + * 如果给定的bean名字在bean定义中有别名,则返回这些别名 + * + * @param name + * @return + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + */ + public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { + return beanFactory.getAliases(name); + } + + /** + * 获取aop代理对象 + * + * @param invoker + * @return + */ + @SuppressWarnings("unchecked") + public static T getAopProxy(T invoker) { + return (T) AopContext.currentProxy(); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java index b31804b67..088893315 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java @@ -4,11 +4,10 @@ import com.ruoyi.common.utils.StringUtils; /** * sql操作工具类 - * + * * @author ruoyi */ -public class SqlUtil -{ +public class SqlUtil { /** * 仅支持字母、数字、下划线、空格、逗号(支持多个字段排序) */ @@ -17,10 +16,8 @@ public class SqlUtil /** * 检查字符,防止注入绕过 */ - public static String escapeOrderBySql(String value) - { - if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) - { + public static String escapeOrderBySql(String value) { + if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { return StringUtils.EMPTY; } return value; @@ -29,8 +26,7 @@ public class SqlUtil /** * 验证 order by 语法是否符合规范 */ - public static boolean isValidOrderBySql(String value) - { + public static boolean isValidOrderBySql(String value) { return value.matches(SQL_PATTERN); } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssFilter.java b/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssFilter.java index d307fbc9f..61c502c85 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssFilter.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssFilter.java @@ -1,97 +1,85 @@ -package com.ruoyi.common.xss; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import com.ruoyi.common.utils.StringUtils; - -/** - * 防止XSS攻击的过滤器 - * - * @author ruoyi - */ -public class XssFilter implements Filter -{ - /** - * 排除链接 - */ - public List excludes = new ArrayList<>(); - - /** - * xss过滤开关 - */ - public boolean enabled = false; - - @Override - public void init(FilterConfig filterConfig) throws ServletException - { - String tempExcludes = filterConfig.getInitParameter("excludes"); - String tempEnabled = filterConfig.getInitParameter("enabled"); - if (StringUtils.isNotEmpty(tempExcludes)) - { - String[] url = tempExcludes.split(","); - for (int i = 0; url != null && i < url.length; i++) - { - excludes.add(url[i]); - } - } - if (StringUtils.isNotEmpty(tempEnabled)) - { - enabled = Boolean.valueOf(tempEnabled); - } - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException - { - HttpServletRequest req = (HttpServletRequest) request; - HttpServletResponse resp = (HttpServletResponse) response; - if (handleExcludeURL(req, resp)) - { - chain.doFilter(request, response); - return; - } - XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); - chain.doFilter(xssRequest, response); - } - - private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) - { - if (!enabled) - { - return true; - } - if (excludes == null || excludes.isEmpty()) - { - return false; - } - String url = request.getServletPath(); - for (String pattern : excludes) - { - Pattern p = Pattern.compile("^" + pattern); - Matcher m = p.matcher(url); - if (m.find()) - { - return true; - } - } - return false; - } - - @Override - public void destroy() - { - - } +package com.ruoyi.common.xss; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.ruoyi.common.utils.StringUtils; + +/** + * 防止XSS攻击的过滤器 + * + * @author ruoyi + */ +public class XssFilter implements Filter { + /** + * 排除链接 + */ + public List excludes = new ArrayList<>(); + + /** + * xss过滤开关 + */ + public boolean enabled = false; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + String tempExcludes = filterConfig.getInitParameter("excludes"); + String tempEnabled = filterConfig.getInitParameter("enabled"); + if (StringUtils.isNotEmpty(tempExcludes)) { + String[] url = tempExcludes.split(","); + for (int i = 0; url != null && i < url.length; i++) { + excludes.add(url[i]); + } + } + if (StringUtils.isNotEmpty(tempEnabled)) { + enabled = Boolean.valueOf(tempEnabled); + } + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse resp = (HttpServletResponse) response; + if (handleExcludeURL(req, resp)) { + chain.doFilter(request, response); + return; + } + XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); + chain.doFilter(xssRequest, response); + } + + private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { + if (!enabled) { + return true; + } + if (excludes == null || excludes.isEmpty()) { + return false; + } + String url = request.getServletPath(); + for (String pattern : excludes) { + Pattern p = Pattern.compile("^" + pattern); + Matcher m = p.matcher(url); + if (m.find()) { + return true; + } + } + return false; + } + + @Override + public void destroy() { + + } } \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssHttpServletRequestWrapper.java b/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssHttpServletRequestWrapper.java index 516db0a90..671b83c7a 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssHttpServletRequestWrapper.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssHttpServletRequestWrapper.java @@ -1,39 +1,35 @@ -package com.ruoyi.common.xss; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import com.ruoyi.common.utils.html.EscapeUtil; - -/** - * XSS过滤处理 - * - * @author ruoyi - */ -public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper -{ - /** - * @param request - */ - public XssHttpServletRequestWrapper(HttpServletRequest request) - { - super(request); - } - - @Override - public String[] getParameterValues(String name) - { - String[] values = super.getParameterValues(name); - if (values != null) - { - int length = values.length; - String[] escapseValues = new String[length]; - for (int i = 0; i < length; i++) - { - // 防xss攻击和过滤前后空格 - escapseValues[i] = EscapeUtil.clean(values[i]).trim(); - } - return escapseValues; - } - return super.getParameterValues(name); - } +package com.ruoyi.common.xss; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +import com.ruoyi.common.utils.html.EscapeUtil; + +/** + * XSS过滤处理 + * + * @author ruoyi + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { + /** + * @param request + */ + public XssHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + } + + @Override + public String[] getParameterValues(String name) { + String[] values = super.getParameterValues(name); + if (values != null) { + int length = values.length; + String[] escapseValues = new String[length]; + for (int i = 0; i < length; i++) { + // 防xss攻击和过滤前后空格 + escapseValues[i] = EscapeUtil.clean(values[i]).trim(); + } + return escapseValues; + } + return super.getParameterValues(name); + } } \ No newline at end of file From a41994e88be16b1d1d2af2b2add4e4fa3262c9b4 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:15:39 +0800 Subject: [PATCH 04/52] format code --- .../main/java/com/ruoyi/RuoYiApplication.java | 90 +- .../controller/common/CommonController.java | 213 +++-- .../demo/controller/DemoDialogController.java | 152 ++-- .../demo/controller/DemoFormController.java | 520 ++++++------ .../demo/controller/DemoIconController.java | 67 +- .../controller/DemoOperateController.java | 590 +++++++------ .../demo/controller/DemoReportController.java | 101 ++- .../demo/controller/DemoTableController.java | 780 +++++++++--------- .../demo/domain/UserOperateModel.java | 272 +++--- .../controller/monitor/DruidController.java | 50 +- .../controller/monitor/ServerController.java | 60 +- .../monitor/SysLogininforController.java | 182 ++-- .../monitor/SysOperlogController.java | 172 ++-- .../monitor/SysUserOnlineController.java | 217 +++-- .../system/SysCaptchaController.java | 169 ++-- .../system/SysConfigController.java | 277 +++---- .../controller/system/SysDeptController.java | 342 ++++---- .../system/SysDictDataController.java | 232 +++--- .../system/SysDictTypeController.java | 347 ++++---- .../controller/system/SysIndexController.java | 107 ++- .../controller/system/SysLoginController.java | 28 +- .../controller/system/SysMenuController.java | 371 ++++----- .../system/SysNoticeController.java | 217 +++-- .../controller/system/SysPostController.java | 307 ++++--- .../system/SysProfileController.java | 326 ++++---- .../controller/system/SysRoleController.java | 575 ++++++------- .../controller/system/SysUserController.java | 491 ++++++----- .../web/controller/tool/BuildController.java | 50 +- .../controller/tool/SwaggerController.java | 46 +- .../web/controller/tool/TestController.java | 326 ++++---- .../ruoyi/web/core/config/SwaggerConfig.java | 121 ++- 31 files changed, 3703 insertions(+), 4095 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java index 03b2765e4..bafa08b4b 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java @@ -1,46 +1,46 @@ -package com.ruoyi; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Bean; - -/** - * 启动程序 - * - * @author ruoyi - */ -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) -public class RuoYiApplication extends SpringBootServletInitializer { - public static void main(String[] args) { - // System.setProperty("spring.devtools.restart.enabled", "false"); - SpringApplication.run(RuoYiApplication.class, args); - } - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(RuoYiApplication.class); - } - - @Bean - public CommandLineRunner startupCommandLineRunner(){ - return new CommandLineRunner() { - @Override - public void run(String... args) throws Exception { - System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + - " .-------. ____ __ \n" + - " | _ _ \\ \\ \\ / / \n" + - " | ( ' ) | \\ _. / ' \n" + - " |(_ o _) / _( )_ .' \n" + - " | (_,_).' __ ___(_ o _)' \n" + - " | |\\ \\ | || |(_,_)' \n" + - " | | \\ `' /| `-' / \n" + - " | | \\ / \\ / \n" + - " ''-' `'-' `-..-' "); - } - }; - } +package com.ruoyi; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; + +/** + * 启动程序 + * + * @author ruoyi + */ +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) +public class RuoYiApplication extends SpringBootServletInitializer { + public static void main(String[] args) { + // System.setProperty("spring.devtools.restart.enabled", "false"); + SpringApplication.run(RuoYiApplication.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(RuoYiApplication.class); + } + + @Bean + public CommandLineRunner startupCommandLineRunner() { + return new CommandLineRunner() { + @Override + public void run(String... args) throws Exception { + System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + + " .-------. ____ __ \n" + + " | _ _ \\ \\ \\ / / \n" + + " | ( ' ) | \\ _. / ' \n" + + " |(_ o _) / _( )_ .' \n" + + " | (_,_).' __ ___(_ o _)' \n" + + " | |\\ \\ | || |(_,_)' \n" + + " | | \\ `' /| `-' / \n" + + " | | \\ / \\ / \n" + + " ''-' `'-' `-..-' "); + } + }; + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java index c8f7e3ad0..69b8034de 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java @@ -1,112 +1,101 @@ -package com.ruoyi.web.controller.common; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.config.ServerConfig; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.file.FileUploadUtils; -import com.ruoyi.common.utils.file.FileUtils; - -/** - * 通用请求处理 - * - * @author ruoyi - */ -@Controller -public class CommonController -{ - private static final Logger log = LoggerFactory.getLogger(CommonController.class); - - @Autowired - private ServerConfig serverConfig; - - /** - * 通用下载请求 - * - * @param fileName 文件名称 - * @param delete 是否删除 - */ - @GetMapping("common/download") - public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) - { - try - { - if (!FileUtils.isValidFilename(fileName)) - { - throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName)); - } - String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1); - String filePath = Global.getDownloadPath() + fileName; - - response.setCharacterEncoding("utf-8"); - response.setContentType("multipart/form-data"); - response.setHeader("Content-Disposition", - "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName)); - FileUtils.writeBytes(filePath, response.getOutputStream()); - if (delete) - { - FileUtils.deleteFile(filePath); - } - } - catch (Exception e) - { - log.error("下载文件失败", e); - } - } - - /** - * 通用上传请求 - */ - @PostMapping("/common/upload") - @ResponseBody - public AjaxResult uploadFile(MultipartFile file) throws Exception - { - try - { - // 上传文件路径 - String filePath = Global.getUploadPath(); - // 上传并返回新文件名称 - String fileName = FileUploadUtils.upload(filePath, file); - String url = serverConfig.getUrl() + fileName; - AjaxResult ajax = AjaxResult.success(); - ajax.put("fileName", fileName); - ajax.put("url", url); - return ajax; - } - catch (Exception e) - { - return AjaxResult.error(e.getMessage()); - } - } - - /** - * 本地资源通用下载 - */ - @GetMapping("/common/download/resource") - public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) - throws Exception - { - // 本地资源路径 - String localPath = Global.getProfile(); - // 数据库资源地址 - String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX); - // 下载名称 - String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); - response.setCharacterEncoding("utf-8"); - response.setContentType("multipart/form-data"); - response.setHeader("Content-Disposition", - "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName)); - FileUtils.writeBytes(downloadPath, response.getOutputStream()); - } -} +package com.ruoyi.web.controller.common; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.config.ServerConfig; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.file.FileUploadUtils; +import com.ruoyi.common.utils.file.FileUtils; + +/** + * 通用请求处理 + * + * @author ruoyi + */ +@Controller +public class CommonController { + private static final Logger log = LoggerFactory.getLogger(CommonController.class); + + @Autowired + private ServerConfig serverConfig; + + /** + * 通用下载请求 + * + * @param fileName 文件名称 + * @param delete 是否删除 + */ + @GetMapping("common/download") + public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) { + try { + if (!FileUtils.isValidFilename(fileName)) { + throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName)); + } + String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1); + String filePath = Global.getDownloadPath() + fileName; + + response.setCharacterEncoding("utf-8"); + response.setContentType("multipart/form-data"); + response.setHeader("Content-Disposition", + "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName)); + FileUtils.writeBytes(filePath, response.getOutputStream()); + if (delete) { + FileUtils.deleteFile(filePath); + } + } catch (Exception e) { + log.error("下载文件失败", e); + } + } + + /** + * 通用上传请求 + */ + @PostMapping("/common/upload") + @ResponseBody + public AjaxResult uploadFile(MultipartFile file) throws Exception { + try { + // 上传文件路径 + String filePath = Global.getUploadPath(); + // 上传并返回新文件名称 + String fileName = FileUploadUtils.upload(filePath, file); + String url = serverConfig.getUrl() + fileName; + AjaxResult ajax = AjaxResult.success(); + ajax.put("fileName", fileName); + ajax.put("url", url); + return ajax; + } catch (Exception e) { + return AjaxResult.error(e.getMessage()); + } + } + + /** + * 本地资源通用下载 + */ + @GetMapping("/common/download/resource") + public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) + throws Exception { + // 本地资源路径 + String localPath = Global.getProfile(); + // 数据库资源地址 + String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX); + // 下载名称 + String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); + response.setCharacterEncoding("utf-8"); + response.setContentType("multipart/form-data"); + response.setHeader("Content-Disposition", + "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName)); + FileUtils.writeBytes(downloadPath, response.getOutputStream()); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoDialogController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoDialogController.java index 78d6da74b..e709b2dcc 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoDialogController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoDialogController.java @@ -1,80 +1,72 @@ -package com.ruoyi.web.controller.demo.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * 模态窗口 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/modal") -public class DemoDialogController -{ - private String prefix = "demo/modal"; - - /** - * 模态窗口 - */ - @GetMapping("/dialog") - public String dialog() - { - return prefix + "/dialog"; - } - - /** - * 弹层组件 - */ - @GetMapping("/layer") - public String layer() - { - return prefix + "/layer"; - } - - /** - * 表单 - */ - @GetMapping("/form") - public String form() - { - return prefix + "/form"; - } - - /** - * 表格 - */ - @GetMapping("/table") - public String table() - { - return prefix + "/table"; - } - - /** - * 表格check - */ - @GetMapping("/check") - public String check() - { - return prefix + "/table/check"; - } - - /** - * 表格radio - */ - @GetMapping("/radio") - public String radio() - { - return prefix + "/table/radio"; - } - - /** - * 表格回传父窗体 - */ - @GetMapping("/parent") - public String parent() - { - return prefix + "/table/parent"; - } -} +package com.ruoyi.web.controller.demo.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 模态窗口 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/modal") +public class DemoDialogController { + private String prefix = "demo/modal"; + + /** + * 模态窗口 + */ + @GetMapping("/dialog") + public String dialog() { + return prefix + "/dialog"; + } + + /** + * 弹层组件 + */ + @GetMapping("/layer") + public String layer() { + return prefix + "/layer"; + } + + /** + * 表单 + */ + @GetMapping("/form") + public String form() { + return prefix + "/form"; + } + + /** + * 表格 + */ + @GetMapping("/table") + public String table() { + return prefix + "/table"; + } + + /** + * 表格check + */ + @GetMapping("/check") + public String check() { + return prefix + "/table/check"; + } + + /** + * 表格radio + */ + @GetMapping("/radio") + public String radio() { + return prefix + "/table/radio"; + } + + /** + * 表格回传父窗体 + */ + @GetMapping("/parent") + public String parent() { + return prefix + "/table/parent"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoFormController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoFormController.java index f53537b6e..5b3e402f9 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoFormController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoFormController.java @@ -1,270 +1,250 @@ -package com.ruoyi.web.controller.demo.controller; - -import java.util.ArrayList; -import java.util.List; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.core.domain.AjaxResult; - -/** - * 表单相关 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/form") -public class DemoFormController -{ - private String prefix = "demo/form"; - - private final static List users = new ArrayList(); - { - users.add(new UserFormModel(1, "1000001", "测试1", "15888888888")); - users.add(new UserFormModel(2, "1000002", "测试2", "15666666666")); - users.add(new UserFormModel(3, "1000003", "测试3", "15666666666")); - users.add(new UserFormModel(4, "1000004", "测试4", "15666666666")); - users.add(new UserFormModel(5, "1000005", "测试5", "15666666666")); - } - - /** - * 按钮页 - */ - @GetMapping("/button") - public String button() - { - return prefix + "/button"; - } - - /** - * 下拉框 - */ - @GetMapping("/select") - public String select() - { - return prefix + "/select"; - } - - /** - * 时间轴 - */ - @GetMapping("/timeline") - public String timeline() - { - return prefix + "/timeline"; - } - - /** - * 表单校验 - */ - @GetMapping("/validate") - public String validate() - { - return prefix + "/validate"; - } - - /** - * 功能扩展(包含文件上传) - */ - @GetMapping("/jasny") - public String jasny() - { - return prefix + "/jasny"; - } - - /** - * 拖动排序 - */ - @GetMapping("/sortable") - public String sortable() - { - return prefix + "/sortable"; - } - - /** - * 选项卡 & 面板 - */ - @GetMapping("/tabs_panels") - public String tabs_panels() - { - return prefix + "/tabs_panels"; - } - - /** - * 栅格 - */ - @GetMapping("/grid") - public String grid() - { - return prefix + "/grid"; - } - - /** - * 表单向导 - */ - @GetMapping("/wizard") - public String wizard() - { - return prefix + "/wizard"; - } - - /** - * 文件上传 - */ - @GetMapping("/upload") - public String upload() - { - return prefix + "/upload"; - } - - /** - * 日期和时间页 - */ - @GetMapping("/datetime") - public String datetime() - { - return prefix + "/datetime"; - } - - /** - * 左右互选组件 - */ - @GetMapping("/duallistbox") - public String duallistbox() - { - return prefix + "/duallistbox"; - } - - /** - * 基本表单 - */ - @GetMapping("/basic") - public String basic() - { - return prefix + "/basic"; - } - - /** - * 卡片列表 - */ - @GetMapping("/cards") - public String cards() - { - return prefix + "/cards"; - } - - /** - * summernote 富文本编辑器 - */ - @GetMapping("/summernote") - public String summernote() - { - return prefix + "/summernote"; - } - - /** - * 搜索自动补全 - */ - @GetMapping("/autocomplete") - public String autocomplete() - { - return prefix + "/autocomplete"; - } - - /** - * 获取用户数据 - */ - @GetMapping("/userModel") - @ResponseBody - public AjaxResult userModel() - { - AjaxResult ajax = new AjaxResult(); - - ajax.put("code", 200); - ajax.put("value", users); - return ajax; - } - - /** - * 获取数据集合 - */ - @GetMapping("/collection") - @ResponseBody - public AjaxResult collection() - { - String[] array = { "ruoyi 1", "ruoyi 2", "ruoyi 3", "ruoyi 4", "ruoyi 5" }; - AjaxResult ajax = new AjaxResult(); - ajax.put("value", array); - return ajax; - } -} - -class UserFormModel -{ - /** 用户ID */ - private int userId; - - /** 用户编号 */ - private String userCode; - - /** 用户姓名 */ - private String userName; - - /** 用户手机 */ - private String userPhone; - - public UserFormModel() - { - - } - - public UserFormModel(int userId, String userCode, String userName, String userPhone) - { - this.userId = userId; - this.userCode = userCode; - this.userName = userName; - this.userPhone = userPhone; - } - - public int getUserId() - { - return userId; - } - - public void setUserId(int userId) - { - this.userId = userId; - } - - public String getUserCode() - { - return userCode; - } - - public void setUserCode(String userCode) - { - this.userCode = userCode; - } - - public String getUserName() - { - return userName; - } - - public void setUserName(String userName) - { - this.userName = userName; - } - - public String getUserPhone() - { - return userPhone; - } - - public void setUserPhone(String userPhone) - { - this.userPhone = userPhone; - } - -} +package com.ruoyi.web.controller.demo.controller; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.core.domain.AjaxResult; + +/** + * 表单相关 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/form") +public class DemoFormController { + private String prefix = "demo/form"; + + private final static List users = new ArrayList(); + + { + users.add(new UserFormModel(1, "1000001", "测试1", "15888888888")); + users.add(new UserFormModel(2, "1000002", "测试2", "15666666666")); + users.add(new UserFormModel(3, "1000003", "测试3", "15666666666")); + users.add(new UserFormModel(4, "1000004", "测试4", "15666666666")); + users.add(new UserFormModel(5, "1000005", "测试5", "15666666666")); + } + + /** + * 按钮页 + */ + @GetMapping("/button") + public String button() { + return prefix + "/button"; + } + + /** + * 下拉框 + */ + @GetMapping("/select") + public String select() { + return prefix + "/select"; + } + + /** + * 时间轴 + */ + @GetMapping("/timeline") + public String timeline() { + return prefix + "/timeline"; + } + + /** + * 表单校验 + */ + @GetMapping("/validate") + public String validate() { + return prefix + "/validate"; + } + + /** + * 功能扩展(包含文件上传) + */ + @GetMapping("/jasny") + public String jasny() { + return prefix + "/jasny"; + } + + /** + * 拖动排序 + */ + @GetMapping("/sortable") + public String sortable() { + return prefix + "/sortable"; + } + + /** + * 选项卡 & 面板 + */ + @GetMapping("/tabs_panels") + public String tabs_panels() { + return prefix + "/tabs_panels"; + } + + /** + * 栅格 + */ + @GetMapping("/grid") + public String grid() { + return prefix + "/grid"; + } + + /** + * 表单向导 + */ + @GetMapping("/wizard") + public String wizard() { + return prefix + "/wizard"; + } + + /** + * 文件上传 + */ + @GetMapping("/upload") + public String upload() { + return prefix + "/upload"; + } + + /** + * 日期和时间页 + */ + @GetMapping("/datetime") + public String datetime() { + return prefix + "/datetime"; + } + + /** + * 左右互选组件 + */ + @GetMapping("/duallistbox") + public String duallistbox() { + return prefix + "/duallistbox"; + } + + /** + * 基本表单 + */ + @GetMapping("/basic") + public String basic() { + return prefix + "/basic"; + } + + /** + * 卡片列表 + */ + @GetMapping("/cards") + public String cards() { + return prefix + "/cards"; + } + + /** + * summernote 富文本编辑器 + */ + @GetMapping("/summernote") + public String summernote() { + return prefix + "/summernote"; + } + + /** + * 搜索自动补全 + */ + @GetMapping("/autocomplete") + public String autocomplete() { + return prefix + "/autocomplete"; + } + + /** + * 获取用户数据 + */ + @GetMapping("/userModel") + @ResponseBody + public AjaxResult userModel() { + AjaxResult ajax = new AjaxResult(); + + ajax.put("code", 200); + ajax.put("value", users); + return ajax; + } + + /** + * 获取数据集合 + */ + @GetMapping("/collection") + @ResponseBody + public AjaxResult collection() { + String[] array = {"ruoyi 1", "ruoyi 2", "ruoyi 3", "ruoyi 4", "ruoyi 5"}; + AjaxResult ajax = new AjaxResult(); + ajax.put("value", array); + return ajax; + } +} + +class UserFormModel { + /** + * 用户ID + */ + private int userId; + + /** + * 用户编号 + */ + private String userCode; + + /** + * 用户姓名 + */ + private String userName; + + /** + * 用户手机 + */ + private String userPhone; + + public UserFormModel() { + + } + + public UserFormModel(int userId, String userCode, String userName, String userPhone) { + this.userId = userId; + this.userCode = userCode; + this.userName = userName; + this.userPhone = userPhone; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserCode() { + return userCode; + } + + public void setUserCode(String userCode) { + this.userCode = userCode; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoIconController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoIconController.java index 490c3e061..05519aab0 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoIconController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoIconController.java @@ -1,35 +1,32 @@ -package com.ruoyi.web.controller.demo.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * 图标相关 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/icon") -public class DemoIconController -{ - private String prefix = "demo/icon"; - - /** - * FontAwesome图标 - */ - @GetMapping("/fontawesome") - public String fontAwesome() - { - return prefix + "/fontawesome"; - } - - /** - * Glyphicons图标 - */ - @GetMapping("/glyphicons") - public String glyphicons() - { - return prefix + "/glyphicons"; - } -} +package com.ruoyi.web.controller.demo.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 图标相关 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/icon") +public class DemoIconController { + private String prefix = "demo/icon"; + + /** + * FontAwesome图标 + */ + @GetMapping("/fontawesome") + public String fontAwesome() { + return prefix + "/fontawesome"; + } + + /** + * Glyphicons图标 + */ + @GetMapping("/glyphicons") + public String glyphicons() { + return prefix + "/glyphicons"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoOperateController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoOperateController.java index a628ebecb..23b2a5d6e 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoOperateController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoOperateController.java @@ -1,314 +1,276 @@ -package com.ruoyi.web.controller.demo.controller; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.PageDomain; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.core.page.TableSupport; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.web.controller.demo.domain.UserOperateModel; - -/** - * 操作控制 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/operate") -public class DemoOperateController extends BaseController -{ - private String prefix = "demo/operate"; - - private final static Map users = new LinkedHashMap(); - { - users.put(1, new UserOperateModel(1, "1000001", "测试1", "0", "15888888888", "ry@qq.com", 150.0, "0")); - users.put(2, new UserOperateModel(2, "1000002", "测试2", "1", "15666666666", "ry@qq.com", 180.0, "1")); - users.put(3, new UserOperateModel(3, "1000003", "测试3", "0", "15666666666", "ry@qq.com", 110.0, "1")); - users.put(4, new UserOperateModel(4, "1000004", "测试4", "1", "15666666666", "ry@qq.com", 220.0, "1")); - users.put(5, new UserOperateModel(5, "1000005", "测试5", "0", "15666666666", "ry@qq.com", 140.0, "1")); - users.put(6, new UserOperateModel(6, "1000006", "测试6", "1", "15666666666", "ry@qq.com", 330.0, "1")); - users.put(7, new UserOperateModel(7, "1000007", "测试7", "0", "15666666666", "ry@qq.com", 160.0, "1")); - users.put(8, new UserOperateModel(8, "1000008", "测试8", "1", "15666666666", "ry@qq.com", 170.0, "1")); - users.put(9, new UserOperateModel(9, "1000009", "测试9", "0", "15666666666", "ry@qq.com", 180.0, "1")); - users.put(10, new UserOperateModel(10, "1000010", "测试10", "0", "15666666666", "ry@qq.com", 210.0, "1")); - users.put(11, new UserOperateModel(11, "1000011", "测试11", "1", "15666666666", "ry@qq.com", 110.0, "1")); - users.put(12, new UserOperateModel(12, "1000012", "测试12", "0", "15666666666", "ry@qq.com", 120.0, "1")); - users.put(13, new UserOperateModel(13, "1000013", "测试13", "1", "15666666666", "ry@qq.com", 380.0, "1")); - users.put(14, new UserOperateModel(14, "1000014", "测试14", "0", "15666666666", "ry@qq.com", 280.0, "1")); - users.put(15, new UserOperateModel(15, "1000015", "测试15", "0", "15666666666", "ry@qq.com", 570.0, "1")); - users.put(16, new UserOperateModel(16, "1000016", "测试16", "1", "15666666666", "ry@qq.com", 260.0, "1")); - users.put(17, new UserOperateModel(17, "1000017", "测试17", "1", "15666666666", "ry@qq.com", 210.0, "1")); - users.put(18, new UserOperateModel(18, "1000018", "测试18", "1", "15666666666", "ry@qq.com", 340.0, "1")); - users.put(19, new UserOperateModel(19, "1000019", "测试19", "1", "15666666666", "ry@qq.com", 160.0, "1")); - users.put(20, new UserOperateModel(20, "1000020", "测试20", "1", "15666666666", "ry@qq.com", 220.0, "1")); - users.put(21, new UserOperateModel(21, "1000021", "测试21", "1", "15666666666", "ry@qq.com", 120.0, "1")); - users.put(22, new UserOperateModel(22, "1000022", "测试22", "1", "15666666666", "ry@qq.com", 130.0, "1")); - users.put(23, new UserOperateModel(23, "1000023", "测试23", "1", "15666666666", "ry@qq.com", 490.0, "1")); - users.put(24, new UserOperateModel(24, "1000024", "测试24", "1", "15666666666", "ry@qq.com", 570.0, "1")); - users.put(25, new UserOperateModel(25, "1000025", "测试25", "1", "15666666666", "ry@qq.com", 250.0, "1")); - users.put(26, new UserOperateModel(26, "1000026", "测试26", "1", "15666666666", "ry@qq.com", 250.0, "1")); - } - - /** - * 表格 - */ - @GetMapping("/table") - public String table() - { - return prefix + "/table"; - } - - /** - * 其他 - */ - @GetMapping("/other") - public String other() - { - return prefix + "/other"; - } - - /** - * 查询数据 - */ - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(UserOperateModel userModel) - { - TableDataInfo rspData = new TableDataInfo(); - List userList = new ArrayList(users.values()); - // 查询条件过滤 - if (StringUtils.isNotEmpty(userModel.getSearchValue())) - { - userList.clear(); - for (Map.Entry entry : users.entrySet()) - { - if (entry.getValue().getUserName().equals(userModel.getSearchValue())) - { - userList.add(entry.getValue()); - } - } - } - else if (StringUtils.isNotEmpty(userModel.getUserName())) - { - userList.clear(); - for (Map.Entry entry : users.entrySet()) - { - if (entry.getValue().getUserName().equals(userModel.getUserName())) - { - userList.add(entry.getValue()); - } - } - } - PageDomain pageDomain = TableSupport.buildPageRequest(); - if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) - { - rspData.setRows(userList); - rspData.setTotal(userList.size()); - return rspData; - } - Integer pageNum = (pageDomain.getPageNum() - 1) * 10; - Integer pageSize = pageDomain.getPageNum() * 10; - if (pageSize > userList.size()) - { - pageSize = userList.size(); - } - rspData.setRows(userList.subList(pageNum, pageSize)); - rspData.setTotal(userList.size()); - return rspData; - } - - /** - * 新增用户 - */ - @GetMapping("/add") - public String add(ModelMap mmap) - { - return prefix + "/add"; - } - - /** - * 新增保存用户 - */ - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(UserOperateModel user) - { - Integer userId = users.size() + 1; - user.setUserId(userId); - return AjaxResult.success(users.put(userId, user)); - } - - /** - * 修改用户 - */ - @GetMapping("/edit/{userId}") - public String edit(@PathVariable("userId") Integer userId, ModelMap mmap) - { - mmap.put("user", users.get(userId)); - return prefix + "/edit"; - } - - /** - * 修改保存用户 - */ - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(UserOperateModel user) - { - return AjaxResult.success(users.put(user.getUserId(), user)); - } - - /** - * 导出 - */ - @PostMapping("/export") - @ResponseBody - public AjaxResult export(UserOperateModel user) - { - List list = new ArrayList(users.values()); - ExcelUtil util = new ExcelUtil(UserOperateModel.class); - return util.exportExcel(list, "用户数据"); - } - - /** - * 下载模板 - */ - @GetMapping("/importTemplate") - @ResponseBody - public AjaxResult importTemplate() - { - ExcelUtil util = new ExcelUtil(UserOperateModel.class); - return util.importTemplateExcel("用户数据"); - } - - /** - * 导入数据 - */ - @PostMapping("/importData") - @ResponseBody - public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception - { - ExcelUtil util = new ExcelUtil(UserOperateModel.class); - List userList = util.importExcel(file.getInputStream()); - String message = importUser(userList, updateSupport); - return AjaxResult.success(message); - } - - /** - * 删除用户 - */ - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - Integer[] userIds = Convert.toIntArray(ids); - for (Integer userId : userIds) - { - users.remove(userId); - } - return AjaxResult.success(); - } - - /** - * 查看详细 - */ - @GetMapping("/detail/{userId}") - public String detail(@PathVariable("userId") Integer userId, ModelMap mmap) - { - mmap.put("user", users.get(userId)); - return prefix + "/detail"; - } - - @PostMapping("/clean") - @ResponseBody - public AjaxResult clean() - { - users.clear(); - return success(); - } - - /** - * 导入用户数据 - * - * @param userList 用户数据列表 - * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 - * @return 结果 - */ - public String importUser(List userList, Boolean isUpdateSupport) - { - if (StringUtils.isNull(userList) || userList.size() == 0) - { - throw new BusinessException("导入用户数据不能为空!"); - } - int successNum = 0; - int failureNum = 0; - StringBuilder successMsg = new StringBuilder(); - StringBuilder failureMsg = new StringBuilder(); - for (UserOperateModel user : userList) - { - try - { - // 验证是否存在这个用户 - boolean userFlag = false; - for (Map.Entry entry : users.entrySet()) - { - if (entry.getValue().getUserName().equals(user.getUserName())) - { - userFlag = true; - break; - } - } - if (!userFlag) - { - Integer userId = users.size() + 1; - user.setUserId(userId); - users.put(userId, user); - successNum++; - successMsg.append("
" + successNum + "、用户 " + user.getUserName() + " 导入成功"); - } - else if (isUpdateSupport) - { - users.put(user.getUserId(), user); - successNum++; - successMsg.append("
" + successNum + "、用户 " + user.getUserName() + " 更新成功"); - } - else - { - failureNum++; - failureMsg.append("
" + failureNum + "、用户 " + user.getUserName() + " 已存在"); - } - } - catch (Exception e) - { - failureNum++; - String msg = "
" + failureNum + "、账号 " + user.getUserName() + " 导入失败:"; - failureMsg.append(msg + e.getMessage()); - } - } - if (failureNum > 0) - { - failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); - throw new BusinessException(failureMsg.toString()); - } - else - { - successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); - } - return successMsg.toString(); - } -} +package com.ruoyi.web.controller.demo.controller; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.PageDomain; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.core.page.TableSupport; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.web.controller.demo.domain.UserOperateModel; + +/** + * 操作控制 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/operate") +public class DemoOperateController extends BaseController { + private String prefix = "demo/operate"; + + private final static Map users = new LinkedHashMap(); + + { + users.put(1, new UserOperateModel(1, "1000001", "测试1", "0", "15888888888", "ry@qq.com", 150.0, "0")); + users.put(2, new UserOperateModel(2, "1000002", "测试2", "1", "15666666666", "ry@qq.com", 180.0, "1")); + users.put(3, new UserOperateModel(3, "1000003", "测试3", "0", "15666666666", "ry@qq.com", 110.0, "1")); + users.put(4, new UserOperateModel(4, "1000004", "测试4", "1", "15666666666", "ry@qq.com", 220.0, "1")); + users.put(5, new UserOperateModel(5, "1000005", "测试5", "0", "15666666666", "ry@qq.com", 140.0, "1")); + users.put(6, new UserOperateModel(6, "1000006", "测试6", "1", "15666666666", "ry@qq.com", 330.0, "1")); + users.put(7, new UserOperateModel(7, "1000007", "测试7", "0", "15666666666", "ry@qq.com", 160.0, "1")); + users.put(8, new UserOperateModel(8, "1000008", "测试8", "1", "15666666666", "ry@qq.com", 170.0, "1")); + users.put(9, new UserOperateModel(9, "1000009", "测试9", "0", "15666666666", "ry@qq.com", 180.0, "1")); + users.put(10, new UserOperateModel(10, "1000010", "测试10", "0", "15666666666", "ry@qq.com", 210.0, "1")); + users.put(11, new UserOperateModel(11, "1000011", "测试11", "1", "15666666666", "ry@qq.com", 110.0, "1")); + users.put(12, new UserOperateModel(12, "1000012", "测试12", "0", "15666666666", "ry@qq.com", 120.0, "1")); + users.put(13, new UserOperateModel(13, "1000013", "测试13", "1", "15666666666", "ry@qq.com", 380.0, "1")); + users.put(14, new UserOperateModel(14, "1000014", "测试14", "0", "15666666666", "ry@qq.com", 280.0, "1")); + users.put(15, new UserOperateModel(15, "1000015", "测试15", "0", "15666666666", "ry@qq.com", 570.0, "1")); + users.put(16, new UserOperateModel(16, "1000016", "测试16", "1", "15666666666", "ry@qq.com", 260.0, "1")); + users.put(17, new UserOperateModel(17, "1000017", "测试17", "1", "15666666666", "ry@qq.com", 210.0, "1")); + users.put(18, new UserOperateModel(18, "1000018", "测试18", "1", "15666666666", "ry@qq.com", 340.0, "1")); + users.put(19, new UserOperateModel(19, "1000019", "测试19", "1", "15666666666", "ry@qq.com", 160.0, "1")); + users.put(20, new UserOperateModel(20, "1000020", "测试20", "1", "15666666666", "ry@qq.com", 220.0, "1")); + users.put(21, new UserOperateModel(21, "1000021", "测试21", "1", "15666666666", "ry@qq.com", 120.0, "1")); + users.put(22, new UserOperateModel(22, "1000022", "测试22", "1", "15666666666", "ry@qq.com", 130.0, "1")); + users.put(23, new UserOperateModel(23, "1000023", "测试23", "1", "15666666666", "ry@qq.com", 490.0, "1")); + users.put(24, new UserOperateModel(24, "1000024", "测试24", "1", "15666666666", "ry@qq.com", 570.0, "1")); + users.put(25, new UserOperateModel(25, "1000025", "测试25", "1", "15666666666", "ry@qq.com", 250.0, "1")); + users.put(26, new UserOperateModel(26, "1000026", "测试26", "1", "15666666666", "ry@qq.com", 250.0, "1")); + } + + /** + * 表格 + */ + @GetMapping("/table") + public String table() { + return prefix + "/table"; + } + + /** + * 其他 + */ + @GetMapping("/other") + public String other() { + return prefix + "/other"; + } + + /** + * 查询数据 + */ + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(UserOperateModel userModel) { + TableDataInfo rspData = new TableDataInfo(); + List userList = new ArrayList(users.values()); + // 查询条件过滤 + if (StringUtils.isNotEmpty(userModel.getSearchValue())) { + userList.clear(); + for (Map.Entry entry : users.entrySet()) { + if (entry.getValue().getUserName().equals(userModel.getSearchValue())) { + userList.add(entry.getValue()); + } + } + } else if (StringUtils.isNotEmpty(userModel.getUserName())) { + userList.clear(); + for (Map.Entry entry : users.entrySet()) { + if (entry.getValue().getUserName().equals(userModel.getUserName())) { + userList.add(entry.getValue()); + } + } + } + PageDomain pageDomain = TableSupport.buildPageRequest(); + if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) { + rspData.setRows(userList); + rspData.setTotal(userList.size()); + return rspData; + } + Integer pageNum = (pageDomain.getPageNum() - 1) * 10; + Integer pageSize = pageDomain.getPageNum() * 10; + if (pageSize > userList.size()) { + pageSize = userList.size(); + } + rspData.setRows(userList.subList(pageNum, pageSize)); + rspData.setTotal(userList.size()); + return rspData; + } + + /** + * 新增用户 + */ + @GetMapping("/add") + public String add(ModelMap mmap) { + return prefix + "/add"; + } + + /** + * 新增保存用户 + */ + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(UserOperateModel user) { + Integer userId = users.size() + 1; + user.setUserId(userId); + return AjaxResult.success(users.put(userId, user)); + } + + /** + * 修改用户 + */ + @GetMapping("/edit/{userId}") + public String edit(@PathVariable("userId") Integer userId, ModelMap mmap) { + mmap.put("user", users.get(userId)); + return prefix + "/edit"; + } + + /** + * 修改保存用户 + */ + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(UserOperateModel user) { + return AjaxResult.success(users.put(user.getUserId(), user)); + } + + /** + * 导出 + */ + @PostMapping("/export") + @ResponseBody + public AjaxResult export(UserOperateModel user) { + List list = new ArrayList(users.values()); + ExcelUtil util = new ExcelUtil(UserOperateModel.class); + return util.exportExcel(list, "用户数据"); + } + + /** + * 下载模板 + */ + @GetMapping("/importTemplate") + @ResponseBody + public AjaxResult importTemplate() { + ExcelUtil util = new ExcelUtil(UserOperateModel.class); + return util.importTemplateExcel("用户数据"); + } + + /** + * 导入数据 + */ + @PostMapping("/importData") + @ResponseBody + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(UserOperateModel.class); + List userList = util.importExcel(file.getInputStream()); + String message = importUser(userList, updateSupport); + return AjaxResult.success(message); + } + + /** + * 删除用户 + */ + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + Integer[] userIds = Convert.toIntArray(ids); + for (Integer userId : userIds) { + users.remove(userId); + } + return AjaxResult.success(); + } + + /** + * 查看详细 + */ + @GetMapping("/detail/{userId}") + public String detail(@PathVariable("userId") Integer userId, ModelMap mmap) { + mmap.put("user", users.get(userId)); + return prefix + "/detail"; + } + + @PostMapping("/clean") + @ResponseBody + public AjaxResult clean() { + users.clear(); + return success(); + } + + /** + * 导入用户数据 + * + * @param userList 用户数据列表 + * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 + * @return 结果 + */ + public String importUser(List userList, Boolean isUpdateSupport) { + if (StringUtils.isNull(userList) || userList.size() == 0) { + throw new BusinessException("导入用户数据不能为空!"); + } + int successNum = 0; + int failureNum = 0; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + for (UserOperateModel user : userList) { + try { + // 验证是否存在这个用户 + boolean userFlag = false; + for (Map.Entry entry : users.entrySet()) { + if (entry.getValue().getUserName().equals(user.getUserName())) { + userFlag = true; + break; + } + } + if (!userFlag) { + Integer userId = users.size() + 1; + user.setUserId(userId); + users.put(userId, user); + successNum++; + successMsg.append("
" + successNum + "、用户 " + user.getUserName() + " 导入成功"); + } else if (isUpdateSupport) { + users.put(user.getUserId(), user); + successNum++; + successMsg.append("
" + successNum + "、用户 " + user.getUserName() + " 更新成功"); + } else { + failureNum++; + failureMsg.append("
" + failureNum + "、用户 " + user.getUserName() + " 已存在"); + } + } catch (Exception e) { + failureNum++; + String msg = "
" + failureNum + "、账号 " + user.getUserName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + } + } + if (failureNum > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); + throw new BusinessException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoReportController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoReportController.java index 318e8f08b..e129c75eb 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoReportController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoReportController.java @@ -1,53 +1,48 @@ -package com.ruoyi.web.controller.demo.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * 报表 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/report") -public class DemoReportController -{ - private String prefix = "demo/report"; - - /** - * 百度ECharts - */ - @GetMapping("/echarts") - public String echarts() - { - return prefix + "/echarts"; - } - - /** - * 图表插件 - */ - @GetMapping("/peity") - public String peity() - { - return prefix + "/peity"; - } - - /** - * 线状图插件 - */ - @GetMapping("/sparkline") - public String sparkline() - { - return prefix + "/sparkline"; - } - - /** - * 图表组合 - */ - @GetMapping("/metrics") - public String metrics() - { - return prefix + "/metrics"; - } -} +package com.ruoyi.web.controller.demo.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 报表 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/report") +public class DemoReportController { + private String prefix = "demo/report"; + + /** + * 百度ECharts + */ + @GetMapping("/echarts") + public String echarts() { + return prefix + "/echarts"; + } + + /** + * 图表插件 + */ + @GetMapping("/peity") + public String peity() { + return prefix + "/peity"; + } + + /** + * 线状图插件 + */ + @GetMapping("/sparkline") + public String sparkline() { + return prefix + "/sparkline"; + } + + /** + * 图表组合 + */ + @GetMapping("/metrics") + public String metrics() { + return prefix + "/metrics"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoTableController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoTableController.java index e51c880a5..8ba3bd0b9 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoTableController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/controller/DemoTableController.java @@ -1,403 +1,377 @@ -package com.ruoyi.web.controller.demo.controller; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.page.PageDomain; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.core.page.TableSupport; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.StringUtils; - -/** - * 表格相关 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/demo/table") -public class DemoTableController extends BaseController -{ - private String prefix = "demo/table"; - - private final static List users = new ArrayList(); - { - users.add(new UserTableModel(1, "1000001", "测试1", "0", "15888888888", "ry@qq.com", 150.0, "0")); - users.add(new UserTableModel(2, "1000002", "测试2", "1", "15666666666", "ry@qq.com", 180.0, "1")); - users.add(new UserTableModel(3, "1000003", "测试3", "0", "15666666666", "ry@qq.com", 110.0, "1")); - users.add(new UserTableModel(4, "1000004", "测试4", "1", "15666666666", "ry@qq.com", 220.0, "1")); - users.add(new UserTableModel(5, "1000005", "测试5", "0", "15666666666", "ry@qq.com", 140.0, "1")); - users.add(new UserTableModel(6, "1000006", "测试6", "1", "15666666666", "ry@qq.com", 330.0, "1")); - users.add(new UserTableModel(7, "1000007", "测试7", "0", "15666666666", "ry@qq.com", 160.0, "1")); - users.add(new UserTableModel(8, "1000008", "测试8", "1", "15666666666", "ry@qq.com", 170.0, "1")); - users.add(new UserTableModel(9, "1000009", "测试9", "0", "15666666666", "ry@qq.com", 180.0, "1")); - users.add(new UserTableModel(10, "1000010", "测试10", "0", "15666666666", "ry@qq.com", 210.0, "1")); - users.add(new UserTableModel(11, "1000011", "测试11", "1", "15666666666", "ry@qq.com", 110.0, "1")); - users.add(new UserTableModel(12, "1000012", "测试12", "0", "15666666666", "ry@qq.com", 120.0, "1")); - users.add(new UserTableModel(13, "1000013", "测试13", "1", "15666666666", "ry@qq.com", 380.0, "1")); - users.add(new UserTableModel(14, "1000014", "测试14", "0", "15666666666", "ry@qq.com", 280.0, "1")); - users.add(new UserTableModel(15, "1000015", "测试15", "0", "15666666666", "ry@qq.com", 570.0, "1")); - users.add(new UserTableModel(16, "1000016", "测试16", "1", "15666666666", "ry@qq.com", 260.0, "1")); - users.add(new UserTableModel(17, "1000017", "测试17", "1", "15666666666", "ry@qq.com", 210.0, "1")); - users.add(new UserTableModel(18, "1000018", "测试18", "1", "15666666666", "ry@qq.com", 340.0, "1")); - users.add(new UserTableModel(19, "1000019", "测试19", "1", "15666666666", "ry@qq.com", 160.0, "1")); - users.add(new UserTableModel(20, "1000020", "测试20", "1", "15666666666", "ry@qq.com", 220.0, "1")); - users.add(new UserTableModel(21, "1000021", "测试21", "1", "15666666666", "ry@qq.com", 120.0, "1")); - users.add(new UserTableModel(22, "1000022", "测试22", "1", "15666666666", "ry@qq.com", 130.0, "1")); - users.add(new UserTableModel(23, "1000023", "测试23", "1", "15666666666", "ry@qq.com", 490.0, "1")); - users.add(new UserTableModel(24, "1000024", "测试24", "1", "15666666666", "ry@qq.com", 570.0, "1")); - users.add(new UserTableModel(25, "1000025", "测试25", "1", "15666666666", "ry@qq.com", 250.0, "1")); - users.add(new UserTableModel(26, "1000026", "测试26", "1", "15666666666", "ry@qq.com", 250.0, "1")); - } - - /** - * 搜索相关 - */ - @GetMapping("/search") - public String search() - { - return prefix + "/search"; - } - - /** - * 数据汇总 - */ - @GetMapping("/footer") - public String footer() - { - return prefix + "/footer"; - } - - /** - * 组合表头 - */ - @GetMapping("/groupHeader") - public String groupHeader() - { - return prefix + "/groupHeader"; - } - - /** - * 表格导出 - */ - @GetMapping("/export") - public String export() - { - return prefix + "/export"; - } - - /** - * 翻页记住选择 - */ - @GetMapping("/remember") - public String remember() - { - return prefix + "/remember"; - } - - /** - * 跳转至指定页 - */ - @GetMapping("/pageGo") - public String pageGo() - { - return prefix + "/pageGo"; - } - - /** - * 自定义查询参数 - */ - @GetMapping("/params") - public String params() - { - return prefix + "/params"; - } - - /** - * 多表格 - */ - @GetMapping("/multi") - public String multi() - { - return prefix + "/multi"; - } - - /** - * 点击按钮加载表格 - */ - @GetMapping("/button") - public String button() - { - return prefix + "/button"; - } - - /** - * 表格冻结列 - */ - @GetMapping("/fixedColumns") - public String fixedColumns() - { - return prefix + "/fixedColumns"; - } - - /** - * 自定义触发事件 - */ - @GetMapping("/event") - public String event() - { - return prefix + "/event"; - } - - /** - * 表格细节视图 - */ - @GetMapping("/detail") - public String detail() - { - return prefix + "/detail"; - } - - /** - * 表格父子视图 - */ - @GetMapping("/child") - public String child() - { - return prefix + "/child"; - } - - /** - * 表格图片预览 - */ - @GetMapping("/image") - public String image() - { - return prefix + "/image"; - } - - /** - * 动态增删改查 - */ - @GetMapping("/curd") - public String curd() - { - return prefix + "/curd"; - } - - /** - * 表格拖拽操作 - */ - @GetMapping("/reorder") - public String reorder() - { - return prefix + "/reorder"; - } - - /** - * 表格行内编辑操作 - */ - @GetMapping("/editable") - public String editable() - { - return prefix + "/editable"; - } - - /** - * 表格其他操作 - */ - @GetMapping("/other") - public String other() - { - return prefix + "/other"; - } - - /** - * 查询数据 - */ - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(UserTableModel userModel) - { - TableDataInfo rspData = new TableDataInfo(); - List userList = new ArrayList(Arrays.asList(new UserTableModel[users.size()])); - Collections.copy(userList, users); - // 查询条件过滤 - if (StringUtils.isNotEmpty(userModel.getUserName())) - { - userList.clear(); - for (UserTableModel user : users) - { - if (user.getUserName().equals(userModel.getUserName())) - { - userList.add(user); - } - } - } - PageDomain pageDomain = TableSupport.buildPageRequest(); - if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) - { - rspData.setRows(userList); - rspData.setTotal(userList.size()); - return rspData; - } - Integer pageNum = (pageDomain.getPageNum() - 1) * 10; - Integer pageSize = pageDomain.getPageNum() * 10; - if (pageSize > userList.size()) - { - pageSize = userList.size(); - } - rspData.setRows(userList.subList(pageNum, pageSize)); - rspData.setTotal(userList.size()); - return rspData; - } -} - -class UserTableModel -{ - /** 用户ID */ - private int userId; - - /** 用户编号 */ - private String userCode; - - /** 用户姓名 */ - private String userName; - - /** 用户性别 */ - private String userSex; - - /** 用户手机 */ - private String userPhone; - - /** 用户邮箱 */ - private String userEmail; - - /** 用户余额 */ - private double userBalance; - - /** 用户状态(0正常 1停用) */ - private String status; - - /** 创建时间 */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; - - public UserTableModel() - { - - } - - public UserTableModel(int userId, String userCode, String userName, String userSex, String userPhone, - String userEmail, double userBalance, String status) - { - this.userId = userId; - this.userCode = userCode; - this.userName = userName; - this.userSex = userSex; - this.userPhone = userPhone; - this.userEmail = userEmail; - this.userBalance = userBalance; - this.status = status; - this.createTime = DateUtils.getNowDate(); - } - - public int getUserId() - { - return userId; - } - - public void setUserId(int userId) - { - this.userId = userId; - } - - public String getUserCode() - { - return userCode; - } - - public void setUserCode(String userCode) - { - this.userCode = userCode; - } - - public String getUserName() - { - return userName; - } - - public void setUserName(String userName) - { - this.userName = userName; - } - - public String getUserSex() - { - return userSex; - } - - public void setUserSex(String userSex) - { - this.userSex = userSex; - } - - public String getUserPhone() - { - return userPhone; - } - - public void setUserPhone(String userPhone) - { - this.userPhone = userPhone; - } - - public String getUserEmail() - { - return userEmail; - } - - public void setUserEmail(String userEmail) - { - this.userEmail = userEmail; - } - - public double getUserBalance() - { - return userBalance; - } - - public void setUserBalance(double userBalance) - { - this.userBalance = userBalance; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public Date getCreateTime() - { - return createTime; - } - - public void setCreateTime(Date createTime) - { - this.createTime = createTime; - } -} +package com.ruoyi.web.controller.demo.controller; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.page.PageDomain; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.core.page.TableSupport; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.StringUtils; + +/** + * 表格相关 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/demo/table") +public class DemoTableController extends BaseController { + private String prefix = "demo/table"; + + private final static List users = new ArrayList(); + + { + users.add(new UserTableModel(1, "1000001", "测试1", "0", "15888888888", "ry@qq.com", 150.0, "0")); + users.add(new UserTableModel(2, "1000002", "测试2", "1", "15666666666", "ry@qq.com", 180.0, "1")); + users.add(new UserTableModel(3, "1000003", "测试3", "0", "15666666666", "ry@qq.com", 110.0, "1")); + users.add(new UserTableModel(4, "1000004", "测试4", "1", "15666666666", "ry@qq.com", 220.0, "1")); + users.add(new UserTableModel(5, "1000005", "测试5", "0", "15666666666", "ry@qq.com", 140.0, "1")); + users.add(new UserTableModel(6, "1000006", "测试6", "1", "15666666666", "ry@qq.com", 330.0, "1")); + users.add(new UserTableModel(7, "1000007", "测试7", "0", "15666666666", "ry@qq.com", 160.0, "1")); + users.add(new UserTableModel(8, "1000008", "测试8", "1", "15666666666", "ry@qq.com", 170.0, "1")); + users.add(new UserTableModel(9, "1000009", "测试9", "0", "15666666666", "ry@qq.com", 180.0, "1")); + users.add(new UserTableModel(10, "1000010", "测试10", "0", "15666666666", "ry@qq.com", 210.0, "1")); + users.add(new UserTableModel(11, "1000011", "测试11", "1", "15666666666", "ry@qq.com", 110.0, "1")); + users.add(new UserTableModel(12, "1000012", "测试12", "0", "15666666666", "ry@qq.com", 120.0, "1")); + users.add(new UserTableModel(13, "1000013", "测试13", "1", "15666666666", "ry@qq.com", 380.0, "1")); + users.add(new UserTableModel(14, "1000014", "测试14", "0", "15666666666", "ry@qq.com", 280.0, "1")); + users.add(new UserTableModel(15, "1000015", "测试15", "0", "15666666666", "ry@qq.com", 570.0, "1")); + users.add(new UserTableModel(16, "1000016", "测试16", "1", "15666666666", "ry@qq.com", 260.0, "1")); + users.add(new UserTableModel(17, "1000017", "测试17", "1", "15666666666", "ry@qq.com", 210.0, "1")); + users.add(new UserTableModel(18, "1000018", "测试18", "1", "15666666666", "ry@qq.com", 340.0, "1")); + users.add(new UserTableModel(19, "1000019", "测试19", "1", "15666666666", "ry@qq.com", 160.0, "1")); + users.add(new UserTableModel(20, "1000020", "测试20", "1", "15666666666", "ry@qq.com", 220.0, "1")); + users.add(new UserTableModel(21, "1000021", "测试21", "1", "15666666666", "ry@qq.com", 120.0, "1")); + users.add(new UserTableModel(22, "1000022", "测试22", "1", "15666666666", "ry@qq.com", 130.0, "1")); + users.add(new UserTableModel(23, "1000023", "测试23", "1", "15666666666", "ry@qq.com", 490.0, "1")); + users.add(new UserTableModel(24, "1000024", "测试24", "1", "15666666666", "ry@qq.com", 570.0, "1")); + users.add(new UserTableModel(25, "1000025", "测试25", "1", "15666666666", "ry@qq.com", 250.0, "1")); + users.add(new UserTableModel(26, "1000026", "测试26", "1", "15666666666", "ry@qq.com", 250.0, "1")); + } + + /** + * 搜索相关 + */ + @GetMapping("/search") + public String search() { + return prefix + "/search"; + } + + /** + * 数据汇总 + */ + @GetMapping("/footer") + public String footer() { + return prefix + "/footer"; + } + + /** + * 组合表头 + */ + @GetMapping("/groupHeader") + public String groupHeader() { + return prefix + "/groupHeader"; + } + + /** + * 表格导出 + */ + @GetMapping("/export") + public String export() { + return prefix + "/export"; + } + + /** + * 翻页记住选择 + */ + @GetMapping("/remember") + public String remember() { + return prefix + "/remember"; + } + + /** + * 跳转至指定页 + */ + @GetMapping("/pageGo") + public String pageGo() { + return prefix + "/pageGo"; + } + + /** + * 自定义查询参数 + */ + @GetMapping("/params") + public String params() { + return prefix + "/params"; + } + + /** + * 多表格 + */ + @GetMapping("/multi") + public String multi() { + return prefix + "/multi"; + } + + /** + * 点击按钮加载表格 + */ + @GetMapping("/button") + public String button() { + return prefix + "/button"; + } + + /** + * 表格冻结列 + */ + @GetMapping("/fixedColumns") + public String fixedColumns() { + return prefix + "/fixedColumns"; + } + + /** + * 自定义触发事件 + */ + @GetMapping("/event") + public String event() { + return prefix + "/event"; + } + + /** + * 表格细节视图 + */ + @GetMapping("/detail") + public String detail() { + return prefix + "/detail"; + } + + /** + * 表格父子视图 + */ + @GetMapping("/child") + public String child() { + return prefix + "/child"; + } + + /** + * 表格图片预览 + */ + @GetMapping("/image") + public String image() { + return prefix + "/image"; + } + + /** + * 动态增删改查 + */ + @GetMapping("/curd") + public String curd() { + return prefix + "/curd"; + } + + /** + * 表格拖拽操作 + */ + @GetMapping("/reorder") + public String reorder() { + return prefix + "/reorder"; + } + + /** + * 表格行内编辑操作 + */ + @GetMapping("/editable") + public String editable() { + return prefix + "/editable"; + } + + /** + * 表格其他操作 + */ + @GetMapping("/other") + public String other() { + return prefix + "/other"; + } + + /** + * 查询数据 + */ + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(UserTableModel userModel) { + TableDataInfo rspData = new TableDataInfo(); + List userList = new ArrayList(Arrays.asList(new UserTableModel[users.size()])); + Collections.copy(userList, users); + // 查询条件过滤 + if (StringUtils.isNotEmpty(userModel.getUserName())) { + userList.clear(); + for (UserTableModel user : users) { + if (user.getUserName().equals(userModel.getUserName())) { + userList.add(user); + } + } + } + PageDomain pageDomain = TableSupport.buildPageRequest(); + if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) { + rspData.setRows(userList); + rspData.setTotal(userList.size()); + return rspData; + } + Integer pageNum = (pageDomain.getPageNum() - 1) * 10; + Integer pageSize = pageDomain.getPageNum() * 10; + if (pageSize > userList.size()) { + pageSize = userList.size(); + } + rspData.setRows(userList.subList(pageNum, pageSize)); + rspData.setTotal(userList.size()); + return rspData; + } +} + +class UserTableModel { + /** + * 用户ID + */ + private int userId; + + /** + * 用户编号 + */ + private String userCode; + + /** + * 用户姓名 + */ + private String userName; + + /** + * 用户性别 + */ + private String userSex; + + /** + * 用户手机 + */ + private String userPhone; + + /** + * 用户邮箱 + */ + private String userEmail; + + /** + * 用户余额 + */ + private double userBalance; + + /** + * 用户状态(0正常 1停用) + */ + private String status; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; + + public UserTableModel() { + + } + + public UserTableModel(int userId, String userCode, String userName, String userSex, String userPhone, + String userEmail, double userBalance, String status) { + this.userId = userId; + this.userCode = userCode; + this.userName = userName; + this.userSex = userSex; + this.userPhone = userPhone; + this.userEmail = userEmail; + this.userBalance = userBalance; + this.status = status; + this.createTime = DateUtils.getNowDate(); + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserCode() { + return userCode; + } + + public void setUserCode(String userCode) { + this.userCode = userCode; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserSex() { + return userSex; + } + + public void setUserSex(String userSex) { + this.userSex = userSex; + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + public double getUserBalance() { + return userBalance; + } + + public void setUserBalance(double userBalance) { + this.userBalance = userBalance; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/domain/UserOperateModel.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/domain/UserOperateModel.java index ac95abf2f..5cfef057c 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/domain/UserOperateModel.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/domain/UserOperateModel.java @@ -1,147 +1,127 @@ -package com.ruoyi.web.controller.demo.domain; - -import java.util.Date; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.Type; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.utils.DateUtils; - -public class UserOperateModel extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - private int userId; - - @Excel(name = "用户编号") - private String userCode; - - @Excel(name = "用户姓名") - private String userName; - - @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知") - private String userSex; - - @Excel(name = "用户手机") - private String userPhone; - - @Excel(name = "用户邮箱") - private String userEmail; - - @Excel(name = "用户余额") - private double userBalance; - - @Excel(name = "用户状态", readConverterExp = "0=正常,1=停用") - private String status; - - @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT) - private Date createTime; - - public UserOperateModel() - { - - } - - public UserOperateModel(int userId, String userCode, String userName, String userSex, String userPhone, - String userEmail, double userBalance, String status) - { - this.userId = userId; - this.userCode = userCode; - this.userName = userName; - this.userSex = userSex; - this.userPhone = userPhone; - this.userEmail = userEmail; - this.userBalance = userBalance; - this.status = status; - this.createTime = DateUtils.getNowDate(); - } - - public int getUserId() - { - return userId; - } - - public void setUserId(int userId) - { - this.userId = userId; - } - - public String getUserCode() - { - return userCode; - } - - public void setUserCode(String userCode) - { - this.userCode = userCode; - } - - public String getUserName() - { - return userName; - } - - public void setUserName(String userName) - { - this.userName = userName; - } - - public String getUserSex() - { - return userSex; - } - - public void setUserSex(String userSex) - { - this.userSex = userSex; - } - - public String getUserPhone() - { - return userPhone; - } - - public void setUserPhone(String userPhone) - { - this.userPhone = userPhone; - } - - public String getUserEmail() - { - return userEmail; - } - - public void setUserEmail(String userEmail) - { - this.userEmail = userEmail; - } - - public double getUserBalance() - { - return userBalance; - } - - public void setUserBalance(double userBalance) - { - this.userBalance = userBalance; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public Date getCreateTime() - { - return createTime; - } - - public void setCreateTime(Date createTime) - { - this.createTime = createTime; - } +package com.ruoyi.web.controller.demo.domain; + +import java.util.Date; + +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.Type; +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.utils.DateUtils; + +public class UserOperateModel extends BaseEntity { + private static final long serialVersionUID = 1L; + + private int userId; + + @Excel(name = "用户编号") + private String userCode; + + @Excel(name = "用户姓名") + private String userName; + + @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知") + private String userSex; + + @Excel(name = "用户手机") + private String userPhone; + + @Excel(name = "用户邮箱") + private String userEmail; + + @Excel(name = "用户余额") + private double userBalance; + + @Excel(name = "用户状态", readConverterExp = "0=正常,1=停用") + private String status; + + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT) + private Date createTime; + + public UserOperateModel() { + + } + + public UserOperateModel(int userId, String userCode, String userName, String userSex, String userPhone, + String userEmail, double userBalance, String status) { + this.userId = userId; + this.userCode = userCode; + this.userName = userName; + this.userSex = userSex; + this.userPhone = userPhone; + this.userEmail = userEmail; + this.userBalance = userBalance; + this.status = status; + this.createTime = DateUtils.getNowDate(); + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserCode() { + return userCode; + } + + public void setUserCode(String userCode) { + this.userCode = userCode; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserSex() { + return userSex; + } + + public void setUserSex(String userSex) { + this.userSex = userSex; + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + public double getUserBalance() { + return userBalance; + } + + public void setUserBalance(double userBalance) { + this.userBalance = userBalance; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/DruidController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/DruidController.java index b2647893c..323d42bc5 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/DruidController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/DruidController.java @@ -1,26 +1,24 @@ -package com.ruoyi.web.controller.monitor; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import com.ruoyi.common.core.controller.BaseController; - -/** - * druid 监控 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/data") -public class DruidController extends BaseController -{ - private String prefix = "/druid"; - - @RequiresPermissions("monitor:data:view") - @GetMapping() - public String index() - { - return redirect(prefix + "/index"); - } -} +package com.ruoyi.web.controller.monitor; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import com.ruoyi.common.core.controller.BaseController; + +/** + * druid 监控 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/data") +public class DruidController extends BaseController { + private String prefix = "/druid"; + + @RequiresPermissions("monitor:data:view") + @GetMapping() + public String index() { + return redirect(prefix + "/index"); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/ServerController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/ServerController.java index 764197d39..f7e100872 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/ServerController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/ServerController.java @@ -1,31 +1,29 @@ -package com.ruoyi.web.controller.monitor; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.framework.web.domain.Server; - -/** - * 服务器监控 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/server") -public class ServerController extends BaseController -{ - private String prefix = "monitor/server"; - - @RequiresPermissions("monitor:server:view") - @GetMapping() - public String server(ModelMap mmap) throws Exception - { - Server server = new Server(); - server.copyTo(); - mmap.put("server", server); - return prefix + "/server"; - } -} +package com.ruoyi.web.controller.monitor; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.framework.web.domain.Server; + +/** + * 服务器监控 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/server") +public class ServerController extends BaseController { + private String prefix = "monitor/server"; + + @RequiresPermissions("monitor:server:view") + @GetMapping() + public String server(ModelMap mmap) throws Exception { + Server server = new Server(); + server.copyTo(); + mmap.put("server", server); + return prefix + "/server"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java index 688c088b2..7fa7ec19a 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java @@ -1,94 +1,88 @@ -package com.ruoyi.web.controller.monitor; - -import java.util.List; -import com.ruoyi.framework.shiro.service.SysPasswordService; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.system.domain.SysLogininfor; -import com.ruoyi.system.service.ISysLogininforService; - -/** - * 系统访问记录 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/logininfor") -public class SysLogininforController extends BaseController -{ - private String prefix = "monitor/logininfor"; - - @Autowired - private ISysLogininforService logininforService; - - @Autowired - private SysPasswordService passwordService; - - @RequiresPermissions("monitor:logininfor:view") - @GetMapping() - public String logininfor() - { - return prefix + "/logininfor"; - } - - @RequiresPermissions("monitor:logininfor:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysLogininfor logininfor) - { - startPage(); - List list = logininforService.selectLogininforList(logininfor); - return getDataTable(list); - } - - @Log(title = "登陆日志", businessType = BusinessType.EXPORT) - @RequiresPermissions("monitor:logininfor:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysLogininfor logininfor) - { - List list = logininforService.selectLogininforList(logininfor); - ExcelUtil util = new ExcelUtil(SysLogininfor.class); - return util.exportExcel(list, "登陆日志"); - } - - @RequiresPermissions("monitor:logininfor:remove") - @Log(title = "登陆日志", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(logininforService.deleteLogininforByIds(ids)); - } - - @RequiresPermissions("monitor:logininfor:remove") - @Log(title = "登陆日志", businessType = BusinessType.CLEAN) - @PostMapping("/clean") - @ResponseBody - public AjaxResult clean() - { - logininforService.cleanLogininfor(); - return success(); - } - - @RequiresPermissions("monitor:logininfor:unlock") - @Log(title = "账户解锁", businessType = BusinessType.OTHER) - @PostMapping("/unlock") - @ResponseBody - public AjaxResult unlock(String loginName) - { - passwordService.unlock(loginName); - return success(); - } -} +package com.ruoyi.web.controller.monitor; + +import java.util.List; + +import com.ruoyi.framework.shiro.service.SysPasswordService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.system.domain.SysLogininfor; +import com.ruoyi.system.service.ISysLogininforService; + +/** + * 系统访问记录 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/logininfor") +public class SysLogininforController extends BaseController { + private String prefix = "monitor/logininfor"; + + @Autowired + private ISysLogininforService logininforService; + + @Autowired + private SysPasswordService passwordService; + + @RequiresPermissions("monitor:logininfor:view") + @GetMapping() + public String logininfor() { + return prefix + "/logininfor"; + } + + @RequiresPermissions("monitor:logininfor:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysLogininfor logininfor) { + startPage(); + List list = logininforService.selectLogininforList(logininfor); + return getDataTable(list); + } + + @Log(title = "登陆日志", businessType = BusinessType.EXPORT) + @RequiresPermissions("monitor:logininfor:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysLogininfor logininfor) { + List list = logininforService.selectLogininforList(logininfor); + ExcelUtil util = new ExcelUtil(SysLogininfor.class); + return util.exportExcel(list, "登陆日志"); + } + + @RequiresPermissions("monitor:logininfor:remove") + @Log(title = "登陆日志", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(logininforService.deleteLogininforByIds(ids)); + } + + @RequiresPermissions("monitor:logininfor:remove") + @Log(title = "登陆日志", businessType = BusinessType.CLEAN) + @PostMapping("/clean") + @ResponseBody + public AjaxResult clean() { + logininforService.cleanLogininfor(); + return success(); + } + + @RequiresPermissions("monitor:logininfor:unlock") + @Log(title = "账户解锁", businessType = BusinessType.OTHER) + @PostMapping("/unlock") + @ResponseBody + public AjaxResult unlock(String loginName) { + passwordService.unlock(loginName); + return success(); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java index 468866e18..2c51d7891 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java @@ -1,89 +1,83 @@ -package com.ruoyi.web.controller.monitor; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.service.ISysOperLogService; - -/** - * 操作日志记录 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/operlog") -public class SysOperlogController extends BaseController -{ - private String prefix = "monitor/operlog"; - - @Autowired - private ISysOperLogService operLogService; - - @RequiresPermissions("monitor:operlog:view") - @GetMapping() - public String operlog() - { - return prefix + "/operlog"; - } - - @RequiresPermissions("monitor:operlog:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysOperLog operLog) - { - startPage(); - List list = operLogService.selectOperLogList(operLog); - return getDataTable(list); - } - - @Log(title = "操作日志", businessType = BusinessType.EXPORT) - @RequiresPermissions("monitor:operlog:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysOperLog operLog) - { - List list = operLogService.selectOperLogList(operLog); - ExcelUtil util = new ExcelUtil(SysOperLog.class); - return util.exportExcel(list, "操作日志"); - } - - @RequiresPermissions("monitor:operlog:remove") - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(operLogService.deleteOperLogByIds(ids)); - } - - @RequiresPermissions("monitor:operlog:detail") - @GetMapping("/detail/{operId}") - public String detail(@PathVariable("operId") Long operId, ModelMap mmap) - { - mmap.put("operLog", operLogService.selectOperLogById(operId)); - return prefix + "/detail"; - } - - @Log(title = "操作日志", businessType = BusinessType.CLEAN) - @RequiresPermissions("monitor:operlog:remove") - @PostMapping("/clean") - @ResponseBody - public AjaxResult clean() - { - operLogService.cleanOperLog(); - return success(); - } -} +package com.ruoyi.web.controller.monitor; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.system.domain.SysOperLog; +import com.ruoyi.system.service.ISysOperLogService; + +/** + * 操作日志记录 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/operlog") +public class SysOperlogController extends BaseController { + private String prefix = "monitor/operlog"; + + @Autowired + private ISysOperLogService operLogService; + + @RequiresPermissions("monitor:operlog:view") + @GetMapping() + public String operlog() { + return prefix + "/operlog"; + } + + @RequiresPermissions("monitor:operlog:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysOperLog operLog) { + startPage(); + List list = operLogService.selectOperLogList(operLog); + return getDataTable(list); + } + + @Log(title = "操作日志", businessType = BusinessType.EXPORT) + @RequiresPermissions("monitor:operlog:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysOperLog operLog) { + List list = operLogService.selectOperLogList(operLog); + ExcelUtil util = new ExcelUtil(SysOperLog.class); + return util.exportExcel(list, "操作日志"); + } + + @RequiresPermissions("monitor:operlog:remove") + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(operLogService.deleteOperLogByIds(ids)); + } + + @RequiresPermissions("monitor:operlog:detail") + @GetMapping("/detail/{operId}") + public String detail(@PathVariable("operId") Long operId, ModelMap mmap) { + mmap.put("operLog", operLogService.selectOperLogById(operId)); + return prefix + "/detail"; + } + + @Log(title = "操作日志", businessType = BusinessType.CLEAN) + @RequiresPermissions("monitor:operlog:remove") + @PostMapping("/clean") + @ResponseBody + public AjaxResult clean() { + operLogService.cleanOperLog(); + return success(); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java index c3ea3ad72..5ba8700cb 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java @@ -1,114 +1,103 @@ -package com.ruoyi.web.controller.monitor; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.enums.OnlineStatus; -import com.ruoyi.framework.shiro.session.OnlineSession; -import com.ruoyi.framework.shiro.session.OnlineSessionDAO; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.service.ISysUserOnlineService; - -/** - * 在线用户监控 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/online") -public class SysUserOnlineController extends BaseController -{ - private String prefix = "monitor/online"; - - @Autowired - private ISysUserOnlineService userOnlineService; - - @Autowired - private OnlineSessionDAO onlineSessionDAO; - - @RequiresPermissions("monitor:online:view") - @GetMapping() - public String online() - { - return prefix + "/online"; - } - - @RequiresPermissions("monitor:online:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysUserOnline userOnline) - { - startPage(); - List list = userOnlineService.selectUserOnlineList(userOnline); - return getDataTable(list); - } - - @RequiresPermissions("monitor:online:batchForceLogout") - @Log(title = "在线用户", businessType = BusinessType.FORCE) - @PostMapping("/batchForceLogout") - @ResponseBody - public AjaxResult batchForceLogout(@RequestParam("ids[]") String[] ids) - { - for (String sessionId : ids) - { - SysUserOnline online = userOnlineService.selectOnlineById(sessionId); - if (online == null) - { - return error("用户已下线"); - } - OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId()); - if (onlineSession == null) - { - return error("用户已下线"); - } - if (sessionId.equals(ShiroUtils.getSessionId())) - { - return error("当前登陆用户无法强退"); - } - onlineSession.setStatus(OnlineStatus.off_line); - onlineSessionDAO.update(onlineSession); - online.setStatus(OnlineStatus.off_line); - userOnlineService.saveOnline(online); - } - return success(); - } - - @RequiresPermissions("monitor:online:forceLogout") - @Log(title = "在线用户", businessType = BusinessType.FORCE) - @PostMapping("/forceLogout") - @ResponseBody - public AjaxResult forceLogout(String sessionId) - { - SysUserOnline online = userOnlineService.selectOnlineById(sessionId); - if (sessionId.equals(ShiroUtils.getSessionId())) - { - return error("当前登陆用户无法强退"); - } - if (online == null) - { - return error("用户已下线"); - } - OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId()); - if (onlineSession == null) - { - return error("用户已下线"); - } - onlineSession.setStatus(OnlineStatus.off_line); - onlineSessionDAO.update(onlineSession); - online.setStatus(OnlineStatus.off_line); - userOnlineService.saveOnline(online); - return success(); - } -} +package com.ruoyi.web.controller.monitor; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.enums.OnlineStatus; +import com.ruoyi.framework.shiro.session.OnlineSession; +import com.ruoyi.framework.shiro.session.OnlineSessionDAO; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.service.ISysUserOnlineService; + +/** + * 在线用户监控 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/online") +public class SysUserOnlineController extends BaseController { + private String prefix = "monitor/online"; + + @Autowired + private ISysUserOnlineService userOnlineService; + + @Autowired + private OnlineSessionDAO onlineSessionDAO; + + @RequiresPermissions("monitor:online:view") + @GetMapping() + public String online() { + return prefix + "/online"; + } + + @RequiresPermissions("monitor:online:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysUserOnline userOnline) { + startPage(); + List list = userOnlineService.selectUserOnlineList(userOnline); + return getDataTable(list); + } + + @RequiresPermissions("monitor:online:batchForceLogout") + @Log(title = "在线用户", businessType = BusinessType.FORCE) + @PostMapping("/batchForceLogout") + @ResponseBody + public AjaxResult batchForceLogout(@RequestParam("ids[]") String[] ids) { + for (String sessionId : ids) { + SysUserOnline online = userOnlineService.selectOnlineById(sessionId); + if (online == null) { + return error("用户已下线"); + } + OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId()); + if (onlineSession == null) { + return error("用户已下线"); + } + if (sessionId.equals(ShiroUtils.getSessionId())) { + return error("当前登陆用户无法强退"); + } + onlineSession.setStatus(OnlineStatus.off_line); + onlineSessionDAO.update(onlineSession); + online.setStatus(OnlineStatus.off_line); + userOnlineService.saveOnline(online); + } + return success(); + } + + @RequiresPermissions("monitor:online:forceLogout") + @Log(title = "在线用户", businessType = BusinessType.FORCE) + @PostMapping("/forceLogout") + @ResponseBody + public AjaxResult forceLogout(String sessionId) { + SysUserOnline online = userOnlineService.selectOnlineById(sessionId); + if (sessionId.equals(ShiroUtils.getSessionId())) { + return error("当前登陆用户无法强退"); + } + if (online == null) { + return error("用户已下线"); + } + OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId()); + if (onlineSession == null) { + return error("用户已下线"); + } + onlineSession.setStatus(OnlineStatus.off_line); + onlineSessionDAO.update(onlineSession); + online.setStatus(OnlineStatus.off_line); + userOnlineService.saveOnline(online); + return success(); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysCaptchaController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysCaptchaController.java index 230cc3b29..c9d055e62 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysCaptchaController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysCaptchaController.java @@ -1,92 +1,79 @@ -package com.ruoyi.web.controller.system; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import javax.annotation.Resource; -import javax.imageio.ImageIO; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; -import com.google.code.kaptcha.Constants; -import com.google.code.kaptcha.Producer; -import com.ruoyi.common.core.controller.BaseController; - -/** - * 图片验证码(支持算术形式) - * - * @author ruoyi - */ -@Controller -@RequestMapping("/captcha") -public class SysCaptchaController extends BaseController -{ - @Resource(name = "captchaProducer") - private Producer captchaProducer; - - @Resource(name = "captchaProducerMath") - private Producer captchaProducerMath; - - /** - * 验证码生成 - */ - @GetMapping(value = "/captchaImage") - public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) - { - ServletOutputStream out = null; - try - { - HttpSession session = request.getSession(); - response.setDateHeader("Expires", 0); - response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); - response.addHeader("Cache-Control", "post-check=0, pre-check=0"); - response.setHeader("Pragma", "no-cache"); - response.setContentType("image/jpeg"); - - String type = request.getParameter("type"); - String capStr = null; - String code = null; - BufferedImage bi = null; - if ("math".equals(type)) - { - String capText = captchaProducerMath.createText(); - capStr = capText.substring(0, capText.lastIndexOf("@")); - code = capText.substring(capText.lastIndexOf("@") + 1); - bi = captchaProducerMath.createImage(capStr); - } - else if ("char".equals(type)) - { - capStr = code = captchaProducer.createText(); - bi = captchaProducer.createImage(capStr); - } - session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code); - out = response.getOutputStream(); - ImageIO.write(bi, "jpg", out); - out.flush(); - - } - catch (Exception e) - { - e.printStackTrace(); - } - finally - { - try - { - if (out != null) - { - out.close(); - } - } - catch (IOException e) - { - e.printStackTrace(); - } - } - return null; - } +package com.ruoyi.web.controller.system; + +import java.awt.image.BufferedImage; +import java.io.IOException; +import javax.annotation.Resource; +import javax.imageio.ImageIO; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; +import com.google.code.kaptcha.Constants; +import com.google.code.kaptcha.Producer; +import com.ruoyi.common.core.controller.BaseController; + +/** + * 图片验证码(支持算术形式) + * + * @author ruoyi + */ +@Controller +@RequestMapping("/captcha") +public class SysCaptchaController extends BaseController { + @Resource(name = "captchaProducer") + private Producer captchaProducer; + + @Resource(name = "captchaProducerMath") + private Producer captchaProducerMath; + + /** + * 验证码生成 + */ + @GetMapping(value = "/captchaImage") + public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) { + ServletOutputStream out = null; + try { + HttpSession session = request.getSession(); + response.setDateHeader("Expires", 0); + response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); + response.addHeader("Cache-Control", "post-check=0, pre-check=0"); + response.setHeader("Pragma", "no-cache"); + response.setContentType("image/jpeg"); + + String type = request.getParameter("type"); + String capStr = null; + String code = null; + BufferedImage bi = null; + if ("math".equals(type)) { + String capText = captchaProducerMath.createText(); + capStr = capText.substring(0, capText.lastIndexOf("@")); + code = capText.substring(capText.lastIndexOf("@") + 1); + bi = captchaProducerMath.createImage(capStr); + } else if ("char".equals(type)) { + capStr = code = captchaProducer.createText(); + bi = captchaProducer.createImage(capStr); + } + session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code); + out = response.getOutputStream(); + ImageIO.write(bi, "jpg", out); + out.flush(); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java index 139469d25..9af0ed815 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java @@ -1,144 +1,133 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysConfig; -import com.ruoyi.system.service.ISysConfigService; - -/** - * 参数配置 信息操作处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/config") -public class SysConfigController extends BaseController -{ - private String prefix = "system/config"; - - @Autowired - private ISysConfigService configService; - - @RequiresPermissions("system:config:view") - @GetMapping() - public String config() - { - return prefix + "/config"; - } - - /** - * 查询参数配置列表 - */ - @RequiresPermissions("system:config:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysConfig config) - { - startPage(); - List list = configService.selectConfigList(config); - return getDataTable(list); - } - - @Log(title = "参数管理", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:config:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysConfig config) - { - List list = configService.selectConfigList(config); - ExcelUtil util = new ExcelUtil(SysConfig.class); - return util.exportExcel(list, "参数数据"); - } - - /** - * 新增参数配置 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存参数配置 - */ - @RequiresPermissions("system:config:add") - @Log(title = "参数管理", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysConfig config) - { - if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) - { - return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); - } - config.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(configService.insertConfig(config)); - } - - /** - * 修改参数配置 - */ - @GetMapping("/edit/{configId}") - public String edit(@PathVariable("configId") Long configId, ModelMap mmap) - { - mmap.put("config", configService.selectConfigById(configId)); - return prefix + "/edit"; - } - - /** - * 修改保存参数配置 - */ - @RequiresPermissions("system:config:edit") - @Log(title = "参数管理", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysConfig config) - { - if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) - { - return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); - } - config.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(configService.updateConfig(config)); - } - - /** - * 删除参数配置 - */ - @RequiresPermissions("system:config:remove") - @Log(title = "参数管理", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(configService.deleteConfigByIds(ids)); - } - - /** - * 校验参数键名 - */ - @PostMapping("/checkConfigKeyUnique") - @ResponseBody - public String checkConfigKeyUnique(SysConfig config) - { - return configService.checkConfigKeyUnique(config); - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysConfig; +import com.ruoyi.system.service.ISysConfigService; + +/** + * 参数配置 信息操作处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/config") +public class SysConfigController extends BaseController { + private String prefix = "system/config"; + + @Autowired + private ISysConfigService configService; + + @RequiresPermissions("system:config:view") + @GetMapping() + public String config() { + return prefix + "/config"; + } + + /** + * 查询参数配置列表 + */ + @RequiresPermissions("system:config:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysConfig config) { + startPage(); + List list = configService.selectConfigList(config); + return getDataTable(list); + } + + @Log(title = "参数管理", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:config:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysConfig config) { + List list = configService.selectConfigList(config); + ExcelUtil util = new ExcelUtil(SysConfig.class); + return util.exportExcel(list, "参数数据"); + } + + /** + * 新增参数配置 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存参数配置 + */ + @RequiresPermissions("system:config:add") + @Log(title = "参数管理", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysConfig config) { + if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) { + return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); + } + config.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(configService.insertConfig(config)); + } + + /** + * 修改参数配置 + */ + @GetMapping("/edit/{configId}") + public String edit(@PathVariable("configId") Long configId, ModelMap mmap) { + mmap.put("config", configService.selectConfigById(configId)); + return prefix + "/edit"; + } + + /** + * 修改保存参数配置 + */ + @RequiresPermissions("system:config:edit") + @Log(title = "参数管理", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysConfig config) { + if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) { + return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); + } + config.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(configService.updateConfig(config)); + } + + /** + * 删除参数配置 + */ + @RequiresPermissions("system:config:remove") + @Log(title = "参数管理", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(configService.deleteConfigByIds(ids)); + } + + /** + * 校验参数键名 + */ + @PostMapping("/checkConfigKeyUnique") + @ResponseBody + public String checkConfigKeyUnique(SysConfig config) { + return configService.checkConfigKeyUnique(config); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java index bb17d9f3b..59b6b9ab6 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java @@ -1,180 +1,162 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysDept; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.service.ISysDeptService; - -/** - * 部门信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/dept") -public class SysDeptController extends BaseController -{ - private String prefix = "system/dept"; - - @Autowired - private ISysDeptService deptService; - - @RequiresPermissions("system:dept:view") - @GetMapping() - public String dept() - { - return prefix + "/dept"; - } - - @RequiresPermissions("system:dept:list") - @PostMapping("/list") - @ResponseBody - public List list(SysDept dept) - { - List deptList = deptService.selectDeptList(dept); - return deptList; - } - - /** - * 新增部门 - */ - @GetMapping("/add/{parentId}") - public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) - { - mmap.put("dept", deptService.selectDeptById(parentId)); - return prefix + "/add"; - } - - /** - * 新增保存部门 - */ - @Log(title = "部门管理", businessType = BusinessType.INSERT) - @RequiresPermissions("system:dept:add") - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysDept dept) - { - if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) - { - return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); - } - dept.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(deptService.insertDept(dept)); - } - - /** - * 修改 - */ - @GetMapping("/edit/{deptId}") - public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) - { - SysDept dept = deptService.selectDeptById(deptId); - if (StringUtils.isNotNull(dept) && 100L == deptId) - { - dept.setParentName("无"); - } - mmap.put("dept", dept); - return prefix + "/edit"; - } - - /** - * 保存 - */ - @Log(title = "部门管理", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:dept:edit") - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysDept dept) - { - if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) - { - return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); - } - else if (dept.getParentId().equals(dept.getDeptId())) - { - return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); - } - dept.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(deptService.updateDept(dept)); - } - - /** - * 删除 - */ - @Log(title = "部门管理", businessType = BusinessType.DELETE) - @RequiresPermissions("system:dept:remove") - @GetMapping("/remove/{deptId}") - @ResponseBody - public AjaxResult remove(@PathVariable("deptId") Long deptId) - { - if (deptService.selectDeptCount(deptId) > 0) - { - return AjaxResult.warn("存在下级部门,不允许删除"); - } - if (deptService.checkDeptExistUser(deptId)) - { - return AjaxResult.warn("部门存在用户,不允许删除"); - } - return toAjax(deptService.deleteDeptById(deptId)); - } - - /** - * 校验部门名称 - */ - @PostMapping("/checkDeptNameUnique") - @ResponseBody - public String checkDeptNameUnique(SysDept dept) - { - return deptService.checkDeptNameUnique(dept); - } - - /** - * 选择部门树 - */ - @GetMapping("/selectDeptTree/{deptId}") - public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) - { - mmap.put("dept", deptService.selectDeptById(deptId)); - return prefix + "/tree"; - } - - /** - * 加载部门列表树 - */ - @GetMapping("/treeData") - @ResponseBody - public List treeData() - { - List ztrees = deptService.selectDeptTree(new SysDept()); - return ztrees; - } - - /** - * 加载角色部门(数据权限)列表树 - */ - @GetMapping("/roleDeptTreeData") - @ResponseBody - public List deptTreeData(SysRole role) - { - List ztrees = deptService.roleDeptTreeData(role); - return ztrees; - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.service.ISysDeptService; + +/** + * 部门信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/dept") +public class SysDeptController extends BaseController { + private String prefix = "system/dept"; + + @Autowired + private ISysDeptService deptService; + + @RequiresPermissions("system:dept:view") + @GetMapping() + public String dept() { + return prefix + "/dept"; + } + + @RequiresPermissions("system:dept:list") + @PostMapping("/list") + @ResponseBody + public List list(SysDept dept) { + List deptList = deptService.selectDeptList(dept); + return deptList; + } + + /** + * 新增部门 + */ + @GetMapping("/add/{parentId}") + public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) { + mmap.put("dept", deptService.selectDeptById(parentId)); + return prefix + "/add"; + } + + /** + * 新增保存部门 + */ + @Log(title = "部门管理", businessType = BusinessType.INSERT) + @RequiresPermissions("system:dept:add") + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysDept dept) { + if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) { + return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); + } + dept.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(deptService.insertDept(dept)); + } + + /** + * 修改 + */ + @GetMapping("/edit/{deptId}") + public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) { + SysDept dept = deptService.selectDeptById(deptId); + if (StringUtils.isNotNull(dept) && 100L == deptId) { + dept.setParentName("无"); + } + mmap.put("dept", dept); + return prefix + "/edit"; + } + + /** + * 保存 + */ + @Log(title = "部门管理", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:dept:edit") + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysDept dept) { + if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) { + return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); + } else if (dept.getParentId().equals(dept.getDeptId())) { + return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); + } + dept.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(deptService.updateDept(dept)); + } + + /** + * 删除 + */ + @Log(title = "部门管理", businessType = BusinessType.DELETE) + @RequiresPermissions("system:dept:remove") + @GetMapping("/remove/{deptId}") + @ResponseBody + public AjaxResult remove(@PathVariable("deptId") Long deptId) { + if (deptService.selectDeptCount(deptId) > 0) { + return AjaxResult.warn("存在下级部门,不允许删除"); + } + if (deptService.checkDeptExistUser(deptId)) { + return AjaxResult.warn("部门存在用户,不允许删除"); + } + return toAjax(deptService.deleteDeptById(deptId)); + } + + /** + * 校验部门名称 + */ + @PostMapping("/checkDeptNameUnique") + @ResponseBody + public String checkDeptNameUnique(SysDept dept) { + return deptService.checkDeptNameUnique(dept); + } + + /** + * 选择部门树 + */ + @GetMapping("/selectDeptTree/{deptId}") + public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) { + mmap.put("dept", deptService.selectDeptById(deptId)); + return prefix + "/tree"; + } + + /** + * 加载部门列表树 + */ + @GetMapping("/treeData") + @ResponseBody + public List treeData() { + List ztrees = deptService.selectDeptTree(new SysDept()); + return ztrees; + } + + /** + * 加载角色部门(数据权限)列表树 + */ + @GetMapping("/roleDeptTreeData") + @ResponseBody + public List deptTreeData(SysRole role) { + List ztrees = deptService.roleDeptTreeData(role); + return ztrees; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java index 945109858..167c2f459 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java @@ -1,120 +1,112 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysDictData; -import com.ruoyi.system.service.ISysDictDataService; - -/** - * 数据字典信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/dict/data") -public class SysDictDataController extends BaseController -{ - private String prefix = "system/dict/data"; - - @Autowired - private ISysDictDataService dictDataService; - - @RequiresPermissions("system:dict:view") - @GetMapping() - public String dictData() - { - return prefix + "/data"; - } - - @PostMapping("/list") - @RequiresPermissions("system:dict:list") - @ResponseBody - public TableDataInfo list(SysDictData dictData) - { - startPage(); - List list = dictDataService.selectDictDataList(dictData); - return getDataTable(list); - } - - @Log(title = "字典数据", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:dict:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysDictData dictData) - { - List list = dictDataService.selectDictDataList(dictData); - ExcelUtil util = new ExcelUtil(SysDictData.class); - return util.exportExcel(list, "字典数据"); - } - - /** - * 新增字典类型 - */ - @GetMapping("/add/{dictType}") - public String add(@PathVariable("dictType") String dictType, ModelMap mmap) - { - mmap.put("dictType", dictType); - return prefix + "/add"; - } - - /** - * 新增保存字典类型 - */ - @Log(title = "字典数据", businessType = BusinessType.INSERT) - @RequiresPermissions("system:dict:add") - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysDictData dict) - { - dict.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(dictDataService.insertDictData(dict)); - } - - /** - * 修改字典类型 - */ - @GetMapping("/edit/{dictCode}") - public String edit(@PathVariable("dictCode") Long dictCode, ModelMap mmap) - { - mmap.put("dict", dictDataService.selectDictDataById(dictCode)); - return prefix + "/edit"; - } - - /** - * 修改保存字典类型 - */ - @Log(title = "字典数据", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:dict:edit") - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysDictData dict) - { - dict.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(dictDataService.updateDictData(dict)); - } - - @Log(title = "字典数据", businessType = BusinessType.DELETE) - @RequiresPermissions("system:dict:remove") - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(dictDataService.deleteDictDataByIds(ids)); - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysDictData; +import com.ruoyi.system.service.ISysDictDataService; + +/** + * 数据字典信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/dict/data") +public class SysDictDataController extends BaseController { + private String prefix = "system/dict/data"; + + @Autowired + private ISysDictDataService dictDataService; + + @RequiresPermissions("system:dict:view") + @GetMapping() + public String dictData() { + return prefix + "/data"; + } + + @PostMapping("/list") + @RequiresPermissions("system:dict:list") + @ResponseBody + public TableDataInfo list(SysDictData dictData) { + startPage(); + List list = dictDataService.selectDictDataList(dictData); + return getDataTable(list); + } + + @Log(title = "字典数据", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:dict:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysDictData dictData) { + List list = dictDataService.selectDictDataList(dictData); + ExcelUtil util = new ExcelUtil(SysDictData.class); + return util.exportExcel(list, "字典数据"); + } + + /** + * 新增字典类型 + */ + @GetMapping("/add/{dictType}") + public String add(@PathVariable("dictType") String dictType, ModelMap mmap) { + mmap.put("dictType", dictType); + return prefix + "/add"; + } + + /** + * 新增保存字典类型 + */ + @Log(title = "字典数据", businessType = BusinessType.INSERT) + @RequiresPermissions("system:dict:add") + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysDictData dict) { + dict.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(dictDataService.insertDictData(dict)); + } + + /** + * 修改字典类型 + */ + @GetMapping("/edit/{dictCode}") + public String edit(@PathVariable("dictCode") Long dictCode, ModelMap mmap) { + mmap.put("dict", dictDataService.selectDictDataById(dictCode)); + return prefix + "/edit"; + } + + /** + * 修改保存字典类型 + */ + @Log(title = "字典数据", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:dict:edit") + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysDictData dict) { + dict.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(dictDataService.updateDictData(dict)); + } + + @Log(title = "字典数据", businessType = BusinessType.DELETE) + @RequiresPermissions("system:dict:remove") + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(dictDataService.deleteDictDataByIds(ids)); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java index bc8950d76..37f67fcdc 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java @@ -1,182 +1,165 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysDictType; -import com.ruoyi.system.service.ISysDictTypeService; - -/** - * 数据字典信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/dict") -public class SysDictTypeController extends BaseController -{ - private String prefix = "system/dict/type"; - - @Autowired - private ISysDictTypeService dictTypeService; - - @RequiresPermissions("system:dict:view") - @GetMapping() - public String dictType() - { - return prefix + "/type"; - } - - @PostMapping("/list") - @RequiresPermissions("system:dict:list") - @ResponseBody - public TableDataInfo list(SysDictType dictType) - { - startPage(); - List list = dictTypeService.selectDictTypeList(dictType); - return getDataTable(list); - } - - @Log(title = "字典类型", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:dict:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysDictType dictType) - { - - List list = dictTypeService.selectDictTypeList(dictType); - ExcelUtil util = new ExcelUtil(SysDictType.class); - return util.exportExcel(list, "字典类型"); - } - - /** - * 新增字典类型 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存字典类型 - */ - @Log(title = "字典类型", businessType = BusinessType.INSERT) - @RequiresPermissions("system:dict:add") - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysDictType dict) - { - if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) - { - return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); - } - dict.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(dictTypeService.insertDictType(dict)); - } - - /** - * 修改字典类型 - */ - @GetMapping("/edit/{dictId}") - public String edit(@PathVariable("dictId") Long dictId, ModelMap mmap) - { - mmap.put("dict", dictTypeService.selectDictTypeById(dictId)); - return prefix + "/edit"; - } - - /** - * 修改保存字典类型 - */ - @Log(title = "字典类型", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:dict:edit") - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysDictType dict) - { - if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) - { - return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); - } - dict.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(dictTypeService.updateDictType(dict)); - } - - @Log(title = "字典类型", businessType = BusinessType.DELETE) - @RequiresPermissions("system:dict:remove") - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - try - { - return toAjax(dictTypeService.deleteDictTypeByIds(ids)); - } - catch (Exception e) - { - return error(e.getMessage()); - } - } - - /** - * 查询字典详细 - */ - @RequiresPermissions("system:dict:list") - @GetMapping("/detail/{dictId}") - public String detail(@PathVariable("dictId") Long dictId, ModelMap mmap) - { - mmap.put("dict", dictTypeService.selectDictTypeById(dictId)); - mmap.put("dictList", dictTypeService.selectDictTypeAll()); - return "system/dict/data/data"; - } - - /** - * 校验字典类型 - */ - @PostMapping("/checkDictTypeUnique") - @ResponseBody - public String checkDictTypeUnique(SysDictType dictType) - { - return dictTypeService.checkDictTypeUnique(dictType); - } - - /** - * 选择字典树 - */ - @GetMapping("/selectDictTree/{columnId}/{dictType}") - public String selectDeptTree(@PathVariable("columnId") Long columnId, @PathVariable("dictType") String dictType, - ModelMap mmap) - { - mmap.put("columnId", columnId); - mmap.put("dict", dictTypeService.selectDictTypeByType(dictType)); - return prefix + "/tree"; - } - - /** - * 加载字典列表树 - */ - @GetMapping("/treeData") - @ResponseBody - public List treeData() - { - List ztrees = dictTypeService.selectDictTree(new SysDictType()); - return ztrees; - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysDictType; +import com.ruoyi.system.service.ISysDictTypeService; + +/** + * 数据字典信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/dict") +public class SysDictTypeController extends BaseController { + private String prefix = "system/dict/type"; + + @Autowired + private ISysDictTypeService dictTypeService; + + @RequiresPermissions("system:dict:view") + @GetMapping() + public String dictType() { + return prefix + "/type"; + } + + @PostMapping("/list") + @RequiresPermissions("system:dict:list") + @ResponseBody + public TableDataInfo list(SysDictType dictType) { + startPage(); + List list = dictTypeService.selectDictTypeList(dictType); + return getDataTable(list); + } + + @Log(title = "字典类型", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:dict:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysDictType dictType) { + + List list = dictTypeService.selectDictTypeList(dictType); + ExcelUtil util = new ExcelUtil(SysDictType.class); + return util.exportExcel(list, "字典类型"); + } + + /** + * 新增字典类型 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存字典类型 + */ + @Log(title = "字典类型", businessType = BusinessType.INSERT) + @RequiresPermissions("system:dict:add") + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysDictType dict) { + if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) { + return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); + } + dict.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(dictTypeService.insertDictType(dict)); + } + + /** + * 修改字典类型 + */ + @GetMapping("/edit/{dictId}") + public String edit(@PathVariable("dictId") Long dictId, ModelMap mmap) { + mmap.put("dict", dictTypeService.selectDictTypeById(dictId)); + return prefix + "/edit"; + } + + /** + * 修改保存字典类型 + */ + @Log(title = "字典类型", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:dict:edit") + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysDictType dict) { + if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) { + return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); + } + dict.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(dictTypeService.updateDictType(dict)); + } + + @Log(title = "字典类型", businessType = BusinessType.DELETE) + @RequiresPermissions("system:dict:remove") + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + try { + return toAjax(dictTypeService.deleteDictTypeByIds(ids)); + } catch (Exception e) { + return error(e.getMessage()); + } + } + + /** + * 查询字典详细 + */ + @RequiresPermissions("system:dict:list") + @GetMapping("/detail/{dictId}") + public String detail(@PathVariable("dictId") Long dictId, ModelMap mmap) { + mmap.put("dict", dictTypeService.selectDictTypeById(dictId)); + mmap.put("dictList", dictTypeService.selectDictTypeAll()); + return "system/dict/data/data"; + } + + /** + * 校验字典类型 + */ + @PostMapping("/checkDictTypeUnique") + @ResponseBody + public String checkDictTypeUnique(SysDictType dictType) { + return dictTypeService.checkDictTypeUnique(dictType); + } + + /** + * 选择字典树 + */ + @GetMapping("/selectDictTree/{columnId}/{dictType}") + public String selectDeptTree(@PathVariable("columnId") Long columnId, @PathVariable("dictType") String dictType, + ModelMap mmap) { + mmap.put("columnId", columnId); + mmap.put("dict", dictTypeService.selectDictTypeByType(dictType)); + return prefix + "/tree"; + } + + /** + * 加载字典列表树 + */ + @GetMapping("/treeData") + @ResponseBody + public List treeData() { + List ztrees = dictTypeService.selectDictTree(new SysDictType()); + return ztrees; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java index 8c0a0eed5..b0e575bc4 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java @@ -1,55 +1,52 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysMenu; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.service.ISysMenuService; - -/** - * 首页 业务处理 - * - * @author ruoyi - */ -@Controller -public class SysIndexController extends BaseController -{ - @Autowired - private ISysMenuService menuService; - - // 系统首页 - @GetMapping("/index") - public String index(ModelMap mmap) - { - // 取身份信息 - SysUser user = ShiroUtils.getSysUser(); - // 根据用户id取出菜单 - List menus = menuService.selectMenusByUser(user); - mmap.put("menus", menus); - mmap.put("user", user); - mmap.put("copyrightYear", Global.getCopyrightYear()); - mmap.put("demoEnabled", Global.isDemoEnabled()); - return "index"; - } - - // 切换主题 - @GetMapping("/system/switchSkin") - public String switchSkin(ModelMap mmap) - { - return "skin"; - } - - // 系统介绍 - @GetMapping("/system/main") - public String main(ModelMap mmap) - { - mmap.put("version", Global.getVersion()); - return "main"; - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysMenuService; + +/** + * 首页 业务处理 + * + * @author ruoyi + */ +@Controller +public class SysIndexController extends BaseController { + @Autowired + private ISysMenuService menuService; + + // 系统首页 + @GetMapping("/index") + public String index(ModelMap mmap) { + // 取身份信息 + SysUser user = ShiroUtils.getSysUser(); + // 根据用户id取出菜单 + List menus = menuService.selectMenusByUser(user); + mmap.put("menus", menus); + mmap.put("user", user); + mmap.put("copyrightYear", Global.getCopyrightYear()); + mmap.put("demoEnabled", Global.isDemoEnabled()); + return "index"; + } + + // 切换主题 + @GetMapping("/system/switchSkin") + public String switchSkin(ModelMap mmap) { + return "skin"; + } + + // 系统介绍 + @GetMapping("/system/main") + public String main(ModelMap mmap) { + mmap.put("version", Global.getVersion()); + return "main"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java index 1652f74ef..094f817ab 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java @@ -2,6 +2,7 @@ package com.ruoyi.web.controller.system; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; @@ -17,18 +18,15 @@ import com.ruoyi.common.utils.StringUtils; /** * 登录验证 - * + * * @author ruoyi */ @Controller -public class SysLoginController extends BaseController -{ +public class SysLoginController extends BaseController { @GetMapping("/login") - public String login(HttpServletRequest request, HttpServletResponse response) - { + public String login(HttpServletRequest request, HttpServletResponse response) { // 如果是Ajax请求,返回Json字符串。 - if (ServletUtils.isAjaxRequest(request)) - { + if (ServletUtils.isAjaxRequest(request)) { return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}"); } @@ -37,20 +35,15 @@ public class SysLoginController extends BaseController @PostMapping("/login") @ResponseBody - public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) - { + public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) { UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe); Subject subject = SecurityUtils.getSubject(); - try - { + try { subject.login(token); return success(); - } - catch (AuthenticationException e) - { + } catch (AuthenticationException e) { String msg = "用户或密码错误"; - if (StringUtils.isNotEmpty(e.getMessage())) - { + if (StringUtils.isNotEmpty(e.getMessage())) { msg = e.getMessage(); } return error(msg); @@ -58,8 +51,7 @@ public class SysLoginController extends BaseController } @GetMapping("/unauth") - public String unauth() - { + public String unauth() { return "error/unauth"; } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java index 3615c7599..e8e7e41d2 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java @@ -1,196 +1,177 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysMenu; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.service.ISysMenuService; - -/** - * 菜单信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/menu") -public class SysMenuController extends BaseController -{ - private String prefix = "system/menu"; - - @Autowired - private ISysMenuService menuService; - - @RequiresPermissions("system:menu:view") - @GetMapping() - public String menu() - { - return prefix + "/menu"; - } - - @RequiresPermissions("system:menu:list") - @PostMapping("/list") - @ResponseBody - public List list(SysMenu menu) - { - Long userId = ShiroUtils.getUserId(); - List menuList = menuService.selectMenuList(menu, userId); - return menuList; - } - - /** - * 删除菜单 - */ - @Log(title = "菜单管理", businessType = BusinessType.DELETE) - @RequiresPermissions("system:menu:remove") - @GetMapping("/remove/{menuId}") - @ResponseBody - public AjaxResult remove(@PathVariable("menuId") Long menuId) - { - if (menuService.selectCountMenuByParentId(menuId) > 0) - { - return AjaxResult.warn("存在子菜单,不允许删除"); - } - if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) - { - return AjaxResult.warn("菜单已分配,不允许删除"); - } - ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(menuService.deleteMenuById(menuId)); - } - - /** - * 新增 - */ - @GetMapping("/add/{parentId}") - public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) - { - SysMenu menu = null; - if (0L != parentId) - { - menu = menuService.selectMenuById(parentId); - } - else - { - menu = new SysMenu(); - menu.setMenuId(0L); - menu.setMenuName("主目录"); - } - mmap.put("menu", menu); - return prefix + "/add"; - } - - /** - * 新增保存菜单 - */ - @Log(title = "菜单管理", businessType = BusinessType.INSERT) - @RequiresPermissions("system:menu:add") - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysMenu menu) - { - if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) - { - return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); - } - menu.setCreateBy(ShiroUtils.getLoginName()); - ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(menuService.insertMenu(menu)); - } - - /** - * 修改菜单 - */ - @GetMapping("/edit/{menuId}") - public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap) - { - mmap.put("menu", menuService.selectMenuById(menuId)); - return prefix + "/edit"; - } - - /** - * 修改保存菜单 - */ - @Log(title = "菜单管理", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:menu:edit") - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysMenu menu) - { - if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) - { - return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); - } - menu.setUpdateBy(ShiroUtils.getLoginName()); - ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(menuService.updateMenu(menu)); - } - - /** - * 选择菜单图标 - */ - @GetMapping("/icon") - public String icon() - { - return prefix + "/icon"; - } - - /** - * 校验菜单名称 - */ - @PostMapping("/checkMenuNameUnique") - @ResponseBody - public String checkMenuNameUnique(SysMenu menu) - { - return menuService.checkMenuNameUnique(menu); - } - - /** - * 加载角色菜单列表树 - */ - @GetMapping("/roleMenuTreeData") - @ResponseBody - public List roleMenuTreeData(SysRole role) - { - Long userId = ShiroUtils.getUserId(); - List ztrees = menuService.roleMenuTreeData(role, userId); - return ztrees; - } - - /** - * 加载所有菜单列表树 - */ - @GetMapping("/menuTreeData") - @ResponseBody - public List menuTreeData() - { - Long userId = ShiroUtils.getUserId(); - List ztrees = menuService.menuTreeData(userId); - return ztrees; - } - - /** - * 选择菜单树 - */ - @GetMapping("/selectMenuTree/{menuId}") - public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mmap) - { - mmap.put("menu", menuService.selectMenuById(menuId)); - return prefix + "/tree"; - } +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.service.ISysMenuService; + +/** + * 菜单信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/menu") +public class SysMenuController extends BaseController { + private String prefix = "system/menu"; + + @Autowired + private ISysMenuService menuService; + + @RequiresPermissions("system:menu:view") + @GetMapping() + public String menu() { + return prefix + "/menu"; + } + + @RequiresPermissions("system:menu:list") + @PostMapping("/list") + @ResponseBody + public List list(SysMenu menu) { + Long userId = ShiroUtils.getUserId(); + List menuList = menuService.selectMenuList(menu, userId); + return menuList; + } + + /** + * 删除菜单 + */ + @Log(title = "菜单管理", businessType = BusinessType.DELETE) + @RequiresPermissions("system:menu:remove") + @GetMapping("/remove/{menuId}") + @ResponseBody + public AjaxResult remove(@PathVariable("menuId") Long menuId) { + if (menuService.selectCountMenuByParentId(menuId) > 0) { + return AjaxResult.warn("存在子菜单,不允许删除"); + } + if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) { + return AjaxResult.warn("菜单已分配,不允许删除"); + } + ShiroUtils.clearCachedAuthorizationInfo(); + return toAjax(menuService.deleteMenuById(menuId)); + } + + /** + * 新增 + */ + @GetMapping("/add/{parentId}") + public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) { + SysMenu menu = null; + if (0L != parentId) { + menu = menuService.selectMenuById(parentId); + } else { + menu = new SysMenu(); + menu.setMenuId(0L); + menu.setMenuName("主目录"); + } + mmap.put("menu", menu); + return prefix + "/add"; + } + + /** + * 新增保存菜单 + */ + @Log(title = "菜单管理", businessType = BusinessType.INSERT) + @RequiresPermissions("system:menu:add") + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysMenu menu) { + if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { + return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); + } + menu.setCreateBy(ShiroUtils.getLoginName()); + ShiroUtils.clearCachedAuthorizationInfo(); + return toAjax(menuService.insertMenu(menu)); + } + + /** + * 修改菜单 + */ + @GetMapping("/edit/{menuId}") + public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap) { + mmap.put("menu", menuService.selectMenuById(menuId)); + return prefix + "/edit"; + } + + /** + * 修改保存菜单 + */ + @Log(title = "菜单管理", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:menu:edit") + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysMenu menu) { + if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { + return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); + } + menu.setUpdateBy(ShiroUtils.getLoginName()); + ShiroUtils.clearCachedAuthorizationInfo(); + return toAjax(menuService.updateMenu(menu)); + } + + /** + * 选择菜单图标 + */ + @GetMapping("/icon") + public String icon() { + return prefix + "/icon"; + } + + /** + * 校验菜单名称 + */ + @PostMapping("/checkMenuNameUnique") + @ResponseBody + public String checkMenuNameUnique(SysMenu menu) { + return menuService.checkMenuNameUnique(menu); + } + + /** + * 加载角色菜单列表树 + */ + @GetMapping("/roleMenuTreeData") + @ResponseBody + public List roleMenuTreeData(SysRole role) { + Long userId = ShiroUtils.getUserId(); + List ztrees = menuService.roleMenuTreeData(role, userId); + return ztrees; + } + + /** + * 加载所有菜单列表树 + */ + @GetMapping("/menuTreeData") + @ResponseBody + public List menuTreeData() { + Long userId = ShiroUtils.getUserId(); + List ztrees = menuService.menuTreeData(userId); + return ztrees; + } + + /** + * 选择菜单树 + */ + @GetMapping("/selectMenuTree/{menuId}") + public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mmap) { + mmap.put("menu", menuService.selectMenuById(menuId)); + return prefix + "/tree"; + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java index 671dc11e3..c9a1aceb2 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java @@ -1,112 +1,105 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysNotice; -import com.ruoyi.system.service.ISysNoticeService; - -/** - * 公告 信息操作处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/notice") -public class SysNoticeController extends BaseController -{ - private String prefix = "system/notice"; - - @Autowired - private ISysNoticeService noticeService; - - @RequiresPermissions("system:notice:view") - @GetMapping() - public String notice() - { - return prefix + "/notice"; - } - - /** - * 查询公告列表 - */ - @RequiresPermissions("system:notice:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysNotice notice) - { - startPage(); - List list = noticeService.selectNoticeList(notice); - return getDataTable(list); - } - - /** - * 新增公告 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存公告 - */ - @RequiresPermissions("system:notice:add") - @Log(title = "通知公告", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(SysNotice notice) - { - notice.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(noticeService.insertNotice(notice)); - } - - /** - * 修改公告 - */ - @GetMapping("/edit/{noticeId}") - public String edit(@PathVariable("noticeId") Long noticeId, ModelMap mmap) - { - mmap.put("notice", noticeService.selectNoticeById(noticeId)); - return prefix + "/edit"; - } - - /** - * 修改保存公告 - */ - @RequiresPermissions("system:notice:edit") - @Log(title = "通知公告", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(SysNotice notice) - { - notice.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(noticeService.updateNotice(notice)); - } - - /** - * 删除公告 - */ - @RequiresPermissions("system:notice:remove") - @Log(title = "通知公告", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(noticeService.deleteNoticeByIds(ids)); - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysNotice; +import com.ruoyi.system.service.ISysNoticeService; + +/** + * 公告 信息操作处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/notice") +public class SysNoticeController extends BaseController { + private String prefix = "system/notice"; + + @Autowired + private ISysNoticeService noticeService; + + @RequiresPermissions("system:notice:view") + @GetMapping() + public String notice() { + return prefix + "/notice"; + } + + /** + * 查询公告列表 + */ + @RequiresPermissions("system:notice:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysNotice notice) { + startPage(); + List list = noticeService.selectNoticeList(notice); + return getDataTable(list); + } + + /** + * 新增公告 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存公告 + */ + @RequiresPermissions("system:notice:add") + @Log(title = "通知公告", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(SysNotice notice) { + notice.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(noticeService.insertNotice(notice)); + } + + /** + * 修改公告 + */ + @GetMapping("/edit/{noticeId}") + public String edit(@PathVariable("noticeId") Long noticeId, ModelMap mmap) { + mmap.put("notice", noticeService.selectNoticeById(noticeId)); + return prefix + "/edit"; + } + + /** + * 修改保存公告 + */ + @RequiresPermissions("system:notice:edit") + @Log(title = "通知公告", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(SysNotice notice) { + notice.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(noticeService.updateNotice(notice)); + } + + /** + * 删除公告 + */ + @RequiresPermissions("system:notice:remove") + @Log(title = "通知公告", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(noticeService.deleteNoticeByIds(ids)); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java index d6db9fdf0..7af40d1d9 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java @@ -1,163 +1,144 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.service.ISysPostService; - -/** - * 岗位信息操作处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/post") -public class SysPostController extends BaseController -{ - private String prefix = "system/post"; - - @Autowired - private ISysPostService postService; - - @RequiresPermissions("system:post:view") - @GetMapping() - public String operlog() - { - return prefix + "/post"; - } - - @RequiresPermissions("system:post:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysPost post) - { - startPage(); - List list = postService.selectPostList(post); - return getDataTable(list); - } - - @Log(title = "岗位管理", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:post:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysPost post) - { - List list = postService.selectPostList(post); - ExcelUtil util = new ExcelUtil(SysPost.class); - return util.exportExcel(list, "岗位数据"); - } - - @RequiresPermissions("system:post:remove") - @Log(title = "岗位管理", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - try - { - return toAjax(postService.deletePostByIds(ids)); - } - catch (Exception e) - { - return error(e.getMessage()); - } - } - - /** - * 新增岗位 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存岗位 - */ - @RequiresPermissions("system:post:add") - @Log(title = "岗位管理", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysPost post) - { - if (UserConstants.POST_NAME_NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) - { - return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在"); - } - else if (UserConstants.POST_CODE_NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) - { - return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); - } - post.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(postService.insertPost(post)); - } - - /** - * 修改岗位 - */ - @GetMapping("/edit/{postId}") - public String edit(@PathVariable("postId") Long postId, ModelMap mmap) - { - mmap.put("post", postService.selectPostById(postId)); - return prefix + "/edit"; - } - - /** - * 修改保存岗位 - */ - @RequiresPermissions("system:post:edit") - @Log(title = "岗位管理", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysPost post) - { - if (UserConstants.POST_NAME_NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) - { - return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在"); - } - else if (UserConstants.POST_CODE_NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) - { - return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); - } - post.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(postService.updatePost(post)); - } - - /** - * 校验岗位名称 - */ - @PostMapping("/checkPostNameUnique") - @ResponseBody - public String checkPostNameUnique(SysPost post) - { - return postService.checkPostNameUnique(post); - } - - /** - * 校验岗位编码 - */ - @PostMapping("/checkPostCodeUnique") - @ResponseBody - public String checkPostCodeUnique(SysPost post) - { - return postService.checkPostCodeUnique(post); - } -} +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.service.ISysPostService; + +/** + * 岗位信息操作处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/post") +public class SysPostController extends BaseController { + private String prefix = "system/post"; + + @Autowired + private ISysPostService postService; + + @RequiresPermissions("system:post:view") + @GetMapping() + public String operlog() { + return prefix + "/post"; + } + + @RequiresPermissions("system:post:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysPost post) { + startPage(); + List list = postService.selectPostList(post); + return getDataTable(list); + } + + @Log(title = "岗位管理", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:post:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysPost post) { + List list = postService.selectPostList(post); + ExcelUtil util = new ExcelUtil(SysPost.class); + return util.exportExcel(list, "岗位数据"); + } + + @RequiresPermissions("system:post:remove") + @Log(title = "岗位管理", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + try { + return toAjax(postService.deletePostByIds(ids)); + } catch (Exception e) { + return error(e.getMessage()); + } + } + + /** + * 新增岗位 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存岗位 + */ + @RequiresPermissions("system:post:add") + @Log(title = "岗位管理", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysPost post) { + if (UserConstants.POST_NAME_NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) { + return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在"); + } else if (UserConstants.POST_CODE_NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) { + return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); + } + post.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(postService.insertPost(post)); + } + + /** + * 修改岗位 + */ + @GetMapping("/edit/{postId}") + public String edit(@PathVariable("postId") Long postId, ModelMap mmap) { + mmap.put("post", postService.selectPostById(postId)); + return prefix + "/edit"; + } + + /** + * 修改保存岗位 + */ + @RequiresPermissions("system:post:edit") + @Log(title = "岗位管理", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysPost post) { + if (UserConstants.POST_NAME_NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) { + return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在"); + } else if (UserConstants.POST_CODE_NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) { + return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); + } + post.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(postService.updatePost(post)); + } + + /** + * 校验岗位名称 + */ + @PostMapping("/checkPostNameUnique") + @ResponseBody + public String checkPostNameUnique(SysPost post) { + return postService.checkPostNameUnique(post); + } + + /** + * 校验岗位编码 + */ + @PostMapping("/checkPostCodeUnique") + @ResponseBody + public String checkPostCodeUnique(SysPost post) { + return postService.checkPostCodeUnique(post); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java index f8a462dda..21a65838d 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java @@ -1,173 +1,153 @@ -package com.ruoyi.web.controller.system; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.file.FileUploadUtils; -import com.ruoyi.framework.shiro.service.SysPasswordService; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.service.ISysUserService; - -/** - * 个人信息 业务处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/user/profile") -public class SysProfileController extends BaseController -{ - private static final Logger log = LoggerFactory.getLogger(SysProfileController.class); - - private String prefix = "system/user/profile"; - - @Autowired - private ISysUserService userService; - - @Autowired - private SysPasswordService passwordService; - - /** - * 个人信息 - */ - @GetMapping() - public String profile(ModelMap mmap) - { - SysUser user = ShiroUtils.getSysUser(); - mmap.put("user", user); - mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId())); - mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId())); - return prefix + "/profile"; - } - - @GetMapping("/checkPassword") - @ResponseBody - public boolean checkPassword(String password) - { - SysUser user = ShiroUtils.getSysUser(); - if (passwordService.matches(user, password)) - { - return true; - } - return false; - } - - @GetMapping("/resetPwd") - public String resetPwd(ModelMap mmap) - { - SysUser user = ShiroUtils.getSysUser(); - mmap.put("user", userService.selectUserById(user.getUserId())); - return prefix + "/resetPwd"; - } - - @Log(title = "重置密码", businessType = BusinessType.UPDATE) - @PostMapping("/resetPwd") - @ResponseBody - public AjaxResult resetPwd(String oldPassword, String newPassword) - { - SysUser user = ShiroUtils.getSysUser(); - if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) - { - user.setSalt(ShiroUtils.randomSalt()); - user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt())); - if (userService.resetUserPwd(user) > 0) - { - ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); - return success(); - } - return error(); - } - else - { - return error("修改密码失败,旧密码错误"); - } - } - - /** - * 修改用户 - */ - @GetMapping("/edit") - public String edit(ModelMap mmap) - { - SysUser user = ShiroUtils.getSysUser(); - mmap.put("user", userService.selectUserById(user.getUserId())); - return prefix + "/edit"; - } - - /** - * 修改头像 - */ - @GetMapping("/avatar") - public String avatar(ModelMap mmap) - { - SysUser user = ShiroUtils.getSysUser(); - mmap.put("user", userService.selectUserById(user.getUserId())); - return prefix + "/avatar"; - } - - /** - * 修改用户 - */ - @Log(title = "个人信息", businessType = BusinessType.UPDATE) - @PostMapping("/update") - @ResponseBody - public AjaxResult update(SysUser user) - { - SysUser currentUser = ShiroUtils.getSysUser(); - currentUser.setUserName(user.getUserName()); - currentUser.setEmail(user.getEmail()); - currentUser.setPhonenumber(user.getPhonenumber()); - currentUser.setSex(user.getSex()); - if (userService.updateUserInfo(currentUser) > 0) - { - ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); - return success(); - } - return error(); - } - - /** - * 保存头像 - */ - @Log(title = "个人信息", businessType = BusinessType.UPDATE) - @PostMapping("/updateAvatar") - @ResponseBody - public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file) - { - SysUser currentUser = ShiroUtils.getSysUser(); - try - { - if (!file.isEmpty()) - { - String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file); - currentUser.setAvatar(avatar); - if (userService.updateUserInfo(currentUser) > 0) - { - ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); - return success(); - } - } - return error(); - } - catch (Exception e) - { - log.error("修改头像失败!", e); - return error(e.getMessage()); - } - } -} +package com.ruoyi.web.controller.system; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.file.FileUploadUtils; +import com.ruoyi.framework.shiro.service.SysPasswordService; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysUserService; + +/** + * 个人信息 业务处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/user/profile") +public class SysProfileController extends BaseController { + private static final Logger log = LoggerFactory.getLogger(SysProfileController.class); + + private String prefix = "system/user/profile"; + + @Autowired + private ISysUserService userService; + + @Autowired + private SysPasswordService passwordService; + + /** + * 个人信息 + */ + @GetMapping() + public String profile(ModelMap mmap) { + SysUser user = ShiroUtils.getSysUser(); + mmap.put("user", user); + mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId())); + mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId())); + return prefix + "/profile"; + } + + @GetMapping("/checkPassword") + @ResponseBody + public boolean checkPassword(String password) { + SysUser user = ShiroUtils.getSysUser(); + if (passwordService.matches(user, password)) { + return true; + } + return false; + } + + @GetMapping("/resetPwd") + public String resetPwd(ModelMap mmap) { + SysUser user = ShiroUtils.getSysUser(); + mmap.put("user", userService.selectUserById(user.getUserId())); + return prefix + "/resetPwd"; + } + + @Log(title = "重置密码", businessType = BusinessType.UPDATE) + @PostMapping("/resetPwd") + @ResponseBody + public AjaxResult resetPwd(String oldPassword, String newPassword) { + SysUser user = ShiroUtils.getSysUser(); + if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) { + user.setSalt(ShiroUtils.randomSalt()); + user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt())); + if (userService.resetUserPwd(user) > 0) { + ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); + return success(); + } + return error(); + } else { + return error("修改密码失败,旧密码错误"); + } + } + + /** + * 修改用户 + */ + @GetMapping("/edit") + public String edit(ModelMap mmap) { + SysUser user = ShiroUtils.getSysUser(); + mmap.put("user", userService.selectUserById(user.getUserId())); + return prefix + "/edit"; + } + + /** + * 修改头像 + */ + @GetMapping("/avatar") + public String avatar(ModelMap mmap) { + SysUser user = ShiroUtils.getSysUser(); + mmap.put("user", userService.selectUserById(user.getUserId())); + return prefix + "/avatar"; + } + + /** + * 修改用户 + */ + @Log(title = "个人信息", businessType = BusinessType.UPDATE) + @PostMapping("/update") + @ResponseBody + public AjaxResult update(SysUser user) { + SysUser currentUser = ShiroUtils.getSysUser(); + currentUser.setUserName(user.getUserName()); + currentUser.setEmail(user.getEmail()); + currentUser.setPhonenumber(user.getPhonenumber()); + currentUser.setSex(user.getSex()); + if (userService.updateUserInfo(currentUser) > 0) { + ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); + return success(); + } + return error(); + } + + /** + * 保存头像 + */ + @Log(title = "个人信息", businessType = BusinessType.UPDATE) + @PostMapping("/updateAvatar") + @ResponseBody + public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file) { + SysUser currentUser = ShiroUtils.getSysUser(); + try { + if (!file.isEmpty()) { + String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file); + currentUser.setAvatar(avatar); + if (userService.updateUserInfo(currentUser) > 0) { + ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); + return success(); + } + } + return error(); + } catch (Exception e) { + log.error("修改头像失败!", e); + return error(e.getMessage()); + } + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 0f7379d1a..82a9eb845 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -1,304 +1,273 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.domain.SysUserRole; -import com.ruoyi.system.service.ISysRoleService; -import com.ruoyi.system.service.ISysUserService; - -/** - * 角色信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/role") -public class SysRoleController extends BaseController -{ - private String prefix = "system/role"; - - @Autowired - private ISysRoleService roleService; - - @Autowired - private ISysUserService userService; - - @RequiresPermissions("system:role:view") - @GetMapping() - public String role() - { - return prefix + "/role"; - } - - @RequiresPermissions("system:role:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysRole role) - { - startPage(); - List list = roleService.selectRoleList(role); - return getDataTable(list); - } - - @Log(title = "角色管理", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:role:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysRole role) - { - List list = roleService.selectRoleList(role); - ExcelUtil util = new ExcelUtil(SysRole.class); - return util.exportExcel(list, "角色数据"); - } - - /** - * 新增角色 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存角色 - */ - @RequiresPermissions("system:role:add") - @Log(title = "角色管理", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysRole role) - { - if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) - { - return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在"); - } - else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) - { - return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在"); - } - role.setCreateBy(ShiroUtils.getLoginName()); - ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(roleService.insertRole(role)); - - } - - /** - * 修改角色 - */ - @GetMapping("/edit/{roleId}") - public String edit(@PathVariable("roleId") Long roleId, ModelMap mmap) - { - mmap.put("role", roleService.selectRoleById(roleId)); - return prefix + "/edit"; - } - - /** - * 修改保存角色 - */ - @RequiresPermissions("system:role:edit") - @Log(title = "角色管理", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysRole role) - { - roleService.checkRoleAllowed(role); - if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) - { - return error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在"); - } - else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) - { - return error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在"); - } - role.setUpdateBy(ShiroUtils.getLoginName()); - ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(roleService.updateRole(role)); - } - - /** - * 角色分配数据权限 - */ - @GetMapping("/authDataScope/{roleId}") - public String authDataScope(@PathVariable("roleId") Long roleId, ModelMap mmap) - { - mmap.put("role", roleService.selectRoleById(roleId)); - return prefix + "/dataScope"; - } - - /** - * 保存角色分配数据权限 - */ - @RequiresPermissions("system:role:edit") - @Log(title = "角色管理", businessType = BusinessType.UPDATE) - @PostMapping("/authDataScope") - @ResponseBody - public AjaxResult authDataScopeSave(SysRole role) - { - roleService.checkRoleAllowed(role); - role.setUpdateBy(ShiroUtils.getLoginName()); - if (roleService.authDataScope(role) > 0) - { - ShiroUtils.setSysUser(userService.selectUserById(ShiroUtils.getSysUser().getUserId())); - return success(); - } - return error(); - } - - @RequiresPermissions("system:role:remove") - @Log(title = "角色管理", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - try - { - return toAjax(roleService.deleteRoleByIds(ids)); - } - catch (Exception e) - { - return error(e.getMessage()); - } - } - - /** - * 校验角色名称 - */ - @PostMapping("/checkRoleNameUnique") - @ResponseBody - public String checkRoleNameUnique(SysRole role) - { - return roleService.checkRoleNameUnique(role); - } - - /** - * 校验角色权限 - */ - @PostMapping("/checkRoleKeyUnique") - @ResponseBody - public String checkRoleKeyUnique(SysRole role) - { - return roleService.checkRoleKeyUnique(role); - } - - /** - * 选择菜单树 - */ - @GetMapping("/selectMenuTree") - public String selectMenuTree() - { - return prefix + "/tree"; - } - - /** - * 角色状态修改 - */ - @Log(title = "角色管理", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:role:edit") - @PostMapping("/changeStatus") - @ResponseBody - public AjaxResult changeStatus(SysRole role) - { - roleService.checkRoleAllowed(role); - return toAjax(roleService.changeStatus(role)); - } - - /** - * 分配用户 - */ - @RequiresPermissions("system:role:edit") - @GetMapping("/authUser/{roleId}") - public String authUser(@PathVariable("roleId") Long roleId, ModelMap mmap) - { - mmap.put("role", roleService.selectRoleById(roleId)); - return prefix + "/authUser"; - } - - /** - * 查询已分配用户角色列表 - */ - @RequiresPermissions("system:role:list") - @PostMapping("/authUser/allocatedList") - @ResponseBody - public TableDataInfo allocatedList(SysUser user) - { - startPage(); - List list = userService.selectAllocatedList(user); - return getDataTable(list); - } - - /** - * 取消授权 - */ - @Log(title = "角色管理", businessType = BusinessType.GRANT) - @PostMapping("/authUser/cancel") - @ResponseBody - public AjaxResult cancelAuthUser(SysUserRole userRole) - { - return toAjax(roleService.deleteAuthUser(userRole)); - } - - /** - * 批量取消授权 - */ - @Log(title = "角色管理", businessType = BusinessType.GRANT) - @PostMapping("/authUser/cancelAll") - @ResponseBody - public AjaxResult cancelAuthUserAll(Long roleId, String userIds) - { - return toAjax(roleService.deleteAuthUsers(roleId, userIds)); - } - - /** - * 选择用户 - */ - @GetMapping("/authUser/selectUser/{roleId}") - public String selectUser(@PathVariable("roleId") Long roleId, ModelMap mmap) - { - mmap.put("role", roleService.selectRoleById(roleId)); - return prefix + "/selectUser"; - } - - /** - * 查询未分配用户角色列表 - */ - @RequiresPermissions("system:role:list") - @PostMapping("/authUser/unallocatedList") - @ResponseBody - public TableDataInfo unallocatedList(SysUser user) - { - startPage(); - List list = userService.selectUnallocatedList(user); - return getDataTable(list); - } - - /** - * 批量选择用户授权 - */ - @Log(title = "角色管理", businessType = BusinessType.GRANT) - @PostMapping("/authUser/selectAll") - @ResponseBody - public AjaxResult selectAuthUserAll(Long roleId, String userIds) - { - return toAjax(roleService.insertAuthUsers(roleId, userIds)); - } +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.domain.SysUserRole; +import com.ruoyi.system.service.ISysRoleService; +import com.ruoyi.system.service.ISysUserService; + +/** + * 角色信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/role") +public class SysRoleController extends BaseController { + private String prefix = "system/role"; + + @Autowired + private ISysRoleService roleService; + + @Autowired + private ISysUserService userService; + + @RequiresPermissions("system:role:view") + @GetMapping() + public String role() { + return prefix + "/role"; + } + + @RequiresPermissions("system:role:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysRole role) { + startPage(); + List list = roleService.selectRoleList(role); + return getDataTable(list); + } + + @Log(title = "角色管理", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:role:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysRole role) { + List list = roleService.selectRoleList(role); + ExcelUtil util = new ExcelUtil(SysRole.class); + return util.exportExcel(list, "角色数据"); + } + + /** + * 新增角色 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存角色 + */ + @RequiresPermissions("system:role:add") + @Log(title = "角色管理", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysRole role) { + if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) { + return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在"); + } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) { + return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在"); + } + role.setCreateBy(ShiroUtils.getLoginName()); + ShiroUtils.clearCachedAuthorizationInfo(); + return toAjax(roleService.insertRole(role)); + + } + + /** + * 修改角色 + */ + @GetMapping("/edit/{roleId}") + public String edit(@PathVariable("roleId") Long roleId, ModelMap mmap) { + mmap.put("role", roleService.selectRoleById(roleId)); + return prefix + "/edit"; + } + + /** + * 修改保存角色 + */ + @RequiresPermissions("system:role:edit") + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysRole role) { + roleService.checkRoleAllowed(role); + if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) { + return error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在"); + } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) { + return error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在"); + } + role.setUpdateBy(ShiroUtils.getLoginName()); + ShiroUtils.clearCachedAuthorizationInfo(); + return toAjax(roleService.updateRole(role)); + } + + /** + * 角色分配数据权限 + */ + @GetMapping("/authDataScope/{roleId}") + public String authDataScope(@PathVariable("roleId") Long roleId, ModelMap mmap) { + mmap.put("role", roleService.selectRoleById(roleId)); + return prefix + "/dataScope"; + } + + /** + * 保存角色分配数据权限 + */ + @RequiresPermissions("system:role:edit") + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @PostMapping("/authDataScope") + @ResponseBody + public AjaxResult authDataScopeSave(SysRole role) { + roleService.checkRoleAllowed(role); + role.setUpdateBy(ShiroUtils.getLoginName()); + if (roleService.authDataScope(role) > 0) { + ShiroUtils.setSysUser(userService.selectUserById(ShiroUtils.getSysUser().getUserId())); + return success(); + } + return error(); + } + + @RequiresPermissions("system:role:remove") + @Log(title = "角色管理", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + try { + return toAjax(roleService.deleteRoleByIds(ids)); + } catch (Exception e) { + return error(e.getMessage()); + } + } + + /** + * 校验角色名称 + */ + @PostMapping("/checkRoleNameUnique") + @ResponseBody + public String checkRoleNameUnique(SysRole role) { + return roleService.checkRoleNameUnique(role); + } + + /** + * 校验角色权限 + */ + @PostMapping("/checkRoleKeyUnique") + @ResponseBody + public String checkRoleKeyUnique(SysRole role) { + return roleService.checkRoleKeyUnique(role); + } + + /** + * 选择菜单树 + */ + @GetMapping("/selectMenuTree") + public String selectMenuTree() { + return prefix + "/tree"; + } + + /** + * 角色状态修改 + */ + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:role:edit") + @PostMapping("/changeStatus") + @ResponseBody + public AjaxResult changeStatus(SysRole role) { + roleService.checkRoleAllowed(role); + return toAjax(roleService.changeStatus(role)); + } + + /** + * 分配用户 + */ + @RequiresPermissions("system:role:edit") + @GetMapping("/authUser/{roleId}") + public String authUser(@PathVariable("roleId") Long roleId, ModelMap mmap) { + mmap.put("role", roleService.selectRoleById(roleId)); + return prefix + "/authUser"; + } + + /** + * 查询已分配用户角色列表 + */ + @RequiresPermissions("system:role:list") + @PostMapping("/authUser/allocatedList") + @ResponseBody + public TableDataInfo allocatedList(SysUser user) { + startPage(); + List list = userService.selectAllocatedList(user); + return getDataTable(list); + } + + /** + * 取消授权 + */ + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PostMapping("/authUser/cancel") + @ResponseBody + public AjaxResult cancelAuthUser(SysUserRole userRole) { + return toAjax(roleService.deleteAuthUser(userRole)); + } + + /** + * 批量取消授权 + */ + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PostMapping("/authUser/cancelAll") + @ResponseBody + public AjaxResult cancelAuthUserAll(Long roleId, String userIds) { + return toAjax(roleService.deleteAuthUsers(roleId, userIds)); + } + + /** + * 选择用户 + */ + @GetMapping("/authUser/selectUser/{roleId}") + public String selectUser(@PathVariable("roleId") Long roleId, ModelMap mmap) { + mmap.put("role", roleService.selectRoleById(roleId)); + return prefix + "/selectUser"; + } + + /** + * 查询未分配用户角色列表 + */ + @RequiresPermissions("system:role:list") + @PostMapping("/authUser/unallocatedList") + @ResponseBody + public TableDataInfo unallocatedList(SysUser user) { + startPage(); + List list = userService.selectUnallocatedList(user); + return getDataTable(list); + } + + /** + * 批量选择用户授权 + */ + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PostMapping("/authUser/selectAll") + @ResponseBody + public AjaxResult selectAuthUserAll(Long roleId, String userIds) { + return toAjax(roleService.insertAuthUsers(roleId, userIds)); + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index 76fc16b89..441f0cd99 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -1,261 +1,232 @@ -package com.ruoyi.web.controller.system; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.framework.shiro.service.SysPasswordService; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.service.ISysPostService; -import com.ruoyi.system.service.ISysRoleService; -import com.ruoyi.system.service.ISysUserService; - -/** - * 用户信息 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/system/user") -public class SysUserController extends BaseController -{ - private String prefix = "system/user"; - - @Autowired - private ISysUserService userService; - - @Autowired - private ISysRoleService roleService; - - @Autowired - private ISysPostService postService; - - @Autowired - private SysPasswordService passwordService; - - @RequiresPermissions("system:user:view") - @GetMapping() - public String user() - { - return prefix + "/user"; - } - - @RequiresPermissions("system:user:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysUser user) - { - startPage(); - List list = userService.selectUserList(user); - return getDataTable(list); - } - - @Log(title = "用户管理", businessType = BusinessType.EXPORT) - @RequiresPermissions("system:user:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysUser user) - { - List list = userService.selectUserList(user); - ExcelUtil util = new ExcelUtil(SysUser.class); - return util.exportExcel(list, "用户数据"); - } - - @Log(title = "用户管理", businessType = BusinessType.IMPORT) - @RequiresPermissions("system:user:import") - @PostMapping("/importData") - @ResponseBody - public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception - { - ExcelUtil util = new ExcelUtil(SysUser.class); - List userList = util.importExcel(file.getInputStream()); - String operName = ShiroUtils.getSysUser().getLoginName(); - String message = userService.importUser(userList, updateSupport, operName); - return AjaxResult.success(message); - } - - @RequiresPermissions("system:user:view") - @GetMapping("/importTemplate") - @ResponseBody - public AjaxResult importTemplate() - { - ExcelUtil util = new ExcelUtil(SysUser.class); - return util.importTemplateExcel("用户数据"); - } - - /** - * 新增用户 - */ - @GetMapping("/add") - public String add(ModelMap mmap) - { - mmap.put("roles", roleService.selectRoleAll()); - mmap.put("posts", postService.selectPostAll()); - return prefix + "/add"; - } - - /** - * 新增保存用户 - */ - @RequiresPermissions("system:user:add") - @Log(title = "用户管理", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysUser user) - { - if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) - { - return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在"); - } - else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) - { - return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在"); - } - else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) - { - return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); - } - user.setSalt(ShiroUtils.randomSalt()); - user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); - user.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(userService.insertUser(user)); - } - - /** - * 修改用户 - */ - @GetMapping("/edit/{userId}") - public String edit(@PathVariable("userId") Long userId, ModelMap mmap) - { - mmap.put("user", userService.selectUserById(userId)); - mmap.put("roles", roleService.selectRolesByUserId(userId)); - mmap.put("posts", postService.selectPostsByUserId(userId)); - return prefix + "/edit"; - } - - /** - * 修改保存用户 - */ - @RequiresPermissions("system:user:edit") - @Log(title = "用户管理", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysUser user) - { - userService.checkUserAllowed(user); - if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) - { - return error("修改用户'" + user.getLoginName() + "'失败,手机号码已存在"); - } - else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) - { - return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); - } - user.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(userService.updateUser(user)); - } - - @RequiresPermissions("system:user:resetPwd") - @Log(title = "重置密码", businessType = BusinessType.UPDATE) - @GetMapping("/resetPwd/{userId}") - public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) - { - mmap.put("user", userService.selectUserById(userId)); - return prefix + "/resetPwd"; - } - - @RequiresPermissions("system:user:resetPwd") - @Log(title = "重置密码", businessType = BusinessType.UPDATE) - @PostMapping("/resetPwd") - @ResponseBody - public AjaxResult resetPwdSave(SysUser user) - { - userService.checkUserAllowed(user); - user.setSalt(ShiroUtils.randomSalt()); - user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); - if (userService.resetUserPwd(user) > 0) - { - if (ShiroUtils.getUserId() == user.getUserId()) - { - ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); - } - return success(); - } - return error(); - } - - @RequiresPermissions("system:user:remove") - @Log(title = "用户管理", businessType = BusinessType.DELETE) - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - try - { - return toAjax(userService.deleteUserByIds(ids)); - } - catch (Exception e) - { - return error(e.getMessage()); - } - } - - /** - * 校验用户名 - */ - @PostMapping("/checkLoginNameUnique") - @ResponseBody - public String checkLoginNameUnique(SysUser user) - { - return userService.checkLoginNameUnique(user.getLoginName()); - } - - /** - * 校验手机号码 - */ - @PostMapping("/checkPhoneUnique") - @ResponseBody - public String checkPhoneUnique(SysUser user) - { - return userService.checkPhoneUnique(user); - } - - /** - * 校验email邮箱 - */ - @PostMapping("/checkEmailUnique") - @ResponseBody - public String checkEmailUnique(SysUser user) - { - return userService.checkEmailUnique(user); - } - - /** - * 用户状态修改 - */ - @Log(title = "用户管理", businessType = BusinessType.UPDATE) - @RequiresPermissions("system:user:edit") - @PostMapping("/changeStatus") - @ResponseBody - public AjaxResult changeStatus(SysUser user) - { - userService.checkUserAllowed(user); - return toAjax(userService.changeStatus(user)); - } +package com.ruoyi.web.controller.system; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.shiro.service.SysPasswordService; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysPostService; +import com.ruoyi.system.service.ISysRoleService; +import com.ruoyi.system.service.ISysUserService; + +/** + * 用户信息 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/system/user") +public class SysUserController extends BaseController { + private String prefix = "system/user"; + + @Autowired + private ISysUserService userService; + + @Autowired + private ISysRoleService roleService; + + @Autowired + private ISysPostService postService; + + @Autowired + private SysPasswordService passwordService; + + @RequiresPermissions("system:user:view") + @GetMapping() + public String user() { + return prefix + "/user"; + } + + @RequiresPermissions("system:user:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysUser user) { + startPage(); + List list = userService.selectUserList(user); + return getDataTable(list); + } + + @Log(title = "用户管理", businessType = BusinessType.EXPORT) + @RequiresPermissions("system:user:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysUser user) { + List list = userService.selectUserList(user); + ExcelUtil util = new ExcelUtil(SysUser.class); + return util.exportExcel(list, "用户数据"); + } + + @Log(title = "用户管理", businessType = BusinessType.IMPORT) + @RequiresPermissions("system:user:import") + @PostMapping("/importData") + @ResponseBody + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(SysUser.class); + List userList = util.importExcel(file.getInputStream()); + String operName = ShiroUtils.getSysUser().getLoginName(); + String message = userService.importUser(userList, updateSupport, operName); + return AjaxResult.success(message); + } + + @RequiresPermissions("system:user:view") + @GetMapping("/importTemplate") + @ResponseBody + public AjaxResult importTemplate() { + ExcelUtil util = new ExcelUtil(SysUser.class); + return util.importTemplateExcel("用户数据"); + } + + /** + * 新增用户 + */ + @GetMapping("/add") + public String add(ModelMap mmap) { + mmap.put("roles", roleService.selectRoleAll()); + mmap.put("posts", postService.selectPostAll()); + return prefix + "/add"; + } + + /** + * 新增保存用户 + */ + @RequiresPermissions("system:user:add") + @Log(title = "用户管理", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysUser user) { + if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) { + return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在"); + } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { + return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在"); + } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { + return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); + } + user.setSalt(ShiroUtils.randomSalt()); + user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); + user.setCreateBy(ShiroUtils.getLoginName()); + return toAjax(userService.insertUser(user)); + } + + /** + * 修改用户 + */ + @GetMapping("/edit/{userId}") + public String edit(@PathVariable("userId") Long userId, ModelMap mmap) { + mmap.put("user", userService.selectUserById(userId)); + mmap.put("roles", roleService.selectRolesByUserId(userId)); + mmap.put("posts", postService.selectPostsByUserId(userId)); + return prefix + "/edit"; + } + + /** + * 修改保存用户 + */ + @RequiresPermissions("system:user:edit") + @Log(title = "用户管理", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysUser user) { + userService.checkUserAllowed(user); + if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { + return error("修改用户'" + user.getLoginName() + "'失败,手机号码已存在"); + } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { + return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); + } + user.setUpdateBy(ShiroUtils.getLoginName()); + return toAjax(userService.updateUser(user)); + } + + @RequiresPermissions("system:user:resetPwd") + @Log(title = "重置密码", businessType = BusinessType.UPDATE) + @GetMapping("/resetPwd/{userId}") + public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) { + mmap.put("user", userService.selectUserById(userId)); + return prefix + "/resetPwd"; + } + + @RequiresPermissions("system:user:resetPwd") + @Log(title = "重置密码", businessType = BusinessType.UPDATE) + @PostMapping("/resetPwd") + @ResponseBody + public AjaxResult resetPwdSave(SysUser user) { + userService.checkUserAllowed(user); + user.setSalt(ShiroUtils.randomSalt()); + user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); + if (userService.resetUserPwd(user) > 0) { + if (ShiroUtils.getUserId() == user.getUserId()) { + ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); + } + return success(); + } + return error(); + } + + @RequiresPermissions("system:user:remove") + @Log(title = "用户管理", businessType = BusinessType.DELETE) + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + try { + return toAjax(userService.deleteUserByIds(ids)); + } catch (Exception e) { + return error(e.getMessage()); + } + } + + /** + * 校验用户名 + */ + @PostMapping("/checkLoginNameUnique") + @ResponseBody + public String checkLoginNameUnique(SysUser user) { + return userService.checkLoginNameUnique(user.getLoginName()); + } + + /** + * 校验手机号码 + */ + @PostMapping("/checkPhoneUnique") + @ResponseBody + public String checkPhoneUnique(SysUser user) { + return userService.checkPhoneUnique(user); + } + + /** + * 校验email邮箱 + */ + @PostMapping("/checkEmailUnique") + @ResponseBody + public String checkEmailUnique(SysUser user) { + return userService.checkEmailUnique(user); + } + + /** + * 用户状态修改 + */ + @Log(title = "用户管理", businessType = BusinessType.UPDATE) + @RequiresPermissions("system:user:edit") + @PostMapping("/changeStatus") + @ResponseBody + public AjaxResult changeStatus(SysUser user) { + userService.checkUserAllowed(user); + return toAjax(userService.changeStatus(user)); + } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/BuildController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/BuildController.java index 53ce0f1ba..2ac473616 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/BuildController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/BuildController.java @@ -1,26 +1,24 @@ -package com.ruoyi.web.controller.tool; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import com.ruoyi.common.core.controller.BaseController; - -/** - * build 表单构建 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/tool/build") -public class BuildController extends BaseController -{ - private String prefix = "tool/build"; - - @RequiresPermissions("tool:build:view") - @GetMapping() - public String build() - { - return prefix + "/build"; - } -} +package com.ruoyi.web.controller.tool; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import com.ruoyi.common.core.controller.BaseController; + +/** + * build 表单构建 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/tool/build") +public class BuildController extends BaseController { + private String prefix = "tool/build"; + + @RequiresPermissions("tool:build:view") + @GetMapping() + public String build() { + return prefix + "/build"; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/SwaggerController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/SwaggerController.java index cfa748f30..a4c869881 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/SwaggerController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/SwaggerController.java @@ -1,24 +1,22 @@ -package com.ruoyi.web.controller.tool; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import com.ruoyi.common.core.controller.BaseController; - -/** - * swagger 接口 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/tool/swagger") -public class SwaggerController extends BaseController -{ - @RequiresPermissions("tool:swagger:view") - @GetMapping() - public String index() - { - return redirect("/swagger-ui.html"); - } -} +package com.ruoyi.web.controller.tool; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import com.ruoyi.common.core.controller.BaseController; + +/** + * swagger 接口 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/tool/swagger") +public class SwaggerController extends BaseController { + @RequiresPermissions("tool:swagger:view") + @GetMapping() + public String index() { + return redirect("/swagger-ui.html"); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java index bddbe7789..42d810093 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java @@ -1,175 +1,151 @@ -package com.ruoyi.web.controller.tool; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.utils.StringUtils; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.annotations.ApiOperation; - -/** - * swagger 用户测试方法 - * - * @author ruoyi - */ -@Api("用户信息管理") -@RestController -@RequestMapping("/test/user") -public class TestController extends BaseController -{ - private final static Map users = new LinkedHashMap(); - { - users.put(1, new UserEntity(1, "admin", "admin123", "15888888888")); - users.put(2, new UserEntity(2, "ry", "admin123", "15666666666")); - } - - @ApiOperation("获取用户列表") - @GetMapping("/list") - public AjaxResult userList() - { - List userList = new ArrayList(users.values()); - return AjaxResult.success(userList); - } - - @ApiOperation("获取用户详细") - @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path") - @GetMapping("/{userId}") - public AjaxResult getUser(@PathVariable Integer userId) - { - if (!users.isEmpty() && users.containsKey(userId)) - { - return AjaxResult.success(users.get(userId)); - } - else - { - return error("用户不存在"); - } - } - - @ApiOperation("新增用户") - @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity") - @PostMapping("/save") - public AjaxResult save(UserEntity user) - { - if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) - { - return error("用户ID不能为空"); - } - return AjaxResult.success(users.put(user.getUserId(), user)); - } - - @ApiOperation("更新用户") - @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity") - @PutMapping("/update") - public AjaxResult update(UserEntity user) - { - if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) - { - return error("用户ID不能为空"); - } - if (users.isEmpty() || !users.containsKey(user.getUserId())) - { - return error("用户不存在"); - } - users.remove(user.getUserId()); - return AjaxResult.success(users.put(user.getUserId(), user)); - } - - @ApiOperation("删除用户信息") - @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path") - @DeleteMapping("/{userId}") - public AjaxResult delete(@PathVariable Integer userId) - { - if (!users.isEmpty() && users.containsKey(userId)) - { - users.remove(userId); - return success(); - } - else - { - return error("用户不存在"); - } - } -} - -@ApiModel("用户实体") -class UserEntity -{ - @ApiModelProperty("用户ID") - private Integer userId; - - @ApiModelProperty("用户名称") - private String username; - - @ApiModelProperty("用户密码") - private String password; - - @ApiModelProperty("用户手机") - private String mobile; - - public UserEntity() - { - - } - - public UserEntity(Integer userId, String username, String password, String mobile) - { - this.userId = userId; - this.username = username; - this.password = password; - this.mobile = mobile; - } - - public Integer getUserId() - { - return userId; - } - - public void setUserId(Integer userId) - { - this.userId = userId; - } - - public String getUsername() - { - return username; - } - - public void setUsername(String username) - { - this.username = username; - } - - public String getPassword() - { - return password; - } - - public void setPassword(String password) - { - this.password = password; - } - - public String getMobile() - { - return mobile; - } - - public void setMobile(String mobile) - { - this.mobile = mobile; - } -} +package com.ruoyi.web.controller.tool; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.utils.StringUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.annotations.ApiOperation; + +/** + * swagger 用户测试方法 + * + * @author ruoyi + */ +@Api("用户信息管理") +@RestController +@RequestMapping("/test/user") +public class TestController extends BaseController { + private final static Map users = new LinkedHashMap(); + + { + users.put(1, new UserEntity(1, "admin", "admin123", "15888888888")); + users.put(2, new UserEntity(2, "ry", "admin123", "15666666666")); + } + + @ApiOperation("获取用户列表") + @GetMapping("/list") + public AjaxResult userList() { + List userList = new ArrayList(users.values()); + return AjaxResult.success(userList); + } + + @ApiOperation("获取用户详细") + @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path") + @GetMapping("/{userId}") + public AjaxResult getUser(@PathVariable Integer userId) { + if (!users.isEmpty() && users.containsKey(userId)) { + return AjaxResult.success(users.get(userId)); + } else { + return error("用户不存在"); + } + } + + @ApiOperation("新增用户") + @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity") + @PostMapping("/save") + public AjaxResult save(UserEntity user) { + if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) { + return error("用户ID不能为空"); + } + return AjaxResult.success(users.put(user.getUserId(), user)); + } + + @ApiOperation("更新用户") + @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity") + @PutMapping("/update") + public AjaxResult update(UserEntity user) { + if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) { + return error("用户ID不能为空"); + } + if (users.isEmpty() || !users.containsKey(user.getUserId())) { + return error("用户不存在"); + } + users.remove(user.getUserId()); + return AjaxResult.success(users.put(user.getUserId(), user)); + } + + @ApiOperation("删除用户信息") + @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path") + @DeleteMapping("/{userId}") + public AjaxResult delete(@PathVariable Integer userId) { + if (!users.isEmpty() && users.containsKey(userId)) { + users.remove(userId); + return success(); + } else { + return error("用户不存在"); + } + } +} + +@ApiModel("用户实体") +class UserEntity { + @ApiModelProperty("用户ID") + private Integer userId; + + @ApiModelProperty("用户名称") + private String username; + + @ApiModelProperty("用户密码") + private String password; + + @ApiModelProperty("用户手机") + private String mobile; + + public UserEntity() { + + } + + public UserEntity(Integer userId, String username, String password, String mobile) { + this.userId = userId; + this.username = username; + this.password = password; + this.mobile = mobile; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java b/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java index 43353914a..36a30811c 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java @@ -1,62 +1,59 @@ -package com.ruoyi.web.core.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.ruoyi.common.config.Global; -import io.swagger.annotations.ApiOperation; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - * Swagger2的接口配置 - * - * @author ruoyi - */ -@Configuration -@EnableSwagger2 -public class SwaggerConfig -{ - /** - * 创建API - */ - @Bean - public Docket createRestApi() - { - return new Docket(DocumentationType.SWAGGER_2) - // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) - .apiInfo(apiInfo()) - // 设置哪些接口暴露给Swagger展示 - .select() - // 扫描所有有注解的api,用这种方式更灵活 - .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) - // 扫描指定包中的swagger注解 - //.apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger")) - // 扫描所有 .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); - } - - /** - * 添加摘要信息 - */ - private ApiInfo apiInfo() - { - // 用ApiInfoBuilder进行定制 - return new ApiInfoBuilder() - // 设置标题 - .title("标题:若依管理系统_接口文档") - // 描述 - .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...") - // 作者信息 - .contact(new Contact(Global.getName(), null, null)) - // 版本 - .version("版本号:" + Global.getVersion()) - .build(); - } -} +package com.ruoyi.web.core.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import com.ruoyi.common.config.Global; +import io.swagger.annotations.ApiOperation; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * Swagger2的接口配置 + * + * @author ruoyi + */ +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + /** + * 创建API + */ + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) + .apiInfo(apiInfo()) + // 设置哪些接口暴露给Swagger展示 + .select() + // 扫描所有有注解的api,用这种方式更灵活 + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) + // 扫描指定包中的swagger注解 + //.apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger")) + // 扫描所有 .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } + + /** + * 添加摘要信息 + */ + private ApiInfo apiInfo() { + // 用ApiInfoBuilder进行定制 + return new ApiInfoBuilder() + // 设置标题 + .title("标题:若依管理系统_接口文档") + // 描述 + .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...") + // 作者信息 + .contact(new Contact(Global.getName(), null, null)) + // 版本 + .version("版本号:" + Global.getVersion()) + .build(); + } +} From 4c515391e04f0ca40419457b539675773ca32c7b Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:19:14 +0800 Subject: [PATCH 05/52] format code --- .../framework/aspectj/DataScopeAspect.java | 299 ++++---- .../framework/aspectj/DataSourceAspect.java | 142 ++-- .../ruoyi/framework/aspectj/LogAspect.java | 336 ++++---- .../framework/config/ApplicationConfig.java | 3 +- .../ruoyi/framework/config/CaptchaConfig.java | 165 ++-- .../ruoyi/framework/config/DruidConfig.java | 206 +++-- .../ruoyi/framework/config/FilterConfig.java | 91 ++- .../ruoyi/framework/config/I18nConfig.java | 81 +- .../framework/config/KaptchaTextCreator.java | 138 ++-- .../ruoyi/framework/config/MyBatisConfig.java | 48 +- .../framework/config/ResourcesConfig.java | 112 ++- .../ruoyi/framework/config/ShiroConfig.java | 717 +++++++++--------- .../config/properties/DruidProperties.java | 8 +- .../datasource/DynamicDataSource.java | 50 +- .../interceptor/RepeatSubmitInterceptor.java | 24 +- .../impl/SameUrlDataInterceptor.java | 34 +- .../ruoyi/framework/manager/AsyncManager.java | 108 ++- .../framework/manager/ShutdownManager.java | 43 +- .../manager/factory/AsyncFactory.java | 257 +++---- .../framework/shiro/realm/UserRealm.java | 260 +++---- .../shiro/service/SysLoginService.java | 256 +++---- .../shiro/service/SysPasswordService.java | 170 ++--- .../shiro/service/SysShiroService.java | 18 +- .../shiro/session/OnlineSession.java | 294 ++++--- .../shiro/session/OnlineSessionDAO.java | 222 +++--- .../shiro/session/OnlineSessionFactory.java | 83 +- .../shiro/web/filter/LogoutFilter.java | 191 +++-- .../filter/captcha/CaptchaValidateFilter.java | 146 ++-- .../filter/kickout/KickoutSessionFilter.java | 76 +- .../filter/online/OnlineSessionFilter.java | 183 +++-- .../filter/sync/SyncOnlineSessionFilter.java | 70 +- .../web/session/OnlineWebSessionManager.java | 310 ++++---- .../SpringSessionValidationScheduler.java | 247 +++--- .../com/ruoyi/framework/util/LogUtils.java | 261 +++---- .../com/ruoyi/framework/util/ShiroUtils.java | 179 ++--- .../ruoyi/framework/web/domain/Server.java | 457 ++++++----- .../framework/web/domain/server/Cpu.java | 189 +++-- .../framework/web/domain/server/Jvm.java | 229 +++--- .../framework/web/domain/server/Mem.java | 114 ++- .../framework/web/domain/server/Sys.java | 157 ++-- .../framework/web/domain/server/SysFile.java | 213 +++--- .../web/exception/GlobalExceptionHandler.java | 43 +- .../framework/web/service/ConfigService.java | 54 +- .../framework/web/service/DictService.java | 82 +- .../web/service/PermissionService.java | 496 ++++++------ 45 files changed, 3684 insertions(+), 4178 deletions(-) diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java index 9fa9b0afb..554bdd59a 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java @@ -1,161 +1,138 @@ -package com.ruoyi.framework.aspectj; - -import java.lang.reflect.Method; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.Signature; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.stereotype.Component; -import com.ruoyi.common.annotation.DataScope; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; - -/** - * 数据过滤处理 - * - * @author ruoyi - */ -@Aspect -@Component -public class DataScopeAspect -{ - /** - * 全部数据权限 - */ - public static final String DATA_SCOPE_ALL = "1"; - - /** - * 自定数据权限 - */ - public static final String DATA_SCOPE_CUSTOM = "2"; - - /** - * 部门数据权限 - */ - public static final String DATA_SCOPE_DEPT = "3"; - - /** - * 部门及以下数据权限 - */ - public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; - - /** - * 仅本人数据权限 - */ - public static final String DATA_SCOPE_SELF = "5"; - - /** - * 数据权限过滤关键字 - */ - public static final String DATA_SCOPE = "dataScope"; - - // 配置织入点 - @Pointcut("@annotation(com.ruoyi.common.annotation.DataScope)") - public void dataScopePointCut() - { - } - - @Before("dataScopePointCut()") - public void doBefore(JoinPoint point) throws Throwable - { - handleDataScope(point); - } - - protected void handleDataScope(final JoinPoint joinPoint) - { - // 获得注解 - DataScope controllerDataScope = getAnnotationLog(joinPoint); - if (controllerDataScope == null) - { - return; - } - // 获取当前的用户 - SysUser currentUser = ShiroUtils.getSysUser(); - if (currentUser != null) - { - // 如果是超级管理员,则不过滤数据 - if (!currentUser.isAdmin()) - { - dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), - controllerDataScope.userAlias()); - } - } - } - - /** - * 数据范围过滤 - * - * @param joinPoint 切点 - * @param user 用户 - * @param alias 别名 - */ - public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) - { - StringBuilder sqlString = new StringBuilder(); - - for (SysRole role : user.getRoles()) - { - String dataScope = role.getDataScope(); - if (DATA_SCOPE_ALL.equals(dataScope)) - { - sqlString = new StringBuilder(); - break; - } - else if (DATA_SCOPE_CUSTOM.equals(dataScope)) - { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, - role.getRoleId())); - } - else if (DATA_SCOPE_DEPT.equals(dataScope)) - { - sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); - } - else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) - { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", - deptAlias, user.getDeptId(), user.getDeptId())); - } - else if (DATA_SCOPE_SELF.equals(dataScope)) - { - if (StringUtils.isNotBlank(userAlias)) - { - sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); - } - else - { - // 数据权限为仅本人且没有userAlias别名不查询任何数据 - sqlString.append(" OR 1=0 "); - } - } - } - - if (StringUtils.isNotBlank(sqlString.toString())) - { - BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0]; - baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); - } - } - - /** - * 是否存在注解,如果存在就获取 - */ - private DataScope getAnnotationLog(JoinPoint joinPoint) - { - Signature signature = joinPoint.getSignature(); - MethodSignature methodSignature = (MethodSignature) signature; - Method method = methodSignature.getMethod(); - - if (method != null) - { - return method.getAnnotation(DataScope.class); - } - return null; - } -} +package com.ruoyi.framework.aspectj; + +import java.lang.reflect.Method; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.stereotype.Component; +import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; + +/** + * 数据过滤处理 + * + * @author ruoyi + */ +@Aspect +@Component +public class DataScopeAspect { + /** + * 全部数据权限 + */ + public static final String DATA_SCOPE_ALL = "1"; + + /** + * 自定数据权限 + */ + public static final String DATA_SCOPE_CUSTOM = "2"; + + /** + * 部门数据权限 + */ + public static final String DATA_SCOPE_DEPT = "3"; + + /** + * 部门及以下数据权限 + */ + public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; + + /** + * 仅本人数据权限 + */ + public static final String DATA_SCOPE_SELF = "5"; + + /** + * 数据权限过滤关键字 + */ + public static final String DATA_SCOPE = "dataScope"; + + // 配置织入点 + @Pointcut("@annotation(com.ruoyi.common.annotation.DataScope)") + public void dataScopePointCut() { + } + + @Before("dataScopePointCut()") + public void doBefore(JoinPoint point) throws Throwable { + handleDataScope(point); + } + + protected void handleDataScope(final JoinPoint joinPoint) { + // 获得注解 + DataScope controllerDataScope = getAnnotationLog(joinPoint); + if (controllerDataScope == null) { + return; + } + // 获取当前的用户 + SysUser currentUser = ShiroUtils.getSysUser(); + if (currentUser != null) { + // 如果是超级管理员,则不过滤数据 + if (!currentUser.isAdmin()) { + dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), + controllerDataScope.userAlias()); + } + } + } + + /** + * 数据范围过滤 + * + * @param joinPoint 切点 + * @param user 用户 + * @param alias 别名 + */ + public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { + StringBuilder sqlString = new StringBuilder(); + + for (SysRole role : user.getRoles()) { + String dataScope = role.getDataScope(); + if (DATA_SCOPE_ALL.equals(dataScope)) { + sqlString = new StringBuilder(); + break; + } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { + sqlString.append(StringUtils.format( + " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, + role.getRoleId())); + } else if (DATA_SCOPE_DEPT.equals(dataScope)) { + sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); + } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { + sqlString.append(StringUtils.format( + " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", + deptAlias, user.getDeptId(), user.getDeptId())); + } else if (DATA_SCOPE_SELF.equals(dataScope)) { + if (StringUtils.isNotBlank(userAlias)) { + sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); + } else { + // 数据权限为仅本人且没有userAlias别名不查询任何数据 + sqlString.append(" OR 1=0 "); + } + } + } + + if (StringUtils.isNotBlank(sqlString.toString())) { + BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0]; + baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); + } + } + + /** + * 是否存在注解,如果存在就获取 + */ + private DataScope getAnnotationLog(JoinPoint joinPoint) { + Signature signature = joinPoint.getSignature(); + MethodSignature methodSignature = (MethodSignature) signature; + Method method = methodSignature.getMethod(); + + if (method != null) { + return method.getAnnotation(DataScope.class); + } + return null; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java index 4f13ddb37..9a3dda63f 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java @@ -1,76 +1,66 @@ -package com.ruoyi.framework.aspectj; - -import java.lang.reflect.Method; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; -import com.ruoyi.common.annotation.DataSource; -import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder; -import com.ruoyi.common.utils.StringUtils; - -/** - * 多数据源处理 - * - * @author ruoyi - */ -@Aspect -@Order(1) -@Component -public class DataSourceAspect -{ - protected Logger logger = LoggerFactory.getLogger(getClass()); - - @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)" - + "|| @within(com.ruoyi.common.annotation.DataSource)") - public void dsPointCut() - { - - } - - @Around("dsPointCut()") - public Object around(ProceedingJoinPoint point) throws Throwable - { - DataSource dataSource = getDataSource(point); - - if (StringUtils.isNotNull(dataSource)) - { - DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name()); - } - - try - { - return point.proceed(); - } - finally - { - // 销毁数据源 在执行方法之后 - DynamicDataSourceContextHolder.clearDataSourceType(); - } - } - - /** - * 获取需要切换的数据源 - */ - public DataSource getDataSource(ProceedingJoinPoint point) - { - MethodSignature signature = (MethodSignature) point.getSignature(); - Class targetClass = point.getTarget().getClass(); - DataSource targetDataSource = targetClass.getAnnotation(DataSource.class); - if (StringUtils.isNotNull(targetDataSource)) - { - return targetDataSource; - } - else - { - Method method = signature.getMethod(); - DataSource dataSource = method.getAnnotation(DataSource.class); - return dataSource; - } - } -} +package com.ruoyi.framework.aspectj; + +import java.lang.reflect.Method; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import com.ruoyi.common.annotation.DataSource; +import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder; +import com.ruoyi.common.utils.StringUtils; + +/** + * 多数据源处理 + * + * @author ruoyi + */ +@Aspect +@Order(1) +@Component +public class DataSourceAspect { + protected Logger logger = LoggerFactory.getLogger(getClass()); + + @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)" + + "|| @within(com.ruoyi.common.annotation.DataSource)") + public void dsPointCut() { + + } + + @Around("dsPointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable { + DataSource dataSource = getDataSource(point); + + if (StringUtils.isNotNull(dataSource)) { + DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name()); + } + + try { + return point.proceed(); + } finally { + // 销毁数据源 在执行方法之后 + DynamicDataSourceContextHolder.clearDataSourceType(); + } + } + + /** + * 获取需要切换的数据源 + */ + public DataSource getDataSource(ProceedingJoinPoint point) { + MethodSignature signature = (MethodSignature) point.getSignature(); + Class targetClass = point.getTarget().getClass(); + DataSource targetDataSource = targetClass.getAnnotation(DataSource.class); + if (StringUtils.isNotNull(targetDataSource)) { + return targetDataSource; + } else { + Method method = signature.getMethod(); + DataSource dataSource = method.getAnnotation(DataSource.class); + return dataSource; + } + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java index 87a7198b7..1720e4830 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java @@ -1,176 +1,160 @@ -package com.ruoyi.framework.aspectj; - -import java.lang.reflect.Method; -import java.util.Map; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.Signature; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.AfterThrowing; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.enums.BusinessStatus; -import com.ruoyi.common.json.JSON; -import com.ruoyi.common.utils.ServletUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.framework.manager.AsyncManager; -import com.ruoyi.framework.manager.factory.AsyncFactory; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.domain.SysUser; - -/** - * 操作日志记录处理 - * - * @author ruoyi - */ -@Aspect -@Component -public class LogAspect -{ - private static final Logger log = LoggerFactory.getLogger(LogAspect.class); - - // 配置织入点 - @Pointcut("@annotation(com.ruoyi.common.annotation.Log)") - public void logPointCut() - { - } - - /** - * 处理完请求后执行 - * - * @param joinPoint 切点 - */ - @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult") - public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) - { - handleLog(joinPoint, null, jsonResult); - } - - /** - * 拦截异常操作 - * - * @param joinPoint 切点 - * @param e 异常 - */ - @AfterThrowing(value = "logPointCut()", throwing = "e") - public void doAfterThrowing(JoinPoint joinPoint, Exception e) - { - handleLog(joinPoint, e, null); - } - - protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) - { - try - { - // 获得注解 - Log controllerLog = getAnnotationLog(joinPoint); - if (controllerLog == null) - { - return; - } - - // 获取当前的用户 - SysUser currentUser = ShiroUtils.getSysUser(); - - // *========数据库日志=========*// - SysOperLog operLog = new SysOperLog(); - operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); - // 请求的地址 - String ip = ShiroUtils.getIp(); - operLog.setOperIp(ip); - // 返回参数 - operLog.setJsonResult(JSON.marshal(jsonResult)); - - operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); - if (currentUser != null) - { - operLog.setOperName(currentUser.getLoginName()); - if (StringUtils.isNotNull(currentUser.getDept()) - && StringUtils.isNotEmpty(currentUser.getDept().getDeptName())) - { - operLog.setDeptName(currentUser.getDept().getDeptName()); - } - } - - if (e != null) - { - operLog.setStatus(BusinessStatus.FAIL.ordinal()); - operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); - } - // 设置方法名称 - String className = joinPoint.getTarget().getClass().getName(); - String methodName = joinPoint.getSignature().getName(); - operLog.setMethod(className + "." + methodName + "()"); - // 设置请求方式 - operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); - // 处理设置注解上的参数 - getControllerMethodDescription(controllerLog, operLog); - // 保存数据库 - AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); - } - catch (Exception exp) - { - // 记录本地异常日志 - log.error("==前置通知异常=="); - log.error("异常信息:{}", exp.getMessage()); - exp.printStackTrace(); - } - } - - /** - * 获取注解中对方法的描述信息 用于Controller层注解 - * - * @param log 日志 - * @param operLog 操作日志 - * @throws Exception - */ - public void getControllerMethodDescription(Log log, SysOperLog operLog) throws Exception - { - // 设置action动作 - operLog.setBusinessType(log.businessType().ordinal()); - // 设置标题 - operLog.setTitle(log.title()); - // 设置操作人类别 - operLog.setOperatorType(log.operatorType().ordinal()); - // 是否需要保存request,参数和值 - if (log.isSaveRequestData()) - { - // 获取参数的信息,传入到数据库中。 - setRequestValue(operLog); - } - } - - /** - * 获取请求的参数,放到log中 - * - * @param operLog 操作日志 - * @throws Exception 异常 - */ - private void setRequestValue(SysOperLog operLog) throws Exception - { - Map map = ServletUtils.getRequest().getParameterMap(); - String params = JSON.marshal(map); - operLog.setOperParam(StringUtils.substring(params, 0, 2000)); - } - - /** - * 是否存在注解,如果存在就获取 - */ - private Log getAnnotationLog(JoinPoint joinPoint) throws Exception - { - Signature signature = joinPoint.getSignature(); - MethodSignature methodSignature = (MethodSignature) signature; - Method method = methodSignature.getMethod(); - - if (method != null) - { - return method.getAnnotation(Log.class); - } - return null; - } -} +package com.ruoyi.framework.aspectj; + +import java.lang.reflect.Method; +import java.util.Map; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.enums.BusinessStatus; +import com.ruoyi.common.json.JSON; +import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysOperLog; +import com.ruoyi.system.domain.SysUser; + +/** + * 操作日志记录处理 + * + * @author ruoyi + */ +@Aspect +@Component +public class LogAspect { + private static final Logger log = LoggerFactory.getLogger(LogAspect.class); + + // 配置织入点 + @Pointcut("@annotation(com.ruoyi.common.annotation.Log)") + public void logPointCut() { + } + + /** + * 处理完请求后执行 + * + * @param joinPoint 切点 + */ + @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult") + public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) { + handleLog(joinPoint, null, jsonResult); + } + + /** + * 拦截异常操作 + * + * @param joinPoint 切点 + * @param e 异常 + */ + @AfterThrowing(value = "logPointCut()", throwing = "e") + public void doAfterThrowing(JoinPoint joinPoint, Exception e) { + handleLog(joinPoint, e, null); + } + + protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) { + try { + // 获得注解 + Log controllerLog = getAnnotationLog(joinPoint); + if (controllerLog == null) { + return; + } + + // 获取当前的用户 + SysUser currentUser = ShiroUtils.getSysUser(); + + // *========数据库日志=========*// + SysOperLog operLog = new SysOperLog(); + operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); + // 请求的地址 + String ip = ShiroUtils.getIp(); + operLog.setOperIp(ip); + // 返回参数 + operLog.setJsonResult(JSON.marshal(jsonResult)); + + operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); + if (currentUser != null) { + operLog.setOperName(currentUser.getLoginName()); + if (StringUtils.isNotNull(currentUser.getDept()) + && StringUtils.isNotEmpty(currentUser.getDept().getDeptName())) { + operLog.setDeptName(currentUser.getDept().getDeptName()); + } + } + + if (e != null) { + operLog.setStatus(BusinessStatus.FAIL.ordinal()); + operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); + } + // 设置方法名称 + String className = joinPoint.getTarget().getClass().getName(); + String methodName = joinPoint.getSignature().getName(); + operLog.setMethod(className + "." + methodName + "()"); + // 设置请求方式 + operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); + // 处理设置注解上的参数 + getControllerMethodDescription(controllerLog, operLog); + // 保存数据库 + AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); + } catch (Exception exp) { + // 记录本地异常日志 + log.error("==前置通知异常=="); + log.error("异常信息:{}", exp.getMessage()); + exp.printStackTrace(); + } + } + + /** + * 获取注解中对方法的描述信息 用于Controller层注解 + * + * @param log 日志 + * @param operLog 操作日志 + * @throws Exception + */ + public void getControllerMethodDescription(Log log, SysOperLog operLog) throws Exception { + // 设置action动作 + operLog.setBusinessType(log.businessType().ordinal()); + // 设置标题 + operLog.setTitle(log.title()); + // 设置操作人类别 + operLog.setOperatorType(log.operatorType().ordinal()); + // 是否需要保存request,参数和值 + if (log.isSaveRequestData()) { + // 获取参数的信息,传入到数据库中。 + setRequestValue(operLog); + } + } + + /** + * 获取请求的参数,放到log中 + * + * @param operLog 操作日志 + * @throws Exception 异常 + */ + private void setRequestValue(SysOperLog operLog) throws Exception { + Map map = ServletUtils.getRequest().getParameterMap(); + String params = JSON.marshal(map); + operLog.setOperParam(StringUtils.substring(params, 0, 2000)); + } + + /** + * 是否存在注解,如果存在就获取 + */ + private Log getAnnotationLog(JoinPoint joinPoint) throws Exception { + Signature signature = joinPoint.getSignature(); + MethodSignature methodSignature = (MethodSignature) signature; + Method method = methodSignature.getMethod(); + + if (method != null) { + return method.getAnnotation(Log.class); + } + return null; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java index b6b0e88c6..8cfcae95f 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java @@ -14,7 +14,6 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; @EnableAspectJAutoProxy(exposeProxy = true) // 指定要扫描的Mapper类的包的路径 @MapperScan("com.ruoyi.**.mapper") -public class ApplicationConfig -{ +public class ApplicationConfig { } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java index b6f80bf27..be2a6e34d 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java @@ -1,83 +1,82 @@ -package com.ruoyi.framework.config; - -import java.util.Properties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.google.code.kaptcha.impl.DefaultKaptcha; -import com.google.code.kaptcha.util.Config; -import static com.google.code.kaptcha.Constants.*; - -/** - * 验证码配置 - * - * @author ruoyi - */ -@Configuration -public class CaptchaConfig -{ - @Bean(name = "captchaProducer") - public DefaultKaptcha getKaptchaBean() - { - DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); - Properties properties = new Properties(); - // 是否有边框 默认为true 我们可以自己设置yes,no - properties.setProperty(KAPTCHA_BORDER, "yes"); - // 验证码文本字符颜色 默认为Color.BLACK - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black"); - // 验证码图片宽度 默认为200 - properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); - // 验证码图片高度 默认为50 - properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); - // 验证码文本字符大小 默认为40 - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38"); - // KAPTCHA_SESSION_KEY - properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode"); - // 验证码文本字符长度 默认为5 - properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4"); - // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); - // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy - properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); - Config config = new Config(properties); - defaultKaptcha.setConfig(config); - return defaultKaptcha; - } - - @Bean(name = "captchaProducerMath") - public DefaultKaptcha getKaptchaBeanMath() - { - DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); - Properties properties = new Properties(); - // 是否有边框 默认为true 我们可以自己设置yes,no - properties.setProperty(KAPTCHA_BORDER, "yes"); - // 边框颜色 默认为Color.BLACK - properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90"); - // 验证码文本字符颜色 默认为Color.BLACK - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue"); - // 验证码图片宽度 默认为200 - properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); - // 验证码图片高度 默认为50 - properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); - // 验证码文本字符大小 默认为40 - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35"); - // KAPTCHA_SESSION_KEY - properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath"); - // 验证码文本生成器 - properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.ruoyi.framework.config.KaptchaTextCreator"); - // 验证码文本字符间距 默认为2 - properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3"); - // 验证码文本字符长度 默认为5 - properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6"); - // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) - properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); - // 验证码噪点颜色 默认为Color.BLACK - properties.setProperty(KAPTCHA_NOISE_COLOR, "white"); - // 干扰实现类 - properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise"); - // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy - properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); - Config config = new Config(properties); - defaultKaptcha.setConfig(config); - return defaultKaptcha; - } -} +package com.ruoyi.framework.config; + +import java.util.Properties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import com.google.code.kaptcha.impl.DefaultKaptcha; +import com.google.code.kaptcha.util.Config; + +import static com.google.code.kaptcha.Constants.*; + +/** + * 验证码配置 + * + * @author ruoyi + */ +@Configuration +public class CaptchaConfig { + @Bean(name = "captchaProducer") + public DefaultKaptcha getKaptchaBean() { + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + Properties properties = new Properties(); + // 是否有边框 默认为true 我们可以自己设置yes,no + properties.setProperty(KAPTCHA_BORDER, "yes"); + // 验证码文本字符颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black"); + // 验证码图片宽度 默认为200 + properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); + // 验证码图片高度 默认为50 + properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); + // 验证码文本字符大小 默认为40 + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38"); + // KAPTCHA_SESSION_KEY + properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode"); + // 验证码文本字符长度 默认为5 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4"); + // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); + // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy + properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); + Config config = new Config(properties); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } + + @Bean(name = "captchaProducerMath") + public DefaultKaptcha getKaptchaBeanMath() { + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + Properties properties = new Properties(); + // 是否有边框 默认为true 我们可以自己设置yes,no + properties.setProperty(KAPTCHA_BORDER, "yes"); + // 边框颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90"); + // 验证码文本字符颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue"); + // 验证码图片宽度 默认为200 + properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); + // 验证码图片高度 默认为50 + properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); + // 验证码文本字符大小 默认为40 + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35"); + // KAPTCHA_SESSION_KEY + properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath"); + // 验证码文本生成器 + properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.ruoyi.framework.config.KaptchaTextCreator"); + // 验证码文本字符间距 默认为2 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3"); + // 验证码文本字符长度 默认为5 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6"); + // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); + // 验证码噪点颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_NOISE_COLOR, "white"); + // 干扰实现类 + properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise"); + // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy + properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); + Config config = new Config(properties); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java index 3e4a97eff..125483b87 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java @@ -1,106 +1,100 @@ -package com.ruoyi.framework.config; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.sql.DataSource; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; -import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; -import com.alibaba.druid.util.Utils; -import com.ruoyi.common.enums.DataSourceType; -import com.ruoyi.framework.config.properties.DruidProperties; -import com.ruoyi.framework.datasource.DynamicDataSource; - -/** - * druid 配置多数据源 - * - * @author ruoyi - */ -@Configuration -public class DruidConfig -{ - @Bean - @ConfigurationProperties("spring.datasource.druid.master") - public DataSource masterDataSource(DruidProperties druidProperties) - { - DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); - return druidProperties.dataSource(dataSource); - } - - @Bean - @ConfigurationProperties("spring.datasource.druid.slave") - @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") - public DataSource slaveDataSource(DruidProperties druidProperties) - { - DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); - return druidProperties.dataSource(dataSource); - } - - @Bean(name = "dynamicDataSource") - @Primary - public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) - { - Map targetDataSources = new HashMap<>(); - targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource); - targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource); - return new DynamicDataSource(masterDataSource, targetDataSources); - } - - /** - * 去除监控页面底部的广告 - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Bean - @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true") - public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) - { - // 获取web监控页面的参数 - DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); - // 提取common.js的配置路径 - String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; - String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); - final String filePath = "support/http/resources/js/common.js"; - // 创建filter进行过滤 - Filter filter = new Filter() - { - @Override - public void init(javax.servlet.FilterConfig filterConfig) throws ServletException - { - } - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException - { - chain.doFilter(request, response); - // 重置缓冲区,响应头不会被重置 - response.resetBuffer(); - // 获取common.js - String text = Utils.readFromResource(filePath); - // 正则替换banner, 除去底部的广告信息 - text = text.replaceAll("
", ""); - text = text.replaceAll("powered.*?shrek.wang", ""); - response.getWriter().write(text); - } - @Override - public void destroy() - { - } - }; - FilterRegistrationBean registrationBean = new FilterRegistrationBean(); - registrationBean.setFilter(filter); - registrationBean.addUrlPatterns(commonJsPattern); - return registrationBean; - } -} +package com.ruoyi.framework.config; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; +import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; +import com.alibaba.druid.util.Utils; +import com.ruoyi.common.enums.DataSourceType; +import com.ruoyi.framework.config.properties.DruidProperties; +import com.ruoyi.framework.datasource.DynamicDataSource; + +/** + * druid 配置多数据源 + * + * @author ruoyi + */ +@Configuration +public class DruidConfig { + @Bean + @ConfigurationProperties("spring.datasource.druid.master") + public DataSource masterDataSource(DruidProperties druidProperties) { + DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); + return druidProperties.dataSource(dataSource); + } + + @Bean + @ConfigurationProperties("spring.datasource.druid.slave") + @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") + public DataSource slaveDataSource(DruidProperties druidProperties) { + DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); + return druidProperties.dataSource(dataSource); + } + + @Bean(name = "dynamicDataSource") + @Primary + public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) { + Map targetDataSources = new HashMap<>(); + targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource); + targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource); + return new DynamicDataSource(masterDataSource, targetDataSources); + } + + /** + * 去除监控页面底部的广告 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @Bean + @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true") + public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) { + // 获取web监控页面的参数 + DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); + // 提取common.js的配置路径 + String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; + String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); + final String filePath = "support/http/resources/js/common.js"; + // 创建filter进行过滤 + Filter filter = new Filter() { + @Override + public void init(javax.servlet.FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + chain.doFilter(request, response); + // 重置缓冲区,响应头不会被重置 + response.resetBuffer(); + // 获取common.js + String text = Utils.readFromResource(filePath); + // 正则替换banner, 除去底部的广告信息 + text = text.replaceAll("
", ""); + text = text.replaceAll("powered.*?shrek.wang", ""); + response.getWriter().write(text); + } + + @Override + public void destroy() { + } + }; + FilterRegistrationBean registrationBean = new FilterRegistrationBean(); + registrationBean.setFilter(filter); + registrationBean.addUrlPatterns(commonJsPattern); + return registrationBean; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java index 92d010e80..6710a11aa 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java @@ -1,46 +1,45 @@ -package com.ruoyi.framework.config; - -import java.util.HashMap; -import java.util.Map; -import javax.servlet.DispatcherType; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.xss.XssFilter; - -/** - * Filter配置 - * - * @author ruoyi - */ -@Configuration -public class FilterConfig -{ - @Value("${xss.enabled}") - private String enabled; - - @Value("${xss.excludes}") - private String excludes; - - @Value("${xss.urlPatterns}") - private String urlPatterns; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Bean - public FilterRegistrationBean xssFilterRegistration() - { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setDispatcherTypes(DispatcherType.REQUEST); - registration.setFilter(new XssFilter()); - registration.addUrlPatterns(StringUtils.split(urlPatterns, ",")); - registration.setName("xssFilter"); - registration.setOrder(Integer.MAX_VALUE); - Map initParameters = new HashMap(); - initParameters.put("excludes", excludes); - initParameters.put("enabled", enabled); - registration.setInitParameters(initParameters); - return registration; - } -} +package com.ruoyi.framework.config; + +import java.util.HashMap; +import java.util.Map; +import javax.servlet.DispatcherType; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.xss.XssFilter; + +/** + * Filter配置 + * + * @author ruoyi + */ +@Configuration +public class FilterConfig { + @Value("${xss.enabled}") + private String enabled; + + @Value("${xss.excludes}") + private String excludes; + + @Value("${xss.urlPatterns}") + private String urlPatterns; + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Bean + public FilterRegistrationBean xssFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setDispatcherTypes(DispatcherType.REQUEST); + registration.setFilter(new XssFilter()); + registration.addUrlPatterns(StringUtils.split(urlPatterns, ",")); + registration.setName("xssFilter"); + registration.setOrder(Integer.MAX_VALUE); + Map initParameters = new HashMap(); + initParameters.put("excludes", excludes); + initParameters.put("enabled", enabled); + registration.setInitParameters(initParameters); + return registration; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java index c572e1c5c..59666e478 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java @@ -1,43 +1,40 @@ -package com.ruoyi.framework.config; - -import java.util.Locale; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.LocaleResolver; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import org.springframework.web.servlet.i18n.SessionLocaleResolver; - -/** - * 资源文件配置加载 - * - * @author ruoyi - */ -@Configuration -public class I18nConfig implements WebMvcConfigurer -{ - @Bean - public LocaleResolver localeResolver() - { - SessionLocaleResolver slr = new SessionLocaleResolver(); - // 默认语言 - slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); - return slr; - } - - @Bean - public LocaleChangeInterceptor localeChangeInterceptor() - { - LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); - // 参数名 - lci.setParamName("lang"); - return lci; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) - { - registry.addInterceptor(localeChangeInterceptor()); - } +package com.ruoyi.framework.config; + +import java.util.Locale; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; + +/** + * 资源文件配置加载 + * + * @author ruoyi + */ +@Configuration +public class I18nConfig implements WebMvcConfigurer { + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver slr = new SessionLocaleResolver(); + // 默认语言 + slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); + return slr; + } + + @Bean + public LocaleChangeInterceptor localeChangeInterceptor() { + LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); + // 参数名 + lci.setParamName("lang"); + return lci; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(localeChangeInterceptor()); + } } \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java index bd0dabb01..ce9684af7 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java @@ -1,76 +1,62 @@ -package com.ruoyi.framework.config; - -import java.security.SecureRandom; -import java.util.Random; -import com.google.code.kaptcha.text.impl.DefaultTextCreator; - -/** - * 验证码文本生成器 - * - * @author ruoyi - */ -public class KaptchaTextCreator extends DefaultTextCreator -{ - private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); - - @Override - public String getText() - { - Integer result = 0; - Random random = new SecureRandom(); - int x = random.nextInt(10); - int y = random.nextInt(10); - StringBuilder suChinese = new StringBuilder(); - int randomoperands = (int) Math.round(Math.random() * 2); - if (randomoperands == 0) - { - result = x * y; - suChinese.append(CNUMBERS[x]); - suChinese.append("*"); - suChinese.append(CNUMBERS[y]); - } - else if (randomoperands == 1) - { - if (!(x == 0) && y % x == 0) - { - result = y / x; - suChinese.append(CNUMBERS[y]); - suChinese.append("/"); - suChinese.append(CNUMBERS[x]); - } - else - { - result = x + y; - suChinese.append(CNUMBERS[x]); - suChinese.append("+"); - suChinese.append(CNUMBERS[y]); - } - } - else if (randomoperands == 2) - { - if (x >= y) - { - result = x - y; - suChinese.append(CNUMBERS[x]); - suChinese.append("-"); - suChinese.append(CNUMBERS[y]); - } - else - { - result = y - x; - suChinese.append(CNUMBERS[y]); - suChinese.append("-"); - suChinese.append(CNUMBERS[x]); - } - } - else - { - result = x + y; - suChinese.append(CNUMBERS[x]); - suChinese.append("+"); - suChinese.append(CNUMBERS[y]); - } - suChinese.append("=?@" + result); - return suChinese.toString(); - } -} +package com.ruoyi.framework.config; + +import java.security.SecureRandom; +import java.util.Random; + +import com.google.code.kaptcha.text.impl.DefaultTextCreator; + +/** + * 验证码文本生成器 + * + * @author ruoyi + */ +public class KaptchaTextCreator extends DefaultTextCreator { + private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); + + @Override + public String getText() { + Integer result = 0; + Random random = new SecureRandom(); + int x = random.nextInt(10); + int y = random.nextInt(10); + StringBuilder suChinese = new StringBuilder(); + int randomoperands = (int) Math.round(Math.random() * 2); + if (randomoperands == 0) { + result = x * y; + suChinese.append(CNUMBERS[x]); + suChinese.append("*"); + suChinese.append(CNUMBERS[y]); + } else if (randomoperands == 1) { + if (!(x == 0) && y % x == 0) { + result = y / x; + suChinese.append(CNUMBERS[y]); + suChinese.append("/"); + suChinese.append(CNUMBERS[x]); + } else { + result = x + y; + suChinese.append(CNUMBERS[x]); + suChinese.append("+"); + suChinese.append(CNUMBERS[y]); + } + } else if (randomoperands == 2) { + if (x >= y) { + result = x - y; + suChinese.append(CNUMBERS[x]); + suChinese.append("-"); + suChinese.append(CNUMBERS[y]); + } else { + result = y - x; + suChinese.append(CNUMBERS[y]); + suChinese.append("-"); + suChinese.append(CNUMBERS[x]); + } + } else { + result = x + y; + suChinese.append(CNUMBERS[x]); + suChinese.append("+"); + suChinese.append(CNUMBERS[y]); + } + suChinese.append("=?@" + result); + return suChinese.toString(); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java index 0bc8a2bec..09d3db033 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import javax.sql.DataSource; + import org.apache.ibatis.io.VFS; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; @@ -24,74 +25,57 @@ import org.springframework.util.ClassUtils; /** * Mybatis支持*匹配扫描包 - * + * * @author ruoyi */ @Configuration -public class MyBatisConfig -{ +public class MyBatisConfig { @Autowired private Environment env; static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; - public static String setTypeAliasesPackage(String typeAliasesPackage) - { + public static String setTypeAliasesPackage(String typeAliasesPackage) { ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); List allResult = new ArrayList(); - try - { - for (String aliasesPackage : typeAliasesPackage.split(",")) - { + try { + for (String aliasesPackage : typeAliasesPackage.split(",")) { List result = new ArrayList(); aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; Resource[] resources = resolver.getResources(aliasesPackage); - if (resources != null && resources.length > 0) - { + if (resources != null && resources.length > 0) { MetadataReader metadataReader = null; - for (Resource resource : resources) - { - if (resource.isReadable()) - { + for (Resource resource : resources) { + if (resource.isReadable()) { metadataReader = metadataReaderFactory.getMetadataReader(resource); - try - { + try { result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } - if (result.size() > 0) - { + if (result.size() > 0) { HashSet hashResult = new HashSet(result); allResult.addAll(hashResult); } } - if (allResult.size() > 0) - { + if (allResult.size() > 0) { typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); - } - else - { + } else { throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); } - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } return typeAliasesPackage; } @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception - { + public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); String mapperLocations = env.getProperty("mybatis.mapperLocations"); String configLocation = env.getProperty("mybatis.configLocation"); diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java index 999ccb063..8b8fb9380 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java @@ -1,59 +1,55 @@ -package com.ruoyi.framework.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.ruoyi.common.config.Global; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; - -/** - * 通用配置 - * - * @author ruoyi - */ -@Configuration -public class ResourcesConfig implements WebMvcConfigurer -{ - /** - * 首页地址 - */ - @Value("${shiro.user.indexUrl}") - private String indexUrl; - - @Autowired - private RepeatSubmitInterceptor repeatSubmitInterceptor; - - /** - * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 - */ - @Override - public void addViewControllers(ViewControllerRegistry registry) - { - registry.addViewController("/").setViewName("forward:" + indexUrl); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) - { - /** 本地文件上传路径 */ - registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/"); - - /** swagger配置 */ - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - } - - /** - * 自定义拦截规则 - */ - @Override - public void addInterceptors(InterceptorRegistry registry) - { - registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); - } +package com.ruoyi.framework.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.ruoyi.common.config.Global; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; + +/** + * 通用配置 + * + * @author ruoyi + */ +@Configuration +public class ResourcesConfig implements WebMvcConfigurer { + /** + * 首页地址 + */ + @Value("${shiro.user.indexUrl}") + private String indexUrl; + + @Autowired + private RepeatSubmitInterceptor repeatSubmitInterceptor; + + /** + * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 + */ + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("forward:" + indexUrl); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + /** 本地文件上传路径 */ + registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/"); + + /** swagger配置 */ + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + /** + * 自定义拦截规则 + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); + } } \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java index c416d2ab1..16312da17 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java @@ -1,371 +1,346 @@ -package com.ruoyi.framework.config; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.servlet.Filter; -import org.apache.commons.io.IOUtils; -import org.apache.shiro.cache.ehcache.EhCacheManager; -import org.apache.shiro.codec.Base64; -import org.apache.shiro.config.ConfigurationException; -import org.apache.shiro.io.ResourceUtils; -import org.apache.shiro.mgt.SecurityManager; -import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; -import org.apache.shiro.spring.web.ShiroFilterFactoryBean; -import org.apache.shiro.web.mgt.CookieRememberMeManager; -import org.apache.shiro.web.mgt.DefaultWebSecurityManager; -import org.apache.shiro.web.servlet.SimpleCookie; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.framework.shiro.realm.UserRealm; -import com.ruoyi.framework.shiro.session.OnlineSessionDAO; -import com.ruoyi.framework.shiro.session.OnlineSessionFactory; -import com.ruoyi.framework.shiro.web.filter.LogoutFilter; -import com.ruoyi.framework.shiro.web.filter.captcha.CaptchaValidateFilter; -import com.ruoyi.framework.shiro.web.filter.kickout.KickoutSessionFilter; -import com.ruoyi.framework.shiro.web.filter.online.OnlineSessionFilter; -import com.ruoyi.framework.shiro.web.filter.sync.SyncOnlineSessionFilter; -import com.ruoyi.framework.shiro.web.session.OnlineWebSessionManager; -import com.ruoyi.framework.shiro.web.session.SpringSessionValidationScheduler; -import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; - -/** - * 权限配置加载 - * - * @author ruoyi - */ -@Configuration -public class ShiroConfig -{ - public static final String PREMISSION_STRING = "perms[\"{0}\"]"; - - // Session超时时间,单位为毫秒(默认30分钟) - @Value("${shiro.session.expireTime}") - private int expireTime; - - // 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟 - @Value("${shiro.session.validationInterval}") - private int validationInterval; - - // 同一个用户最大会话数 - @Value("${shiro.session.maxSession}") - private int maxSession; - - // 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户 - @Value("${shiro.session.kickoutAfter}") - private boolean kickoutAfter; - - // 验证码开关 - @Value("${shiro.user.captchaEnabled}") - private boolean captchaEnabled; - - // 验证码类型 - @Value("${shiro.user.captchaType}") - private String captchaType; - - // 设置Cookie的域名 - @Value("${shiro.cookie.domain}") - private String domain; - - // 设置cookie的有效访问路径 - @Value("${shiro.cookie.path}") - private String path; - - // 设置HttpOnly属性 - @Value("${shiro.cookie.httpOnly}") - private boolean httpOnly; - - // 设置Cookie的过期时间,秒为单位 - @Value("${shiro.cookie.maxAge}") - private int maxAge; - - // 登录地址 - @Value("${shiro.user.loginUrl}") - private String loginUrl; - - // 权限认证失败地址 - @Value("${shiro.user.unauthorizedUrl}") - private String unauthorizedUrl; - - /** - * 缓存管理器 使用Ehcache实现 - */ - @Bean - public EhCacheManager getEhCacheManager() - { - net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("ruoyi"); - EhCacheManager em = new EhCacheManager(); - if (StringUtils.isNull(cacheManager)) - { - em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream())); - return em; - } - else - { - em.setCacheManager(cacheManager); - return em; - } - } - - /** - * 返回配置文件流 避免ehcache配置文件一直被占用,无法完全销毁项目重新部署 - */ - protected InputStream getCacheManagerConfigFileInputStream() - { - String configFile = "classpath:ehcache/ehcache-shiro.xml"; - InputStream inputStream = null; - try - { - inputStream = ResourceUtils.getInputStreamForPath(configFile); - byte[] b = IOUtils.toByteArray(inputStream); - InputStream in = new ByteArrayInputStream(b); - return in; - } - catch (IOException e) - { - throw new ConfigurationException( - "Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e); - } - finally - { - IOUtils.closeQuietly(inputStream); - } - } - - /** - * 自定义Realm - */ - @Bean - public UserRealm userRealm(EhCacheManager cacheManager) - { - UserRealm userRealm = new UserRealm(); - userRealm.setCacheManager(cacheManager); - return userRealm; - } - - /** - * 自定义sessionDAO会话 - */ - @Bean - public OnlineSessionDAO sessionDAO() - { - OnlineSessionDAO sessionDAO = new OnlineSessionDAO(); - return sessionDAO; - } - - /** - * 自定义sessionFactory会话 - */ - @Bean - public OnlineSessionFactory sessionFactory() - { - OnlineSessionFactory sessionFactory = new OnlineSessionFactory(); - return sessionFactory; - } - - /** - * 会话管理器 - */ - @Bean - public OnlineWebSessionManager sessionManager() - { - OnlineWebSessionManager manager = new OnlineWebSessionManager(); - // 加入缓存管理器 - manager.setCacheManager(getEhCacheManager()); - // 删除过期的session - manager.setDeleteInvalidSessions(true); - // 设置全局session超时时间 - manager.setGlobalSessionTimeout(expireTime * 60 * 1000); - // 去掉 JSESSIONID - manager.setSessionIdUrlRewritingEnabled(false); - // 定义要使用的无效的Session定时调度器 - manager.setSessionValidationScheduler(SpringUtils.getBean(SpringSessionValidationScheduler.class)); - // 是否定时检查session - manager.setSessionValidationSchedulerEnabled(true); - // 自定义SessionDao - manager.setSessionDAO(sessionDAO()); - // 自定义sessionFactory - manager.setSessionFactory(sessionFactory()); - return manager; - } - - /** - * 安全管理器 - */ - @Bean - public SecurityManager securityManager(UserRealm userRealm) - { - DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); - // 设置realm. - securityManager.setRealm(userRealm); - // 记住我 - securityManager.setRememberMeManager(rememberMeManager()); - // 注入缓存管理器; - securityManager.setCacheManager(getEhCacheManager()); - // session管理器 - securityManager.setSessionManager(sessionManager()); - return securityManager; - } - - /** - * 退出过滤器 - */ - public LogoutFilter logoutFilter() - { - LogoutFilter logoutFilter = new LogoutFilter(); - logoutFilter.setCacheManager(getEhCacheManager()); - logoutFilter.setLoginUrl(loginUrl); - return logoutFilter; - } - - /** - * Shiro过滤器配置 - */ - @Bean - public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) - { - ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); - // Shiro的核心安全接口,这个属性是必须的 - shiroFilterFactoryBean.setSecurityManager(securityManager); - // 身份认证失败,则跳转到登录页面的配置 - shiroFilterFactoryBean.setLoginUrl(loginUrl); - // 权限认证失败,则跳转到指定页面 - shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl); - // Shiro连接约束配置,即过滤链的定义 - LinkedHashMap filterChainDefinitionMap = new LinkedHashMap<>(); - // 对静态资源设置匿名访问 - filterChainDefinitionMap.put("/favicon.ico**", "anon"); - filterChainDefinitionMap.put("/ruoyi.png**", "anon"); - filterChainDefinitionMap.put("/css/**", "anon"); - filterChainDefinitionMap.put("/docs/**", "anon"); - filterChainDefinitionMap.put("/fonts/**", "anon"); - filterChainDefinitionMap.put("/img/**", "anon"); - filterChainDefinitionMap.put("/ajax/**", "anon"); - filterChainDefinitionMap.put("/js/**", "anon"); - filterChainDefinitionMap.put("/ruoyi/**", "anon"); - filterChainDefinitionMap.put("/druid/**", "anon"); - filterChainDefinitionMap.put("/captcha/captchaImage**", "anon"); - // 退出 logout地址,shiro去清除session - filterChainDefinitionMap.put("/logout", "logout"); - // 不需要拦截的访问 - filterChainDefinitionMap.put("/login", "anon,captchaValidate"); - // 系统权限列表 - // filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll()); - - Map filters = new LinkedHashMap(); - filters.put("onlineSession", onlineSessionFilter()); - filters.put("syncOnlineSession", syncOnlineSessionFilter()); - filters.put("captchaValidate", captchaValidateFilter()); - filters.put("kickout", kickoutSessionFilter()); - // 注销成功,则跳转到指定页面 - filters.put("logout", logoutFilter()); - shiroFilterFactoryBean.setFilters(filters); - - // 所有请求需要认证 - filterChainDefinitionMap.put("/**", "user,kickout,onlineSession,syncOnlineSession"); - shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); - - return shiroFilterFactoryBean; - } - - /** - * 自定义在线用户处理过滤器 - */ - @Bean - public OnlineSessionFilter onlineSessionFilter() - { - OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter(); - onlineSessionFilter.setLoginUrl(loginUrl); - return onlineSessionFilter; - } - - /** - * 自定义在线用户同步过滤器 - */ - @Bean - public SyncOnlineSessionFilter syncOnlineSessionFilter() - { - SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter(); - return syncOnlineSessionFilter; - } - - /** - * 自定义验证码过滤器 - */ - @Bean - public CaptchaValidateFilter captchaValidateFilter() - { - CaptchaValidateFilter captchaValidateFilter = new CaptchaValidateFilter(); - captchaValidateFilter.setCaptchaEnabled(captchaEnabled); - captchaValidateFilter.setCaptchaType(captchaType); - return captchaValidateFilter; - } - - /** - * cookie 属性设置 - */ - public SimpleCookie rememberMeCookie() - { - SimpleCookie cookie = new SimpleCookie("rememberMe"); - cookie.setDomain(domain); - cookie.setPath(path); - cookie.setHttpOnly(httpOnly); - cookie.setMaxAge(maxAge * 24 * 60 * 60); - return cookie; - } - - /** - * 记住我 - */ - public CookieRememberMeManager rememberMeManager() - { - CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); - cookieRememberMeManager.setCookie(rememberMeCookie()); - cookieRememberMeManager.setCipherKey(Base64.decode("fCq+/xW488hMTCD+cmJ3aQ==")); - return cookieRememberMeManager; - } - - /** - * 同一个用户多设备登录限制 - */ - public KickoutSessionFilter kickoutSessionFilter() - { - KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter(); - kickoutSessionFilter.setCacheManager(getEhCacheManager()); - kickoutSessionFilter.setSessionManager(sessionManager()); - // 同一个用户最大的会话数,默认-1无限制;比如2的意思是同一个用户允许最多同时两个人登录 - kickoutSessionFilter.setMaxSession(maxSession); - // 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序 - kickoutSessionFilter.setKickoutAfter(kickoutAfter); - // 被踢出后重定向到的地址; - kickoutSessionFilter.setKickoutUrl("/login?kickout=1"); - return kickoutSessionFilter; - } - - /** - * thymeleaf模板引擎和shiro框架的整合 - */ - @Bean - public ShiroDialect shiroDialect() - { - return new ShiroDialect(); - } - - /** - * 开启Shiro注解通知器 - */ - @Bean - public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( - @Qualifier("securityManager") SecurityManager securityManager) - { - AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); - authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); - return authorizationAttributeSourceAdvisor; - } -} +package com.ruoyi.framework.config; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.servlet.Filter; + +import org.apache.commons.io.IOUtils; +import org.apache.shiro.cache.ehcache.EhCacheManager; +import org.apache.shiro.codec.Base64; +import org.apache.shiro.config.ConfigurationException; +import org.apache.shiro.io.ResourceUtils; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.CookieRememberMeManager; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.apache.shiro.web.servlet.SimpleCookie; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.framework.shiro.realm.UserRealm; +import com.ruoyi.framework.shiro.session.OnlineSessionDAO; +import com.ruoyi.framework.shiro.session.OnlineSessionFactory; +import com.ruoyi.framework.shiro.web.filter.LogoutFilter; +import com.ruoyi.framework.shiro.web.filter.captcha.CaptchaValidateFilter; +import com.ruoyi.framework.shiro.web.filter.kickout.KickoutSessionFilter; +import com.ruoyi.framework.shiro.web.filter.online.OnlineSessionFilter; +import com.ruoyi.framework.shiro.web.filter.sync.SyncOnlineSessionFilter; +import com.ruoyi.framework.shiro.web.session.OnlineWebSessionManager; +import com.ruoyi.framework.shiro.web.session.SpringSessionValidationScheduler; +import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; + +/** + * 权限配置加载 + * + * @author ruoyi + */ +@Configuration +public class ShiroConfig { + public static final String PREMISSION_STRING = "perms[\"{0}\"]"; + + // Session超时时间,单位为毫秒(默认30分钟) + @Value("${shiro.session.expireTime}") + private int expireTime; + + // 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟 + @Value("${shiro.session.validationInterval}") + private int validationInterval; + + // 同一个用户最大会话数 + @Value("${shiro.session.maxSession}") + private int maxSession; + + // 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户 + @Value("${shiro.session.kickoutAfter}") + private boolean kickoutAfter; + + // 验证码开关 + @Value("${shiro.user.captchaEnabled}") + private boolean captchaEnabled; + + // 验证码类型 + @Value("${shiro.user.captchaType}") + private String captchaType; + + // 设置Cookie的域名 + @Value("${shiro.cookie.domain}") + private String domain; + + // 设置cookie的有效访问路径 + @Value("${shiro.cookie.path}") + private String path; + + // 设置HttpOnly属性 + @Value("${shiro.cookie.httpOnly}") + private boolean httpOnly; + + // 设置Cookie的过期时间,秒为单位 + @Value("${shiro.cookie.maxAge}") + private int maxAge; + + // 登录地址 + @Value("${shiro.user.loginUrl}") + private String loginUrl; + + // 权限认证失败地址 + @Value("${shiro.user.unauthorizedUrl}") + private String unauthorizedUrl; + + /** + * 缓存管理器 使用Ehcache实现 + */ + @Bean + public EhCacheManager getEhCacheManager() { + net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("ruoyi"); + EhCacheManager em = new EhCacheManager(); + if (StringUtils.isNull(cacheManager)) { + em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream())); + return em; + } else { + em.setCacheManager(cacheManager); + return em; + } + } + + /** + * 返回配置文件流 避免ehcache配置文件一直被占用,无法完全销毁项目重新部署 + */ + protected InputStream getCacheManagerConfigFileInputStream() { + String configFile = "classpath:ehcache/ehcache-shiro.xml"; + InputStream inputStream = null; + try { + inputStream = ResourceUtils.getInputStreamForPath(configFile); + byte[] b = IOUtils.toByteArray(inputStream); + InputStream in = new ByteArrayInputStream(b); + return in; + } catch (IOException e) { + throw new ConfigurationException( + "Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e); + } finally { + IOUtils.closeQuietly(inputStream); + } + } + + /** + * 自定义Realm + */ + @Bean + public UserRealm userRealm(EhCacheManager cacheManager) { + UserRealm userRealm = new UserRealm(); + userRealm.setCacheManager(cacheManager); + return userRealm; + } + + /** + * 自定义sessionDAO会话 + */ + @Bean + public OnlineSessionDAO sessionDAO() { + OnlineSessionDAO sessionDAO = new OnlineSessionDAO(); + return sessionDAO; + } + + /** + * 自定义sessionFactory会话 + */ + @Bean + public OnlineSessionFactory sessionFactory() { + OnlineSessionFactory sessionFactory = new OnlineSessionFactory(); + return sessionFactory; + } + + /** + * 会话管理器 + */ + @Bean + public OnlineWebSessionManager sessionManager() { + OnlineWebSessionManager manager = new OnlineWebSessionManager(); + // 加入缓存管理器 + manager.setCacheManager(getEhCacheManager()); + // 删除过期的session + manager.setDeleteInvalidSessions(true); + // 设置全局session超时时间 + manager.setGlobalSessionTimeout(expireTime * 60 * 1000); + // 去掉 JSESSIONID + manager.setSessionIdUrlRewritingEnabled(false); + // 定义要使用的无效的Session定时调度器 + manager.setSessionValidationScheduler(SpringUtils.getBean(SpringSessionValidationScheduler.class)); + // 是否定时检查session + manager.setSessionValidationSchedulerEnabled(true); + // 自定义SessionDao + manager.setSessionDAO(sessionDAO()); + // 自定义sessionFactory + manager.setSessionFactory(sessionFactory()); + return manager; + } + + /** + * 安全管理器 + */ + @Bean + public SecurityManager securityManager(UserRealm userRealm) { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); + // 设置realm. + securityManager.setRealm(userRealm); + // 记住我 + securityManager.setRememberMeManager(rememberMeManager()); + // 注入缓存管理器; + securityManager.setCacheManager(getEhCacheManager()); + // session管理器 + securityManager.setSessionManager(sessionManager()); + return securityManager; + } + + /** + * 退出过滤器 + */ + public LogoutFilter logoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter(); + logoutFilter.setCacheManager(getEhCacheManager()); + logoutFilter.setLoginUrl(loginUrl); + return logoutFilter; + } + + /** + * Shiro过滤器配置 + */ + @Bean + public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { + ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); + // Shiro的核心安全接口,这个属性是必须的 + shiroFilterFactoryBean.setSecurityManager(securityManager); + // 身份认证失败,则跳转到登录页面的配置 + shiroFilterFactoryBean.setLoginUrl(loginUrl); + // 权限认证失败,则跳转到指定页面 + shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl); + // Shiro连接约束配置,即过滤链的定义 + LinkedHashMap filterChainDefinitionMap = new LinkedHashMap<>(); + // 对静态资源设置匿名访问 + filterChainDefinitionMap.put("/favicon.ico**", "anon"); + filterChainDefinitionMap.put("/ruoyi.png**", "anon"); + filterChainDefinitionMap.put("/css/**", "anon"); + filterChainDefinitionMap.put("/docs/**", "anon"); + filterChainDefinitionMap.put("/fonts/**", "anon"); + filterChainDefinitionMap.put("/img/**", "anon"); + filterChainDefinitionMap.put("/ajax/**", "anon"); + filterChainDefinitionMap.put("/js/**", "anon"); + filterChainDefinitionMap.put("/ruoyi/**", "anon"); + filterChainDefinitionMap.put("/druid/**", "anon"); + filterChainDefinitionMap.put("/captcha/captchaImage**", "anon"); + // 退出 logout地址,shiro去清除session + filterChainDefinitionMap.put("/logout", "logout"); + // 不需要拦截的访问 + filterChainDefinitionMap.put("/login", "anon,captchaValidate"); + // 系统权限列表 + // filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll()); + + Map filters = new LinkedHashMap(); + filters.put("onlineSession", onlineSessionFilter()); + filters.put("syncOnlineSession", syncOnlineSessionFilter()); + filters.put("captchaValidate", captchaValidateFilter()); + filters.put("kickout", kickoutSessionFilter()); + // 注销成功,则跳转到指定页面 + filters.put("logout", logoutFilter()); + shiroFilterFactoryBean.setFilters(filters); + + // 所有请求需要认证 + filterChainDefinitionMap.put("/**", "user,kickout,onlineSession,syncOnlineSession"); + shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); + + return shiroFilterFactoryBean; + } + + /** + * 自定义在线用户处理过滤器 + */ + @Bean + public OnlineSessionFilter onlineSessionFilter() { + OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter(); + onlineSessionFilter.setLoginUrl(loginUrl); + return onlineSessionFilter; + } + + /** + * 自定义在线用户同步过滤器 + */ + @Bean + public SyncOnlineSessionFilter syncOnlineSessionFilter() { + SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter(); + return syncOnlineSessionFilter; + } + + /** + * 自定义验证码过滤器 + */ + @Bean + public CaptchaValidateFilter captchaValidateFilter() { + CaptchaValidateFilter captchaValidateFilter = new CaptchaValidateFilter(); + captchaValidateFilter.setCaptchaEnabled(captchaEnabled); + captchaValidateFilter.setCaptchaType(captchaType); + return captchaValidateFilter; + } + + /** + * cookie 属性设置 + */ + public SimpleCookie rememberMeCookie() { + SimpleCookie cookie = new SimpleCookie("rememberMe"); + cookie.setDomain(domain); + cookie.setPath(path); + cookie.setHttpOnly(httpOnly); + cookie.setMaxAge(maxAge * 24 * 60 * 60); + return cookie; + } + + /** + * 记住我 + */ + public CookieRememberMeManager rememberMeManager() { + CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); + cookieRememberMeManager.setCookie(rememberMeCookie()); + cookieRememberMeManager.setCipherKey(Base64.decode("fCq+/xW488hMTCD+cmJ3aQ==")); + return cookieRememberMeManager; + } + + /** + * 同一个用户多设备登录限制 + */ + public KickoutSessionFilter kickoutSessionFilter() { + KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter(); + kickoutSessionFilter.setCacheManager(getEhCacheManager()); + kickoutSessionFilter.setSessionManager(sessionManager()); + // 同一个用户最大的会话数,默认-1无限制;比如2的意思是同一个用户允许最多同时两个人登录 + kickoutSessionFilter.setMaxSession(maxSession); + // 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序 + kickoutSessionFilter.setKickoutAfter(kickoutAfter); + // 被踢出后重定向到的地址; + kickoutSessionFilter.setKickoutUrl("/login?kickout=1"); + return kickoutSessionFilter; + } + + /** + * thymeleaf模板引擎和shiro框架的整合 + */ + @Bean + public ShiroDialect shiroDialect() { + return new ShiroDialect(); + } + + /** + * 开启Shiro注解通知器 + */ + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( + @Qualifier("securityManager") SecurityManager securityManager) { + AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); + authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); + return authorizationAttributeSourceAdvisor; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java index 84f7e0090..339839001 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java @@ -6,12 +6,11 @@ import com.alibaba.druid.pool.DruidDataSource; /** * druid 配置属性 - * + * * @author ruoyi */ @Configuration -public class DruidProperties -{ +public class DruidProperties { @Value("${spring.datasource.druid.initialSize}") private int initialSize; @@ -45,8 +44,7 @@ public class DruidProperties @Value("${spring.datasource.druid.testOnReturn}") private boolean testOnReturn; - public DruidDataSource dataSource(DruidDataSource datasource) - { + public DruidDataSource dataSource(DruidDataSource datasource) { /** 配置初始化大小、最小、最大 */ datasource.setInitialSize(initialSize); datasource.setMaxActive(maxActive); diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/datasource/DynamicDataSource.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/datasource/DynamicDataSource.java index a5f764072..f9253ece6 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/datasource/DynamicDataSource.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/datasource/DynamicDataSource.java @@ -1,27 +1,25 @@ -package com.ruoyi.framework.datasource; - -import java.util.Map; -import javax.sql.DataSource; -import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; -import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder; - -/** - * 动态数据源 - * - * @author ruoyi - */ -public class DynamicDataSource extends AbstractRoutingDataSource -{ - public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) - { - super.setDefaultTargetDataSource(defaultTargetDataSource); - super.setTargetDataSources(targetDataSources); - super.afterPropertiesSet(); - } - - @Override - protected Object determineCurrentLookupKey() - { - return DynamicDataSourceContextHolder.getDataSourceType(); - } +package com.ruoyi.framework.datasource; + +import java.util.Map; +import javax.sql.DataSource; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; +import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder; + +/** + * 动态数据源 + * + * @author ruoyi + */ +public class DynamicDataSource extends AbstractRoutingDataSource { + public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) { + super.setDefaultTargetDataSource(defaultTargetDataSource); + super.setTargetDataSources(targetDataSources); + super.afterPropertiesSet(); + } + + @Override + protected Object determineCurrentLookupKey() { + return DynamicDataSourceContextHolder.getDataSourceType(); + } } \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java index a84e8ac7a..913d51cba 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java @@ -3,6 +3,7 @@ package com.ruoyi.framework.interceptor; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @@ -13,40 +14,33 @@ import com.ruoyi.common.utils.ServletUtils; /** * 防止重复提交拦截器 - * + * * @author ruoyi */ @Component -public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter -{ +public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter { @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception - { - if (handler instanceof HandlerMethod) - { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class); - if (annotation != null) - { - if (this.isRepeatSubmit(request)) - { + if (annotation != null) { + if (this.isRepeatSubmit(request)) { AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试"); ServletUtils.renderString(response, JSON.marshal(ajaxResult)); return false; } } return true; - } - else - { + } else { return super.preHandle(request, response, handler); } } /** * 验证是否重复提交由子类实现具体的防重复提交的规则 - * + * * @param httpServletRequest * @return * @throws Exception diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java index 1c490e66b..81de23b1d 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java @@ -4,19 +4,19 @@ import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.springframework.stereotype.Component; import com.ruoyi.common.json.JSON; import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; /** - * 判断请求url和数据是否和上一次相同, + * 判断请求url和数据是否和上一次相同, * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 - * + * * @author ruoyi */ @Component -public class SameUrlDataInterceptor extends RepeatSubmitInterceptor -{ +public class SameUrlDataInterceptor extends RepeatSubmitInterceptor { public final String REPEAT_PARAMS = "repeatParams"; public final String REPEAT_TIME = "repeatTime"; @@ -25,20 +25,18 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 间隔时间,单位:秒 默认10秒 - * + *

* 两次相同参数的请求,如果间隔时间大于该参数,系统不会认定为重复提交的数据 */ private int intervalTime = 10; - public void setIntervalTime(int intervalTime) - { + public void setIntervalTime(int intervalTime) { this.intervalTime = intervalTime; } @SuppressWarnings("unchecked") @Override - public boolean isRepeatSubmit(HttpServletRequest request) throws Exception - { + public boolean isRepeatSubmit(HttpServletRequest request) throws Exception { // 本次参数及系统时间 String nowParams = JSON.marshal(request.getParameterMap()); Map nowDataMap = new HashMap(); @@ -50,14 +48,11 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor HttpSession session = request.getSession(); Object sessionObj = session.getAttribute(SESSION_REPEAT_KEY); - if (sessionObj != null) - { + if (sessionObj != null) { Map sessionMap = (Map) sessionObj; - if (sessionMap.containsKey(url)) - { + if (sessionMap.containsKey(url)) { Map preDataMap = (Map) sessionMap.get(url); - if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap)) - { + if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap)) { return true; } } @@ -71,8 +66,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 判断参数是否相同 */ - private boolean compareParams(Map nowMap, Map preMap) - { + private boolean compareParams(Map nowMap, Map preMap) { String nowParams = (String) nowMap.get(REPEAT_PARAMS); String preParams = (String) preMap.get(REPEAT_PARAMS); return nowParams.equals(preParams); @@ -81,12 +75,10 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 判断两次间隔时间 */ - private boolean compareTime(Map nowMap, Map preMap) - { + private boolean compareTime(Map nowMap, Map preMap) { long time1 = (Long) nowMap.get(REPEAT_TIME); long time2 = (Long) preMap.get(REPEAT_TIME); - if ((time1 - time2) < (this.intervalTime * 1000)) - { + if ((time1 - time2) < (this.intervalTime * 1000)) { return true; } return false; diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/AsyncManager.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/AsyncManager.java index a30067dd9..e6aac6061 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/AsyncManager.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/AsyncManager.java @@ -1,55 +1,53 @@ -package com.ruoyi.framework.manager; - -import java.util.TimerTask; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import com.ruoyi.common.utils.Threads; -import com.ruoyi.common.utils.spring.SpringUtils; - -/** - * 异步任务管理器 - * - * @author liuhulu - */ -public class AsyncManager -{ - /** - * 操作延迟10毫秒 - */ - private final int OPERATE_DELAY_TIME = 10; - - /** - * 异步操作任务调度线程池 - */ - private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); - - /** - * 单例模式 - */ - private AsyncManager(){} - - private static AsyncManager me = new AsyncManager(); - - public static AsyncManager me() - { - return me; - } - - /** - * 执行任务 - * - * @param task 任务 - */ - public void execute(TimerTask task) - { - executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); - } - - /** - * 停止任务线程池 - */ - public void shutdown() - { - Threads.shutdownAndAwaitTermination(executor); - } -} +package com.ruoyi.framework.manager; + +import java.util.TimerTask; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import com.ruoyi.common.utils.Threads; +import com.ruoyi.common.utils.spring.SpringUtils; + +/** + * 异步任务管理器 + * + * @author liuhulu + */ +public class AsyncManager { + /** + * 操作延迟10毫秒 + */ + private final int OPERATE_DELAY_TIME = 10; + + /** + * 异步操作任务调度线程池 + */ + private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); + + /** + * 单例模式 + */ + private AsyncManager() { + } + + private static AsyncManager me = new AsyncManager(); + + public static AsyncManager me() { + return me; + } + + /** + * 执行任务 + * + * @param task 任务 + */ + public void execute(TimerTask task) { + executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); + } + + /** + * 停止任务线程池 + */ + public void shutdown() { + Threads.shutdownAndAwaitTermination(executor); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java index 78a4af372..0722539a9 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java @@ -7,6 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; + import javax.annotation.PreDestroy; /** @@ -15,8 +16,7 @@ import javax.annotation.PreDestroy; * @author cj */ @Component -public class ShutdownManager -{ +public class ShutdownManager { private static final Logger logger = LoggerFactory.getLogger("sys-user"); @Autowired(required = false) @@ -26,8 +26,7 @@ public class ShutdownManager private EhCacheManager ehCacheManager; @PreDestroy - public void destroy() - { + public void destroy() { shutdownSpringSessionValidationScheduler(); shutdownAsyncManager(); shutdownEhCacheManager(); @@ -36,17 +35,12 @@ public class ShutdownManager /** * 停止Seesion会话检查 */ - private void shutdownSpringSessionValidationScheduler() - { - if (springSessionValidationScheduler != null && springSessionValidationScheduler.isEnabled()) - { - try - { + private void shutdownSpringSessionValidationScheduler() { + if (springSessionValidationScheduler != null && springSessionValidationScheduler.isEnabled()) { + try { logger.info("====关闭会话验证任务===="); springSessionValidationScheduler.disableSessionValidation(); - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e.getMessage(), e); } } @@ -55,32 +49,23 @@ public class ShutdownManager /** * 停止异步执行任务 */ - private void shutdownAsyncManager() - { - try - { + private void shutdownAsyncManager() { + try { logger.info("====关闭后台任务任务线程池===="); AsyncManager.me().shutdown(); - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e.getMessage(), e); } } - private void shutdownEhCacheManager() - { - try - { + private void shutdownEhCacheManager() { + try { logger.info("====关闭缓存===="); - if (ehCacheManager != null) - { + if (ehCacheManager != null) { CacheManager cacheManager = ehCacheManager.getCacheManager(); cacheManager.shutdown(); } - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e.getMessage(), e); } } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java index 719c380e4..6312e8ea0 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java @@ -1,135 +1,122 @@ -package com.ruoyi.framework.manager.factory; - -import java.util.TimerTask; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.utils.AddressUtils; -import com.ruoyi.common.utils.ServletUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.framework.shiro.session.OnlineSession; -import com.ruoyi.framework.util.LogUtils; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysLogininfor; -import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.service.ISysOperLogService; -import com.ruoyi.system.service.ISysUserOnlineService; -import com.ruoyi.system.service.impl.SysLogininforServiceImpl; -import eu.bitwalker.useragentutils.UserAgent; - -/** - * 异步工厂(产生任务用) - * - * @author liuhulu - * - */ -public class AsyncFactory -{ - private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); - - /** - * 同步session到数据库 - * - * @param session 在线用户会话 - * @return 任务task - */ - public static TimerTask syncSessionToDb(final OnlineSession session) - { - return new TimerTask() - { - @Override - public void run() - { - SysUserOnline online = new SysUserOnline(); - online.setSessionId(String.valueOf(session.getId())); - online.setDeptName(session.getDeptName()); - online.setLoginName(session.getLoginName()); - online.setStartTimestamp(session.getStartTimestamp()); - online.setLastAccessTime(session.getLastAccessTime()); - online.setExpireTime(session.getTimeout()); - online.setIpaddr(session.getHost()); - online.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost())); - online.setBrowser(session.getBrowser()); - online.setOs(session.getOs()); - online.setStatus(session.getStatus()); - SpringUtils.getBean(ISysUserOnlineService.class).saveOnline(online); - - } - }; - } - - /** - * 操作日志记录 - * - * @param operLog 操作日志信息 - * @return 任务task - */ - public static TimerTask recordOper(final SysOperLog operLog) - { - return new TimerTask() - { - @Override - public void run() - { - // 远程查询操作地点 - operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); - SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog); - } - }; - } - - /** - * 记录登陆信息 - * - * @param username 用户名 - * @param status 状态 - * @param message 消息 - * @param args 列表 - * @return 任务task - */ - public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) - { - final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); - final String ip = ShiroUtils.getIp(); - return new TimerTask() - { - @Override - public void run() - { - String address = AddressUtils.getRealAddressByIP(ip); - StringBuilder s = new StringBuilder(); - s.append(LogUtils.getBlock(ip)); - s.append(address); - s.append(LogUtils.getBlock(username)); - s.append(LogUtils.getBlock(status)); - s.append(LogUtils.getBlock(message)); - // 打印信息到日志 - sys_user_logger.info(s.toString(), args); - // 获取客户端操作系统 - String os = userAgent.getOperatingSystem().getName(); - // 获取客户端浏览器 - String browser = userAgent.getBrowser().getName(); - // 封装对象 - SysLogininfor logininfor = new SysLogininfor(); - logininfor.setLoginName(username); - logininfor.setIpaddr(ip); - logininfor.setLoginLocation(address); - logininfor.setBrowser(browser); - logininfor.setOs(os); - logininfor.setMsg(message); - // 日志状态 - if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) - { - logininfor.setStatus(Constants.SUCCESS); - } - else if (Constants.LOGIN_FAIL.equals(status)) - { - logininfor.setStatus(Constants.FAIL); - } - // 插入数据 - SpringUtils.getBean(SysLogininforServiceImpl.class).insertLogininfor(logininfor); - } - }; - } -} +package com.ruoyi.framework.manager.factory; + +import java.util.TimerTask; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.utils.AddressUtils; +import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.framework.shiro.session.OnlineSession; +import com.ruoyi.framework.util.LogUtils; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysLogininfor; +import com.ruoyi.system.domain.SysOperLog; +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.service.ISysOperLogService; +import com.ruoyi.system.service.ISysUserOnlineService; +import com.ruoyi.system.service.impl.SysLogininforServiceImpl; +import eu.bitwalker.useragentutils.UserAgent; + +/** + * 异步工厂(产生任务用) + * + * @author liuhulu + */ +public class AsyncFactory { + private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); + + /** + * 同步session到数据库 + * + * @param session 在线用户会话 + * @return 任务task + */ + public static TimerTask syncSessionToDb(final OnlineSession session) { + return new TimerTask() { + @Override + public void run() { + SysUserOnline online = new SysUserOnline(); + online.setSessionId(String.valueOf(session.getId())); + online.setDeptName(session.getDeptName()); + online.setLoginName(session.getLoginName()); + online.setStartTimestamp(session.getStartTimestamp()); + online.setLastAccessTime(session.getLastAccessTime()); + online.setExpireTime(session.getTimeout()); + online.setIpaddr(session.getHost()); + online.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost())); + online.setBrowser(session.getBrowser()); + online.setOs(session.getOs()); + online.setStatus(session.getStatus()); + SpringUtils.getBean(ISysUserOnlineService.class).saveOnline(online); + + } + }; + } + + /** + * 操作日志记录 + * + * @param operLog 操作日志信息 + * @return 任务task + */ + public static TimerTask recordOper(final SysOperLog operLog) { + return new TimerTask() { + @Override + public void run() { + // 远程查询操作地点 + operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); + SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog); + } + }; + } + + /** + * 记录登陆信息 + * + * @param username 用户名 + * @param status 状态 + * @param message 消息 + * @param args 列表 + * @return 任务task + */ + public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) { + final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); + final String ip = ShiroUtils.getIp(); + return new TimerTask() { + @Override + public void run() { + String address = AddressUtils.getRealAddressByIP(ip); + StringBuilder s = new StringBuilder(); + s.append(LogUtils.getBlock(ip)); + s.append(address); + s.append(LogUtils.getBlock(username)); + s.append(LogUtils.getBlock(status)); + s.append(LogUtils.getBlock(message)); + // 打印信息到日志 + sys_user_logger.info(s.toString(), args); + // 获取客户端操作系统 + String os = userAgent.getOperatingSystem().getName(); + // 获取客户端浏览器 + String browser = userAgent.getBrowser().getName(); + // 封装对象 + SysLogininfor logininfor = new SysLogininfor(); + logininfor.setLoginName(username); + logininfor.setIpaddr(ip); + logininfor.setLoginLocation(address); + logininfor.setBrowser(browser); + logininfor.setOs(os); + logininfor.setMsg(message); + // 日志状态 + if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) { + logininfor.setStatus(Constants.SUCCESS); + } else if (Constants.LOGIN_FAIL.equals(status)) { + logininfor.setStatus(Constants.FAIL); + } + // 插入数据 + SpringUtils.getBean(SysLogininforServiceImpl.class).insertLogininfor(logininfor); + } + }; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java index 7554f7c11..9bfaa4bb7 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java @@ -1,141 +1,119 @@ -package com.ruoyi.framework.shiro.realm; - -import java.util.HashSet; -import java.util.Set; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.AuthenticationInfo; -import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.ExcessiveAttemptsException; -import org.apache.shiro.authc.IncorrectCredentialsException; -import org.apache.shiro.authc.LockedAccountException; -import org.apache.shiro.authc.SimpleAuthenticationInfo; -import org.apache.shiro.authc.UnknownAccountException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.authz.AuthorizationInfo; -import org.apache.shiro.authz.SimpleAuthorizationInfo; -import org.apache.shiro.realm.AuthorizingRealm; -import org.apache.shiro.subject.PrincipalCollection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import com.ruoyi.common.exception.user.CaptchaException; -import com.ruoyi.common.exception.user.RoleBlockedException; -import com.ruoyi.common.exception.user.UserBlockedException; -import com.ruoyi.common.exception.user.UserNotExistsException; -import com.ruoyi.common.exception.user.UserPasswordNotMatchException; -import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; -import com.ruoyi.framework.shiro.service.SysLoginService; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.service.ISysMenuService; -import com.ruoyi.system.service.ISysRoleService; - -/** - * 自定义Realm 处理登录 权限 - * - * @author ruoyi - */ -public class UserRealm extends AuthorizingRealm -{ - private static final Logger log = LoggerFactory.getLogger(UserRealm.class); - - @Autowired - private ISysMenuService menuService; - - @Autowired - private ISysRoleService roleService; - - @Autowired - private SysLoginService loginService; - - /** - * 授权 - */ - @Override - protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) - { - SysUser user = ShiroUtils.getSysUser(); - // 角色列表 - Set roles = new HashSet(); - // 功能列表 - Set menus = new HashSet(); - SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); - // 管理员拥有所有权限 - if (user.isAdmin()) - { - info.addRole("admin"); - info.addStringPermission("*:*:*"); - } - else - { - roles = roleService.selectRoleKeys(user.getUserId()); - menus = menuService.selectPermsByUserId(user.getUserId()); - // 角色加入AuthorizationInfo认证对象 - info.setRoles(roles); - // 权限加入AuthorizationInfo认证对象 - info.setStringPermissions(menus); - } - return info; - } - - /** - * 登录认证 - */ - @Override - protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException - { - UsernamePasswordToken upToken = (UsernamePasswordToken) token; - String username = upToken.getUsername(); - String password = ""; - if (upToken.getPassword() != null) - { - password = new String(upToken.getPassword()); - } - - SysUser user = null; - try - { - user = loginService.login(username, password); - } - catch (CaptchaException e) - { - throw new AuthenticationException(e.getMessage(), e); - } - catch (UserNotExistsException e) - { - throw new UnknownAccountException(e.getMessage(), e); - } - catch (UserPasswordNotMatchException e) - { - throw new IncorrectCredentialsException(e.getMessage(), e); - } - catch (UserPasswordRetryLimitExceedException e) - { - throw new ExcessiveAttemptsException(e.getMessage(), e); - } - catch (UserBlockedException e) - { - throw new LockedAccountException(e.getMessage(), e); - } - catch (RoleBlockedException e) - { - throw new LockedAccountException(e.getMessage(), e); - } - catch (Exception e) - { - log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage()); - throw new AuthenticationException(e.getMessage(), e); - } - SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); - return info; - } - - /** - * 清理缓存权限 - */ - public void clearCachedAuthorizationInfo() - { - this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); - } -} +package com.ruoyi.framework.shiro.realm; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.ExcessiveAttemptsException; +import org.apache.shiro.authc.IncorrectCredentialsException; +import org.apache.shiro.authc.LockedAccountException; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import com.ruoyi.common.exception.user.CaptchaException; +import com.ruoyi.common.exception.user.RoleBlockedException; +import com.ruoyi.common.exception.user.UserBlockedException; +import com.ruoyi.common.exception.user.UserNotExistsException; +import com.ruoyi.common.exception.user.UserPasswordNotMatchException; +import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; +import com.ruoyi.framework.shiro.service.SysLoginService; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysMenuService; +import com.ruoyi.system.service.ISysRoleService; + +/** + * 自定义Realm 处理登录 权限 + * + * @author ruoyi + */ +public class UserRealm extends AuthorizingRealm { + private static final Logger log = LoggerFactory.getLogger(UserRealm.class); + + @Autowired + private ISysMenuService menuService; + + @Autowired + private ISysRoleService roleService; + + @Autowired + private SysLoginService loginService; + + /** + * 授权 + */ + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { + SysUser user = ShiroUtils.getSysUser(); + // 角色列表 + Set roles = new HashSet(); + // 功能列表 + Set menus = new HashSet(); + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); + // 管理员拥有所有权限 + if (user.isAdmin()) { + info.addRole("admin"); + info.addStringPermission("*:*:*"); + } else { + roles = roleService.selectRoleKeys(user.getUserId()); + menus = menuService.selectPermsByUserId(user.getUserId()); + // 角色加入AuthorizationInfo认证对象 + info.setRoles(roles); + // 权限加入AuthorizationInfo认证对象 + info.setStringPermissions(menus); + } + return info; + } + + /** + * 登录认证 + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + UsernamePasswordToken upToken = (UsernamePasswordToken) token; + String username = upToken.getUsername(); + String password = ""; + if (upToken.getPassword() != null) { + password = new String(upToken.getPassword()); + } + + SysUser user = null; + try { + user = loginService.login(username, password); + } catch (CaptchaException e) { + throw new AuthenticationException(e.getMessage(), e); + } catch (UserNotExistsException e) { + throw new UnknownAccountException(e.getMessage(), e); + } catch (UserPasswordNotMatchException e) { + throw new IncorrectCredentialsException(e.getMessage(), e); + } catch (UserPasswordRetryLimitExceedException e) { + throw new ExcessiveAttemptsException(e.getMessage(), e); + } catch (UserBlockedException e) { + throw new LockedAccountException(e.getMessage(), e); + } catch (RoleBlockedException e) { + throw new LockedAccountException(e.getMessage(), e); + } catch (Exception e) { + log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage()); + throw new AuthenticationException(e.getMessage(), e); + } + SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); + return info; + } + + /** + * 清理缓存权限 + */ + public void clearCachedAuthorizationInfo() { + this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysLoginService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysLoginService.java index 92ebe89d8..651b62d2a 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysLoginService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysLoginService.java @@ -1,136 +1,120 @@ -package com.ruoyi.framework.shiro.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.enums.UserStatus; -import com.ruoyi.common.exception.user.CaptchaException; -import com.ruoyi.common.exception.user.UserBlockedException; -import com.ruoyi.common.exception.user.UserDeleteException; -import com.ruoyi.common.exception.user.UserNotExistsException; -import com.ruoyi.common.exception.user.UserPasswordNotMatchException; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.MessageUtils; -import com.ruoyi.common.utils.ServletUtils; -import com.ruoyi.framework.manager.AsyncManager; -import com.ruoyi.framework.manager.factory.AsyncFactory; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.service.ISysUserService; - -/** - * 登录校验方法 - * - * @author ruoyi - */ -@Component -public class SysLoginService -{ - @Autowired - private SysPasswordService passwordService; - - @Autowired - private ISysUserService userService; - - /** - * 登录 - */ - public SysUser login(String username, String password) - { - // 验证码校验 - if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); - throw new CaptchaException(); - } - // 用户名或密码为空 错误 - if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"))); - throw new UserNotExistsException(); - } - // 密码如果不在指定范围内 错误 - if (password.length() < UserConstants.PASSWORD_MIN_LENGTH - || password.length() > UserConstants.PASSWORD_MAX_LENGTH) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); - throw new UserPasswordNotMatchException(); - } - - // 用户名不在指定范围内 错误 - if (username.length() < UserConstants.USERNAME_MIN_LENGTH - || username.length() > UserConstants.USERNAME_MAX_LENGTH) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); - throw new UserPasswordNotMatchException(); - } - - // 查询用户信息 - SysUser user = userService.selectUserByLoginName(username); - - if (user == null && maybeMobilePhoneNumber(username)) - { - user = userService.selectUserByPhoneNumber(username); - } - - if (user == null && maybeEmail(username)) - { - user = userService.selectUserByEmail(username); - } - - if (user == null) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists"))); - throw new UserNotExistsException(); - } - - if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.delete"))); - throw new UserDeleteException(); - } - - if (UserStatus.DISABLE.getCode().equals(user.getStatus())) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark()))); - throw new UserBlockedException(); - } - - passwordService.validate(user, password); - - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); - recordLoginInfo(user); - return user; - } - - private boolean maybeEmail(String username) - { - if (!username.matches(UserConstants.EMAIL_PATTERN)) - { - return false; - } - return true; - } - - private boolean maybeMobilePhoneNumber(String username) - { - if (!username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN)) - { - return false; - } - return true; - } - - /** - * 记录登录信息 - */ - public void recordLoginInfo(SysUser user) - { - user.setLoginIp(ShiroUtils.getIp()); - user.setLoginDate(DateUtils.getNowDate()); - userService.updateUserInfo(user); - } -} +package com.ruoyi.framework.shiro.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.enums.UserStatus; +import com.ruoyi.common.exception.user.CaptchaException; +import com.ruoyi.common.exception.user.UserBlockedException; +import com.ruoyi.common.exception.user.UserDeleteException; +import com.ruoyi.common.exception.user.UserNotExistsException; +import com.ruoyi.common.exception.user.UserPasswordNotMatchException; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.MessageUtils; +import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysUserService; + +/** + * 登录校验方法 + * + * @author ruoyi + */ +@Component +public class SysLoginService { + @Autowired + private SysPasswordService passwordService; + + @Autowired + private ISysUserService userService; + + /** + * 登录 + */ + public SysUser login(String username, String password) { + // 验证码校验 + if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); + throw new CaptchaException(); + } + // 用户名或密码为空 错误 + if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"))); + throw new UserNotExistsException(); + } + // 密码如果不在指定范围内 错误 + if (password.length() < UserConstants.PASSWORD_MIN_LENGTH + || password.length() > UserConstants.PASSWORD_MAX_LENGTH) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); + throw new UserPasswordNotMatchException(); + } + + // 用户名不在指定范围内 错误 + if (username.length() < UserConstants.USERNAME_MIN_LENGTH + || username.length() > UserConstants.USERNAME_MAX_LENGTH) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); + throw new UserPasswordNotMatchException(); + } + + // 查询用户信息 + SysUser user = userService.selectUserByLoginName(username); + + if (user == null && maybeMobilePhoneNumber(username)) { + user = userService.selectUserByPhoneNumber(username); + } + + if (user == null && maybeEmail(username)) { + user = userService.selectUserByEmail(username); + } + + if (user == null) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists"))); + throw new UserNotExistsException(); + } + + if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.delete"))); + throw new UserDeleteException(); + } + + if (UserStatus.DISABLE.getCode().equals(user.getStatus())) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark()))); + throw new UserBlockedException(); + } + + passwordService.validate(user, password); + + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); + recordLoginInfo(user); + return user; + } + + private boolean maybeEmail(String username) { + if (!username.matches(UserConstants.EMAIL_PATTERN)) { + return false; + } + return true; + } + + private boolean maybeMobilePhoneNumber(String username) { + if (!username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN)) { + return false; + } + return true; + } + + /** + * 记录登录信息 + */ + public void recordLoginInfo(SysUser user) { + user.setLoginIp(ShiroUtils.getIp()); + user.setLoginDate(DateUtils.getNowDate()); + userService.updateUserInfo(user); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysPasswordService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysPasswordService.java index 3ff8f92ab..283ef869a 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysPasswordService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysPasswordService.java @@ -1,90 +1,80 @@ -package com.ruoyi.framework.shiro.service; - -import java.util.concurrent.atomic.AtomicInteger; -import javax.annotation.PostConstruct; -import org.apache.shiro.cache.Cache; -import org.apache.shiro.cache.CacheManager; -import org.apache.shiro.crypto.hash.Md5Hash; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.exception.user.UserPasswordNotMatchException; -import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; -import com.ruoyi.common.utils.MessageUtils; -import com.ruoyi.framework.manager.AsyncManager; -import com.ruoyi.framework.manager.factory.AsyncFactory; -import com.ruoyi.system.domain.SysUser; - -/** - * 登录密码方法 - * - * @author ruoyi - */ -@Component -public class SysPasswordService -{ - @Autowired - private CacheManager cacheManager; - - private Cache loginRecordCache; - - @Value(value = "${user.password.maxRetryCount}") - private String maxRetryCount; - - @PostConstruct - public void init() - { - loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE); - } - - public void validate(SysUser user, String password) - { - String loginName = user.getLoginName(); - - AtomicInteger retryCount = loginRecordCache.get(loginName); - - if (retryCount == null) - { - retryCount = new AtomicInteger(0); - loginRecordCache.put(loginName, retryCount); - } - if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount))); - throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue()); - } - - if (!matches(user, password)) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); - loginRecordCache.put(loginName, retryCount); - throw new UserPasswordNotMatchException(); - } - else - { - clearLoginRecordCache(loginName); - } - } - - public boolean matches(SysUser user, String newPassword) - { - return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt())); - } - - public void clearLoginRecordCache(String username) - { - loginRecordCache.remove(username); - } - - public String encryptPassword(String username, String password, String salt) - { - return new Md5Hash(username + password + salt).toHex().toString(); - } - - public void unlock(String loginName){ - loginRecordCache.remove(loginName); - } - -} +package com.ruoyi.framework.shiro.service; + +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.PostConstruct; + +import org.apache.shiro.cache.Cache; +import org.apache.shiro.cache.CacheManager; +import org.apache.shiro.crypto.hash.Md5Hash; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.exception.user.UserPasswordNotMatchException; +import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; +import com.ruoyi.common.utils.MessageUtils; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.system.domain.SysUser; + +/** + * 登录密码方法 + * + * @author ruoyi + */ +@Component +public class SysPasswordService { + @Autowired + private CacheManager cacheManager; + + private Cache loginRecordCache; + + @Value(value = "${user.password.maxRetryCount}") + private String maxRetryCount; + + @PostConstruct + public void init() { + loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE); + } + + public void validate(SysUser user, String password) { + String loginName = user.getLoginName(); + + AtomicInteger retryCount = loginRecordCache.get(loginName); + + if (retryCount == null) { + retryCount = new AtomicInteger(0); + loginRecordCache.put(loginName, retryCount); + } + if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount))); + throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue()); + } + + if (!matches(user, password)) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); + loginRecordCache.put(loginName, retryCount); + throw new UserPasswordNotMatchException(); + } else { + clearLoginRecordCache(loginName); + } + } + + public boolean matches(SysUser user, String newPassword) { + return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt())); + } + + public void clearLoginRecordCache(String username) { + loginRecordCache.remove(username); + } + + public String encryptPassword(String username, String password, String salt) { + return new Md5Hash(username + password + salt).toHex().toString(); + } + + public void unlock(String loginName) { + loginRecordCache.remove(loginName); + } + +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysShiroService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysShiroService.java index 1fb9c7e46..f8142a130 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysShiroService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/service/SysShiroService.java @@ -1,6 +1,7 @@ package com.ruoyi.framework.shiro.service; import java.io.Serializable; + import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -11,12 +12,11 @@ import com.ruoyi.system.service.ISysUserOnlineService; /** * 会话db操作处理 - * + * * @author ruoyi */ @Component -public class SysShiroService -{ +public class SysShiroService { @Autowired private ISysUserOnlineService onlineService; @@ -25,8 +25,7 @@ public class SysShiroService * * @param onlineSession 会话信息 */ - public void deleteSession(OnlineSession onlineSession) - { + public void deleteSession(OnlineSession onlineSession) { onlineService.deleteOnlineById(String.valueOf(onlineSession.getId())); } @@ -36,17 +35,14 @@ public class SysShiroService * @param sessionId * @return */ - public Session getSession(Serializable sessionId) - { + public Session getSession(Serializable sessionId) { SysUserOnline userOnline = onlineService.selectOnlineById(String.valueOf(sessionId)); return StringUtils.isNull(userOnline) ? null : createSession(userOnline); } - public Session createSession(SysUserOnline userOnline) - { + public Session createSession(SysUserOnline userOnline) { OnlineSession onlineSession = new OnlineSession(); - if (StringUtils.isNotNull(userOnline)) - { + if (StringUtils.isNotNull(userOnline)) { onlineSession.setId(userOnline.getSessionId()); onlineSession.setHost(userOnline.getIpaddr()); onlineSession.setBrowser(userOnline.getBrowser()); diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSession.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSession.java index 09b88c5ce..978fc0dc6 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSession.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSession.java @@ -1,148 +1,146 @@ -package com.ruoyi.framework.shiro.session; - -import org.apache.shiro.session.mgt.SimpleSession; -import com.ruoyi.common.enums.OnlineStatus; - -/** - * 在线用户会话属性 - * - * @author ruoyi - */ -public class OnlineSession extends SimpleSession -{ - private static final long serialVersionUID = 1L; - - /** 用户ID */ - private Long userId; - - /** 用户名称 */ - private String loginName; - - /** 部门名称 */ - private String deptName; - - /** 用户头像 */ - private String avatar; - - /** 登录IP地址 */ - private String host; - - /** 浏览器类型 */ - private String browser; - - /** 操作系统 */ - private String os; - - /** 在线状态 */ - private OnlineStatus status = OnlineStatus.on_line; - - /** 属性是否改变 优化session数据同步 */ - private transient boolean attributeChanged = false; - - @Override - public String getHost() - { - return host; - } - - @Override - public void setHost(String host) - { - this.host = host; - } - - public String getBrowser() - { - return browser; - } - - public void setBrowser(String browser) - { - this.browser = browser; - } - - public String getOs() - { - return os; - } - - public void setOs(String os) - { - this.os = os; - } - - public Long getUserId() - { - return userId; - } - - public void setUserId(Long userId) - { - this.userId = userId; - } - - public String getLoginName() - { - return loginName; - } - - public void setLoginName(String loginName) - { - this.loginName = loginName; - } - - public String getDeptName() - { - return deptName; - } - - public void setDeptName(String deptName) - { - this.deptName = deptName; - } - - public OnlineStatus getStatus() - { - return status; - } - - public void setStatus(OnlineStatus status) - { - this.status = status; - } - - public void markAttributeChanged() - { - this.attributeChanged = true; - } - - public void resetAttributeChanged() - { - this.attributeChanged = false; - } - - public boolean isAttributeChanged() - { - return attributeChanged; - } - - public String getAvatar() { - return avatar; - } - - public void setAvatar(String avatar) { - this.avatar = avatar; - } - - @Override - public void setAttribute(Object key, Object value) - { - super.setAttribute(key, value); - } - - @Override - public Object removeAttribute(Object key) - { - return super.removeAttribute(key); - } -} +package com.ruoyi.framework.shiro.session; + +import org.apache.shiro.session.mgt.SimpleSession; +import com.ruoyi.common.enums.OnlineStatus; + +/** + * 在线用户会话属性 + * + * @author ruoyi + */ +public class OnlineSession extends SimpleSession { + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + private Long userId; + + /** + * 用户名称 + */ + private String loginName; + + /** + * 部门名称 + */ + private String deptName; + + /** + * 用户头像 + */ + private String avatar; + + /** + * 登录IP地址 + */ + private String host; + + /** + * 浏览器类型 + */ + private String browser; + + /** + * 操作系统 + */ + private String os; + + /** + * 在线状态 + */ + private OnlineStatus status = OnlineStatus.on_line; + + /** + * 属性是否改变 优化session数据同步 + */ + private transient boolean attributeChanged = false; + + @Override + public String getHost() { + return host; + } + + @Override + public void setHost(String host) { + this.host = host; + } + + public String getBrowser() { + return browser; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + public OnlineStatus getStatus() { + return status; + } + + public void setStatus(OnlineStatus status) { + this.status = status; + } + + public void markAttributeChanged() { + this.attributeChanged = true; + } + + public void resetAttributeChanged() { + this.attributeChanged = false; + } + + public boolean isAttributeChanged() { + return attributeChanged; + } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + @Override + public void setAttribute(Object key, Object value) { + super.setAttribute(key, value); + } + + @Override + public Object removeAttribute(Object key) { + return super.removeAttribute(key); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java index 40ff31277..8c7702e80 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java @@ -1,117 +1,105 @@ -package com.ruoyi.framework.shiro.session; - -import java.io.Serializable; -import java.util.Date; -import org.apache.shiro.session.Session; -import org.apache.shiro.session.UnknownSessionException; -import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import com.ruoyi.common.enums.OnlineStatus; -import com.ruoyi.framework.manager.AsyncManager; -import com.ruoyi.framework.manager.factory.AsyncFactory; -import com.ruoyi.framework.shiro.service.SysShiroService; - -/** - * 针对自定义的ShiroSession的db操作 - * - * @author ruoyi - */ -public class OnlineSessionDAO extends EnterpriseCacheSessionDAO -{ - /** - * 同步session到数据库的周期 单位为毫秒(默认1分钟) - */ - @Value("${shiro.session.dbSyncPeriod}") - private int dbSyncPeriod; - - /** - * 上次同步数据库的时间戳 - */ - private static final String LAST_SYNC_DB_TIMESTAMP = OnlineSessionDAO.class.getName() + "LAST_SYNC_DB_TIMESTAMP"; - - @Autowired - private SysShiroService sysShiroService; - - public OnlineSessionDAO() - { - super(); - } - - public OnlineSessionDAO(long expireTime) - { - super(); - } - - /** - * 根据会话ID获取会话 - * - * @param sessionId 会话ID - * @return ShiroSession - */ - @Override - protected Session doReadSession(Serializable sessionId) - { - return sysShiroService.getSession(sessionId); - } - - @Override - public void update(Session session) throws UnknownSessionException - { - super.update(session); - } - - /** - * 更新会话;如更新会话最后访问时间/停止会话/设置超时时间/设置移除属性等会调用 - */ - public void syncToDb(OnlineSession onlineSession) - { - Date lastSyncTimestamp = (Date) onlineSession.getAttribute(LAST_SYNC_DB_TIMESTAMP); - if (lastSyncTimestamp != null) - { - boolean needSync = true; - long deltaTime = onlineSession.getLastAccessTime().getTime() - lastSyncTimestamp.getTime(); - if (deltaTime < dbSyncPeriod * 60 * 1000) - { - // 时间差不足 无需同步 - needSync = false; - } - // isGuest = true 访客 - boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L; - - // session 数据变更了 同步 - if (isGuest == false && onlineSession.isAttributeChanged()) - { - needSync = true; - } - - if (needSync == false) - { - return; - } - } - // 更新上次同步数据库时间 - onlineSession.setAttribute(LAST_SYNC_DB_TIMESTAMP, onlineSession.getLastAccessTime()); - // 更新完后 重置标识 - if (onlineSession.isAttributeChanged()) - { - onlineSession.resetAttributeChanged(); - } - AsyncManager.me().execute(AsyncFactory.syncSessionToDb(onlineSession)); - } - - /** - * 当会话过期/停止(如用户退出时)属性等会调用 - */ - @Override - protected void doDelete(Session session) - { - OnlineSession onlineSession = (OnlineSession) session; - if (null == onlineSession) - { - return; - } - onlineSession.setStatus(OnlineStatus.off_line); - sysShiroService.deleteSession(onlineSession); - } -} +package com.ruoyi.framework.shiro.session; + +import java.io.Serializable; +import java.util.Date; + +import org.apache.shiro.session.Session; +import org.apache.shiro.session.UnknownSessionException; +import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import com.ruoyi.common.enums.OnlineStatus; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.framework.shiro.service.SysShiroService; + +/** + * 针对自定义的ShiroSession的db操作 + * + * @author ruoyi + */ +public class OnlineSessionDAO extends EnterpriseCacheSessionDAO { + /** + * 同步session到数据库的周期 单位为毫秒(默认1分钟) + */ + @Value("${shiro.session.dbSyncPeriod}") + private int dbSyncPeriod; + + /** + * 上次同步数据库的时间戳 + */ + private static final String LAST_SYNC_DB_TIMESTAMP = OnlineSessionDAO.class.getName() + "LAST_SYNC_DB_TIMESTAMP"; + + @Autowired + private SysShiroService sysShiroService; + + public OnlineSessionDAO() { + super(); + } + + public OnlineSessionDAO(long expireTime) { + super(); + } + + /** + * 根据会话ID获取会话 + * + * @param sessionId 会话ID + * @return ShiroSession + */ + @Override + protected Session doReadSession(Serializable sessionId) { + return sysShiroService.getSession(sessionId); + } + + @Override + public void update(Session session) throws UnknownSessionException { + super.update(session); + } + + /** + * 更新会话;如更新会话最后访问时间/停止会话/设置超时时间/设置移除属性等会调用 + */ + public void syncToDb(OnlineSession onlineSession) { + Date lastSyncTimestamp = (Date) onlineSession.getAttribute(LAST_SYNC_DB_TIMESTAMP); + if (lastSyncTimestamp != null) { + boolean needSync = true; + long deltaTime = onlineSession.getLastAccessTime().getTime() - lastSyncTimestamp.getTime(); + if (deltaTime < dbSyncPeriod * 60 * 1000) { + // 时间差不足 无需同步 + needSync = false; + } + // isGuest = true 访客 + boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L; + + // session 数据变更了 同步 + if (isGuest == false && onlineSession.isAttributeChanged()) { + needSync = true; + } + + if (needSync == false) { + return; + } + } + // 更新上次同步数据库时间 + onlineSession.setAttribute(LAST_SYNC_DB_TIMESTAMP, onlineSession.getLastAccessTime()); + // 更新完后 重置标识 + if (onlineSession.isAttributeChanged()) { + onlineSession.resetAttributeChanged(); + } + AsyncManager.me().execute(AsyncFactory.syncSessionToDb(onlineSession)); + } + + /** + * 当会话过期/停止(如用户退出时)属性等会调用 + */ + @Override + protected void doDelete(Session session) { + OnlineSession onlineSession = (OnlineSession) session; + if (null == onlineSession) { + return; + } + onlineSession.setStatus(OnlineStatus.off_line); + sysShiroService.deleteSession(onlineSession); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionFactory.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionFactory.java index bb6c0aaf2..3305f6173 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionFactory.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionFactory.java @@ -1,43 +1,40 @@ -package com.ruoyi.framework.shiro.session; - -import javax.servlet.http.HttpServletRequest; -import org.apache.shiro.session.Session; -import org.apache.shiro.session.mgt.SessionContext; -import org.apache.shiro.session.mgt.SessionFactory; -import org.apache.shiro.web.session.mgt.WebSessionContext; -import org.springframework.stereotype.Component; -import com.ruoyi.common.utils.IpUtils; -import com.ruoyi.common.utils.ServletUtils; -import eu.bitwalker.useragentutils.UserAgent; - -/** - * 自定义sessionFactory会话 - * - * @author ruoyi - */ -@Component -public class OnlineSessionFactory implements SessionFactory -{ - @Override - public Session createSession(SessionContext initData) - { - OnlineSession session = new OnlineSession(); - if (initData != null && initData instanceof WebSessionContext) - { - WebSessionContext sessionContext = (WebSessionContext) initData; - HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest(); - if (request != null) - { - UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); - // 获取客户端操作系统 - String os = userAgent.getOperatingSystem().getName(); - // 获取客户端浏览器 - String browser = userAgent.getBrowser().getName(); - session.setHost(IpUtils.getIpAddr(request)); - session.setBrowser(browser); - session.setOs(os); - } - } - return session; - } -} +package com.ruoyi.framework.shiro.session; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.shiro.session.Session; +import org.apache.shiro.session.mgt.SessionContext; +import org.apache.shiro.session.mgt.SessionFactory; +import org.apache.shiro.web.session.mgt.WebSessionContext; +import org.springframework.stereotype.Component; +import com.ruoyi.common.utils.IpUtils; +import com.ruoyi.common.utils.ServletUtils; +import eu.bitwalker.useragentutils.UserAgent; + +/** + * 自定义sessionFactory会话 + * + * @author ruoyi + */ +@Component +public class OnlineSessionFactory implements SessionFactory { + @Override + public Session createSession(SessionContext initData) { + OnlineSession session = new OnlineSession(); + if (initData != null && initData instanceof WebSessionContext) { + WebSessionContext sessionContext = (WebSessionContext) initData; + HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest(); + if (request != null) { + UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); + // 获取客户端操作系统 + String os = userAgent.getOperatingSystem().getName(); + // 获取客户端浏览器 + String browser = userAgent.getBrowser().getName(); + session.setHost(IpUtils.getIpAddr(request)); + session.setBrowser(browser); + session.setOs(os); + } + } + return session; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/LogoutFilter.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/LogoutFilter.java index f5aa96647..9b73275f4 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/LogoutFilter.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/LogoutFilter.java @@ -1,102 +1,89 @@ -package com.ruoyi.framework.shiro.web.filter; - -import java.io.Serializable; -import java.util.Deque; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import org.apache.shiro.cache.Cache; -import org.apache.shiro.cache.CacheManager; -import org.apache.shiro.session.SessionException; -import org.apache.shiro.subject.Subject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.utils.MessageUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.framework.manager.AsyncManager; -import com.ruoyi.framework.manager.factory.AsyncFactory; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; - -/** - * 退出过滤器 - * - * @author ruoyi - */ -public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter -{ - private static final Logger log = LoggerFactory.getLogger(LogoutFilter.class); - - /** - * 退出后重定向的地址 - */ - private String loginUrl; - - private Cache> cache; - - public String getLoginUrl() - { - return loginUrl; - } - - public void setLoginUrl(String loginUrl) - { - this.loginUrl = loginUrl; - } - - @Override - protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception - { - try - { - Subject subject = getSubject(request, response); - String redirectUrl = getRedirectUrl(request, response, subject); - try - { - SysUser user = ShiroUtils.getSysUser(); - if (StringUtils.isNotNull(user)) - { - String loginName = user.getLoginName(); - // 记录用户退出日志 - AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success"))); - // 清理缓存 - cache.remove(loginName); - } - // 退出登录 - subject.logout(); - } - catch (SessionException ise) - { - log.error("logout fail.", ise); - } - issueRedirect(request, response, redirectUrl); - } - catch (Exception e) - { - log.error("Encountered session exception during logout. This can generally safely be ignored.", e); - } - return false; - } - - /** - * 退出跳转URL - */ - @Override - protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) - { - String url = getLoginUrl(); - if (StringUtils.isNotEmpty(url)) - { - return url; - } - return super.getRedirectUrl(request, response, subject); - } - - // 设置Cache的key的前缀 - public void setCacheManager(CacheManager cacheManager) - { - // 必须和ehcache缓存配置中的缓存name一致 - this.cache = cacheManager.getCache(ShiroConstants.SYS_USERCACHE); - } -} +package com.ruoyi.framework.shiro.web.filter; + +import java.io.Serializable; +import java.util.Deque; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.apache.shiro.cache.Cache; +import org.apache.shiro.cache.CacheManager; +import org.apache.shiro.session.SessionException; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.utils.MessageUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; + +/** + * 退出过滤器 + * + * @author ruoyi + */ +public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter { + private static final Logger log = LoggerFactory.getLogger(LogoutFilter.class); + + /** + * 退出后重定向的地址 + */ + private String loginUrl; + + private Cache> cache; + + public String getLoginUrl() { + return loginUrl; + } + + public void setLoginUrl(String loginUrl) { + this.loginUrl = loginUrl; + } + + @Override + protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { + try { + Subject subject = getSubject(request, response); + String redirectUrl = getRedirectUrl(request, response, subject); + try { + SysUser user = ShiroUtils.getSysUser(); + if (StringUtils.isNotNull(user)) { + String loginName = user.getLoginName(); + // 记录用户退出日志 + AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success"))); + // 清理缓存 + cache.remove(loginName); + } + // 退出登录 + subject.logout(); + } catch (SessionException ise) { + log.error("logout fail.", ise); + } + issueRedirect(request, response, redirectUrl); + } catch (Exception e) { + log.error("Encountered session exception during logout. This can generally safely be ignored.", e); + } + return false; + } + + /** + * 退出跳转URL + */ + @Override + protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) { + String url = getLoginUrl(); + if (StringUtils.isNotEmpty(url)) { + return url; + } + return super.getRedirectUrl(request, response, subject); + } + + // 设置Cache的key的前缀 + public void setCacheManager(CacheManager cacheManager) { + // 必须和ehcache缓存配置中的缓存name一致 + this.cache = cacheManager.getCache(ShiroConstants.SYS_USERCACHE); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/captcha/CaptchaValidateFilter.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/captcha/CaptchaValidateFilter.java index 743d27933..331f31a72 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/captcha/CaptchaValidateFilter.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/captcha/CaptchaValidateFilter.java @@ -1,77 +1,69 @@ -package com.ruoyi.framework.shiro.web.filter.captcha; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import org.apache.shiro.web.filter.AccessControlFilter; -import com.google.code.kaptcha.Constants; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.framework.util.ShiroUtils; - -/** - * 验证码过滤器 - * - * @author ruoyi - */ -public class CaptchaValidateFilter extends AccessControlFilter -{ - /** - * 是否开启验证码 - */ - private boolean captchaEnabled = true; - - /** - * 验证码类型 - */ - private String captchaType = "math"; - - public void setCaptchaEnabled(boolean captchaEnabled) - { - this.captchaEnabled = captchaEnabled; - } - - public void setCaptchaType(String captchaType) - { - this.captchaType = captchaType; - } - - @Override - public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception - { - request.setAttribute(ShiroConstants.CURRENT_ENABLED, captchaEnabled); - request.setAttribute(ShiroConstants.CURRENT_TYPE, captchaType); - return super.onPreHandle(request, response, mappedValue); - } - - @Override - protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) - throws Exception - { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - // 验证码禁用 或不是表单提交 允许访问 - if (captchaEnabled == false || !"post".equals(httpServletRequest.getMethod().toLowerCase())) - { - return true; - } - return validateResponse(httpServletRequest, httpServletRequest.getParameter(ShiroConstants.CURRENT_VALIDATECODE)); - } - - public boolean validateResponse(HttpServletRequest request, String validateCode) - { - Object obj = ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); - String code = String.valueOf(obj != null ? obj : ""); - if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code)) - { - return false; - } - return true; - } - - @Override - protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception - { - request.setAttribute(ShiroConstants.CURRENT_CAPTCHA, ShiroConstants.CAPTCHA_ERROR); - return true; - } -} +package com.ruoyi.framework.shiro.web.filter.captcha; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.apache.shiro.web.filter.AccessControlFilter; +import com.google.code.kaptcha.Constants; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.util.ShiroUtils; + +/** + * 验证码过滤器 + * + * @author ruoyi + */ +public class CaptchaValidateFilter extends AccessControlFilter { + /** + * 是否开启验证码 + */ + private boolean captchaEnabled = true; + + /** + * 验证码类型 + */ + private String captchaType = "math"; + + public void setCaptchaEnabled(boolean captchaEnabled) { + this.captchaEnabled = captchaEnabled; + } + + public void setCaptchaType(String captchaType) { + this.captchaType = captchaType; + } + + @Override + public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { + request.setAttribute(ShiroConstants.CURRENT_ENABLED, captchaEnabled); + request.setAttribute(ShiroConstants.CURRENT_TYPE, captchaType); + return super.onPreHandle(request, response, mappedValue); + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) + throws Exception { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + // 验证码禁用 或不是表单提交 允许访问 + if (captchaEnabled == false || !"post".equals(httpServletRequest.getMethod().toLowerCase())) { + return true; + } + return validateResponse(httpServletRequest, httpServletRequest.getParameter(ShiroConstants.CURRENT_VALIDATECODE)); + } + + public boolean validateResponse(HttpServletRequest request, String validateCode) { + Object obj = ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); + String code = String.valueOf(obj != null ? obj : ""); + if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code)) { + return false; + } + return true; + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + request.setAttribute(ShiroConstants.CURRENT_CAPTCHA, ShiroConstants.CAPTCHA_ERROR); + return true; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/kickout/KickoutSessionFilter.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/kickout/KickoutSessionFilter.java index 2c94499e6..84ab47ba1 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/kickout/KickoutSessionFilter.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/kickout/KickoutSessionFilter.java @@ -8,6 +8,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.session.Session; @@ -25,11 +26,10 @@ import com.ruoyi.system.domain.SysUser; /** * 登录帐号控制过滤器 - * + * * @author ruoyi */ -public class KickoutSessionFilter extends AccessControlFilter -{ +public class KickoutSessionFilter extends AccessControlFilter { private final static ObjectMapper objectMapper = new ObjectMapper(); /** @@ -52,22 +52,18 @@ public class KickoutSessionFilter extends AccessControlFilter @Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) - throws Exception - { + throws Exception { return false; } @Override - protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception - { + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); - if (!subject.isAuthenticated() && !subject.isRemembered() || maxSession == -1) - { + if (!subject.isAuthenticated() && !subject.isRemembered() || maxSession == -1) { // 如果没有登录或用户最大会话数为-1,直接进行之后的流程 return true; } - try - { + try { Session session = subject.getSession(); // 当前登录用户 SysUser user = ShiroUtils.getSysUser(); @@ -76,15 +72,13 @@ public class KickoutSessionFilter extends AccessControlFilter // 读取缓存用户 没有就存入 Deque deque = cache.get(loginName); - if (deque == null) - { + if (deque == null) { // 初始化队列 deque = new ArrayDeque(); } // 如果队列里没有此sessionId,且用户没有被踢出;放入队列 - if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) - { + if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) { // 将sessionId存入队列 deque.push(sessionId); // 将用户的sessionId队列缓存 @@ -92,94 +86,74 @@ public class KickoutSessionFilter extends AccessControlFilter } // 如果队列里的sessionId数超出最大会话数,开始踢人 - while (deque.size() > maxSession) - { + while (deque.size() > maxSession) { Serializable kickoutSessionId = null; // 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户; - if (kickoutAfter) - { + if (kickoutAfter) { // 踢出后者 kickoutSessionId = deque.removeFirst(); - } - else - { + } else { // 踢出前者 kickoutSessionId = deque.removeLast(); } // 踢出后再更新下缓存队列 cache.put(loginName, deque); - try - { + try { // 获取被踢出的sessionId的session对象 Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId)); - if (null != kickoutSession) - { + if (null != kickoutSession) { // 设置会话的kickout属性表示踢出了 kickoutSession.setAttribute("kickout", true); } - } - catch (Exception e) - { + } catch (Exception e) { // 面对异常,我们选择忽略 } } // 如果被踢出了,(前者或后者)直接退出,重定向到踢出后的地址 - if ((Boolean) session.getAttribute("kickout") != null && (Boolean) session.getAttribute("kickout") == true) - { + if ((Boolean) session.getAttribute("kickout") != null && (Boolean) session.getAttribute("kickout") == true) { // 退出登录 subject.logout(); saveRequest(request); return isAjaxResponse(request, response); } return true; - } - catch (Exception e) - { + } catch (Exception e) { return isAjaxResponse(request, response); } } - private boolean isAjaxResponse(ServletRequest request, ServletResponse response) throws IOException - { + private boolean isAjaxResponse(ServletRequest request, ServletResponse response) throws IOException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; - if (ServletUtils.isAjaxRequest(req)) - { + if (ServletUtils.isAjaxRequest(req)) { AjaxResult ajaxResult = AjaxResult.error("您已在别处登录,请您修改密码或重新登录"); ServletUtils.renderString(res, objectMapper.writeValueAsString(ajaxResult)); - } - else - { + } else { WebUtils.issueRedirect(request, response, kickoutUrl); } return false; } - public void setMaxSession(int maxSession) - { + public void setMaxSession(int maxSession) { this.maxSession = maxSession; } - public void setKickoutAfter(boolean kickoutAfter) - { + public void setKickoutAfter(boolean kickoutAfter) { this.kickoutAfter = kickoutAfter; } - public void setKickoutUrl(String kickoutUrl) - { + public void setKickoutUrl(String kickoutUrl) { this.kickoutUrl = kickoutUrl; } - public void setSessionManager(SessionManager sessionManager) - { + public void setSessionManager(SessionManager sessionManager) { this.sessionManager = sessionManager; } // 设置Cache的key的前缀 - public void setCacheManager(CacheManager cacheManager) - { + public void setCacheManager(CacheManager cacheManager) { // 必须和ehcache缓存配置中的缓存name一致 this.cache = cacheManager.getCache(ShiroConstants.SYS_USERCACHE); } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/online/OnlineSessionFilter.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/online/OnlineSessionFilter.java index 070d91e82..84b77206b 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/online/OnlineSessionFilter.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/online/OnlineSessionFilter.java @@ -1,96 +1,87 @@ -package com.ruoyi.framework.shiro.web.filter.online; - -import java.io.IOException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import org.apache.shiro.session.Session; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.web.filter.AccessControlFilter; -import org.apache.shiro.web.util.WebUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.enums.OnlineStatus; -import com.ruoyi.framework.shiro.session.OnlineSession; -import com.ruoyi.framework.shiro.session.OnlineSessionDAO; -import com.ruoyi.framework.util.ShiroUtils; -import com.ruoyi.system.domain.SysUser; - -/** - * 自定义访问控制 - * - * @author ruoyi - */ -public class OnlineSessionFilter extends AccessControlFilter -{ - /** - * 强制退出后重定向的地址 - */ - @Value("${shiro.user.loginUrl}") - private String loginUrl; - - @Autowired - private OnlineSessionDAO onlineSessionDAO; - - /** - * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false; - */ - @Override - protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) - throws Exception - { - Subject subject = getSubject(request, response); - if (subject == null || subject.getSession() == null) - { - return true; - } - Session session = onlineSessionDAO.readSession(subject.getSession().getId()); - if (session != null && session instanceof OnlineSession) - { - OnlineSession onlineSession = (OnlineSession) session; - request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession); - // 把user对象设置进去 - boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L; - if (isGuest == true) - { - SysUser user = ShiroUtils.getSysUser(); - if (user != null) - { - onlineSession.setUserId(user.getUserId()); - onlineSession.setLoginName(user.getLoginName()); - onlineSession.setAvatar(user.getAvatar()); - onlineSession.setDeptName(user.getDept().getDeptName()); - onlineSession.markAttributeChanged(); - } - } - - if (onlineSession.getStatus() == OnlineStatus.off_line) - { - return false; - } - } - return true; - } - - /** - * 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。 - */ - @Override - protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception - { - Subject subject = getSubject(request, response); - if (subject != null) - { - subject.logout(); - } - saveRequestAndRedirectToLogin(request, response); - return false; - } - - // 跳转到登录页 - @Override - protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException - { - WebUtils.issueRedirect(request, response, loginUrl); - } -} +package com.ruoyi.framework.shiro.web.filter.online; + +import java.io.IOException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.filter.AccessControlFilter; +import org.apache.shiro.web.util.WebUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.enums.OnlineStatus; +import com.ruoyi.framework.shiro.session.OnlineSession; +import com.ruoyi.framework.shiro.session.OnlineSessionDAO; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; + +/** + * 自定义访问控制 + * + * @author ruoyi + */ +public class OnlineSessionFilter extends AccessControlFilter { + /** + * 强制退出后重定向的地址 + */ + @Value("${shiro.user.loginUrl}") + private String loginUrl; + + @Autowired + private OnlineSessionDAO onlineSessionDAO; + + /** + * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false; + */ + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) + throws Exception { + Subject subject = getSubject(request, response); + if (subject == null || subject.getSession() == null) { + return true; + } + Session session = onlineSessionDAO.readSession(subject.getSession().getId()); + if (session != null && session instanceof OnlineSession) { + OnlineSession onlineSession = (OnlineSession) session; + request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession); + // 把user对象设置进去 + boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L; + if (isGuest == true) { + SysUser user = ShiroUtils.getSysUser(); + if (user != null) { + onlineSession.setUserId(user.getUserId()); + onlineSession.setLoginName(user.getLoginName()); + onlineSession.setAvatar(user.getAvatar()); + onlineSession.setDeptName(user.getDept().getDeptName()); + onlineSession.markAttributeChanged(); + } + } + + if (onlineSession.getStatus() == OnlineStatus.off_line) { + return false; + } + } + return true; + } + + /** + * 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。 + */ + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + Subject subject = getSubject(request, response); + if (subject != null) { + subject.logout(); + } + saveRequestAndRedirectToLogin(request, response); + return false; + } + + // 跳转到登录页 + @Override + protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException { + WebUtils.issueRedirect(request, response, loginUrl); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/sync/SyncOnlineSessionFilter.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/sync/SyncOnlineSessionFilter.java index e1af32d97..01da013b8 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/sync/SyncOnlineSessionFilter.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/sync/SyncOnlineSessionFilter.java @@ -1,36 +1,34 @@ -package com.ruoyi.framework.shiro.web.filter.sync; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import org.apache.shiro.web.filter.PathMatchingFilter; -import org.springframework.beans.factory.annotation.Autowired; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.framework.shiro.session.OnlineSession; -import com.ruoyi.framework.shiro.session.OnlineSessionDAO; - -/** - * 同步Session数据到Db - * - * @author ruoyi - */ -public class SyncOnlineSessionFilter extends PathMatchingFilter -{ - @Autowired - private OnlineSessionDAO onlineSessionDAO; - - /** - * 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前 - */ - @Override - protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception - { - OnlineSession session = (OnlineSession) request.getAttribute(ShiroConstants.ONLINE_SESSION); - // 如果session stop了 也不同步 - // session停止时间,如果stopTimestamp不为null,则代表已停止 - if (session != null && session.getUserId() != null && session.getStopTimestamp() == null) - { - onlineSessionDAO.syncToDb(session); - } - return true; - } -} +package com.ruoyi.framework.shiro.web.filter.sync; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.apache.shiro.web.filter.PathMatchingFilter; +import org.springframework.beans.factory.annotation.Autowired; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.framework.shiro.session.OnlineSession; +import com.ruoyi.framework.shiro.session.OnlineSessionDAO; + +/** + * 同步Session数据到Db + * + * @author ruoyi + */ +public class SyncOnlineSessionFilter extends PathMatchingFilter { + @Autowired + private OnlineSessionDAO onlineSessionDAO; + + /** + * 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前 + */ + @Override + protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { + OnlineSession session = (OnlineSession) request.getAttribute(ShiroConstants.ONLINE_SESSION); + // 如果session stop了 也不同步 + // session停止时间,如果stopTimestamp不为null,则代表已停止 + if (session != null && session.getUserId() != null && session.getStopTimestamp() == null) { + onlineSessionDAO.syncToDb(session); + } + return true; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/OnlineWebSessionManager.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/OnlineWebSessionManager.java index 089806733..b834d602b 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/OnlineWebSessionManager.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/OnlineWebSessionManager.java @@ -1,169 +1,141 @@ -package com.ruoyi.framework.shiro.web.session; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import org.apache.commons.lang3.time.DateUtils; -import org.apache.shiro.session.ExpiredSessionException; -import org.apache.shiro.session.InvalidSessionException; -import org.apache.shiro.session.Session; -import org.apache.shiro.session.mgt.DefaultSessionKey; -import org.apache.shiro.session.mgt.SessionKey; -import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.bean.BeanUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.framework.shiro.session.OnlineSession; -import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.service.ISysUserOnlineService; - -/** - * 主要是在此如果会话的属性修改了 就标识下其修改了 然后方便 OnlineSessionDao同步 - * - * @author ruoyi - */ -public class OnlineWebSessionManager extends DefaultWebSessionManager -{ - private static final Logger log = LoggerFactory.getLogger(OnlineWebSessionManager.class); - - @Override - public void setAttribute(SessionKey sessionKey, Object attributeKey, Object value) throws InvalidSessionException - { - super.setAttribute(sessionKey, attributeKey, value); - if (value != null && needMarkAttributeChanged(attributeKey)) - { - OnlineSession session = getOnlineSession(sessionKey); - session.markAttributeChanged(); - } - } - - private boolean needMarkAttributeChanged(Object attributeKey) - { - if (attributeKey == null) - { - return false; - } - String attributeKeyStr = attributeKey.toString(); - // 优化 flash属性没必要持久化 - if (attributeKeyStr.startsWith("org.springframework")) - { - return false; - } - if (attributeKeyStr.startsWith("javax.servlet")) - { - return false; - } - if (attributeKeyStr.equals(ShiroConstants.CURRENT_USERNAME)) - { - return false; - } - return true; - } - - @Override - public Object removeAttribute(SessionKey sessionKey, Object attributeKey) throws InvalidSessionException - { - Object removed = super.removeAttribute(sessionKey, attributeKey); - if (removed != null) - { - OnlineSession s = getOnlineSession(sessionKey); - s.markAttributeChanged(); - } - - return removed; - } - - public OnlineSession getOnlineSession(SessionKey sessionKey) - { - OnlineSession session = null; - Object obj = doGetSession(sessionKey); - if (StringUtils.isNotNull(obj)) - { - session = new OnlineSession(); - BeanUtils.copyBeanProp(session, obj); - } - return session; - } - - /** - * 验证session是否有效 用于删除过期session - */ - @Override - public void validateSessions() - { - if (log.isInfoEnabled()) - { - log.info("invalidation sessions..."); - } - - int invalidCount = 0; - - int timeout = (int) this.getGlobalSessionTimeout(); - Date expiredDate = DateUtils.addMilliseconds(new Date(), 0 - timeout); - ISysUserOnlineService userOnlineService = SpringUtils.getBean(ISysUserOnlineService.class); - List userOnlineList = userOnlineService.selectOnlineByExpired(expiredDate); - // 批量过期删除 - List needOfflineIdList = new ArrayList(); - for (SysUserOnline userOnline : userOnlineList) - { - try - { - SessionKey key = new DefaultSessionKey(userOnline.getSessionId()); - Session session = retrieveSession(key); - if (session != null) - { - throw new InvalidSessionException(); - } - } - catch (InvalidSessionException e) - { - if (log.isDebugEnabled()) - { - boolean expired = (e instanceof ExpiredSessionException); - String msg = "Invalidated session with id [" + userOnline.getSessionId() + "]" - + (expired ? " (expired)" : " (stopped)"); - log.debug(msg); - } - invalidCount++; - needOfflineIdList.add(userOnline.getSessionId()); - } - - } - if (needOfflineIdList.size() > 0) - { - try - { - userOnlineService.batchDeleteOnline(needOfflineIdList); - } - catch (Exception e) - { - log.error("batch delete db session error.", e); - } - } - - if (log.isInfoEnabled()) - { - String msg = "Finished invalidation session."; - if (invalidCount > 0) - { - msg += " [" + invalidCount + "] sessions were stopped."; - } - else - { - msg += " No sessions were stopped."; - } - log.info(msg); - } - - } - - @Override - protected Collection getActiveSessions() - { - throw new UnsupportedOperationException("getActiveSessions method not supported"); - } -} +package com.ruoyi.framework.shiro.web.session; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang3.time.DateUtils; +import org.apache.shiro.session.ExpiredSessionException; +import org.apache.shiro.session.InvalidSessionException; +import org.apache.shiro.session.Session; +import org.apache.shiro.session.mgt.DefaultSessionKey; +import org.apache.shiro.session.mgt.SessionKey; +import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.bean.BeanUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.framework.shiro.session.OnlineSession; +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.service.ISysUserOnlineService; + +/** + * 主要是在此如果会话的属性修改了 就标识下其修改了 然后方便 OnlineSessionDao同步 + * + * @author ruoyi + */ +public class OnlineWebSessionManager extends DefaultWebSessionManager { + private static final Logger log = LoggerFactory.getLogger(OnlineWebSessionManager.class); + + @Override + public void setAttribute(SessionKey sessionKey, Object attributeKey, Object value) throws InvalidSessionException { + super.setAttribute(sessionKey, attributeKey, value); + if (value != null && needMarkAttributeChanged(attributeKey)) { + OnlineSession session = getOnlineSession(sessionKey); + session.markAttributeChanged(); + } + } + + private boolean needMarkAttributeChanged(Object attributeKey) { + if (attributeKey == null) { + return false; + } + String attributeKeyStr = attributeKey.toString(); + // 优化 flash属性没必要持久化 + if (attributeKeyStr.startsWith("org.springframework")) { + return false; + } + if (attributeKeyStr.startsWith("javax.servlet")) { + return false; + } + if (attributeKeyStr.equals(ShiroConstants.CURRENT_USERNAME)) { + return false; + } + return true; + } + + @Override + public Object removeAttribute(SessionKey sessionKey, Object attributeKey) throws InvalidSessionException { + Object removed = super.removeAttribute(sessionKey, attributeKey); + if (removed != null) { + OnlineSession s = getOnlineSession(sessionKey); + s.markAttributeChanged(); + } + + return removed; + } + + public OnlineSession getOnlineSession(SessionKey sessionKey) { + OnlineSession session = null; + Object obj = doGetSession(sessionKey); + if (StringUtils.isNotNull(obj)) { + session = new OnlineSession(); + BeanUtils.copyBeanProp(session, obj); + } + return session; + } + + /** + * 验证session是否有效 用于删除过期session + */ + @Override + public void validateSessions() { + if (log.isInfoEnabled()) { + log.info("invalidation sessions..."); + } + + int invalidCount = 0; + + int timeout = (int) this.getGlobalSessionTimeout(); + Date expiredDate = DateUtils.addMilliseconds(new Date(), 0 - timeout); + ISysUserOnlineService userOnlineService = SpringUtils.getBean(ISysUserOnlineService.class); + List userOnlineList = userOnlineService.selectOnlineByExpired(expiredDate); + // 批量过期删除 + List needOfflineIdList = new ArrayList(); + for (SysUserOnline userOnline : userOnlineList) { + try { + SessionKey key = new DefaultSessionKey(userOnline.getSessionId()); + Session session = retrieveSession(key); + if (session != null) { + throw new InvalidSessionException(); + } + } catch (InvalidSessionException e) { + if (log.isDebugEnabled()) { + boolean expired = (e instanceof ExpiredSessionException); + String msg = "Invalidated session with id [" + userOnline.getSessionId() + "]" + + (expired ? " (expired)" : " (stopped)"); + log.debug(msg); + } + invalidCount++; + needOfflineIdList.add(userOnline.getSessionId()); + } + + } + if (needOfflineIdList.size() > 0) { + try { + userOnlineService.batchDeleteOnline(needOfflineIdList); + } catch (Exception e) { + log.error("batch delete db session error.", e); + } + } + + if (log.isInfoEnabled()) { + String msg = "Finished invalidation session."; + if (invalidCount > 0) { + msg += " [" + invalidCount + "] sessions were stopped."; + } else { + msg += " No sessions were stopped."; + } + log.info(msg); + } + + } + + @Override + protected Collection getActiveSessions() { + throw new UnsupportedOperationException("getActiveSessions method not supported"); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/SpringSessionValidationScheduler.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/SpringSessionValidationScheduler.java index f5c9d1e6a..cb8a985c7 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/SpringSessionValidationScheduler.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/session/SpringSessionValidationScheduler.java @@ -1,131 +1,116 @@ -package com.ruoyi.framework.shiro.web.session; - -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import org.apache.shiro.session.mgt.DefaultSessionManager; -import org.apache.shiro.session.mgt.SessionValidationScheduler; -import org.apache.shiro.session.mgt.ValidatingSessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Component; -import com.ruoyi.common.utils.Threads; - -/** - * 自定义任务调度器完成 - * - * @author ruoyi - */ -@Component -public class SpringSessionValidationScheduler implements SessionValidationScheduler -{ - private static final Logger log = LoggerFactory.getLogger(SpringSessionValidationScheduler.class); - - public static final long DEFAULT_SESSION_VALIDATION_INTERVAL = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL; - - /** - * 定时器,用于处理超时的挂起请求,也用于连接断开时的重连。 - */ - @Autowired - @Qualifier("scheduledExecutorService") - private ScheduledExecutorService executorService; - - private volatile boolean enabled = false; - - /** - * 会话验证管理器 - */ - @Autowired - @Qualifier("sessionManager") - @Lazy - private ValidatingSessionManager sessionManager; - - // 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟 - @Value("${shiro.session.validationInterval}") - private long sessionValidationInterval; - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - /** - * Specifies how frequently (in milliseconds) this Scheduler will call the - * {@link org.apache.shiro.session.mgt.ValidatingSessionManager#validateSessions() - * ValidatingSessionManager#validateSessions()} method. - * - *

- * Unless this method is called, the default value is {@link #DEFAULT_SESSION_VALIDATION_INTERVAL}. - * - * @param sessionValidationInterval - */ - public void setSessionValidationInterval(long sessionValidationInterval) - { - this.sessionValidationInterval = sessionValidationInterval; - } - - /** - * Starts session validation by creating a spring PeriodicTrigger. - */ - @Override - public void enableSessionValidation() - { - - enabled = true; - - if (log.isDebugEnabled()) - { - log.debug("Scheduling session validation job using Spring Scheduler with " - + "session validation interval of [" + sessionValidationInterval + "]ms..."); - } - - try - { - executorService.scheduleAtFixedRate(new Runnable() - { - @Override - public void run() - { - if (enabled) - { - sessionManager.validateSessions(); - } - } - }, 1000, sessionValidationInterval * 60 * 1000, TimeUnit.MILLISECONDS); - - this.enabled = true; - - if (log.isDebugEnabled()) - { - log.debug("Session validation job successfully scheduled with Spring Scheduler."); - } - - } - catch (Exception e) - { - if (log.isErrorEnabled()) - { - log.error("Error starting the Spring Scheduler session validation job. Session validation may not occur.", e); - } - } - } - - @Override - public void disableSessionValidation() - { - if (log.isDebugEnabled()) - { - log.debug("Stopping Spring Scheduler session validation job..."); - } - - if (this.enabled) - { - Threads.shutdownAndAwaitTermination(executorService); - } - this.enabled = false; - } -} +package com.ruoyi.framework.shiro.web.session; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.apache.shiro.session.mgt.DefaultSessionManager; +import org.apache.shiro.session.mgt.SessionValidationScheduler; +import org.apache.shiro.session.mgt.ValidatingSessionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; +import com.ruoyi.common.utils.Threads; + +/** + * 自定义任务调度器完成 + * + * @author ruoyi + */ +@Component +public class SpringSessionValidationScheduler implements SessionValidationScheduler { + private static final Logger log = LoggerFactory.getLogger(SpringSessionValidationScheduler.class); + + public static final long DEFAULT_SESSION_VALIDATION_INTERVAL = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL; + + /** + * 定时器,用于处理超时的挂起请求,也用于连接断开时的重连。 + */ + @Autowired + @Qualifier("scheduledExecutorService") + private ScheduledExecutorService executorService; + + private volatile boolean enabled = false; + + /** + * 会话验证管理器 + */ + @Autowired + @Qualifier("sessionManager") + @Lazy + private ValidatingSessionManager sessionManager; + + // 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟 + @Value("${shiro.session.validationInterval}") + private long sessionValidationInterval; + + @Override + public boolean isEnabled() { + return this.enabled; + } + + /** + * Specifies how frequently (in milliseconds) this Scheduler will call the + * {@link org.apache.shiro.session.mgt.ValidatingSessionManager#validateSessions() + * ValidatingSessionManager#validateSessions()} method. + * + *

+ * Unless this method is called, the default value is {@link #DEFAULT_SESSION_VALIDATION_INTERVAL}. + * + * @param sessionValidationInterval + */ + public void setSessionValidationInterval(long sessionValidationInterval) { + this.sessionValidationInterval = sessionValidationInterval; + } + + /** + * Starts session validation by creating a spring PeriodicTrigger. + */ + @Override + public void enableSessionValidation() { + + enabled = true; + + if (log.isDebugEnabled()) { + log.debug("Scheduling session validation job using Spring Scheduler with " + + "session validation interval of [" + sessionValidationInterval + "]ms..."); + } + + try { + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + if (enabled) { + sessionManager.validateSessions(); + } + } + }, 1000, sessionValidationInterval * 60 * 1000, TimeUnit.MILLISECONDS); + + this.enabled = true; + + if (log.isDebugEnabled()) { + log.debug("Session validation job successfully scheduled with Spring Scheduler."); + } + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Error starting the Spring Scheduler session validation job. Session validation may not occur.", e); + } + } + } + + @Override + public void disableSessionValidation() { + if (log.isDebugEnabled()) { + log.debug("Stopping Spring Scheduler session validation job..."); + } + + if (this.enabled) { + Threads.shutdownAndAwaitTermination(executorService); + } + this.enabled = false; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/util/LogUtils.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/util/LogUtils.java index 96a38eb55..15763bb60 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/util/LogUtils.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/util/LogUtils.java @@ -1,136 +1,125 @@ -package com.ruoyi.framework.util; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import org.apache.shiro.SecurityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.json.JSON; -import com.ruoyi.common.utils.IpUtils; - -/** - * 处理并记录日志文件 - * - * @author ruoyi - */ -public class LogUtils -{ - public static final Logger ERROR_LOG = LoggerFactory.getLogger("sys-error"); - public static final Logger ACCESS_LOG = LoggerFactory.getLogger("sys-access"); - - /** - * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer] - * - * @param request - * @throws Exception - */ - public static void logAccess(HttpServletRequest request) throws Exception - { - String username = getUsername(); - String jsessionId = request.getRequestedSessionId(); - String ip = IpUtils.getIpAddr(request); - String accept = request.getHeader("accept"); - String userAgent = request.getHeader("User-Agent"); - String url = request.getRequestURI(); - String params = getParams(request); - - StringBuilder s = new StringBuilder(); - s.append(getBlock(username)); - s.append(getBlock(jsessionId)); - s.append(getBlock(ip)); - s.append(getBlock(accept)); - s.append(getBlock(userAgent)); - s.append(getBlock(url)); - s.append(getBlock(params)); - s.append(getBlock(request.getHeader("Referer"))); - getAccessLog().info(s.toString()); - } - - /** - * 记录异常错误 格式 [exception] - * - * @param message - * @param e - */ - public static void logError(String message, Throwable e) - { - String username = getUsername(); - StringBuilder s = new StringBuilder(); - s.append(getBlock("exception")); - s.append(getBlock(username)); - s.append(getBlock(message)); - ERROR_LOG.error(s.toString(), e); - } - - /** - * 记录页面错误 错误日志记录 [page/eception][username][statusCode][errorMessage][servletName][uri][exceptionName][ip][exception] - * - * @param request - */ - public static void logPageError(HttpServletRequest request) - { - String username = getUsername(); - - Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); - String message = (String) request.getAttribute("javax.servlet.error.message"); - String uri = (String) request.getAttribute("javax.servlet.error.request_uri"); - Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception"); - - if (statusCode == null) - { - statusCode = 0; - } - - StringBuilder s = new StringBuilder(); - s.append(getBlock(t == null ? "page" : "exception")); - s.append(getBlock(username)); - s.append(getBlock(statusCode)); - s.append(getBlock(message)); - s.append(getBlock(IpUtils.getIpAddr(request))); - - s.append(getBlock(uri)); - s.append(getBlock(request.getHeader("Referer"))); - StringWriter sw = new StringWriter(); - - while (t != null) - { - t.printStackTrace(new PrintWriter(sw)); - t = t.getCause(); - } - s.append(getBlock(sw.toString())); - getErrorLog().error(s.toString()); - - } - - public static String getBlock(Object msg) - { - if (msg == null) - { - msg = ""; - } - return "[" + msg.toString() + "]"; - } - - protected static String getParams(HttpServletRequest request) throws Exception - { - Map params = request.getParameterMap(); - return JSON.marshal(params); - } - - protected static String getUsername() - { - return (String) SecurityUtils.getSubject().getPrincipal(); - } - - public static Logger getAccessLog() - { - return ACCESS_LOG; - } - - public static Logger getErrorLog() - { - return ERROR_LOG; - } -} +package com.ruoyi.framework.util; + +import com.ruoyi.common.json.JSON; +import com.ruoyi.common.utils.IpUtils; +import org.apache.shiro.SecurityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Map; + +/** + * 处理并记录日志文件 + * + * @author ruoyi + */ +public class LogUtils { + public static final Logger ERROR_LOG = LoggerFactory.getLogger("sys-error"); + public static final Logger ACCESS_LOG = LoggerFactory.getLogger("sys-access"); + + /** + * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer] + * + * @param request + * @throws Exception + */ + public static void logAccess(HttpServletRequest request) throws Exception { + String username = getUsername(); + String jsessionId = request.getRequestedSessionId(); + String ip = IpUtils.getIpAddr(request); + String accept = request.getHeader("accept"); + String userAgent = request.getHeader("User-Agent"); + String url = request.getRequestURI(); + String params = getParams(request); + + StringBuilder s = new StringBuilder(); + s.append(getBlock(username)); + s.append(getBlock(jsessionId)); + s.append(getBlock(ip)); + s.append(getBlock(accept)); + s.append(getBlock(userAgent)); + s.append(getBlock(url)); + s.append(getBlock(params)); + s.append(getBlock(request.getHeader("Referer"))); + getAccessLog().info(s.toString()); + } + + /** + * 记录异常错误 格式 [exception] + * + * @param message + * @param e + */ + public static void logError(String message, Throwable e) { + String username = getUsername(); + StringBuilder s = new StringBuilder(); + s.append(getBlock("exception")); + s.append(getBlock(username)); + s.append(getBlock(message)); + ERROR_LOG.error(s.toString(), e); + } + + /** + * 记录页面错误 错误日志记录 [page/eception][username][statusCode][errorMessage][servletName][uri][exceptionName][ip][exception] + * + * @param request + */ + public static void logPageError(HttpServletRequest request) { + String username = getUsername(); + + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); + String message = (String) request.getAttribute("javax.servlet.error.message"); + String uri = (String) request.getAttribute("javax.servlet.error.request_uri"); + Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception"); + + if (statusCode == null) { + statusCode = 0; + } + + StringBuilder s = new StringBuilder(); + s.append(getBlock(t == null ? "page" : "exception")); + s.append(getBlock(username)); + s.append(getBlock(statusCode)); + s.append(getBlock(message)); + s.append(getBlock(IpUtils.getIpAddr(request))); + + s.append(getBlock(uri)); + s.append(getBlock(request.getHeader("Referer"))); + StringWriter sw = new StringWriter(); + + while (t != null) { + t.printStackTrace(new PrintWriter(sw)); + t = t.getCause(); + } + s.append(getBlock(sw.toString())); + getErrorLog().error(s.toString()); + + } + + public static String getBlock(Object msg) { + if (msg == null) { + msg = ""; + } + return "[" + msg.toString() + "]"; + } + + protected static String getParams(HttpServletRequest request) throws Exception { + Map params = request.getParameterMap(); + return JSON.marshal(params); + } + + protected static String getUsername() { + return (String) SecurityUtils.getSubject().getPrincipal(); + } + + public static Logger getAccessLog() { + return ACCESS_LOG; + } + + public static Logger getErrorLog() { + return ERROR_LOG; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/util/ShiroUtils.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/util/ShiroUtils.java index 05fce47bf..268a25ecd 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/util/ShiroUtils.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/util/ShiroUtils.java @@ -1,96 +1,83 @@ -package com.ruoyi.framework.util; - -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.crypto.SecureRandomNumberGenerator; -import org.apache.shiro.mgt.RealmSecurityManager; -import org.apache.shiro.session.Session; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.subject.PrincipalCollection; -import org.apache.shiro.subject.SimplePrincipalCollection; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.bean.BeanUtils; -import com.ruoyi.framework.shiro.realm.UserRealm; -import com.ruoyi.system.domain.SysUser; - -/** - * shiro 工具类 - * - * @author ruoyi - */ -public class ShiroUtils -{ - public static Subject getSubject() - { - return SecurityUtils.getSubject(); - } - - public static Session getSession() - { - return SecurityUtils.getSubject().getSession(); - } - - public static void logout() - { - getSubject().logout(); - } - - public static SysUser getSysUser() - { - SysUser user = null; - Object obj = getSubject().getPrincipal(); - if (StringUtils.isNotNull(obj)) - { - user = new SysUser(); - BeanUtils.copyBeanProp(user, obj); - } - return user; - } - - public static void setSysUser(SysUser user) - { - Subject subject = getSubject(); - PrincipalCollection principalCollection = subject.getPrincipals(); - String realmName = principalCollection.getRealmNames().iterator().next(); - PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName); - // 重新加载Principal - subject.runAs(newPrincipalCollection); - } - - public static void clearCachedAuthorizationInfo() - { - RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager(); - UserRealm realm = (UserRealm) rsm.getRealms().iterator().next(); - realm.clearCachedAuthorizationInfo(); - } - - public static Long getUserId() - { - return getSysUser().getUserId().longValue(); - } - - public static String getLoginName() - { - return getSysUser().getLoginName(); - } - - public static String getIp() - { - return getSubject().getSession().getHost(); - } - - public static String getSessionId() - { - return String.valueOf(getSubject().getSession().getId()); - } - - /** - * 生成随机盐 - */ - public static String randomSalt() - { - // 一个Byte占两个字节,此处生成的3字节,字符串长度为6 - SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator(); - String hex = secureRandom.nextBytes(3).toHex(); - return hex; - } -} +package com.ruoyi.framework.util; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.crypto.SecureRandomNumberGenerator; +import org.apache.shiro.mgt.RealmSecurityManager; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.subject.PrincipalCollection; +import org.apache.shiro.subject.SimplePrincipalCollection; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.bean.BeanUtils; +import com.ruoyi.framework.shiro.realm.UserRealm; +import com.ruoyi.system.domain.SysUser; + +/** + * shiro 工具类 + * + * @author ruoyi + */ +public class ShiroUtils { + public static Subject getSubject() { + return SecurityUtils.getSubject(); + } + + public static Session getSession() { + return SecurityUtils.getSubject().getSession(); + } + + public static void logout() { + getSubject().logout(); + } + + public static SysUser getSysUser() { + SysUser user = null; + Object obj = getSubject().getPrincipal(); + if (StringUtils.isNotNull(obj)) { + user = new SysUser(); + BeanUtils.copyBeanProp(user, obj); + } + return user; + } + + public static void setSysUser(SysUser user) { + Subject subject = getSubject(); + PrincipalCollection principalCollection = subject.getPrincipals(); + String realmName = principalCollection.getRealmNames().iterator().next(); + PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName); + // 重新加载Principal + subject.runAs(newPrincipalCollection); + } + + public static void clearCachedAuthorizationInfo() { + RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager(); + UserRealm realm = (UserRealm) rsm.getRealms().iterator().next(); + realm.clearCachedAuthorizationInfo(); + } + + public static Long getUserId() { + return getSysUser().getUserId().longValue(); + } + + public static String getLoginName() { + return getSysUser().getLoginName(); + } + + public static String getIp() { + return getSubject().getSession().getHost(); + } + + public static String getSessionId() { + return String.valueOf(getSubject().getSession().getId()); + } + + /** + * 生成随机盐 + */ + public static String randomSalt() { + // 一个Byte占两个字节,此处生成的3字节,字符串长度为6 + SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator(); + String hex = secureRandom.nextBytes(3).toHex(); + return hex; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/Server.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/Server.java index 26aed47db..7171b3bd0 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/Server.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/Server.java @@ -1,241 +1,216 @@ -package com.ruoyi.framework.web.domain; - -import java.net.UnknownHostException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import com.ruoyi.common.utils.Arith; -import com.ruoyi.common.utils.IpUtils; -import com.ruoyi.framework.web.domain.server.Cpu; -import com.ruoyi.framework.web.domain.server.Jvm; -import com.ruoyi.framework.web.domain.server.Mem; -import com.ruoyi.framework.web.domain.server.Sys; -import com.ruoyi.framework.web.domain.server.SysFile; -import oshi.SystemInfo; -import oshi.hardware.CentralProcessor; -import oshi.hardware.CentralProcessor.TickType; -import oshi.hardware.GlobalMemory; -import oshi.hardware.HardwareAbstractionLayer; -import oshi.software.os.FileSystem; -import oshi.software.os.OSFileStore; -import oshi.software.os.OperatingSystem; -import oshi.util.Util; - -/** - * 服务器相关信息 - * - * @author ruoyi - */ -public class Server -{ - - private static final int OSHI_WAIT_SECOND = 1000; - - /** - * CPU相关信息 - */ - private Cpu cpu = new Cpu(); - - /** - * 內存相关信息 - */ - private Mem mem = new Mem(); - - /** - * JVM相关信息 - */ - private Jvm jvm = new Jvm(); - - /** - * 服务器相关信息 - */ - private Sys sys = new Sys(); - - /** - * 磁盘相关信息 - */ - private List sysFiles = new LinkedList(); - - public Cpu getCpu() - { - return cpu; - } - - public void setCpu(Cpu cpu) - { - this.cpu = cpu; - } - - public Mem getMem() - { - return mem; - } - - public void setMem(Mem mem) - { - this.mem = mem; - } - - public Jvm getJvm() - { - return jvm; - } - - public void setJvm(Jvm jvm) - { - this.jvm = jvm; - } - - public Sys getSys() - { - return sys; - } - - public void setSys(Sys sys) - { - this.sys = sys; - } - - public List getSysFiles() - { - return sysFiles; - } - - public void setSysFiles(List sysFiles) - { - this.sysFiles = sysFiles; - } - - public void copyTo() throws Exception - { - SystemInfo si = new SystemInfo(); - HardwareAbstractionLayer hal = si.getHardware(); - - setCpuInfo(hal.getProcessor()); - - setMemInfo(hal.getMemory()); - - setSysInfo(); - - setJvmInfo(); - - setSysFiles(si.getOperatingSystem()); - } - - /** - * 设置CPU信息 - */ - private void setCpuInfo(CentralProcessor processor) - { - // CPU信息 - long[] prevTicks = processor.getSystemCpuLoadTicks(); - Util.sleep(OSHI_WAIT_SECOND); - long[] ticks = processor.getSystemCpuLoadTicks(); - long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; - long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; - long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; - long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; - long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; - long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; - long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; - long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; - long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; - cpu.setCpuNum(processor.getLogicalProcessorCount()); - cpu.setTotal(totalCpu); - cpu.setSys(cSys); - cpu.setUsed(user); - cpu.setWait(iowait); - cpu.setFree(idle); - } - - /** - * 设置内存信息 - */ - private void setMemInfo(GlobalMemory memory) - { - mem.setTotal(memory.getTotal()); - mem.setUsed(memory.getTotal() - memory.getAvailable()); - mem.setFree(memory.getAvailable()); - } - - /** - * 设置服务器信息 - */ - private void setSysInfo() - { - Properties props = System.getProperties(); - sys.setComputerName(IpUtils.getHostName()); - sys.setComputerIp(IpUtils.getHostIp()); - sys.setOsName(props.getProperty("os.name")); - sys.setOsArch(props.getProperty("os.arch")); - sys.setUserDir(props.getProperty("user.dir")); - } - - /** - * 设置Java虚拟机 - */ - private void setJvmInfo() throws UnknownHostException - { - Properties props = System.getProperties(); - jvm.setTotal(Runtime.getRuntime().totalMemory()); - jvm.setMax(Runtime.getRuntime().maxMemory()); - jvm.setFree(Runtime.getRuntime().freeMemory()); - jvm.setVersion(props.getProperty("java.version")); - jvm.setHome(props.getProperty("java.home")); - } - - /** - * 设置磁盘信息 - */ - private void setSysFiles(OperatingSystem os) - { - FileSystem fileSystem = os.getFileSystem(); - OSFileStore[] fsArray = fileSystem.getFileStores(); - for (OSFileStore fs : fsArray) - { - long free = fs.getUsableSpace(); - long total = fs.getTotalSpace(); - long used = total - free; - SysFile sysFile = new SysFile(); - sysFile.setDirName(fs.getMount()); - sysFile.setSysTypeName(fs.getType()); - sysFile.setTypeName(fs.getName()); - sysFile.setTotal(convertFileSize(total)); - sysFile.setFree(convertFileSize(free)); - sysFile.setUsed(convertFileSize(used)); - sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100)); - sysFiles.add(sysFile); - } - } - - /** - * 字节转换 - * - * @param size 字节大小 - * @return 转换后值 - */ - public String convertFileSize(long size) - { - long kb = 1024; - long mb = kb * 1024; - long gb = mb * 1024; - if (size >= gb) - { - return String.format("%.1f GB", (float) size / gb); - } - else if (size >= mb) - { - float f = (float) size / mb; - return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); - } - else if (size >= kb) - { - float f = (float) size / kb; - return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); - } - else - { - return String.format("%d B", size); - } - } -} +package com.ruoyi.framework.web.domain; + +import java.net.UnknownHostException; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import com.ruoyi.common.utils.Arith; +import com.ruoyi.common.utils.IpUtils; +import com.ruoyi.framework.web.domain.server.Cpu; +import com.ruoyi.framework.web.domain.server.Jvm; +import com.ruoyi.framework.web.domain.server.Mem; +import com.ruoyi.framework.web.domain.server.Sys; +import com.ruoyi.framework.web.domain.server.SysFile; +import oshi.SystemInfo; +import oshi.hardware.CentralProcessor; +import oshi.hardware.CentralProcessor.TickType; +import oshi.hardware.GlobalMemory; +import oshi.hardware.HardwareAbstractionLayer; +import oshi.software.os.FileSystem; +import oshi.software.os.OSFileStore; +import oshi.software.os.OperatingSystem; +import oshi.util.Util; + +/** + * 服务器相关信息 + * + * @author ruoyi + */ +public class Server { + + private static final int OSHI_WAIT_SECOND = 1000; + + /** + * CPU相关信息 + */ + private Cpu cpu = new Cpu(); + + /** + * 內存相关信息 + */ + private Mem mem = new Mem(); + + /** + * JVM相关信息 + */ + private Jvm jvm = new Jvm(); + + /** + * 服务器相关信息 + */ + private Sys sys = new Sys(); + + /** + * 磁盘相关信息 + */ + private List sysFiles = new LinkedList(); + + public Cpu getCpu() { + return cpu; + } + + public void setCpu(Cpu cpu) { + this.cpu = cpu; + } + + public Mem getMem() { + return mem; + } + + public void setMem(Mem mem) { + this.mem = mem; + } + + public Jvm getJvm() { + return jvm; + } + + public void setJvm(Jvm jvm) { + this.jvm = jvm; + } + + public Sys getSys() { + return sys; + } + + public void setSys(Sys sys) { + this.sys = sys; + } + + public List getSysFiles() { + return sysFiles; + } + + public void setSysFiles(List sysFiles) { + this.sysFiles = sysFiles; + } + + public void copyTo() throws Exception { + SystemInfo si = new SystemInfo(); + HardwareAbstractionLayer hal = si.getHardware(); + + setCpuInfo(hal.getProcessor()); + + setMemInfo(hal.getMemory()); + + setSysInfo(); + + setJvmInfo(); + + setSysFiles(si.getOperatingSystem()); + } + + /** + * 设置CPU信息 + */ + private void setCpuInfo(CentralProcessor processor) { + // CPU信息 + long[] prevTicks = processor.getSystemCpuLoadTicks(); + Util.sleep(OSHI_WAIT_SECOND); + long[] ticks = processor.getSystemCpuLoadTicks(); + long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; + long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; + long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; + long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; + long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; + long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; + long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; + long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; + long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; + cpu.setCpuNum(processor.getLogicalProcessorCount()); + cpu.setTotal(totalCpu); + cpu.setSys(cSys); + cpu.setUsed(user); + cpu.setWait(iowait); + cpu.setFree(idle); + } + + /** + * 设置内存信息 + */ + private void setMemInfo(GlobalMemory memory) { + mem.setTotal(memory.getTotal()); + mem.setUsed(memory.getTotal() - memory.getAvailable()); + mem.setFree(memory.getAvailable()); + } + + /** + * 设置服务器信息 + */ + private void setSysInfo() { + Properties props = System.getProperties(); + sys.setComputerName(IpUtils.getHostName()); + sys.setComputerIp(IpUtils.getHostIp()); + sys.setOsName(props.getProperty("os.name")); + sys.setOsArch(props.getProperty("os.arch")); + sys.setUserDir(props.getProperty("user.dir")); + } + + /** + * 设置Java虚拟机 + */ + private void setJvmInfo() throws UnknownHostException { + Properties props = System.getProperties(); + jvm.setTotal(Runtime.getRuntime().totalMemory()); + jvm.setMax(Runtime.getRuntime().maxMemory()); + jvm.setFree(Runtime.getRuntime().freeMemory()); + jvm.setVersion(props.getProperty("java.version")); + jvm.setHome(props.getProperty("java.home")); + } + + /** + * 设置磁盘信息 + */ + private void setSysFiles(OperatingSystem os) { + FileSystem fileSystem = os.getFileSystem(); + OSFileStore[] fsArray = fileSystem.getFileStores(); + for (OSFileStore fs : fsArray) { + long free = fs.getUsableSpace(); + long total = fs.getTotalSpace(); + long used = total - free; + SysFile sysFile = new SysFile(); + sysFile.setDirName(fs.getMount()); + sysFile.setSysTypeName(fs.getType()); + sysFile.setTypeName(fs.getName()); + sysFile.setTotal(convertFileSize(total)); + sysFile.setFree(convertFileSize(free)); + sysFile.setUsed(convertFileSize(used)); + sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100)); + sysFiles.add(sysFile); + } + } + + /** + * 字节转换 + * + * @param size 字节大小 + * @return 转换后值 + */ + public String convertFileSize(long size) { + long kb = 1024; + long mb = kb * 1024; + long gb = mb * 1024; + if (size >= gb) { + return String.format("%.1f GB", (float) size / gb); + } else if (size >= mb) { + float f = (float) size / mb; + return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); + } else if (size >= kb) { + float f = (float) size / kb; + return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); + } else { + return String.format("%d B", size); + } + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java index cf7b46e1e..4878bbd35 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java @@ -1,101 +1,88 @@ -package com.ruoyi.framework.web.domain.server; - -import com.ruoyi.common.utils.Arith; - -/** - * CPU相关信息 - * - * @author ruoyi - */ -public class Cpu -{ - /** - * 核心数 - */ - private int cpuNum; - - /** - * CPU总的使用率 - */ - private double total; - - /** - * CPU系统使用率 - */ - private double sys; - - /** - * CPU用户使用率 - */ - private double used; - - /** - * CPU当前等待率 - */ - private double wait; - - /** - * CPU当前空闲率 - */ - private double free; - - public int getCpuNum() - { - return cpuNum; - } - - public void setCpuNum(int cpuNum) - { - this.cpuNum = cpuNum; - } - - public double getTotal() - { - return Arith.round(Arith.mul(total, 100), 2); - } - - public void setTotal(double total) - { - this.total = total; - } - - public double getSys() - { - return Arith.round(Arith.mul(sys / total, 100), 2); - } - - public void setSys(double sys) - { - this.sys = sys; - } - - public double getUsed() - { - return Arith.round(Arith.mul(used / total, 100), 2); - } - - public void setUsed(double used) - { - this.used = used; - } - - public double getWait() - { - return Arith.round(Arith.mul(wait / total, 100), 2); - } - - public void setWait(double wait) - { - this.wait = wait; - } - - public double getFree() - { - return Arith.round(Arith.mul(free / total, 100), 2); - } - - public void setFree(double free) - { - this.free = free; - } -} +package com.ruoyi.framework.web.domain.server; + +import com.ruoyi.common.utils.Arith; + +/** + * CPU相关信息 + * + * @author ruoyi + */ +public class Cpu { + /** + * 核心数 + */ + private int cpuNum; + + /** + * CPU总的使用率 + */ + private double total; + + /** + * CPU系统使用率 + */ + private double sys; + + /** + * CPU用户使用率 + */ + private double used; + + /** + * CPU当前等待率 + */ + private double wait; + + /** + * CPU当前空闲率 + */ + private double free; + + public int getCpuNum() { + return cpuNum; + } + + public void setCpuNum(int cpuNum) { + this.cpuNum = cpuNum; + } + + public double getTotal() { + return Arith.round(Arith.mul(total, 100), 2); + } + + public void setTotal(double total) { + this.total = total; + } + + public double getSys() { + return Arith.round(Arith.mul(sys / total, 100), 2); + } + + public void setSys(double sys) { + this.sys = sys; + } + + public double getUsed() { + return Arith.round(Arith.mul(used / total, 100), 2); + } + + public void setUsed(double used) { + this.used = used; + } + + public double getWait() { + return Arith.round(Arith.mul(wait / total, 100), 2); + } + + public void setWait(double wait) { + this.wait = wait; + } + + public double getFree() { + return Arith.round(Arith.mul(free / total, 100), 2); + } + + public void setFree(double free) { + this.free = free; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Jvm.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Jvm.java index f29d2cbe6..62d043b11 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Jvm.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Jvm.java @@ -1,122 +1,107 @@ -package com.ruoyi.framework.web.domain.server; - -import java.lang.management.ManagementFactory; -import com.ruoyi.common.utils.Arith; -import com.ruoyi.common.utils.DateUtils; - -/** - * JVM相关信息 - * - * @author ruoyi - */ -public class Jvm -{ - /** - * 当前JVM占用的内存总数(M) - */ - private double total; - - /** - * JVM最大可用内存总数(M) - */ - private double max; - - /** - * JVM空闲内存(M) - */ - private double free; - - /** - * JDK版本 - */ - private String version; - - /** - * JDK路径 - */ - private String home; - - public double getTotal() - { - return Arith.div(total, (1024 * 1024), 2); - } - - public void setTotal(double total) - { - this.total = total; - } - - public double getMax() - { - return Arith.div(max, (1024 * 1024), 2); - } - - public void setMax(double max) - { - this.max = max; - } - - public double getFree() - { - return Arith.div(free, (1024 * 1024), 2); - } - - public void setFree(double free) - { - this.free = free; - } - - public double getUsed() - { - return Arith.div(total - free, (1024 * 1024), 2); - } - - public double getUsage() - { - return Arith.mul(Arith.div(total - free, total, 4), 100); - } - - /** - * 获取JDK名称 - */ - public String getName() - { - return ManagementFactory.getRuntimeMXBean().getVmName(); - } - - public String getVersion() - { - return version; - } - - public void setVersion(String version) - { - this.version = version; - } - - public String getHome() - { - return home; - } - - public void setHome(String home) - { - this.home = home; - } - - /** - * JDK启动时间 - */ - public String getStartTime() - { - return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate()); - } - - /** - * JDK运行时间 - */ - public String getRunTime() - { - return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate()); - } -} +package com.ruoyi.framework.web.domain.server; + +import java.lang.management.ManagementFactory; + +import com.ruoyi.common.utils.Arith; +import com.ruoyi.common.utils.DateUtils; + +/** + * JVM相关信息 + * + * @author ruoyi + */ +public class Jvm { + /** + * 当前JVM占用的内存总数(M) + */ + private double total; + + /** + * JVM最大可用内存总数(M) + */ + private double max; + + /** + * JVM空闲内存(M) + */ + private double free; + + /** + * JDK版本 + */ + private String version; + + /** + * JDK路径 + */ + private String home; + + public double getTotal() { + return Arith.div(total, (1024 * 1024), 2); + } + + public void setTotal(double total) { + this.total = total; + } + + public double getMax() { + return Arith.div(max, (1024 * 1024), 2); + } + + public void setMax(double max) { + this.max = max; + } + + public double getFree() { + return Arith.div(free, (1024 * 1024), 2); + } + + public void setFree(double free) { + this.free = free; + } + + public double getUsed() { + return Arith.div(total - free, (1024 * 1024), 2); + } + + public double getUsage() { + return Arith.mul(Arith.div(total - free, total, 4), 100); + } + + /** + * 获取JDK名称 + */ + public String getName() { + return ManagementFactory.getRuntimeMXBean().getVmName(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getHome() { + return home; + } + + public void setHome(String home) { + this.home = home; + } + + /** + * JDK启动时间 + */ + public String getStartTime() { + return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate()); + } + + /** + * JDK运行时间 + */ + public String getRunTime() { + return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate()); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Mem.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Mem.java index ac715049a..f065d819a 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Mem.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Mem.java @@ -1,61 +1,53 @@ -package com.ruoyi.framework.web.domain.server; - -import com.ruoyi.common.utils.Arith; - -/** - * 內存相关信息 - * - * @author ruoyi - */ -public class Mem -{ - /** - * 内存总量 - */ - private double total; - - /** - * 已用内存 - */ - private double used; - - /** - * 剩余内存 - */ - private double free; - - public double getTotal() - { - return Arith.div(total, (1024 * 1024 * 1024), 2); - } - - public void setTotal(long total) - { - this.total = total; - } - - public double getUsed() - { - return Arith.div(used, (1024 * 1024 * 1024), 2); - } - - public void setUsed(long used) - { - this.used = used; - } - - public double getFree() - { - return Arith.div(free, (1024 * 1024 * 1024), 2); - } - - public void setFree(long free) - { - this.free = free; - } - - public double getUsage() - { - return Arith.mul(Arith.div(used, total, 4), 100); - } -} +package com.ruoyi.framework.web.domain.server; + +import com.ruoyi.common.utils.Arith; + +/** + * 內存相关信息 + * + * @author ruoyi + */ +public class Mem { + /** + * 内存总量 + */ + private double total; + + /** + * 已用内存 + */ + private double used; + + /** + * 剩余内存 + */ + private double free; + + public double getTotal() { + return Arith.div(total, (1024 * 1024 * 1024), 2); + } + + public void setTotal(long total) { + this.total = total; + } + + public double getUsed() { + return Arith.div(used, (1024 * 1024 * 1024), 2); + } + + public void setUsed(long used) { + this.used = used; + } + + public double getFree() { + return Arith.div(free, (1024 * 1024 * 1024), 2); + } + + public void setFree(long free) { + this.free = free; + } + + public double getUsage() { + return Arith.mul(Arith.div(used, total, 4), 100); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Sys.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Sys.java index a5f65e46e..7c3857eee 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Sys.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/Sys.java @@ -1,84 +1,73 @@ -package com.ruoyi.framework.web.domain.server; - -/** - * 系统相关信息 - * - * @author ruoyi - */ -public class Sys -{ - /** - * 服务器名称 - */ - private String computerName; - - /** - * 服务器Ip - */ - private String computerIp; - - /** - * 项目路径 - */ - private String userDir; - - /** - * 操作系统 - */ - private String osName; - - /** - * 系统架构 - */ - private String osArch; - - public String getComputerName() - { - return computerName; - } - - public void setComputerName(String computerName) - { - this.computerName = computerName; - } - - public String getComputerIp() - { - return computerIp; - } - - public void setComputerIp(String computerIp) - { - this.computerIp = computerIp; - } - - public String getUserDir() - { - return userDir; - } - - public void setUserDir(String userDir) - { - this.userDir = userDir; - } - - public String getOsName() - { - return osName; - } - - public void setOsName(String osName) - { - this.osName = osName; - } - - public String getOsArch() - { - return osArch; - } - - public void setOsArch(String osArch) - { - this.osArch = osArch; - } -} +package com.ruoyi.framework.web.domain.server; + +/** + * 系统相关信息 + * + * @author ruoyi + */ +public class Sys { + /** + * 服务器名称 + */ + private String computerName; + + /** + * 服务器Ip + */ + private String computerIp; + + /** + * 项目路径 + */ + private String userDir; + + /** + * 操作系统 + */ + private String osName; + + /** + * 系统架构 + */ + private String osArch; + + public String getComputerName() { + return computerName; + } + + public void setComputerName(String computerName) { + this.computerName = computerName; + } + + public String getComputerIp() { + return computerIp; + } + + public void setComputerIp(String computerIp) { + this.computerIp = computerIp; + } + + public String getUserDir() { + return userDir; + } + + public void setUserDir(String userDir) { + this.userDir = userDir; + } + + public String getOsName() { + return osName; + } + + public void setOsName(String osName) { + this.osName = osName; + } + + public String getOsArch() { + return osArch; + } + + public void setOsArch(String osArch) { + this.osArch = osArch; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/SysFile.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/SysFile.java index 47ecf3f3e..0c4710a65 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/SysFile.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/domain/server/SysFile.java @@ -1,114 +1,99 @@ -package com.ruoyi.framework.web.domain.server; - -/** - * 系统文件相关信息 - * - * @author ruoyi - */ -public class SysFile -{ - /** - * 盘符路径 - */ - private String dirName; - - /** - * 盘符类型 - */ - private String sysTypeName; - - /** - * 文件类型 - */ - private String typeName; - - /** - * 总大小 - */ - private String total; - - /** - * 剩余大小 - */ - private String free; - - /** - * 已经使用量 - */ - private String used; - - /** - * 资源的使用率 - */ - private double usage; - - public String getDirName() - { - return dirName; - } - - public void setDirName(String dirName) - { - this.dirName = dirName; - } - - public String getSysTypeName() - { - return sysTypeName; - } - - public void setSysTypeName(String sysTypeName) - { - this.sysTypeName = sysTypeName; - } - - public String getTypeName() - { - return typeName; - } - - public void setTypeName(String typeName) - { - this.typeName = typeName; - } - - public String getTotal() - { - return total; - } - - public void setTotal(String total) - { - this.total = total; - } - - public String getFree() - { - return free; - } - - public void setFree(String free) - { - this.free = free; - } - - public String getUsed() - { - return used; - } - - public void setUsed(String used) - { - this.used = used; - } - - public double getUsage() - { - return usage; - } - - public void setUsage(double usage) - { - this.usage = usage; - } -} +package com.ruoyi.framework.web.domain.server; + +/** + * 系统文件相关信息 + * + * @author ruoyi + */ +public class SysFile { + /** + * 盘符路径 + */ + private String dirName; + + /** + * 盘符类型 + */ + private String sysTypeName; + + /** + * 文件类型 + */ + private String typeName; + + /** + * 总大小 + */ + private String total; + + /** + * 剩余大小 + */ + private String free; + + /** + * 已经使用量 + */ + private String used; + + /** + * 资源的使用率 + */ + private double usage; + + public String getDirName() { + return dirName; + } + + public void setDirName(String dirName) { + this.dirName = dirName; + } + + public String getSysTypeName() { + return sysTypeName; + } + + public void setSysTypeName(String sysTypeName) { + this.sysTypeName = sysTypeName; + } + + public String getTypeName() { + return typeName; + } + + public void setTypeName(String typeName) { + this.typeName = typeName; + } + + public String getTotal() { + return total; + } + + public void setTotal(String total) { + this.total = total; + } + + public String getFree() { + return free; + } + + public void setFree(String free) { + this.free = free; + } + + public String getUsed() { + return used; + } + + public void setUsed(String used) { + this.used = used; + } + + public double getUsage() { + return usage; + } + + public void setUsage(double usage) { + this.usage = usage; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java index 2ff357743..12b43fe5f 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java @@ -1,6 +1,7 @@ package com.ruoyi.framework.web.exception; import javax.servlet.http.HttpServletRequest; + import org.apache.shiro.authz.AuthorizationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,27 +18,22 @@ import com.ruoyi.common.utils.security.PermissionUtils; /** * 全局异常处理器 - * + * * @author ruoyi */ @RestControllerAdvice -public class GlobalExceptionHandler -{ +public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 权限校验失败 如果请求为ajax返回json,普通请求跳转页面 */ @ExceptionHandler(AuthorizationException.class) - public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) - { + public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) { log.error(e.getMessage(), e); - if (ServletUtils.isAjaxRequest(request)) - { + if (ServletUtils.isAjaxRequest(request)) { return AjaxResult.error(PermissionUtils.getMsg(e.getMessage())); - } - else - { + } else { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error/unauth"); return modelAndView; @@ -47,9 +43,8 @@ public class GlobalExceptionHandler /** * 请求方式不支持 */ - @ExceptionHandler({ HttpRequestMethodNotSupportedException.class }) - public AjaxResult handleException(HttpRequestMethodNotSupportedException e) - { + @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) + public AjaxResult handleException(HttpRequestMethodNotSupportedException e) { log.error(e.getMessage(), e); return AjaxResult.error("不支持' " + e.getMethod() + "'请求"); } @@ -58,8 +53,7 @@ public class GlobalExceptionHandler * 拦截未知的运行时异常 */ @ExceptionHandler(RuntimeException.class) - public AjaxResult notFount(RuntimeException e) - { + public AjaxResult notFount(RuntimeException e) { log.error("运行时异常:", e); return AjaxResult.error("运行时异常:" + e.getMessage()); } @@ -68,8 +62,7 @@ public class GlobalExceptionHandler * 系统异常 */ @ExceptionHandler(Exception.class) - public AjaxResult handleException(Exception e) - { + public AjaxResult handleException(Exception e) { log.error(e.getMessage(), e); return AjaxResult.error("服务器错误,请联系管理员"); } @@ -78,15 +71,11 @@ public class GlobalExceptionHandler * 业务异常 */ @ExceptionHandler(BusinessException.class) - public Object businessException(HttpServletRequest request, BusinessException e) - { + public Object businessException(HttpServletRequest request, BusinessException e) { log.error(e.getMessage(), e); - if (ServletUtils.isAjaxRequest(request)) - { + if (ServletUtils.isAjaxRequest(request)) { return AjaxResult.error(e.getMessage()); - } - else - { + } else { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMessage", e.getMessage()); modelAndView.setViewName("error/business"); @@ -98,8 +87,7 @@ public class GlobalExceptionHandler * 自定义验证异常 */ @ExceptionHandler(BindException.class) - public AjaxResult validatedBindException(BindException e) - { + public AjaxResult validatedBindException(BindException e) { log.error(e.getMessage(), e); String message = e.getAllErrors().get(0).getDefaultMessage(); return AjaxResult.error(message); @@ -109,8 +97,7 @@ public class GlobalExceptionHandler * 演示模式异常 */ @ExceptionHandler(DemoModeException.class) - public AjaxResult demoModeException(DemoModeException e) - { + public AjaxResult demoModeException(DemoModeException e) { return AjaxResult.error("演示模式,不允许操作"); } } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/ConfigService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/ConfigService.java index 5ee1b3d8c..2a0d66645 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/ConfigService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/ConfigService.java @@ -1,28 +1,26 @@ -package com.ruoyi.framework.web.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.system.service.ISysConfigService; - -/** - * RuoYi首创 html调用 thymeleaf 实现参数管理 - * - * @author ruoyi - */ -@Service("config") -public class ConfigService -{ - @Autowired - private ISysConfigService configService; - - /** - * 根据键名查询参数配置信息 - * - * @param configName 参数名称 - * @return 参数键值 - */ - public String getKey(String configKey) - { - return configService.selectConfigByKey(configKey); - } -} +package com.ruoyi.framework.web.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.system.service.ISysConfigService; + +/** + * RuoYi首创 html调用 thymeleaf 实现参数管理 + * + * @author ruoyi + */ +@Service("config") +public class ConfigService { + @Autowired + private ISysConfigService configService; + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数名称 + * @return 参数键值 + */ + public String getKey(String configKey) { + return configService.selectConfigByKey(configKey); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/DictService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/DictService.java index 64e7c8a0e..d006c8f74 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/DictService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/DictService.java @@ -1,42 +1,40 @@ -package com.ruoyi.framework.web.service; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.system.domain.SysDictData; -import com.ruoyi.system.service.ISysDictDataService; - -/** - * RuoYi首创 html调用 thymeleaf 实现字典读取 - * - * @author ruoyi - */ -@Service("dict") -public class DictService -{ - @Autowired - private ISysDictDataService dictDataService; - - /** - * 根据字典类型查询字典数据信息 - * - * @param dictType 字典类型 - * @return 参数键值 - */ - public List getType(String dictType) - { - return dictDataService.selectDictDataByType(dictType); - } - - /** - * 根据字典类型和字典键值查询字典数据信息 - * - * @param dictType 字典类型 - * @param dictValue 字典键值 - * @return 字典标签 - */ - public String getLabel(String dictType, String dictValue) - { - return dictDataService.selectDictLabel(dictType, dictValue); - } -} +package com.ruoyi.framework.web.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.system.domain.SysDictData; +import com.ruoyi.system.service.ISysDictDataService; + +/** + * RuoYi首创 html调用 thymeleaf 实现字典读取 + * + * @author ruoyi + */ +@Service("dict") +public class DictService { + @Autowired + private ISysDictDataService dictDataService; + + /** + * 根据字典类型查询字典数据信息 + * + * @param dictType 字典类型 + * @return 参数键值 + */ + public List getType(String dictType) { + return dictDataService.selectDictDataByType(dictType); + } + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + public String getLabel(String dictType, String dictValue) { + return dictDataService.selectDictLabel(dictType, dictValue); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java index 405e0325c..7da29680c 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java @@ -1,262 +1,234 @@ -package com.ruoyi.framework.web.service; - -import java.beans.BeanInfo; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.subject.Subject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import com.ruoyi.common.utils.StringUtils; - -/** - * RuoYi首创 js调用 thymeleaf 实现按钮权限可见性 - * - * @author ruoyi - */ -@Service("permission") -public class PermissionService -{ - private static final Logger log = LoggerFactory.getLogger(PermissionService.class); - - /** 没有权限,hidden用于前端隐藏按钮 */ - public static final String NOACCESS = "hidden"; - - private static final String ROLE_DELIMETER = ","; - - private static final String PERMISSION_DELIMETER = ","; - - /** - * 验证用户是否具备某权限,无权限返回hidden用于前端隐藏(如需返回Boolean使用isPermitted) - * - * @param permission 权限字符串 - * @return 用户是否具备某权限 - */ - public String hasPermi(String permission) - { - return isPermitted(permission) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否不具备某权限,与 hasPermi逻辑相反。无权限返回hidden用于前端隐藏(如需返回Boolean使用isLacksPermitted) - * - * @param permission 权限字符串 - * @return 用户是否不具备某权限 - */ - public String lacksPermi(String permission) - { - return isLacksPermitted(permission) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否具有以下任意一个权限,无权限返回hidden用于隐藏(如需返回Boolean使用hasAnyPermissions) - * - * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 - * @return 用户是否具有以下任意一个权限 - */ - public String hasAnyPermi(String permissions) - { - return hasAnyPermissions(permissions, PERMISSION_DELIMETER) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否具备某角色,无权限返回hidden用于隐藏(如需返回Boolean使用isRole) - * - * @param role 角色字符串 - * @return 用户是否具备某角色 - */ - public String hasRole(String role) - { - return isRole(role) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否不具备某角色,与hasRole逻辑相反。无权限返回hidden用于隐藏(如需返回Boolean使用isLacksRole) - * - * @param role 角色字符串 - * @return 用户是否不具备某角色 - */ - public String lacksRole(String role) - { - return isLacksRole(role) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否具有以下任意一个角色,无权限返回hidden用于隐藏(如需返回Boolean使用isAnyRoles) - * - * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 - * @return 用户是否具有以下任意一个角色 - */ - public String hasAnyRoles(String roles) - { - return isAnyRoles(roles, ROLE_DELIMETER) ? StringUtils.EMPTY : NOACCESS; - } - - /** - * 验证用户是否认证通过或已记住的用户。 - * - * @return 用户是否认证通过或已记住的用户 - */ - public boolean isUser() - { - Subject subject = SecurityUtils.getSubject(); - return subject != null && subject.getPrincipal() != null; - } - - /** - * 判断用户是否拥有某个权限 - * - * @param permission 权限字符串 - * @return 用户是否具备某权限 - */ - public boolean isPermitted(String permission) - { - return SecurityUtils.getSubject().isPermitted(permission); - } - - /** - * 判断用户是否不具备某权限,与 isPermitted逻辑相反。 - * - * @param permission 权限名称 - * @return 用户是否不具备某权限 - */ - public boolean isLacksPermitted(String permission) - { - return isPermitted(permission) != true; - } - - /** - * 验证用户是否具有以下任意一个权限。 - * - * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 - * @return 用户是否具有以下任意一个权限 - */ - public boolean hasAnyPermissions(String permissions) - { - return hasAnyPermissions(permissions, PERMISSION_DELIMETER); - } - - /** - * 验证用户是否具有以下任意一个权限。 - * - * @param permissions 以 delimeter 为分隔符的权限列表 - * @param delimeter 权限列表分隔符 - * @return 用户是否具有以下任意一个权限 - */ - public boolean hasAnyPermissions(String permissions, String delimeter) - { - Subject subject = SecurityUtils.getSubject(); - - if (subject != null) - { - if (delimeter == null || delimeter.length() == 0) - { - delimeter = PERMISSION_DELIMETER; - } - - for (String permission : permissions.split(delimeter)) - { - if (permission != null && subject.isPermitted(permission.trim()) == true) - { - return true; - } - } - } - - return false; - } - - /** - * 判断用户是否拥有某个角色 - * - * @param role 角色字符串 - * @return 用户是否具备某角色 - */ - public boolean isRole(String role) - { - return SecurityUtils.getSubject().hasRole(role); - } - - /** - * 验证用户是否不具备某角色,与 isRole逻辑相反。 - * - * @param role 角色名称 - * @return 用户是否不具备某角色 - */ - public boolean isLacksRole(String role) - { - return isRole(role) != true; - } - - /** - * 验证用户是否具有以下任意一个角色。 - * - * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 - * @return 用户是否具有以下任意一个角色 - */ - public boolean isAnyRoles(String roles) - { - return isAnyRoles(roles, ROLE_DELIMETER); - } - - /** - * 验证用户是否具有以下任意一个角色。 - * - * @param roles 以 delimeter 为分隔符的角色列表 - * @param delimeter 角色列表分隔符 - * @return 用户是否具有以下任意一个角色 - */ - public boolean isAnyRoles(String roles, String delimeter) - { - Subject subject = SecurityUtils.getSubject(); - if (subject != null) - { - if (delimeter == null || delimeter.length() == 0) - { - delimeter = ROLE_DELIMETER; - } - - for (String role : roles.split(delimeter)) - { - if (subject.hasRole(role.trim()) == true) - { - return true; - } - } - } - - return false; - } - - /** - * 返回用户属性值 - * - * @param property 属性名称 - * @return 用户属性值 - */ - public Object getPrincipalProperty(String property) - { - Subject subject = SecurityUtils.getSubject(); - if (subject != null) - { - Object principal = subject.getPrincipal(); - try - { - BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); - for (PropertyDescriptor pd : bi.getPropertyDescriptors()) - { - if (pd.getName().equals(property) == true) - { - return pd.getReadMethod().invoke(principal, (Object[]) null); - } - } - } - catch (Exception e) - { - log.error("Error reading property [{}] from principal of type [{}]", property, principal.getClass().getName()); - } - } - return null; - } -} +package com.ruoyi.framework.web.service; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import com.ruoyi.common.utils.StringUtils; + +/** + * RuoYi首创 js调用 thymeleaf 实现按钮权限可见性 + * + * @author ruoyi + */ +@Service("permission") +public class PermissionService { + private static final Logger log = LoggerFactory.getLogger(PermissionService.class); + + /** + * 没有权限,hidden用于前端隐藏按钮 + */ + public static final String NOACCESS = "hidden"; + + private static final String ROLE_DELIMETER = ","; + + private static final String PERMISSION_DELIMETER = ","; + + /** + * 验证用户是否具备某权限,无权限返回hidden用于前端隐藏(如需返回Boolean使用isPermitted) + * + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + public String hasPermi(String permission) { + return isPermitted(permission) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否不具备某权限,与 hasPermi逻辑相反。无权限返回hidden用于前端隐藏(如需返回Boolean使用isLacksPermitted) + * + * @param permission 权限字符串 + * @return 用户是否不具备某权限 + */ + public String lacksPermi(String permission) { + return isLacksPermitted(permission) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否具有以下任意一个权限,无权限返回hidden用于隐藏(如需返回Boolean使用hasAnyPermissions) + * + * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 + * @return 用户是否具有以下任意一个权限 + */ + public String hasAnyPermi(String permissions) { + return hasAnyPermissions(permissions, PERMISSION_DELIMETER) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否具备某角色,无权限返回hidden用于隐藏(如需返回Boolean使用isRole) + * + * @param role 角色字符串 + * @return 用户是否具备某角色 + */ + public String hasRole(String role) { + return isRole(role) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否不具备某角色,与hasRole逻辑相反。无权限返回hidden用于隐藏(如需返回Boolean使用isLacksRole) + * + * @param role 角色字符串 + * @return 用户是否不具备某角色 + */ + public String lacksRole(String role) { + return isLacksRole(role) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否具有以下任意一个角色,无权限返回hidden用于隐藏(如需返回Boolean使用isAnyRoles) + * + * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 + * @return 用户是否具有以下任意一个角色 + */ + public String hasAnyRoles(String roles) { + return isAnyRoles(roles, ROLE_DELIMETER) ? StringUtils.EMPTY : NOACCESS; + } + + /** + * 验证用户是否认证通过或已记住的用户。 + * + * @return 用户是否认证通过或已记住的用户 + */ + public boolean isUser() { + Subject subject = SecurityUtils.getSubject(); + return subject != null && subject.getPrincipal() != null; + } + + /** + * 判断用户是否拥有某个权限 + * + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + public boolean isPermitted(String permission) { + return SecurityUtils.getSubject().isPermitted(permission); + } + + /** + * 判断用户是否不具备某权限,与 isPermitted逻辑相反。 + * + * @param permission 权限名称 + * @return 用户是否不具备某权限 + */ + public boolean isLacksPermitted(String permission) { + return isPermitted(permission) != true; + } + + /** + * 验证用户是否具有以下任意一个权限。 + * + * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 + * @return 用户是否具有以下任意一个权限 + */ + public boolean hasAnyPermissions(String permissions) { + return hasAnyPermissions(permissions, PERMISSION_DELIMETER); + } + + /** + * 验证用户是否具有以下任意一个权限。 + * + * @param permissions 以 delimeter 为分隔符的权限列表 + * @param delimeter 权限列表分隔符 + * @return 用户是否具有以下任意一个权限 + */ + public boolean hasAnyPermissions(String permissions, String delimeter) { + Subject subject = SecurityUtils.getSubject(); + + if (subject != null) { + if (delimeter == null || delimeter.length() == 0) { + delimeter = PERMISSION_DELIMETER; + } + + for (String permission : permissions.split(delimeter)) { + if (permission != null && subject.isPermitted(permission.trim()) == true) { + return true; + } + } + } + + return false; + } + + /** + * 判断用户是否拥有某个角色 + * + * @param role 角色字符串 + * @return 用户是否具备某角色 + */ + public boolean isRole(String role) { + return SecurityUtils.getSubject().hasRole(role); + } + + /** + * 验证用户是否不具备某角色,与 isRole逻辑相反。 + * + * @param role 角色名称 + * @return 用户是否不具备某角色 + */ + public boolean isLacksRole(String role) { + return isRole(role) != true; + } + + /** + * 验证用户是否具有以下任意一个角色。 + * + * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 + * @return 用户是否具有以下任意一个角色 + */ + public boolean isAnyRoles(String roles) { + return isAnyRoles(roles, ROLE_DELIMETER); + } + + /** + * 验证用户是否具有以下任意一个角色。 + * + * @param roles 以 delimeter 为分隔符的角色列表 + * @param delimeter 角色列表分隔符 + * @return 用户是否具有以下任意一个角色 + */ + public boolean isAnyRoles(String roles, String delimeter) { + Subject subject = SecurityUtils.getSubject(); + if (subject != null) { + if (delimeter == null || delimeter.length() == 0) { + delimeter = ROLE_DELIMETER; + } + + for (String role : roles.split(delimeter)) { + if (subject.hasRole(role.trim()) == true) { + return true; + } + } + } + + return false; + } + + /** + * 返回用户属性值 + * + * @param property 属性名称 + * @return 用户属性值 + */ + public Object getPrincipalProperty(String property) { + Subject subject = SecurityUtils.getSubject(); + if (subject != null) { + Object principal = subject.getPrincipal(); + try { + BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); + for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { + if (pd.getName().equals(property) == true) { + return pd.getReadMethod().invoke(principal, (Object[]) null); + } + } + } catch (Exception e) { + log.error("Error reading property [{}] from principal of type [{}]", property, principal.getClass().getName()); + } + } + return null; + } +} From 8b81b9cd1445a7a75f606864d1149c42ac4c0f2e Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:20:27 +0800 Subject: [PATCH 06/52] format code --- .../com/ruoyi/generator/config/GenConfig.java | 145 ++-- .../generator/controller/GenController.java | 45 +- .../com/ruoyi/generator/domain/GenTable.java | 529 +++++++------ .../generator/domain/GenTableColumn.java | 710 +++++++++--------- .../mapper/GenTableColumnMapper.java | 102 +-- .../generator/mapper/GenTableMapper.java | 150 ++-- .../service/IGenTableColumnService.java | 88 +-- .../generator/service/IGenTableService.java | 200 ++--- .../impl/GenTableColumnServiceImpl.java | 132 ++-- .../service/impl/GenTableServiceImpl.java | 642 ++++++++-------- .../com/ruoyi/generator/util/GenUtils.java | 442 +++++------ .../generator/util/VelocityInitializer.java | 66 +- .../ruoyi/generator/util/VelocityUtils.java | 165 ++-- 13 files changed, 1624 insertions(+), 1792 deletions(-) diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/config/GenConfig.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/config/GenConfig.java index 1b144deb9..7baa6cd5b 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/config/GenConfig.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/config/GenConfig.java @@ -1,73 +1,72 @@ -package com.ruoyi.generator.config; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - -/** - * 读取代码生成相关配置 - * - * @author ruoyi - */ -@Component -@ConfigurationProperties(prefix = "gen") -@PropertySource(value = { "classpath:generator.yml" }) -public class GenConfig -{ - /** 作者 */ - public static String author; - - /** 生成包路径 */ - public static String packageName; - - /** 自动去除表前缀,默认是false */ - public static boolean autoRemovePre; - - /** 表前缀(类名不会包含表前缀) */ - public static String tablePrefix; - - public static String getAuthor() - { - return author; - } - - @Value("${author}") - public void setAuthor(String author) - { - GenConfig.author = author; - } - - public static String getPackageName() - { - return packageName; - } - - @Value("${packageName}") - public void setPackageName(String packageName) - { - GenConfig.packageName = packageName; - } - - public static boolean getAutoRemovePre() - { - return autoRemovePre; - } - - @Value("${autoRemovePre}") - public void setAutoRemovePre(boolean autoRemovePre) - { - GenConfig.autoRemovePre = autoRemovePre; - } - - public static String getTablePrefix() - { - return tablePrefix; - } - - @Value("${tablePrefix}") - public void setTablePrefix(String tablePrefix) - { - GenConfig.tablePrefix = tablePrefix; - } -} +package com.ruoyi.generator.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +/** + * 读取代码生成相关配置 + * + * @author ruoyi + */ +@Component +@ConfigurationProperties(prefix = "gen") +@PropertySource(value = {"classpath:generator.yml"}) +public class GenConfig { + /** + * 作者 + */ + public static String author; + + /** + * 生成包路径 + */ + public static String packageName; + + /** + * 自动去除表前缀,默认是false + */ + public static boolean autoRemovePre; + + /** + * 表前缀(类名不会包含表前缀) + */ + public static String tablePrefix; + + public static String getAuthor() { + return author; + } + + @Value("${author}") + public void setAuthor(String author) { + GenConfig.author = author; + } + + public static String getPackageName() { + return packageName; + } + + @Value("${packageName}") + public void setPackageName(String packageName) { + GenConfig.packageName = packageName; + } + + public static boolean getAutoRemovePre() { + return autoRemovePre; + } + + @Value("${autoRemovePre}") + public void setAutoRemovePre(boolean autoRemovePre) { + GenConfig.autoRemovePre = autoRemovePre; + } + + public static String getTablePrefix() { + return tablePrefix; + } + + @Value("${tablePrefix}") + public void setTablePrefix(String tablePrefix) { + GenConfig.tablePrefix = tablePrefix; + } +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java index 6e4f710dc..efdbb31bc 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.io.IOUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; @@ -29,13 +30,12 @@ import com.ruoyi.generator.service.IGenTableService; /** * 代码生成 操作处理 - * + * * @author ruoyi */ @Controller @RequestMapping("/tool/gen") -public class GenController extends BaseController -{ +public class GenController extends BaseController { private String prefix = "tool/gen"; @Autowired @@ -46,8 +46,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:view") @GetMapping() - public String gen() - { + public String gen() { return prefix + "/gen"; } @@ -57,8 +56,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:list") @PostMapping("/list") @ResponseBody - public TableDataInfo genList(GenTable genTable) - { + public TableDataInfo genList(GenTable genTable) { startPage(); List list = genTableService.selectGenTableList(genTable); return getDataTable(list); @@ -70,8 +68,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:list") @PostMapping("/db/list") @ResponseBody - public TableDataInfo dataList(GenTable genTable) - { + public TableDataInfo dataList(GenTable genTable) { startPage(); List list = genTableService.selectDbTableList(genTable); return getDataTable(list); @@ -83,8 +80,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:list") @PostMapping("/column/list") @ResponseBody - public TableDataInfo columnList(GenTableColumn genTableColumn) - { + public TableDataInfo columnList(GenTableColumn genTableColumn) { TableDataInfo dataInfo = new TableDataInfo(); List list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn); dataInfo.setRows(list); @@ -97,8 +93,7 @@ public class GenController extends BaseController */ @RequiresPermissions("tool:gen:list") @GetMapping("/importTable") - public String importTable() - { + public String importTable() { return prefix + "/importTable"; } @@ -109,8 +104,7 @@ public class GenController extends BaseController @Log(title = "代码生成", businessType = BusinessType.IMPORT) @PostMapping("/importTable") @ResponseBody - public AjaxResult importTableSave(String tables) - { + public AjaxResult importTableSave(String tables) { String[] tableNames = Convert.toStrArray(tables); // 查询表信息 List tableList = genTableService.selectDbTableListByNames(tableNames); @@ -123,8 +117,7 @@ public class GenController extends BaseController * 修改代码生成业务 */ @GetMapping("/edit/{tableId}") - public String edit(@PathVariable("tableId") Long tableId, ModelMap mmap) - { + public String edit(@PathVariable("tableId") Long tableId, ModelMap mmap) { GenTable table = genTableService.selectGenTableById(tableId); mmap.put("table", table); return prefix + "/edit"; @@ -137,8 +130,7 @@ public class GenController extends BaseController @Log(title = "代码生成", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody - public AjaxResult editSave(@Validated GenTable genTable) - { + public AjaxResult editSave(@Validated GenTable genTable) { genTableService.validateEdit(genTable); genTableService.updateGenTable(genTable); return AjaxResult.success(); @@ -148,8 +140,7 @@ public class GenController extends BaseController @Log(title = "代码生成", businessType = BusinessType.DELETE) @PostMapping("/remove") @ResponseBody - public AjaxResult remove(String ids) - { + public AjaxResult remove(String ids) { genTableService.deleteGenTableByIds(ids); return AjaxResult.success(); } @@ -160,8 +151,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:preview") @GetMapping("/preview/{tableId}") @ResponseBody - public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException - { + public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException { Map dataMap = genTableService.previewCode(tableId); return AjaxResult.success(dataMap); } @@ -172,8 +162,7 @@ public class GenController extends BaseController @RequiresPermissions("tool:gen:code") @Log(title = "代码生成", businessType = BusinessType.GENCODE) @GetMapping("/genCode/{tableName}") - public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException - { + public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { byte[] data = genTableService.generatorCode(tableName); genCode(response, data); } @@ -185,8 +174,7 @@ public class GenController extends BaseController @Log(title = "代码生成", businessType = BusinessType.GENCODE) @GetMapping("/batchGenCode") @ResponseBody - public void batchGenCode(HttpServletResponse response, String tables) throws IOException - { + public void batchGenCode(HttpServletResponse response, String tables) throws IOException { String[] tableNames = Convert.toStrArray(tables); byte[] data = genTableService.generatorCode(tableNames); genCode(response, data); @@ -195,8 +183,7 @@ public class GenController extends BaseController /** * 生成zip文件 */ - private void genCode(HttpServletResponse response, byte[] data) throws IOException - { + private void genCode(HttpServletResponse response, byte[] data) throws IOException { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\""); response.addHeader("Content-Length", "" + data.length); diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java index 8e610be44..e08d5017d 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java @@ -1,269 +1,262 @@ -package com.ruoyi.generator.domain; - -import java.util.List; -import javax.validation.Valid; -import javax.validation.constraints.NotBlank; -import com.ruoyi.common.constant.GenConstants; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.utils.StringUtils; - -/** - * 业务表 gen_table - * - * @author ruoyi - */ -public class GenTable extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 编号 */ - private Long tableId; - - /** 表名称 */ - @NotBlank(message = "表名称不能为空") - private String tableName; - - /** 表描述 */ - @NotBlank(message = "表描述不能为空") - private String tableComment; - - /** 实体类名称(首字母大写) */ - @NotBlank(message = "实体类名称不能为空") - private String className; - - /** 使用的模板(crud单表操作 tree树表操作) */ - private String tplCategory; - - /** 生成包路径 */ - @NotBlank(message = "生成包路径不能为空") - private String packageName; - - /** 生成模块名 */ - @NotBlank(message = "生成模块名不能为空") - private String moduleName; - - /** 生成业务名 */ - @NotBlank(message = "生成业务名不能为空") - private String businessName; - - /** 生成功能名 */ - @NotBlank(message = "生成功能名不能为空") - private String functionName; - - /** 生成作者 */ - @NotBlank(message = "作者不能为空") - private String functionAuthor; - - /** 主键信息 */ - private GenTableColumn pkColumn; - - /** 表列信息 */ - @Valid - private List columns; - - /** 其它生成选项 */ - private String options; - - /** 树编码字段 */ - private String treeCode; - - /** 树父编码字段 */ - private String treeParentCode; - - /** 树名称字段 */ - private String treeName; - - public Long getTableId() - { - return tableId; - } - - public void setTableId(Long tableId) - { - this.tableId = tableId; - } - - public String getTableName() - { - return tableName; - } - - public void setTableName(String tableName) - { - this.tableName = tableName; - } - - public String getTableComment() - { - return tableComment; - } - - public void setTableComment(String tableComment) - { - this.tableComment = tableComment; - } - - public String getClassName() - { - return className; - } - - public void setClassName(String className) - { - this.className = className; - } - - public String getTplCategory() - { - return tplCategory; - } - - public void setTplCategory(String tplCategory) - { - this.tplCategory = tplCategory; - } - - public String getPackageName() - { - return packageName; - } - - public void setPackageName(String packageName) - { - this.packageName = packageName; - } - - public String getModuleName() - { - return moduleName; - } - - public void setModuleName(String moduleName) - { - this.moduleName = moduleName; - } - - public String getBusinessName() - { - return businessName; - } - - public void setBusinessName(String businessName) - { - this.businessName = businessName; - } - - public String getFunctionName() - { - return functionName; - } - - public void setFunctionName(String functionName) - { - this.functionName = functionName; - } - - public String getFunctionAuthor() - { - return functionAuthor; - } - - public void setFunctionAuthor(String functionAuthor) - { - this.functionAuthor = functionAuthor; - } - - public GenTableColumn getPkColumn() - { - return pkColumn; - } - - public void setPkColumn(GenTableColumn pkColumn) - { - this.pkColumn = pkColumn; - } - - public List getColumns() - { - return columns; - } - - public void setColumns(List columns) - { - this.columns = columns; - } - - public String getOptions() - { - return options; - } - - public void setOptions(String options) - { - this.options = options; - } - - public String getTreeCode() - { - return treeCode; - } - - public void setTreeCode(String treeCode) - { - this.treeCode = treeCode; - } - - public String getTreeParentCode() - { - return treeParentCode; - } - - public void setTreeParentCode(String treeParentCode) - { - this.treeParentCode = treeParentCode; - } - - public String getTreeName() - { - return treeName; - } - - public void setTreeName(String treeName) - { - this.treeName = treeName; - } - - public boolean isTree() - { - return isTree(this.tplCategory); - } - - public static boolean isTree(String tplCategory) - { - return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); - } - - public boolean isCrud() - { - return isCrud(this.tplCategory); - } - - public static boolean isCrud(String tplCategory) - { - return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); - } - - public boolean isSuperColumn(String javaField) - { - return isSuperColumn(this.tplCategory, javaField); - } - - public static boolean isSuperColumn(String tplCategory, String javaField) - { - if (isTree(tplCategory)) - { - StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.TREE_ENTITY); - } - return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); - } +package com.ruoyi.generator.domain; + +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; + +import com.ruoyi.common.constant.GenConstants; +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.utils.StringUtils; + +/** + * 业务表 gen_table + * + * @author ruoyi + */ +public class GenTable extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + private Long tableId; + + /** + * 表名称 + */ + @NotBlank(message = "表名称不能为空") + private String tableName; + + /** + * 表描述 + */ + @NotBlank(message = "表描述不能为空") + private String tableComment; + + /** + * 实体类名称(首字母大写) + */ + @NotBlank(message = "实体类名称不能为空") + private String className; + + /** + * 使用的模板(crud单表操作 tree树表操作) + */ + private String tplCategory; + + /** + * 生成包路径 + */ + @NotBlank(message = "生成包路径不能为空") + private String packageName; + + /** + * 生成模块名 + */ + @NotBlank(message = "生成模块名不能为空") + private String moduleName; + + /** + * 生成业务名 + */ + @NotBlank(message = "生成业务名不能为空") + private String businessName; + + /** + * 生成功能名 + */ + @NotBlank(message = "生成功能名不能为空") + private String functionName; + + /** + * 生成作者 + */ + @NotBlank(message = "作者不能为空") + private String functionAuthor; + + /** + * 主键信息 + */ + private GenTableColumn pkColumn; + + /** + * 表列信息 + */ + @Valid + private List columns; + + /** + * 其它生成选项 + */ + private String options; + + /** + * 树编码字段 + */ + private String treeCode; + + /** + * 树父编码字段 + */ + private String treeParentCode; + + /** + * 树名称字段 + */ + private String treeName; + + public Long getTableId() { + return tableId; + } + + public void setTableId(Long tableId) { + this.tableId = tableId; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getTableComment() { + return tableComment; + } + + public void setTableComment(String tableComment) { + this.tableComment = tableComment; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getTplCategory() { + return tplCategory; + } + + public void setTplCategory(String tplCategory) { + this.tplCategory = tplCategory; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public String getBusinessName() { + return businessName; + } + + public void setBusinessName(String businessName) { + this.businessName = businessName; + } + + public String getFunctionName() { + return functionName; + } + + public void setFunctionName(String functionName) { + this.functionName = functionName; + } + + public String getFunctionAuthor() { + return functionAuthor; + } + + public void setFunctionAuthor(String functionAuthor) { + this.functionAuthor = functionAuthor; + } + + public GenTableColumn getPkColumn() { + return pkColumn; + } + + public void setPkColumn(GenTableColumn pkColumn) { + this.pkColumn = pkColumn; + } + + public List getColumns() { + return columns; + } + + public void setColumns(List columns) { + this.columns = columns; + } + + public String getOptions() { + return options; + } + + public void setOptions(String options) { + this.options = options; + } + + public String getTreeCode() { + return treeCode; + } + + public void setTreeCode(String treeCode) { + this.treeCode = treeCode; + } + + public String getTreeParentCode() { + return treeParentCode; + } + + public void setTreeParentCode(String treeParentCode) { + this.treeParentCode = treeParentCode; + } + + public String getTreeName() { + return treeName; + } + + public void setTreeName(String treeName) { + this.treeName = treeName; + } + + public boolean isTree() { + return isTree(this.tplCategory); + } + + public static boolean isTree(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); + } + + public boolean isCrud() { + return isCrud(this.tplCategory); + } + + public static boolean isCrud(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); + } + + public boolean isSuperColumn(String javaField) { + return isSuperColumn(this.tplCategory, javaField); + } + + public static boolean isSuperColumn(String tplCategory, String javaField) { + if (isTree(tplCategory)) { + StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.TREE_ENTITY); + } + return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java index b17c38319..0777ccf3a 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java @@ -1,368 +1,344 @@ -package com.ruoyi.generator.domain; - -import javax.validation.constraints.NotBlank; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.utils.StringUtils; - -/** - * 代码生成业务字段表 gen_table_column - * - * @author ruoyi - */ -public class GenTableColumn extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 编号 */ - private Long columnId; - - /** 归属表编号 */ - private Long tableId; - - /** 列名称 */ - private String columnName; - - /** 列描述 */ - private String columnComment; - - /** 列类型 */ - private String columnType; - - /** JAVA类型 */ - private String javaType; - - /** JAVA字段名 */ - @NotBlank(message = "Java属性不能为空") - private String javaField; - - /** 是否主键(1是) */ - private String isPk; - - /** 是否自增(1是) */ - private String isIncrement; - - /** 是否必填(1是) */ - private String isRequired; - - /** 是否为插入字段(1是) */ - private String isInsert; - - /** 是否编辑字段(1是) */ - private String isEdit; - - /** 是否列表字段(1是) */ - private String isList; - - /** 是否查询字段(1是) */ - private String isQuery; - - /** 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) */ - private String queryType; - - /** 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件) */ - private String htmlType; - - /** 字典类型 */ - private String dictType; - - /** 排序 */ - private Integer sort; - - public void setColumnId(Long columnId) - { - this.columnId = columnId; - } - - public Long getColumnId() - { - return columnId; - } - - public void setTableId(Long tableId) - { - this.tableId = tableId; - } - - public Long getTableId() - { - return tableId; - } - - public void setColumnName(String columnName) - { - this.columnName = columnName; - } - - public String getColumnName() - { - return columnName; - } - - public void setColumnComment(String columnComment) - { - this.columnComment = columnComment; - } - - public String getColumnComment() - { - return columnComment; - } - - public void setColumnType(String columnType) - { - this.columnType = columnType; - } - - public String getColumnType() - { - return columnType; - } - - public void setJavaType(String javaType) - { - this.javaType = javaType; - } - - public String getJavaType() - { - return javaType; - } - - public void setJavaField(String javaField) - { - this.javaField = javaField; - } - - public String getJavaField() - { - return javaField; - } - - public void setIsPk(String isPk) - { - this.isPk = isPk; - } - - public String getIsPk() - { - return isPk; - } - - public boolean isPk() - { - return isPk(this.isPk); - } - - public boolean isPk(String isPk) - { - return isPk != null && StringUtils.equals("1", isPk); - } - - public String getIsIncrement() - { - return isIncrement; - } - - public void setIsIncrement(String isIncrement) - { - this.isIncrement = isIncrement; - } - - public boolean isIncrement() - { - return isIncrement(this.isIncrement); - } - - public boolean isIncrement(String isIncrement) - { - return isIncrement != null && StringUtils.equals("1", isIncrement); - } - - public void setIsRequired(String isRequired) - { - this.isRequired = isRequired; - } - - public String getIsRequired() - { - return isRequired; - } - - public boolean isRequired() - { - return isRequired(this.isRequired); - } - - public boolean isRequired(String isRequired) - { - return isRequired != null && StringUtils.equals("1", isRequired); - } - - public void setIsInsert(String isInsert) - { - this.isInsert = isInsert; - } - - public String getIsInsert() - { - return isInsert; - } - - public boolean isInsert() - { - return isInsert(this.isInsert); - } - - public boolean isInsert(String isInsert) - { - return isInsert != null && StringUtils.equals("1", isInsert); - } - - public void setIsEdit(String isEdit) - { - this.isEdit = isEdit; - } - - public String getIsEdit() - { - return isEdit; - } - - public boolean isEdit() - { - return isInsert(this.isEdit); - } - - public boolean isEdit(String isEdit) - { - return isEdit != null && StringUtils.equals("1", isEdit); - } - - public void setIsList(String isList) - { - this.isList = isList; - } - - public String getIsList() - { - return isList; - } - - public boolean isList() - { - return isList(this.isList); - } - - public boolean isList(String isList) - { - return isList != null && StringUtils.equals("1", isList); - } - - public void setIsQuery(String isQuery) - { - this.isQuery = isQuery; - } - - public String getIsQuery() - { - return isQuery; - } - - public boolean isQuery() - { - return isQuery(this.isQuery); - } - - public boolean isQuery(String isQuery) - { - return isQuery != null && StringUtils.equals("1", isQuery); - } - - public void setQueryType(String queryType) - { - this.queryType = queryType; - } - - public String getQueryType() - { - return queryType; - } - - public String getHtmlType() - { - return htmlType; - } - - public void setHtmlType(String htmlType) - { - this.htmlType = htmlType; - } - - public void setDictType(String dictType) - { - this.dictType = dictType; - } - - public String getDictType() - { - return dictType; - } - - public void setSort(Integer sort) - { - this.sort = sort; - } - - public Integer getSort() - { - return sort; - } - - public boolean isSuperColumn() - { - return isSuperColumn(this.javaField); - } - - public static boolean isSuperColumn(String javaField) - { - return StringUtils.equalsAnyIgnoreCase(javaField, - //BaseEntity - "createBy", "createTime", "updateBy", "updateTime", "remark", - //TreeEntity - "parentName", "parentId", "orderNum", "ancestors"); - } - - public boolean isUsableColumn() - { - return isUsableColumn(javaField); - } - - public static boolean isUsableColumn(String javaField) - { - //isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单 - return StringUtils.equalsAnyIgnoreCase(javaField, "parentId" , "orderNum"); - } - - public String readConverterExp() - { - String remarks = StringUtils.substringBetween(this.columnComment, "(", ")"); - StringBuffer sb = new StringBuffer(); - if (StringUtils.isNotEmpty(remarks)) - { - for (String value : remarks.split(" ")) - { - if (StringUtils.isNotEmpty(value)) - { - Object startStr = value.subSequence(0, 1); - String endStr = value.substring(1); - sb.append("").append(startStr).append("=").append(endStr).append(","); - } - } - return sb.deleteCharAt(sb.length() - 1).toString(); - } - else - { - return this.columnComment; - } - } +package com.ruoyi.generator.domain; + +import javax.validation.constraints.NotBlank; + +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.utils.StringUtils; + +/** + * 代码生成业务字段表 gen_table_column + * + * @author ruoyi + */ +public class GenTableColumn extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + private Long columnId; + + /** + * 归属表编号 + */ + private Long tableId; + + /** + * 列名称 + */ + private String columnName; + + /** + * 列描述 + */ + private String columnComment; + + /** + * 列类型 + */ + private String columnType; + + /** + * JAVA类型 + */ + private String javaType; + + /** + * JAVA字段名 + */ + @NotBlank(message = "Java属性不能为空") + private String javaField; + + /** + * 是否主键(1是) + */ + private String isPk; + + /** + * 是否自增(1是) + */ + private String isIncrement; + + /** + * 是否必填(1是) + */ + private String isRequired; + + /** + * 是否为插入字段(1是) + */ + private String isInsert; + + /** + * 是否编辑字段(1是) + */ + private String isEdit; + + /** + * 是否列表字段(1是) + */ + private String isList; + + /** + * 是否查询字段(1是) + */ + private String isQuery; + + /** + * 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) + */ + private String queryType; + + /** + * 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件) + */ + private String htmlType; + + /** + * 字典类型 + */ + private String dictType; + + /** + * 排序 + */ + private Integer sort; + + public void setColumnId(Long columnId) { + this.columnId = columnId; + } + + public Long getColumnId() { + return columnId; + } + + public void setTableId(Long tableId) { + this.tableId = tableId; + } + + public Long getTableId() { + return tableId; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getColumnName() { + return columnName; + } + + public void setColumnComment(String columnComment) { + this.columnComment = columnComment; + } + + public String getColumnComment() { + return columnComment; + } + + public void setColumnType(String columnType) { + this.columnType = columnType; + } + + public String getColumnType() { + return columnType; + } + + public void setJavaType(String javaType) { + this.javaType = javaType; + } + + public String getJavaType() { + return javaType; + } + + public void setJavaField(String javaField) { + this.javaField = javaField; + } + + public String getJavaField() { + return javaField; + } + + public void setIsPk(String isPk) { + this.isPk = isPk; + } + + public String getIsPk() { + return isPk; + } + + public boolean isPk() { + return isPk(this.isPk); + } + + public boolean isPk(String isPk) { + return isPk != null && StringUtils.equals("1", isPk); + } + + public String getIsIncrement() { + return isIncrement; + } + + public void setIsIncrement(String isIncrement) { + this.isIncrement = isIncrement; + } + + public boolean isIncrement() { + return isIncrement(this.isIncrement); + } + + public boolean isIncrement(String isIncrement) { + return isIncrement != null && StringUtils.equals("1", isIncrement); + } + + public void setIsRequired(String isRequired) { + this.isRequired = isRequired; + } + + public String getIsRequired() { + return isRequired; + } + + public boolean isRequired() { + return isRequired(this.isRequired); + } + + public boolean isRequired(String isRequired) { + return isRequired != null && StringUtils.equals("1", isRequired); + } + + public void setIsInsert(String isInsert) { + this.isInsert = isInsert; + } + + public String getIsInsert() { + return isInsert; + } + + public boolean isInsert() { + return isInsert(this.isInsert); + } + + public boolean isInsert(String isInsert) { + return isInsert != null && StringUtils.equals("1", isInsert); + } + + public void setIsEdit(String isEdit) { + this.isEdit = isEdit; + } + + public String getIsEdit() { + return isEdit; + } + + public boolean isEdit() { + return isInsert(this.isEdit); + } + + public boolean isEdit(String isEdit) { + return isEdit != null && StringUtils.equals("1", isEdit); + } + + public void setIsList(String isList) { + this.isList = isList; + } + + public String getIsList() { + return isList; + } + + public boolean isList() { + return isList(this.isList); + } + + public boolean isList(String isList) { + return isList != null && StringUtils.equals("1", isList); + } + + public void setIsQuery(String isQuery) { + this.isQuery = isQuery; + } + + public String getIsQuery() { + return isQuery; + } + + public boolean isQuery() { + return isQuery(this.isQuery); + } + + public boolean isQuery(String isQuery) { + return isQuery != null && StringUtils.equals("1", isQuery); + } + + public void setQueryType(String queryType) { + this.queryType = queryType; + } + + public String getQueryType() { + return queryType; + } + + public String getHtmlType() { + return htmlType; + } + + public void setHtmlType(String htmlType) { + this.htmlType = htmlType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + public String getDictType() { + return dictType; + } + + public void setSort(Integer sort) { + this.sort = sort; + } + + public Integer getSort() { + return sort; + } + + public boolean isSuperColumn() { + return isSuperColumn(this.javaField); + } + + public static boolean isSuperColumn(String javaField) { + return StringUtils.equalsAnyIgnoreCase(javaField, + //BaseEntity + "createBy", "createTime", "updateBy", "updateTime", "remark", + //TreeEntity + "parentName", "parentId", "orderNum", "ancestors"); + } + + public boolean isUsableColumn() { + return isUsableColumn(javaField); + } + + public static boolean isUsableColumn(String javaField) { + //isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单 + return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum"); + } + + public String readConverterExp() { + String remarks = StringUtils.substringBetween(this.columnComment, "(", ")"); + StringBuffer sb = new StringBuffer(); + if (StringUtils.isNotEmpty(remarks)) { + for (String value : remarks.split(" ")) { + if (StringUtils.isNotEmpty(value)) { + Object startStr = value.subSequence(0, 1); + String endStr = value.substring(1); + sb.append("").append(startStr).append("=").append(endStr).append(","); + } + } + return sb.deleteCharAt(sb.length() - 1).toString(); + } else { + return this.columnComment; + } + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java index 6ebe2306b..616a922d7 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java @@ -1,52 +1,52 @@ -package com.ruoyi.generator.mapper; - -import java.util.List; -import com.ruoyi.generator.domain.GenTableColumn; - -/** - * 业务字段 数据层 - * - * @author ruoyi - */ -public interface GenTableColumnMapper -{ - /** - * 根据表名称查询列信息 - * - * @param tableName 表名称 - * @return 列信息 - */ - public List selectDbTableColumnsByName(String tableName); - - /** - * 查询业务字段列表 - * - * @param genTableColumn 业务字段信息 - * @return 业务字段集合 - */ - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); - - /** - * 新增业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int insertGenTableColumn(GenTableColumn genTableColumn); - - /** - * 修改业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int updateGenTableColumn(GenTableColumn genTableColumn); - - /** - * 批量删除业务字段 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteGenTableColumnByIds(Long[] ids); +package com.ruoyi.generator.mapper; + +import java.util.List; + +import com.ruoyi.generator.domain.GenTableColumn; + +/** + * 业务字段 数据层 + * + * @author ruoyi + */ +public interface GenTableColumnMapper { + /** + * 根据表名称查询列信息 + * + * @param tableName 表名称 + * @return 列信息 + */ + public List selectDbTableColumnsByName(String tableName); + + /** + * 查询业务字段列表 + * + * @param genTableColumn 业务字段信息 + * @return 业务字段集合 + */ + public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int insertGenTableColumn(GenTableColumn genTableColumn); + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int updateGenTableColumn(GenTableColumn genTableColumn); + + /** + * 批量删除业务字段 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableColumnByIds(Long[] ids); } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java index 85143e650..086ee8f43 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java @@ -1,76 +1,76 @@ -package com.ruoyi.generator.mapper; - -import java.util.List; -import com.ruoyi.generator.domain.GenTable; - -/** - * 业务 数据层 - * - * @author ruoyi - */ -public interface GenTableMapper -{ - /** - * 查询业务列表 - * - * @param genTable 业务信息 - * @return 业务集合 - */ - public List selectGenTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param genTable 业务信息 - * @return 数据库表集合 - */ - public List selectDbTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param tableNames 表名称组 - * @return 数据库表集合 - */ - public List selectDbTableListByNames(String[] tableNames); - - /** - * 查询表ID业务信息 - * - * @param id 业务ID - * @return 业务信息 - */ - public GenTable selectGenTableById(Long id); - - /** - * 查询表名称业务信息 - * - * @param tableName 表名称 - * @return 业务信息 - */ - public GenTable selectGenTableByName(String tableName); - - /** - * 新增业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - public int insertGenTable(GenTable genTable); - - /** - * 修改业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - public int updateGenTable(GenTable genTable); - - /** - * 批量删除业务 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteGenTableByIds(Long[] ids); +package com.ruoyi.generator.mapper; + +import java.util.List; + +import com.ruoyi.generator.domain.GenTable; + +/** + * 业务 数据层 + * + * @author ruoyi + */ +public interface GenTableMapper { + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + public List selectGenTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + public List selectDbTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + public List selectDbTableListByNames(String[] tableNames); + + /** + * 查询表ID业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + public GenTable selectGenTableById(Long id); + + /** + * 查询表名称业务信息 + * + * @param tableName 表名称 + * @return 业务信息 + */ + public GenTable selectGenTableByName(String tableName); + + /** + * 新增业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public int insertGenTable(GenTable genTable); + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public int updateGenTable(GenTable genTable); + + /** + * 批量删除业务 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableByIds(Long[] ids); } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java index 2ff5f5663..15d7cefb9 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java @@ -1,44 +1,44 @@ -package com.ruoyi.generator.service; - -import java.util.List; -import com.ruoyi.generator.domain.GenTableColumn; - -/** - * 业务字段 服务层 - * - * @author ruoyi - */ -public interface IGenTableColumnService -{ - /** - * 查询业务字段列表 - * - * @param genTableColumn 业务字段信息 - * @return 业务字段集合 - */ - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); - - /** - * 新增业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int insertGenTableColumn(GenTableColumn genTableColumn); - - /** - * 修改业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int updateGenTableColumn(GenTableColumn genTableColumn); - - /** - * 删除业务字段信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteGenTableColumnByIds(String ids); -} +package com.ruoyi.generator.service; + +import java.util.List; + +import com.ruoyi.generator.domain.GenTableColumn; + +/** + * 业务字段 服务层 + * + * @author ruoyi + */ +public interface IGenTableColumnService { + /** + * 查询业务字段列表 + * + * @param genTableColumn 业务字段信息 + * @return 业务字段集合 + */ + public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int insertGenTableColumn(GenTableColumn genTableColumn); + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int updateGenTableColumn(GenTableColumn genTableColumn); + + /** + * 删除业务字段信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableColumnByIds(String ids); +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java index 50e51bcda..3950948ac 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java @@ -1,100 +1,100 @@ -package com.ruoyi.generator.service; - -import java.util.List; -import java.util.Map; -import com.ruoyi.generator.domain.GenTable; - -/** - * 业务 服务层 - * - * @author ruoyi - */ -public interface IGenTableService -{ - /** - * 查询业务列表 - * - * @param genTable 业务信息 - * @return 业务集合 - */ - public List selectGenTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param genTable 业务信息 - * @return 数据库表集合 - */ - public List selectDbTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param tableNames 表名称组 - * @return 数据库表集合 - */ - public List selectDbTableListByNames(String[] tableNames); - - /** - * 查询业务信息 - * - * @param id 业务ID - * @return 业务信息 - */ - public GenTable selectGenTableById(Long id); - - /** - * 修改业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - public void updateGenTable(GenTable genTable); - - /** - * 删除业务信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public void deleteGenTableByIds(String ids); - - /** - * 导入表结构 - * - * @param tableList 导入表列表 - * @param operName 操作人员 - */ - public void importGenTable(List tableList, String operName); - - /** - * 预览代码 - * - * @param tableId 表编号 - * @return 预览数据列表 - */ - public Map previewCode(Long tableId); - - /** - * 生成代码 - * - * @param tableName 表名称 - * @return 数据 - */ - public byte[] generatorCode(String tableName); - - /** - * 批量生成代码 - * - * @param tableNames 表数组 - * @return 数据 - */ - public byte[] generatorCode(String[] tableNames); - - /** - * 修改保存参数校验 - * - * @param genTable 业务信息 - */ - public void validateEdit(GenTable genTable); -} +package com.ruoyi.generator.service; + +import java.util.List; +import java.util.Map; + +import com.ruoyi.generator.domain.GenTable; + +/** + * 业务 服务层 + * + * @author ruoyi + */ +public interface IGenTableService { + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + public List selectGenTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + public List selectDbTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + public List selectDbTableListByNames(String[] tableNames); + + /** + * 查询业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + public GenTable selectGenTableById(Long id); + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public void updateGenTable(GenTable genTable); + + /** + * 删除业务信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public void deleteGenTableByIds(String ids); + + /** + * 导入表结构 + * + * @param tableList 导入表列表 + * @param operName 操作人员 + */ + public void importGenTable(List tableList, String operName); + + /** + * 预览代码 + * + * @param tableId 表编号 + * @return 预览数据列表 + */ + public Map previewCode(Long tableId); + + /** + * 生成代码 + * + * @param tableName 表名称 + * @return 数据 + */ + public byte[] generatorCode(String tableName); + + /** + * 批量生成代码 + * + * @param tableNames 表数组 + * @return 数据 + */ + public byte[] generatorCode(String[] tableNames); + + /** + * 修改保存参数校验 + * + * @param genTable 业务信息 + */ + public void validateEdit(GenTable genTable); +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java index 45d015af2..650166efa 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java @@ -1,69 +1,65 @@ -package com.ruoyi.generator.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.generator.domain.GenTableColumn; -import com.ruoyi.generator.mapper.GenTableColumnMapper; -import com.ruoyi.generator.service.IGenTableColumnService; - -/** - * 业务字段 服务层实现 - * - * @author ruoyi - */ -@Service -public class GenTableColumnServiceImpl implements IGenTableColumnService -{ - @Autowired - private GenTableColumnMapper genTableColumnMapper; - - /** - * 查询业务字段列表 - * - * @param genTableColumn 业务字段信息 - * @return 业务字段集合 - */ - @Override - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn) - { - return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn); - } - - /** - * 新增业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - @Override - public int insertGenTableColumn(GenTableColumn genTableColumn) - { - return genTableColumnMapper.insertGenTableColumn(genTableColumn); - } - - /** - * 修改业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - @Override - public int updateGenTableColumn(GenTableColumn genTableColumn) - { - return genTableColumnMapper.updateGenTableColumn(genTableColumn); - } - - /** - * 删除业务字段对象 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - public int deleteGenTableColumnByIds(String ids) - { - return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); - } +package com.ruoyi.generator.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.generator.domain.GenTableColumn; +import com.ruoyi.generator.mapper.GenTableColumnMapper; +import com.ruoyi.generator.service.IGenTableColumnService; + +/** + * 业务字段 服务层实现 + * + * @author ruoyi + */ +@Service +public class GenTableColumnServiceImpl implements IGenTableColumnService { + @Autowired + private GenTableColumnMapper genTableColumnMapper; + + /** + * 查询业务字段列表 + * + * @param genTableColumn 业务字段信息 + * @return 业务字段集合 + */ + @Override + public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn) { + return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn); + } + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + @Override + public int insertGenTableColumn(GenTableColumn genTableColumn) { + return genTableColumnMapper.insertGenTableColumn(genTableColumn); + } + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + @Override + public int updateGenTableColumn(GenTableColumn genTableColumn) { + return genTableColumnMapper.updateGenTableColumn(genTableColumn); + } + + /** + * 删除业务字段对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteGenTableColumnByIds(String ids) { + return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java index f7edca385..944f33a27 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java @@ -1,341 +1,303 @@ -package com.ruoyi.generator.service.impl; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -import org.apache.commons.io.IOUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.constant.GenConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.generator.domain.GenTable; -import com.ruoyi.generator.domain.GenTableColumn; -import com.ruoyi.generator.mapper.GenTableColumnMapper; -import com.ruoyi.generator.mapper.GenTableMapper; -import com.ruoyi.generator.service.IGenTableService; -import com.ruoyi.generator.util.GenUtils; -import com.ruoyi.generator.util.VelocityInitializer; -import com.ruoyi.generator.util.VelocityUtils; - -/** - * 业务 服务层实现 - * - * @author ruoyi - */ -@Service -public class GenTableServiceImpl implements IGenTableService -{ - private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); - - @Autowired - private GenTableMapper genTableMapper; - - @Autowired - private GenTableColumnMapper genTableColumnMapper; - - /** - * 查询业务信息 - * - * @param id 业务ID - * @return 业务信息 - */ - @Override - public GenTable selectGenTableById(Long id) - { - GenTable genTable = genTableMapper.selectGenTableById(id); - setTableFromOptions(genTable); - return genTable; - } - - /** - * 查询业务列表 - * - * @param genTable 业务信息 - * @return 业务集合 - */ - @Override - public List selectGenTableList(GenTable genTable) - { - return genTableMapper.selectGenTableList(genTable); - } - - /** - * 查询据库列表 - * - * @param genTable 业务信息 - * @return 数据库表集合 - */ - public List selectDbTableList(GenTable genTable) - { - return genTableMapper.selectDbTableList(genTable); - } - - /** - * 查询据库列表 - * - * @param tableNames 表名称组 - * @return 数据库表集合 - */ - public List selectDbTableListByNames(String[] tableNames) - { - return genTableMapper.selectDbTableListByNames(tableNames); - } - - /** - * 修改业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - @Override - @Transactional - public void updateGenTable(GenTable genTable) - { - String options = JSON.toJSONString(genTable.getParams()); - genTable.setOptions(options); - int row = genTableMapper.updateGenTable(genTable); - if (row > 0) - { - for (GenTableColumn cenTableColumn : genTable.getColumns()) - { - genTableColumnMapper.updateGenTableColumn(cenTableColumn); - } - } - } - - /** - * 删除业务对象 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - @Transactional - public void deleteGenTableByIds(String ids) - { - genTableMapper.deleteGenTableByIds(Convert.toLongArray(ids)); - genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); - } - - /** - * 导入表结构 - * - * @param tableList 导入表列表 - * @param operName 操作人员 - */ - @Override - @Transactional - public void importGenTable(List tableList, String operName) - { - for (GenTable table : tableList) - { - try - { - String tableName = table.getTableName(); - GenUtils.initTable(table, operName); - int row = genTableMapper.insertGenTable(table); - if (row > 0) - { - // 保存列信息 - List genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); - for (GenTableColumn column : genTableColumns) - { - GenUtils.initColumnField(column, table); - genTableColumnMapper.insertGenTableColumn(column); - } - } - } - catch (Exception e) - { - log.error("表名 " + table.getTableName() + " 导入失败:", e); - } - } - } - - /** - * 预览代码 - * - * @param tableId 表编号 - * @return 预览数据列表 - */ - public Map previewCode(Long tableId) - { - Map dataMap = new LinkedHashMap<>(); - // 查询表信息 - GenTable table = genTableMapper.selectGenTableById(tableId); - // 查询列信息 - List columns = table.getColumns(); - setPkColumn(table, columns); - VelocityInitializer.initVelocity(); - - VelocityContext context = VelocityUtils.prepareContext(table); - - // 获取模板列表 - List templates = VelocityUtils.getTemplateList(table.getTplCategory()); - for (String template : templates) - { - // 渲染模板 - StringWriter sw = new StringWriter(); - Template tpl = Velocity.getTemplate(template, Constants.UTF8); - tpl.merge(context, sw); - dataMap.put(template, sw.toString()); - } - return dataMap; - } - - /** - * 生成代码 - * - * @param tableName 表名称 - * @return 数据 - */ - @Override - public byte[] generatorCode(String tableName) - { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(outputStream); - generatorCode(tableName, zip); - IOUtils.closeQuietly(zip); - return outputStream.toByteArray(); - } - - /** - * 批量生成代码 - * - * @param tableNames 表数组 - * @return 数据 - */ - @Override - public byte[] generatorCode(String[] tableNames) - { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(outputStream); - for (String tableName : tableNames) - { - generatorCode(tableName, zip); - } - IOUtils.closeQuietly(zip); - return outputStream.toByteArray(); - } - - /** - * 查询表信息并生成代码 - */ - private void generatorCode(String tableName, ZipOutputStream zip) - { - // 查询表信息 - GenTable table = genTableMapper.selectGenTableByName(tableName); - // 查询列信息 - List columns = table.getColumns(); - setPkColumn(table, columns); - - VelocityInitializer.initVelocity(); - - VelocityContext context = VelocityUtils.prepareContext(table); - - // 获取模板列表 - List templates = VelocityUtils.getTemplateList(table.getTplCategory()); - for (String template : templates) - { - // 渲染模板 - StringWriter sw = new StringWriter(); - Template tpl = Velocity.getTemplate(template, Constants.UTF8); - tpl.merge(context, sw); - try - { - // 添加到zip - zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table))); - IOUtils.write(sw.toString(), zip, Constants.UTF8); - IOUtils.closeQuietly(sw); - zip.closeEntry(); - } - catch (IOException e) - { - log.error("渲染模板失败,表名:" + table.getTableName(), e); - } - } - } - - /** - * 修改保存参数校验 - * - * @param genTable 业务信息 - */ - public void validateEdit(GenTable genTable) - { - if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) - { - String options = JSON.toJSONString(genTable.getParams()); - JSONObject paramsObj = JSONObject.parseObject(options); - if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) - { - throw new BusinessException("树编码字段不能为空"); - } - else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) - { - throw new BusinessException("树父编码字段不能为空"); - } - else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) - { - throw new BusinessException("树名称字段不能为空"); - } - } - } - - /** - * 设置主键列信息 - * - * @param genTable 业务表信息 - * @param columns 业务字段列表 - */ - public void setPkColumn(GenTable table, List columns) - { - for (GenTableColumn column : columns) - { - if (column.isPk()) - { - table.setPkColumn(column); - break; - } - } - if (StringUtils.isNull(table.getPkColumn())) - { - table.setPkColumn(columns.get(0)); - } - } - - /** - * 设置代码生成其他选项值 - * - * @param genTable 设置后的生成对象 - */ - public void setTableFromOptions(GenTable genTable) - { - JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions()); - if (StringUtils.isNotNull(paramsObj)) - { - String treeCode = paramsObj.getString(GenConstants.TREE_CODE); - String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE); - String treeName = paramsObj.getString(GenConstants.TREE_NAME); - genTable.setTreeCode(treeCode); - genTable.setTreeParentCode(treeParentCode); - genTable.setTreeName(treeName); - } - } +package com.ruoyi.generator.service.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.commons.io.IOUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.constant.GenConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.generator.domain.GenTable; +import com.ruoyi.generator.domain.GenTableColumn; +import com.ruoyi.generator.mapper.GenTableColumnMapper; +import com.ruoyi.generator.mapper.GenTableMapper; +import com.ruoyi.generator.service.IGenTableService; +import com.ruoyi.generator.util.GenUtils; +import com.ruoyi.generator.util.VelocityInitializer; +import com.ruoyi.generator.util.VelocityUtils; + +/** + * 业务 服务层实现 + * + * @author ruoyi + */ +@Service +public class GenTableServiceImpl implements IGenTableService { + private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); + + @Autowired + private GenTableMapper genTableMapper; + + @Autowired + private GenTableColumnMapper genTableColumnMapper; + + /** + * 查询业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + @Override + public GenTable selectGenTableById(Long id) { + GenTable genTable = genTableMapper.selectGenTableById(id); + setTableFromOptions(genTable); + return genTable; + } + + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + @Override + public List selectGenTableList(GenTable genTable) { + return genTableMapper.selectGenTableList(genTable); + } + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + public List selectDbTableList(GenTable genTable) { + return genTableMapper.selectDbTableList(genTable); + } + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + public List selectDbTableListByNames(String[] tableNames) { + return genTableMapper.selectDbTableListByNames(tableNames); + } + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + @Override + @Transactional + public void updateGenTable(GenTable genTable) { + String options = JSON.toJSONString(genTable.getParams()); + genTable.setOptions(options); + int row = genTableMapper.updateGenTable(genTable); + if (row > 0) { + for (GenTableColumn cenTableColumn : genTable.getColumns()) { + genTableColumnMapper.updateGenTableColumn(cenTableColumn); + } + } + } + + /** + * 删除业务对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + @Transactional + public void deleteGenTableByIds(String ids) { + genTableMapper.deleteGenTableByIds(Convert.toLongArray(ids)); + genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); + } + + /** + * 导入表结构 + * + * @param tableList 导入表列表 + * @param operName 操作人员 + */ + @Override + @Transactional + public void importGenTable(List tableList, String operName) { + for (GenTable table : tableList) { + try { + String tableName = table.getTableName(); + GenUtils.initTable(table, operName); + int row = genTableMapper.insertGenTable(table); + if (row > 0) { + // 保存列信息 + List genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); + for (GenTableColumn column : genTableColumns) { + GenUtils.initColumnField(column, table); + genTableColumnMapper.insertGenTableColumn(column); + } + } + } catch (Exception e) { + log.error("表名 " + table.getTableName() + " 导入失败:", e); + } + } + } + + /** + * 预览代码 + * + * @param tableId 表编号 + * @return 预览数据列表 + */ + public Map previewCode(Long tableId) { + Map dataMap = new LinkedHashMap<>(); + // 查询表信息 + GenTable table = genTableMapper.selectGenTableById(tableId); + // 查询列信息 + List columns = table.getColumns(); + setPkColumn(table, columns); + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 获取模板列表 + List templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + dataMap.put(template, sw.toString()); + } + return dataMap; + } + + /** + * 生成代码 + * + * @param tableName 表名称 + * @return 数据 + */ + @Override + public byte[] generatorCode(String tableName) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + generatorCode(tableName, zip); + IOUtils.closeQuietly(zip); + return outputStream.toByteArray(); + } + + /** + * 批量生成代码 + * + * @param tableNames 表数组 + * @return 数据 + */ + @Override + public byte[] generatorCode(String[] tableNames) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + for (String tableName : tableNames) { + generatorCode(tableName, zip); + } + IOUtils.closeQuietly(zip); + return outputStream.toByteArray(); + } + + /** + * 查询表信息并生成代码 + */ + private void generatorCode(String tableName, ZipOutputStream zip) { + // 查询表信息 + GenTable table = genTableMapper.selectGenTableByName(tableName); + // 查询列信息 + List columns = table.getColumns(); + setPkColumn(table, columns); + + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 获取模板列表 + List templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + try { + // 添加到zip + zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table))); + IOUtils.write(sw.toString(), zip, Constants.UTF8); + IOUtils.closeQuietly(sw); + zip.closeEntry(); + } catch (IOException e) { + log.error("渲染模板失败,表名:" + table.getTableName(), e); + } + } + } + + /** + * 修改保存参数校验 + * + * @param genTable 业务信息 + */ + public void validateEdit(GenTable genTable) { + if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) { + String options = JSON.toJSONString(genTable.getParams()); + JSONObject paramsObj = JSONObject.parseObject(options); + if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) { + throw new BusinessException("树编码字段不能为空"); + } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) { + throw new BusinessException("树父编码字段不能为空"); + } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) { + throw new BusinessException("树名称字段不能为空"); + } + } + } + + /** + * 设置主键列信息 + * + * @param genTable 业务表信息 + * @param columns 业务字段列表 + */ + public void setPkColumn(GenTable table, List columns) { + for (GenTableColumn column : columns) { + if (column.isPk()) { + table.setPkColumn(column); + break; + } + } + if (StringUtils.isNull(table.getPkColumn())) { + table.setPkColumn(columns.get(0)); + } + } + + /** + * 设置代码生成其他选项值 + * + * @param genTable 设置后的生成对象 + */ + public void setTableFromOptions(GenTable genTable) { + JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions()); + if (StringUtils.isNotNull(paramsObj)) { + String treeCode = paramsObj.getString(GenConstants.TREE_CODE); + String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE); + String treeName = paramsObj.getString(GenConstants.TREE_NAME); + genTable.setTreeCode(treeCode); + genTable.setTreeParentCode(treeParentCode); + genTable.setTreeName(treeName); + } + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java index 4f04e8fbc..2f881af25 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java @@ -1,238 +1,206 @@ -package com.ruoyi.generator.util; - -import java.util.Arrays; -import org.apache.commons.lang3.RegExUtils; -import com.ruoyi.common.constant.GenConstants; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.generator.config.GenConfig; -import com.ruoyi.generator.domain.GenTable; -import com.ruoyi.generator.domain.GenTableColumn; - -/** - * 代码生成器 工具类 - * - * @author ruoyi - */ -public class GenUtils -{ - /** - * 初始化表信息 - */ - public static void initTable(GenTable genTable, String operName) - { - genTable.setClassName(convertClassName(genTable.getTableName())); - genTable.setPackageName(GenConfig.getPackageName()); - genTable.setModuleName(getModuleName(GenConfig.getPackageName())); - genTable.setBusinessName(getBusinessName(genTable.getTableName())); - genTable.setFunctionName(replaceText(genTable.getTableComment())); - genTable.setFunctionAuthor(GenConfig.getAuthor()); - genTable.setCreateBy(operName); - } - - /** - * 初始化列属性字段 - */ - public static void initColumnField(GenTableColumn column, GenTable table) - { - String dataType = getDbType(column.getColumnType()); - String columnName = column.getColumnName(); - column.setTableId(table.getTableId()); - column.setCreateBy(table.getCreateBy()); - // 设置java字段名 - column.setJavaField(StringUtils.toCamelCase(columnName)); - - if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType)) - { - column.setJavaType(GenConstants.TYPE_STRING); - // 字符串长度超过500设置为文本域 - Integer columnLength = getColumnLength(column.getColumnType()); - String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT; - column.setHtmlType(htmlType); - } - else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) - { - column.setJavaType(GenConstants.TYPE_DATE); - column.setHtmlType(GenConstants.HTML_DATETIME); - } - else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) - { - column.setHtmlType(GenConstants.HTML_INPUT); - - // 如果是浮点型 - String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); - if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) - { - column.setJavaType(GenConstants.TYPE_DOUBLE); - } - // 如果是整形 - else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) - { - column.setJavaType(GenConstants.TYPE_INTEGER); - } - // 长整形 - else - { - column.setJavaType(GenConstants.TYPE_LONG); - } - } - - // 插入字段(默认所有字段都需要插入) - column.setIsInsert(GenConstants.REQUIRE); - - // 编辑字段 - if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk()) - { - column.setIsEdit(GenConstants.REQUIRE); - } - // 列表字段 - if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk()) - { - column.setIsList(GenConstants.REQUIRE); - } - // 查询字段 - if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) - { - column.setIsQuery(GenConstants.REQUIRE); - } - - // 查询字段类型 - if (StringUtils.endsWithIgnoreCase(columnName, "name")) - { - column.setQueryType(GenConstants.QUERY_LIKE); - } - // 状态字段设置单选框 - if (StringUtils.endsWithIgnoreCase(columnName, "status")) - { - column.setHtmlType(GenConstants.HTML_RADIO); - } - // 类型&性别字段设置下拉框 - else if (StringUtils.endsWithIgnoreCase(columnName, "type") - || StringUtils.endsWithIgnoreCase(columnName, "sex")) - { - column.setHtmlType(GenConstants.HTML_SELECT); - } - } - - /** - * 校验数组是否包含指定值 - * - * @param arr 数组 - * @param targetValue 值 - * @return 是否包含 - */ - public static boolean arraysContains(String[] arr, String targetValue) - { - return Arrays.asList(arr).contains(targetValue); - } - - /** - * 获取模块名 - * - * @param packageName 包名 - * @return 模块名 - */ - public static String getModuleName(String packageName) - { - int lastIndex = packageName.lastIndexOf("."); - int nameLength = packageName.length(); - String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); - return moduleName; - } - - /** - * 获取业务名 - * - * @param tableName 表名 - * @return 业务名 - */ - public static String getBusinessName(String tableName) - { - int lastIndex = tableName.lastIndexOf("_"); - int nameLength = tableName.length(); - String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength); - return businessName; - } - - /** - * 表名转换成Java类名 - * - * @param tableName 表名称 - * @return 类名 - */ - public static String convertClassName(String tableName) - { - boolean autoRemovePre = GenConfig.getAutoRemovePre(); - String tablePrefix = GenConfig.getTablePrefix(); - if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) - { - String[] searchList = StringUtils.split(tablePrefix, ","); - String[] replacementList = emptyList(searchList.length); - tableName = StringUtils.replaceEach(tableName, searchList, replacementList); - } - return StringUtils.convertToCamelCase(tableName); - } - - /** - * 关键字替换 - * - * @param name 需要被替换的名字 - * @return 替换后的名字 - */ - public static String replaceText(String text) - { - return RegExUtils.replaceAll(text, "(?:表|若依)", ""); - } - - /** - * 获取数据库类型字段 - * - * @param columnType 列类型 - * @return 截取后的列类型 - */ - public static String getDbType(String columnType) - { - if (StringUtils.indexOf(columnType, "(") > 0) - { - return StringUtils.substringBefore(columnType, "("); - } - else - { - return columnType; - } - } - - /** - * 获取字段长度 - * - * @param columnType 列类型 - * @return 截取后的列类型 - */ - public static Integer getColumnLength(String columnType) - { - if (StringUtils.indexOf(columnType, "(") > 0) - { - String length = StringUtils.substringBetween(columnType, "(", ")"); - return Integer.valueOf(length); - } - else - { - return 0; - } - } - - /** - * 获取空数组列表 - * - * @param length 长度 - * @return 数组信息 - */ - public static String[] emptyList(int length) - { - String[] values = new String[length]; - for (int i = 0; i < length; i++) - { - values[i] = StringUtils.EMPTY; - } - return values; - } +package com.ruoyi.generator.util; + +import java.util.Arrays; + +import org.apache.commons.lang3.RegExUtils; +import com.ruoyi.common.constant.GenConstants; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.generator.config.GenConfig; +import com.ruoyi.generator.domain.GenTable; +import com.ruoyi.generator.domain.GenTableColumn; + +/** + * 代码生成器 工具类 + * + * @author ruoyi + */ +public class GenUtils { + /** + * 初始化表信息 + */ + public static void initTable(GenTable genTable, String operName) { + genTable.setClassName(convertClassName(genTable.getTableName())); + genTable.setPackageName(GenConfig.getPackageName()); + genTable.setModuleName(getModuleName(GenConfig.getPackageName())); + genTable.setBusinessName(getBusinessName(genTable.getTableName())); + genTable.setFunctionName(replaceText(genTable.getTableComment())); + genTable.setFunctionAuthor(GenConfig.getAuthor()); + genTable.setCreateBy(operName); + } + + /** + * 初始化列属性字段 + */ + public static void initColumnField(GenTableColumn column, GenTable table) { + String dataType = getDbType(column.getColumnType()); + String columnName = column.getColumnName(); + column.setTableId(table.getTableId()); + column.setCreateBy(table.getCreateBy()); + // 设置java字段名 + column.setJavaField(StringUtils.toCamelCase(columnName)); + + if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType)) { + column.setJavaType(GenConstants.TYPE_STRING); + // 字符串长度超过500设置为文本域 + Integer columnLength = getColumnLength(column.getColumnType()); + String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT; + column.setHtmlType(htmlType); + } else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) { + column.setJavaType(GenConstants.TYPE_DATE); + column.setHtmlType(GenConstants.HTML_DATETIME); + } else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) { + column.setHtmlType(GenConstants.HTML_INPUT); + + // 如果是浮点型 + String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); + if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { + column.setJavaType(GenConstants.TYPE_DOUBLE); + } + // 如果是整形 + else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) { + column.setJavaType(GenConstants.TYPE_INTEGER); + } + // 长整形 + else { + column.setJavaType(GenConstants.TYPE_LONG); + } + } + + // 插入字段(默认所有字段都需要插入) + column.setIsInsert(GenConstants.REQUIRE); + + // 编辑字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk()) { + column.setIsEdit(GenConstants.REQUIRE); + } + // 列表字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk()) { + column.setIsList(GenConstants.REQUIRE); + } + // 查询字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) { + column.setIsQuery(GenConstants.REQUIRE); + } + + // 查询字段类型 + if (StringUtils.endsWithIgnoreCase(columnName, "name")) { + column.setQueryType(GenConstants.QUERY_LIKE); + } + // 状态字段设置单选框 + if (StringUtils.endsWithIgnoreCase(columnName, "status")) { + column.setHtmlType(GenConstants.HTML_RADIO); + } + // 类型&性别字段设置下拉框 + else if (StringUtils.endsWithIgnoreCase(columnName, "type") + || StringUtils.endsWithIgnoreCase(columnName, "sex")) { + column.setHtmlType(GenConstants.HTML_SELECT); + } + } + + /** + * 校验数组是否包含指定值 + * + * @param arr 数组 + * @param targetValue 值 + * @return 是否包含 + */ + public static boolean arraysContains(String[] arr, String targetValue) { + return Arrays.asList(arr).contains(targetValue); + } + + /** + * 获取模块名 + * + * @param packageName 包名 + * @return 模块名 + */ + public static String getModuleName(String packageName) { + int lastIndex = packageName.lastIndexOf("."); + int nameLength = packageName.length(); + String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); + return moduleName; + } + + /** + * 获取业务名 + * + * @param tableName 表名 + * @return 业务名 + */ + public static String getBusinessName(String tableName) { + int lastIndex = tableName.lastIndexOf("_"); + int nameLength = tableName.length(); + String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength); + return businessName; + } + + /** + * 表名转换成Java类名 + * + * @param tableName 表名称 + * @return 类名 + */ + public static String convertClassName(String tableName) { + boolean autoRemovePre = GenConfig.getAutoRemovePre(); + String tablePrefix = GenConfig.getTablePrefix(); + if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) { + String[] searchList = StringUtils.split(tablePrefix, ","); + String[] replacementList = emptyList(searchList.length); + tableName = StringUtils.replaceEach(tableName, searchList, replacementList); + } + return StringUtils.convertToCamelCase(tableName); + } + + /** + * 关键字替换 + * + * @param name 需要被替换的名字 + * @return 替换后的名字 + */ + public static String replaceText(String text) { + return RegExUtils.replaceAll(text, "(?:表|若依)", ""); + } + + /** + * 获取数据库类型字段 + * + * @param columnType 列类型 + * @return 截取后的列类型 + */ + public static String getDbType(String columnType) { + if (StringUtils.indexOf(columnType, "(") > 0) { + return StringUtils.substringBefore(columnType, "("); + } else { + return columnType; + } + } + + /** + * 获取字段长度 + * + * @param columnType 列类型 + * @return 截取后的列类型 + */ + public static Integer getColumnLength(String columnType) { + if (StringUtils.indexOf(columnType, "(") > 0) { + String length = StringUtils.substringBetween(columnType, "(", ")"); + return Integer.valueOf(length); + } else { + return 0; + } + } + + /** + * 获取空数组列表 + * + * @param length 长度 + * @return 数组信息 + */ + public static String[] emptyList(int length) { + String[] values = new String[length]; + for (int i = 0; i < length; i++) { + values[i] = StringUtils.EMPTY; + } + return values; + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java index 8f9ee07b8..5abe6ee52 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java @@ -1,35 +1,31 @@ -package com.ruoyi.generator.util; - -import java.util.Properties; -import org.apache.velocity.app.Velocity; -import com.ruoyi.common.constant.Constants; - -/** - * VelocityEngine工厂 - * - * @author RuoYi - */ -public class VelocityInitializer -{ - /** - * 初始化vm方法 - */ - public static void initVelocity() - { - Properties p = new Properties(); - try - { - // 加载classpath目录下的vm文件 - p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - // 定义字符集 - p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8); - p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8); - // 初始化Velocity引擎,指定配置Properties - Velocity.init(p); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } -} +package com.ruoyi.generator.util; + +import java.util.Properties; + +import org.apache.velocity.app.Velocity; +import com.ruoyi.common.constant.Constants; + +/** + * VelocityEngine工厂 + * + * @author RuoYi + */ +public class VelocityInitializer { + /** + * 初始化vm方法 + */ + public static void initVelocity() { + Properties p = new Properties(); + try { + // 加载classpath目录下的vm文件 + p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + // 定义字符集 + p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8); + p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8); + // 初始化Velocity引擎,指定配置Properties + Velocity.init(p); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java index 38fb3bcfb..543916eb9 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java @@ -3,6 +3,7 @@ package com.ruoyi.generator.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; + import org.apache.velocity.VelocityContext; import com.alibaba.fastjson.JSONObject; import com.ruoyi.common.constant.GenConstants; @@ -12,24 +13,28 @@ import com.ruoyi.generator.config.GenConfig; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; -public class VelocityUtils -{ - /** 项目空间路径 */ +public class VelocityUtils { + /** + * 项目空间路径 + */ private static final String PROJECT_PATH = "main/java"; - /** mybatis空间路径 */ + /** + * mybatis空间路径 + */ private static final String MYBATIS_PATH = "main/resources/mapper"; - /** html空间路径 */ + /** + * html空间路径 + */ private static final String TEMPLATES_PATH = "main/resources/templates"; /** * 设置模板变量信息 - * + * * @return 模板列表 */ - public static VelocityContext prepareContext(GenTable genTable) - { + public static VelocityContext prepareContext(GenTable genTable) { String moduleName = genTable.getModuleName(); String businessName = genTable.getBusinessName(); String packageName = genTable.getPackageName(); @@ -53,15 +58,13 @@ public class VelocityUtils velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("columns", genTable.getColumns()); velocityContext.put("table", genTable); - if (GenConstants.TPL_TREE.equals(tplCategory)) - { + if (GenConstants.TPL_TREE.equals(tplCategory)) { setTreeVelocityContext(velocityContext, genTable); } return velocityContext; } - public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) - { + public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) { String options = genTable.getOptions(); JSONObject paramsObj = JSONObject.parseObject(options); String treeCode = getTreecode(paramsObj); @@ -72,23 +75,20 @@ public class VelocityUtils context.put("treeParentCode", treeParentCode); context.put("treeName", treeName); context.put("expandColumn", getExpandColumn(genTable)); - if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) - { + if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE)); } - if (paramsObj.containsKey(GenConstants.TREE_NAME)) - { + if (paramsObj.containsKey(GenConstants.TREE_NAME)) { context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME)); } } /** * 获取模板信息 - * + * * @return 模板列表 */ - public static List getTemplateList(String tplCategory) - { + public static List getTemplateList(String tplCategory) { List templates = new ArrayList(); templates.add("vm/java/domain.java.vm"); templates.add("vm/java/mapper.java.vm"); @@ -96,12 +96,9 @@ public class VelocityUtils templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/controller.java.vm"); templates.add("vm/xml/mapper.xml.vm"); - if (GenConstants.TPL_CRUD.equals(tplCategory)) - { + if (GenConstants.TPL_CRUD.equals(tplCategory)) { templates.add("vm/html/list.html.vm"); - } - else if (GenConstants.TPL_TREE.equals(tplCategory)) - { + } else if (GenConstants.TPL_TREE.equals(tplCategory)) { templates.add("vm/html/tree.html.vm"); templates.add("vm/html/list-tree.html.vm"); } @@ -114,8 +111,7 @@ public class VelocityUtils /** * 获取文件名 */ - public static String getFileName(String template, GenTable genTable) - { + public static String getFileName(String template, GenTable genTable) { // 文件名称 String fileName = ""; // 包路径 @@ -131,52 +127,29 @@ public class VelocityUtils String mybatisPath = MYBATIS_PATH + "/" + moduleName; String htmlPath = TEMPLATES_PATH + "/" + moduleName + "/" + businessName; - if (template.contains("domain.java.vm")) - { + if (template.contains("domain.java.vm")) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); - } - else if (template.contains("mapper.java.vm")) - { + } else if (template.contains("mapper.java.vm")) { fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); - } - else if (template.contains("service.java.vm")) - { + } else if (template.contains("service.java.vm")) { fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); - } - else if (template.contains("serviceImpl.java.vm")) - { + } else if (template.contains("serviceImpl.java.vm")) { fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); - } - else if (template.contains("controller.java.vm")) - { + } else if (template.contains("controller.java.vm")) { fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); - } - else if (template.contains("mapper.xml.vm")) - { + } else if (template.contains("mapper.xml.vm")) { fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); - } - else if (template.contains("list.html.vm")) - { + } else if (template.contains("list.html.vm")) { fileName = StringUtils.format("{}/{}.html", htmlPath, businessName); - } - else if (template.contains("list-tree.html.vm")) - { + } else if (template.contains("list-tree.html.vm")) { fileName = StringUtils.format("{}/{}.html", htmlPath, businessName); - } - else if (template.contains("tree.html.vm")) - { + } else if (template.contains("tree.html.vm")) { fileName = StringUtils.format("{}/tree.html", htmlPath); - } - else if (template.contains("add.html.vm")) - { + } else if (template.contains("add.html.vm")) { fileName = StringUtils.format("{}/add.html", htmlPath); - } - else if (template.contains("edit.html.vm")) - { + } else if (template.contains("edit.html.vm")) { fileName = StringUtils.format("{}/edit.html", htmlPath); - } - else if (template.contains("sql.vm")) - { + } else if (template.contains("sql.vm")) { fileName = businessName + "Menu.sql"; } return fileName; @@ -184,11 +157,10 @@ public class VelocityUtils /** * 获取项目文件路径 - * + * * @return 路径 */ - public static String getProjectPath() - { + public static String getProjectPath() { String packageName = GenConfig.getPackageName(); StringBuffer projectPath = new StringBuffer(); projectPath.append("main/java/"); @@ -199,12 +171,11 @@ public class VelocityUtils /** * 获取包前缀 - * + * * @param packageName 包名称 * @return 包前缀名称 */ - public static String getPackagePrefix(String packageName) - { + public static String getPackagePrefix(String packageName) { int lastIndex = packageName.lastIndexOf("."); String basePackage = StringUtils.substring(packageName, 0, lastIndex); return basePackage; @@ -212,21 +183,16 @@ public class VelocityUtils /** * 根据列类型获取导入包 - * + * * @param column 列集合 * @return 返回需要导入的包列表 */ - public static HashSet getImportList(List columns) - { + public static HashSet getImportList(List columns) { HashSet importList = new HashSet(); - for (GenTableColumn column : columns) - { - if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) - { + for (GenTableColumn column : columns) { + if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) { importList.add("java.util.Date"); - } - else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) - { + } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) { importList.add("java.math.BigDecimal"); } } @@ -235,27 +201,24 @@ public class VelocityUtils /** * 获取权限前缀 - * - * @param moduleName 模块名称 + * + * @param moduleName 模块名称 * @param businessName 业务名称 * @return 返回权限前缀 */ - public static String getPermissionPrefix(String moduleName, String businessName) - { + public static String getPermissionPrefix(String moduleName, String businessName) { return StringUtils.format("{}:{}", moduleName, businessName); } /** * 获取树编码 - * + * * @param options 生成其他选项 * @return 树编码 */ - public static String getTreecode(JSONObject paramsObj) - { - if (paramsObj.containsKey(GenConstants.TREE_CODE)) - { + public static String getTreecode(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_CODE)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); } return ""; @@ -263,14 +226,12 @@ public class VelocityUtils /** * 获取树父编码 - * + * * @param options 生成其他选项 * @return 树父编码 */ - public static String getTreeParentCode(JSONObject paramsObj) - { - if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) - { + public static String getTreeParentCode(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); } return ""; @@ -278,14 +239,12 @@ public class VelocityUtils /** * 获取树名称 - * + * * @param options 生成其他选项 * @return 树名称 */ - public static String getTreeName(JSONObject paramsObj) - { - if (paramsObj.containsKey(GenConstants.TREE_NAME)) - { + public static String getTreeName(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_NAME)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); } return ""; @@ -293,24 +252,20 @@ public class VelocityUtils /** * 获取需要在哪一列上面显示展开按钮 - * + * * @param genTable 业务表对象 * @return 展开按钮列序号 */ - public static int getExpandColumn(GenTable genTable) - { + public static int getExpandColumn(GenTable genTable) { String options = genTable.getOptions(); JSONObject paramsObj = JSONObject.parseObject(options); String treeName = paramsObj.getString(GenConstants.TREE_NAME); int num = 0; - for (GenTableColumn column : genTable.getColumns()) - { - if (column.isList()) - { + for (GenTableColumn column : genTable.getColumns()) { + if (column.isList()) { num++; String columnName = column.getColumnName(); - if (columnName.equals(treeName)) - { + if (columnName.equals(treeName)) { break; } } From b4f9eb5409e116d211ca5f8c0231b92ecca6491a Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:21:52 +0800 Subject: [PATCH 07/52] format code --- .../ruoyi/quartz/config/ScheduleConfig.java | 113 ++-- .../quartz/controller/SysJobController.java | 318 ++++++------ .../controller/SysJobLogController.java | 176 +++---- .../java/com/ruoyi/quartz/domain/SysJob.java | 334 ++++++------ .../com/ruoyi/quartz/domain/SysJobLog.java | 310 +++++------ .../ruoyi/quartz/mapper/SysJobLogMapper.java | 128 ++--- .../com/ruoyi/quartz/mapper/SysJobMapper.java | 134 ++--- .../quartz/service/ISysJobLogService.java | 112 ++-- .../ruoyi/quartz/service/ISysJobService.java | 202 ++++---- .../service/impl/SysJobLogServiceImpl.java | 34 +- .../service/impl/SysJobServiceImpl.java | 485 +++++++++--------- .../java/com/ruoyi/quartz/task/RyTask.java | 52 +- .../ruoyi/quartz/util/AbstractQuartzJob.java | 204 ++++---- .../java/com/ruoyi/quartz/util/CronUtils.java | 30 +- .../com/ruoyi/quartz/util/JobInvokeUtil.java | 341 ++++++------ .../QuartzDisallowConcurrentExecution.java | 39 +- .../ruoyi/quartz/util/QuartzJobExecution.java | 35 +- .../com/ruoyi/quartz/util/ScheduleUtils.java | 214 ++++---- 18 files changed, 1574 insertions(+), 1687 deletions(-) diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/config/ScheduleConfig.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/config/ScheduleConfig.java index e466ed057..98b5bbb17 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/config/ScheduleConfig.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/config/ScheduleConfig.java @@ -1,57 +1,56 @@ -package com.ruoyi.quartz.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.quartz.SchedulerFactoryBean; -import javax.sql.DataSource; -import java.util.Properties; - -/** - * 定时任务配置 - * - * @author ruoyi - */ -@Configuration -public class ScheduleConfig -{ - @Bean - public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) - { - SchedulerFactoryBean factory = new SchedulerFactoryBean(); - factory.setDataSource(dataSource); - - // quartz参数 - Properties prop = new Properties(); - prop.put("org.quartz.scheduler.instanceName", "RuoyiScheduler"); - prop.put("org.quartz.scheduler.instanceId", "AUTO"); - // 线程池配置 - prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); - prop.put("org.quartz.threadPool.threadCount", "20"); - prop.put("org.quartz.threadPool.threadPriority", "5"); - // JobStore配置 - prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); - // 集群配置 - prop.put("org.quartz.jobStore.isClustered", "true"); - prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000"); - prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); - prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true"); - - // sqlserver 启用 - // prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?"); - prop.put("org.quartz.jobStore.misfireThreshold", "12000"); - prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_"); - factory.setQuartzProperties(prop); - - factory.setSchedulerName("RuoyiScheduler"); - // 延时启动 - factory.setStartupDelay(1); - factory.setApplicationContextSchedulerContextKey("applicationContextKey"); - // 可选,QuartzScheduler - // 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 - factory.setOverwriteExistingJobs(true); - // 设置自动启动,默认为true - factory.setAutoStartup(true); - - return factory; - } -} +package com.ruoyi.quartz.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; + +import javax.sql.DataSource; +import java.util.Properties; + +/** + * 定时任务配置 + * + * @author ruoyi + */ +@Configuration +public class ScheduleConfig { + @Bean + public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) { + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setDataSource(dataSource); + + // quartz参数 + Properties prop = new Properties(); + prop.put("org.quartz.scheduler.instanceName", "RuoyiScheduler"); + prop.put("org.quartz.scheduler.instanceId", "AUTO"); + // 线程池配置 + prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); + prop.put("org.quartz.threadPool.threadCount", "20"); + prop.put("org.quartz.threadPool.threadPriority", "5"); + // JobStore配置 + prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); + // 集群配置 + prop.put("org.quartz.jobStore.isClustered", "true"); + prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000"); + prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); + prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true"); + + // sqlserver 启用 + // prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?"); + prop.put("org.quartz.jobStore.misfireThreshold", "12000"); + prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_"); + factory.setQuartzProperties(prop); + + factory.setSchedulerName("RuoyiScheduler"); + // 延时启动 + factory.setStartupDelay(1); + factory.setApplicationContextSchedulerContextKey("applicationContextKey"); + // 可选,QuartzScheduler + // 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 + factory.setOverwriteExistingJobs(true); + // 设置自动启动,默认为true + factory.setAutoStartup(true); + + return factory; + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java index 4bfe4f6d8..e827117d0 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java @@ -1,165 +1,153 @@ -package com.ruoyi.quartz.controller; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.exception.job.TaskException; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.quartz.domain.SysJob; -import com.ruoyi.quartz.service.ISysJobService; - -/** - * 调度任务信息操作处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/job") -public class SysJobController extends BaseController -{ - private String prefix = "monitor/job"; - - @Autowired - private ISysJobService jobService; - - @RequiresPermissions("monitor:job:view") - @GetMapping() - public String job() - { - return prefix + "/job"; - } - - @RequiresPermissions("monitor:job:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysJob job) - { - startPage(); - List list = jobService.selectJobList(job); - return getDataTable(list); - } - - @Log(title = "定时任务", businessType = BusinessType.EXPORT) - @RequiresPermissions("monitor:job:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysJob job) - { - List list = jobService.selectJobList(job); - ExcelUtil util = new ExcelUtil(SysJob.class); - return util.exportExcel(list, "定时任务"); - } - - @Log(title = "定时任务", businessType = BusinessType.DELETE) - @RequiresPermissions("monitor:job:remove") - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) throws SchedulerException - { - jobService.deleteJobByIds(ids); - return success(); - } - - @RequiresPermissions("monitor:job:detail") - @GetMapping("/detail/{jobId}") - public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) - { - mmap.put("name", "job"); - mmap.put("job", jobService.selectJobById(jobId)); - return prefix + "/detail"; - } - - /** - * 任务调度状态修改 - */ - @Log(title = "定时任务", businessType = BusinessType.UPDATE) - @RequiresPermissions("monitor:job:changeStatus") - @PostMapping("/changeStatus") - @ResponseBody - public AjaxResult changeStatus(SysJob job) throws SchedulerException - { - SysJob newJob = jobService.selectJobById(job.getJobId()); - newJob.setStatus(job.getStatus()); - return toAjax(jobService.changeStatus(newJob)); - } - - /** - * 任务调度立即执行一次 - */ - @Log(title = "定时任务", businessType = BusinessType.UPDATE) - @RequiresPermissions("monitor:job:changeStatus") - @PostMapping("/run") - @ResponseBody - public AjaxResult run(SysJob job) throws SchedulerException - { - jobService.run(job); - return success(); - } - - /** - * 新增调度 - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } - - /** - * 新增保存调度 - */ - @Log(title = "定时任务", businessType = BusinessType.INSERT) - @RequiresPermissions("monitor:job:add") - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException - { - return toAjax(jobService.insertJob(job)); - } - - /** - * 修改调度 - */ - @GetMapping("/edit/{jobId}") - public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) - { - mmap.put("job", jobService.selectJobById(jobId)); - return prefix + "/edit"; - } - - /** - * 修改保存调度 - */ - @Log(title = "定时任务", businessType = BusinessType.UPDATE) - @RequiresPermissions("monitor:job:edit") - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(@Validated SysJob job) throws SchedulerException, TaskException - { - return toAjax(jobService.updateJob(job)); - } - - /** - * 校验cron表达式是否有效 - */ - @PostMapping("/checkCronExpressionIsValid") - @ResponseBody - public boolean checkCronExpressionIsValid(SysJob job) - { - return jobService.checkCronExpressionIsValid(job.getCronExpression()); - } -} +package com.ruoyi.quartz.controller; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.exception.job.TaskException; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.quartz.domain.SysJob; +import com.ruoyi.quartz.service.ISysJobService; + +/** + * 调度任务信息操作处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/job") +public class SysJobController extends BaseController { + private String prefix = "monitor/job"; + + @Autowired + private ISysJobService jobService; + + @RequiresPermissions("monitor:job:view") + @GetMapping() + public String job() { + return prefix + "/job"; + } + + @RequiresPermissions("monitor:job:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysJob job) { + startPage(); + List list = jobService.selectJobList(job); + return getDataTable(list); + } + + @Log(title = "定时任务", businessType = BusinessType.EXPORT) + @RequiresPermissions("monitor:job:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysJob job) { + List list = jobService.selectJobList(job); + ExcelUtil util = new ExcelUtil(SysJob.class); + return util.exportExcel(list, "定时任务"); + } + + @Log(title = "定时任务", businessType = BusinessType.DELETE) + @RequiresPermissions("monitor:job:remove") + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) throws SchedulerException { + jobService.deleteJobByIds(ids); + return success(); + } + + @RequiresPermissions("monitor:job:detail") + @GetMapping("/detail/{jobId}") + public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) { + mmap.put("name", "job"); + mmap.put("job", jobService.selectJobById(jobId)); + return prefix + "/detail"; + } + + /** + * 任务调度状态修改 + */ + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @RequiresPermissions("monitor:job:changeStatus") + @PostMapping("/changeStatus") + @ResponseBody + public AjaxResult changeStatus(SysJob job) throws SchedulerException { + SysJob newJob = jobService.selectJobById(job.getJobId()); + newJob.setStatus(job.getStatus()); + return toAjax(jobService.changeStatus(newJob)); + } + + /** + * 任务调度立即执行一次 + */ + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @RequiresPermissions("monitor:job:changeStatus") + @PostMapping("/run") + @ResponseBody + public AjaxResult run(SysJob job) throws SchedulerException { + jobService.run(job); + return success(); + } + + /** + * 新增调度 + */ + @GetMapping("/add") + public String add() { + return prefix + "/add"; + } + + /** + * 新增保存调度 + */ + @Log(title = "定时任务", businessType = BusinessType.INSERT) + @RequiresPermissions("monitor:job:add") + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException { + return toAjax(jobService.insertJob(job)); + } + + /** + * 修改调度 + */ + @GetMapping("/edit/{jobId}") + public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) { + mmap.put("job", jobService.selectJobById(jobId)); + return prefix + "/edit"; + } + + /** + * 修改保存调度 + */ + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @RequiresPermissions("monitor:job:edit") + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(@Validated SysJob job) throws SchedulerException, TaskException { + return toAjax(jobService.updateJob(job)); + } + + /** + * 校验cron表达式是否有效 + */ + @PostMapping("/checkCronExpressionIsValid") + @ResponseBody + public boolean checkCronExpressionIsValid(SysJob job) { + return jobService.checkCronExpressionIsValid(job.getCronExpression()); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java index 2c3d8e271..20ba7403f 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java @@ -1,91 +1,85 @@ -package com.ruoyi.quartz.controller; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.poi.ExcelUtil; -import com.ruoyi.quartz.domain.SysJobLog; -import com.ruoyi.quartz.service.ISysJobLogService; - -/** - * 调度日志操作处理 - * - * @author ruoyi - */ -@Controller -@RequestMapping("/monitor/jobLog") -public class SysJobLogController extends BaseController -{ - private String prefix = "monitor/job"; - - @Autowired - private ISysJobLogService jobLogService; - - @RequiresPermissions("monitor:job:view") - @GetMapping() - public String jobLog() - { - return prefix + "/jobLog"; - } - - @RequiresPermissions("monitor:job:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(SysJobLog jobLog) - { - startPage(); - List list = jobLogService.selectJobLogList(jobLog); - return getDataTable(list); - } - - @Log(title = "调度日志", businessType = BusinessType.EXPORT) - @RequiresPermissions("monitor:job:export") - @PostMapping("/export") - @ResponseBody - public AjaxResult export(SysJobLog jobLog) - { - List list = jobLogService.selectJobLogList(jobLog); - ExcelUtil util = new ExcelUtil(SysJobLog.class); - return util.exportExcel(list, "调度日志"); - } - - @Log(title = "调度日志", businessType = BusinessType.DELETE) - @RequiresPermissions("monitor:job:remove") - @PostMapping("/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(jobLogService.deleteJobLogByIds(ids)); - } - - @RequiresPermissions("monitor:job:detail") - @GetMapping("/detail/{jobLogId}") - public String detail(@PathVariable("jobLogId") Long jobLogId, ModelMap mmap) - { - mmap.put("name", "jobLog"); - mmap.put("jobLog", jobLogService.selectJobLogById(jobLogId)); - return prefix + "/detail"; - } - - @Log(title = "调度日志", businessType = BusinessType.CLEAN) - @RequiresPermissions("monitor:job:remove") - @PostMapping("/clean") - @ResponseBody - public AjaxResult clean() - { - jobLogService.cleanJobLog(); - return success(); - } -} +package com.ruoyi.quartz.controller; + +import java.util.List; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.quartz.domain.SysJobLog; +import com.ruoyi.quartz.service.ISysJobLogService; + +/** + * 调度日志操作处理 + * + * @author ruoyi + */ +@Controller +@RequestMapping("/monitor/jobLog") +public class SysJobLogController extends BaseController { + private String prefix = "monitor/job"; + + @Autowired + private ISysJobLogService jobLogService; + + @RequiresPermissions("monitor:job:view") + @GetMapping() + public String jobLog() { + return prefix + "/jobLog"; + } + + @RequiresPermissions("monitor:job:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(SysJobLog jobLog) { + startPage(); + List list = jobLogService.selectJobLogList(jobLog); + return getDataTable(list); + } + + @Log(title = "调度日志", businessType = BusinessType.EXPORT) + @RequiresPermissions("monitor:job:export") + @PostMapping("/export") + @ResponseBody + public AjaxResult export(SysJobLog jobLog) { + List list = jobLogService.selectJobLogList(jobLog); + ExcelUtil util = new ExcelUtil(SysJobLog.class); + return util.exportExcel(list, "调度日志"); + } + + @Log(title = "调度日志", businessType = BusinessType.DELETE) + @RequiresPermissions("monitor:job:remove") + @PostMapping("/remove") + @ResponseBody + public AjaxResult remove(String ids) { + return toAjax(jobLogService.deleteJobLogByIds(ids)); + } + + @RequiresPermissions("monitor:job:detail") + @GetMapping("/detail/{jobLogId}") + public String detail(@PathVariable("jobLogId") Long jobLogId, ModelMap mmap) { + mmap.put("name", "jobLog"); + mmap.put("jobLog", jobLogService.selectJobLogById(jobLogId)); + return prefix + "/detail"; + } + + @Log(title = "调度日志", businessType = BusinessType.CLEAN) + @RequiresPermissions("monitor:job:remove") + @PostMapping("/clean") + @ResponseBody + public AjaxResult clean() { + jobLogService.cleanJobLog(); + return success(); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java index 286555a2c..b2d36c2f4 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java @@ -1,169 +1,167 @@ -package com.ruoyi.quartz.domain; - -import java.io.Serializable; -import java.util.Date; -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.constant.ScheduleConstants; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.quartz.util.CronUtils; - -/** - * 定时任务调度表 sys_job - * - * @author ruoyi - */ -public class SysJob extends BaseEntity implements Serializable -{ - private static final long serialVersionUID = 1L; - - /** 任务ID */ - @Excel(name = "任务序号", cellType = ColumnType.NUMERIC) - private Long jobId; - - /** 任务名称 */ - @Excel(name = "任务名称") - private String jobName; - - /** 任务组名 */ - @Excel(name = "任务组名") - private String jobGroup; - - /** 调用目标字符串 */ - @Excel(name = "调用目标字符串") - private String invokeTarget; - - /** cron执行表达式 */ - @Excel(name = "执行表达式 ") - private String cronExpression; - - /** cron计划策略 */ - @Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行") - private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT; - - /** 是否并发执行(0允许 1禁止) */ - @Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止") - private String concurrent; - - /** 任务状态(0正常 1暂停) */ - @Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停") - private String status; - - public Long getJobId() - { - return jobId; - } - - public void setJobId(Long jobId) - { - this.jobId = jobId; - } - - @NotBlank(message = "任务名称不能为空") - @Size(min = 0, max = 64, message = "任务名称不能超过64个字符") - public String getJobName() - { - return jobName; - } - - public void setJobName(String jobName) - { - this.jobName = jobName; - } - - public String getJobGroup() - { - return jobGroup; - } - - public void setJobGroup(String jobGroup) - { - this.jobGroup = jobGroup; - } - - @NotBlank(message = "调用目标字符串不能为空") - @Size(min = 0, max = 1000, message = "调用目标字符串长度不能超过500个字符") - public String getInvokeTarget() - { - return invokeTarget; - } - - public void setInvokeTarget(String invokeTarget) - { - this.invokeTarget = invokeTarget; - } - - @NotBlank(message = "Cron执行表达式不能为空") - @Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符") - public String getCronExpression() - { - return cronExpression; - } - - public void setCronExpression(String cronExpression) - { - this.cronExpression = cronExpression; - } - - public Date getNextValidTime() - { - if (StringUtils.isNotEmpty(cronExpression)) - { - return CronUtils.getNextExecution(cronExpression); - } - return null; - } - - public String getMisfirePolicy() - { - return misfirePolicy; - } - - public void setMisfirePolicy(String misfirePolicy) - { - this.misfirePolicy = misfirePolicy; - } - - public String getConcurrent() - { - return concurrent; - } - - public void setConcurrent(String concurrent) - { - this.concurrent = concurrent; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("jobId", getJobId()) - .append("jobName", getJobName()) - .append("jobGroup", getJobGroup()) - .append("cronExpression", getCronExpression()) - .append("nextValidTime", getNextValidTime()) - .append("misfirePolicy", getMisfirePolicy()) - .append("concurrent", getConcurrent()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } +package com.ruoyi.quartz.domain; + +import java.io.Serializable; +import java.util.Date; +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.constant.ScheduleConstants; +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.quartz.util.CronUtils; + +/** + * 定时任务调度表 sys_job + * + * @author ruoyi + */ +public class SysJob extends BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 任务ID + */ + @Excel(name = "任务序号", cellType = ColumnType.NUMERIC) + private Long jobId; + + /** + * 任务名称 + */ + @Excel(name = "任务名称") + private String jobName; + + /** + * 任务组名 + */ + @Excel(name = "任务组名") + private String jobGroup; + + /** + * 调用目标字符串 + */ + @Excel(name = "调用目标字符串") + private String invokeTarget; + + /** + * cron执行表达式 + */ + @Excel(name = "执行表达式 ") + private String cronExpression; + + /** + * cron计划策略 + */ + @Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行") + private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT; + + /** + * 是否并发执行(0允许 1禁止) + */ + @Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止") + private String concurrent; + + /** + * 任务状态(0正常 1暂停) + */ + @Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停") + private String status; + + public Long getJobId() { + return jobId; + } + + public void setJobId(Long jobId) { + this.jobId = jobId; + } + + @NotBlank(message = "任务名称不能为空") + @Size(min = 0, max = 64, message = "任务名称不能超过64个字符") + public String getJobName() { + return jobName; + } + + public void setJobName(String jobName) { + this.jobName = jobName; + } + + public String getJobGroup() { + return jobGroup; + } + + public void setJobGroup(String jobGroup) { + this.jobGroup = jobGroup; + } + + @NotBlank(message = "调用目标字符串不能为空") + @Size(min = 0, max = 1000, message = "调用目标字符串长度不能超过500个字符") + public String getInvokeTarget() { + return invokeTarget; + } + + public void setInvokeTarget(String invokeTarget) { + this.invokeTarget = invokeTarget; + } + + @NotBlank(message = "Cron执行表达式不能为空") + @Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符") + public String getCronExpression() { + return cronExpression; + } + + public void setCronExpression(String cronExpression) { + this.cronExpression = cronExpression; + } + + public Date getNextValidTime() { + if (StringUtils.isNotEmpty(cronExpression)) { + return CronUtils.getNextExecution(cronExpression); + } + return null; + } + + public String getMisfirePolicy() { + return misfirePolicy; + } + + public void setMisfirePolicy(String misfirePolicy) { + this.misfirePolicy = misfirePolicy; + } + + public String getConcurrent() { + return concurrent; + } + + public void setConcurrent(String concurrent) { + this.concurrent = concurrent; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("jobId", getJobId()) + .append("jobName", getJobName()) + .append("jobGroup", getJobGroup()) + .append("cronExpression", getCronExpression()) + .append("nextValidTime", getNextValidTime()) + .append("misfirePolicy", getMisfirePolicy()) + .append("concurrent", getConcurrent()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } } \ No newline at end of file diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java index f044aea7f..af82675dd 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java @@ -1,155 +1,155 @@ -package com.ruoyi.quartz.domain; - -import java.util.Date; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 定时任务调度日志表 sys_job_log - * - * @author ruoyi - */ -public class SysJobLog extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** ID */ - @Excel(name = "日志序号") - private Long jobLogId; - - /** 任务名称 */ - @Excel(name = "任务名称") - private String jobName; - - /** 任务组名 */ - @Excel(name = "任务组名") - private String jobGroup; - - /** 调用目标字符串 */ - @Excel(name = "调用目标字符串") - private String invokeTarget; - - /** 日志信息 */ - @Excel(name = "日志信息") - private String jobMessage; - - /** 执行状态(0正常 1失败) */ - @Excel(name = "执行状态", readConverterExp = "0=正常,1=失败") - private String status; - - /** 异常信息 */ - @Excel(name = "异常信息") - private String exceptionInfo; - - /** 开始时间 */ - private Date startTime; - - /** 结束时间 */ - private Date endTime; - - public Long getJobLogId() - { - return jobLogId; - } - - public void setJobLogId(Long jobLogId) - { - this.jobLogId = jobLogId; - } - - public String getJobName() - { - return jobName; - } - - public void setJobName(String jobName) - { - this.jobName = jobName; - } - - public String getJobGroup() - { - return jobGroup; - } - - public void setJobGroup(String jobGroup) - { - this.jobGroup = jobGroup; - } - - public String getInvokeTarget() - { - return invokeTarget; - } - - public void setInvokeTarget(String invokeTarget) - { - this.invokeTarget = invokeTarget; - } - - public String getJobMessage() - { - return jobMessage; - } - - public void setJobMessage(String jobMessage) - { - this.jobMessage = jobMessage; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public String getExceptionInfo() - { - return exceptionInfo; - } - - public void setExceptionInfo(String exceptionInfo) - { - this.exceptionInfo = exceptionInfo; - } - - public Date getStartTime() - { - return startTime; - } - - public void setStartTime(Date startTime) - { - this.startTime = startTime; - } - - public Date getEndTime() - { - return endTime; - } - - public void setEndTime(Date endTime) - { - this.endTime = endTime; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("jobLogId", getJobLogId()) - .append("jobName", getJobName()) - .append("jobGroup", getJobGroup()) - .append("jobMessage", getJobMessage()) - .append("status", getStatus()) - .append("exceptionInfo", getExceptionInfo()) - .append("startTime", getStartTime()) - .append("endTime", getEndTime()) - .toString(); - } -} +package com.ruoyi.quartz.domain; + +import java.util.Date; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 定时任务调度日志表 sys_job_log + * + * @author ruoyi + */ +public class SysJobLog extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * ID + */ + @Excel(name = "日志序号") + private Long jobLogId; + + /** + * 任务名称 + */ + @Excel(name = "任务名称") + private String jobName; + + /** + * 任务组名 + */ + @Excel(name = "任务组名") + private String jobGroup; + + /** + * 调用目标字符串 + */ + @Excel(name = "调用目标字符串") + private String invokeTarget; + + /** + * 日志信息 + */ + @Excel(name = "日志信息") + private String jobMessage; + + /** + * 执行状态(0正常 1失败) + */ + @Excel(name = "执行状态", readConverterExp = "0=正常,1=失败") + private String status; + + /** + * 异常信息 + */ + @Excel(name = "异常信息") + private String exceptionInfo; + + /** + * 开始时间 + */ + private Date startTime; + + /** + * 结束时间 + */ + private Date endTime; + + public Long getJobLogId() { + return jobLogId; + } + + public void setJobLogId(Long jobLogId) { + this.jobLogId = jobLogId; + } + + public String getJobName() { + return jobName; + } + + public void setJobName(String jobName) { + this.jobName = jobName; + } + + public String getJobGroup() { + return jobGroup; + } + + public void setJobGroup(String jobGroup) { + this.jobGroup = jobGroup; + } + + public String getInvokeTarget() { + return invokeTarget; + } + + public void setInvokeTarget(String invokeTarget) { + this.invokeTarget = invokeTarget; + } + + public String getJobMessage() { + return jobMessage; + } + + public void setJobMessage(String jobMessage) { + this.jobMessage = jobMessage; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getExceptionInfo() { + return exceptionInfo; + } + + public void setExceptionInfo(String exceptionInfo) { + this.exceptionInfo = exceptionInfo; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("jobLogId", getJobLogId()) + .append("jobName", getJobName()) + .append("jobGroup", getJobGroup()) + .append("jobMessage", getJobMessage()) + .append("status", getStatus()) + .append("exceptionInfo", getExceptionInfo()) + .append("startTime", getStartTime()) + .append("endTime", getEndTime()) + .toString(); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java index ee0710cea..d2ec1a700 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java @@ -1,64 +1,64 @@ -package com.ruoyi.quartz.mapper; - -import com.ruoyi.quartz.domain.SysJobLog; -import java.util.List; - -/** - * 调度任务日志信息 数据层 - * - * @author ruoyi - */ -public interface SysJobLogMapper -{ - /** - * 获取quartz调度器日志的计划任务 - * - * @param jobLog 调度日志信息 - * @return 调度任务日志集合 - */ - public List selectJobLogList(SysJobLog jobLog); - - /** - * 查询所有调度任务日志 - * - * @return 调度任务日志列表 - */ - public List selectJobLogAll(); - - /** - * 通过调度任务日志ID查询调度信息 - * - * @param jobLogId 调度任务日志ID - * @return 调度任务日志对象信息 - */ - public SysJobLog selectJobLogById(Long jobLogId); - - /** - * 新增任务日志 - * - * @param jobLog 调度日志信息 - * @return 结果 - */ - public int insertJobLog(SysJobLog jobLog); - - /** - * 批量删除调度日志信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteJobLogByIds(String[] ids); - - /** - * 删除任务日志 - * - * @param jobId 调度日志ID - * @return 结果 - */ - public int deleteJobLogById(Long jobId); - - /** - * 清空任务日志 - */ - public void cleanJobLog(); -} +package com.ruoyi.quartz.mapper; + +import com.ruoyi.quartz.domain.SysJobLog; + +import java.util.List; + +/** + * 调度任务日志信息 数据层 + * + * @author ruoyi + */ +public interface SysJobLogMapper { + /** + * 获取quartz调度器日志的计划任务 + * + * @param jobLog 调度日志信息 + * @return 调度任务日志集合 + */ + public List selectJobLogList(SysJobLog jobLog); + + /** + * 查询所有调度任务日志 + * + * @return 调度任务日志列表 + */ + public List selectJobLogAll(); + + /** + * 通过调度任务日志ID查询调度信息 + * + * @param jobLogId 调度任务日志ID + * @return 调度任务日志对象信息 + */ + public SysJobLog selectJobLogById(Long jobLogId); + + /** + * 新增任务日志 + * + * @param jobLog 调度日志信息 + * @return 结果 + */ + public int insertJobLog(SysJobLog jobLog); + + /** + * 批量删除调度日志信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteJobLogByIds(String[] ids); + + /** + * 删除任务日志 + * + * @param jobId 调度日志ID + * @return 结果 + */ + public int deleteJobLogById(Long jobId); + + /** + * 清空任务日志 + */ + public void cleanJobLog(); +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java index 1e030a3d5..3614b3481 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java @@ -1,67 +1,67 @@ -package com.ruoyi.quartz.mapper; - -import com.ruoyi.quartz.domain.SysJob; -import java.util.List; - -/** - * 调度任务信息 数据层 - * - * @author ruoyi - */ -public interface SysJobMapper -{ - /** - * 查询调度任务日志集合 - * - * @param job 调度信息 - * @return 操作日志集合 - */ - public List selectJobList(SysJob job); - - /** - * 查询所有调度任务 - * - * @return 调度任务列表 - */ - public List selectJobAll(); - - /** - * 通过调度ID查询调度任务信息 - * - * @param jobId 调度ID - * @return 角色对象信息 - */ - public SysJob selectJobById(Long jobId); - - /** - * 通过调度ID删除调度任务信息 - * - * @param jobId 调度ID - * @return 结果 - */ - public int deleteJobById(Long jobId); - - /** - * 批量删除调度任务信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteJobByIds(Long[] ids); - - /** - * 修改调度任务信息 - * - * @param job 调度任务信息 - * @return 结果 - */ - public int updateJob(SysJob job); - - /** - * 新增调度任务信息 - * - * @param job 调度任务信息 - * @return 结果 - */ - public int insertJob(SysJob job); -} +package com.ruoyi.quartz.mapper; + +import com.ruoyi.quartz.domain.SysJob; + +import java.util.List; + +/** + * 调度任务信息 数据层 + * + * @author ruoyi + */ +public interface SysJobMapper { + /** + * 查询调度任务日志集合 + * + * @param job 调度信息 + * @return 操作日志集合 + */ + public List selectJobList(SysJob job); + + /** + * 查询所有调度任务 + * + * @return 调度任务列表 + */ + public List selectJobAll(); + + /** + * 通过调度ID查询调度任务信息 + * + * @param jobId 调度ID + * @return 角色对象信息 + */ + public SysJob selectJobById(Long jobId); + + /** + * 通过调度ID删除调度任务信息 + * + * @param jobId 调度ID + * @return 结果 + */ + public int deleteJobById(Long jobId); + + /** + * 批量删除调度任务信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteJobByIds(Long[] ids); + + /** + * 修改调度任务信息 + * + * @param job 调度任务信息 + * @return 结果 + */ + public int updateJob(SysJob job); + + /** + * 新增调度任务信息 + * + * @param job 调度任务信息 + * @return 结果 + */ + public int insertJob(SysJob job); +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java index 93ae0f77b..9366bc35e 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java @@ -1,56 +1,56 @@ -package com.ruoyi.quartz.service; - -import java.util.List; -import com.ruoyi.quartz.domain.SysJobLog; - -/** - * 定时任务调度日志信息信息 服务层 - * - * @author ruoyi - */ -public interface ISysJobLogService -{ - /** - * 获取quartz调度器日志的计划任务 - * - * @param jobLog 调度日志信息 - * @return 调度任务日志集合 - */ - public List selectJobLogList(SysJobLog jobLog); - - /** - * 通过调度任务日志ID查询调度信息 - * - * @param jobLogId 调度任务日志ID - * @return 调度任务日志对象信息 - */ - public SysJobLog selectJobLogById(Long jobLogId); - - /** - * 新增任务日志 - * - * @param jobLog 调度日志信息 - */ - public void addJobLog(SysJobLog jobLog); - - /** - * 批量删除调度日志信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteJobLogByIds(String ids); - - /** - * 删除任务日志 - * - * @param jobId 调度日志ID - * @return 结果 - */ - public int deleteJobLogById(Long jobId); - - /** - * 清空任务日志 - */ - public void cleanJobLog(); -} +package com.ruoyi.quartz.service; + +import java.util.List; + +import com.ruoyi.quartz.domain.SysJobLog; + +/** + * 定时任务调度日志信息信息 服务层 + * + * @author ruoyi + */ +public interface ISysJobLogService { + /** + * 获取quartz调度器日志的计划任务 + * + * @param jobLog 调度日志信息 + * @return 调度任务日志集合 + */ + public List selectJobLogList(SysJobLog jobLog); + + /** + * 通过调度任务日志ID查询调度信息 + * + * @param jobLogId 调度任务日志ID + * @return 调度任务日志对象信息 + */ + public SysJobLog selectJobLogById(Long jobLogId); + + /** + * 新增任务日志 + * + * @param jobLog 调度日志信息 + */ + public void addJobLog(SysJobLog jobLog); + + /** + * 批量删除调度日志信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteJobLogByIds(String ids); + + /** + * 删除任务日志 + * + * @param jobId 调度日志ID + * @return 结果 + */ + public int deleteJobLogById(Long jobId); + + /** + * 清空任务日志 + */ + public void cleanJobLog(); +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java index ce4953290..84f11e054 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java @@ -1,102 +1,102 @@ -package com.ruoyi.quartz.service; - -import java.util.List; -import org.quartz.SchedulerException; -import com.ruoyi.common.exception.job.TaskException; -import com.ruoyi.quartz.domain.SysJob; - -/** - * 定时任务调度信息信息 服务层 - * - * @author ruoyi - */ -public interface ISysJobService -{ - /** - * 获取quartz调度器的计划任务 - * - * @param job 调度信息 - * @return 调度任务集合 - */ - public List selectJobList(SysJob job); - - /** - * 通过调度任务ID查询调度信息 - * - * @param jobId 调度任务ID - * @return 调度任务对象信息 - */ - public SysJob selectJobById(Long jobId); - - /** - * 暂停任务 - * - * @param job 调度信息 - * @return 结果 - */ - public int pauseJob(SysJob job) throws SchedulerException; - - /** - * 恢复任务 - * - * @param job 调度信息 - * @return 结果 - */ - public int resumeJob(SysJob job) throws SchedulerException; - - /** - * 删除任务后,所对应的trigger也将被删除 - * - * @param job 调度信息 - * @return 结果 - */ - public int deleteJob(SysJob job) throws SchedulerException; - - /** - * 批量删除调度信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public void deleteJobByIds(String ids) throws SchedulerException; - - /** - * 任务调度状态修改 - * - * @param job 调度信息 - * @return 结果 - */ - public int changeStatus(SysJob job) throws SchedulerException; - - /** - * 立即运行任务 - * - * @param job 调度信息 - * @return 结果 - */ - public void run(SysJob job) throws SchedulerException; - - /** - * 新增任务 - * - * @param job 调度信息 - * @return 结果 - */ - public int insertJob(SysJob job) throws SchedulerException, TaskException; - - /** - * 更新任务 - * - * @param job 调度信息 - * @return 结果 - */ - public int updateJob(SysJob job) throws SchedulerException, TaskException; - - /** - * 校验cron表达式是否有效 - * - * @param cronExpression 表达式 - * @return 结果 - */ - public boolean checkCronExpressionIsValid(String cronExpression); +package com.ruoyi.quartz.service; + +import java.util.List; + +import org.quartz.SchedulerException; +import com.ruoyi.common.exception.job.TaskException; +import com.ruoyi.quartz.domain.SysJob; + +/** + * 定时任务调度信息信息 服务层 + * + * @author ruoyi + */ +public interface ISysJobService { + /** + * 获取quartz调度器的计划任务 + * + * @param job 调度信息 + * @return 调度任务集合 + */ + public List selectJobList(SysJob job); + + /** + * 通过调度任务ID查询调度信息 + * + * @param jobId 调度任务ID + * @return 调度任务对象信息 + */ + public SysJob selectJobById(Long jobId); + + /** + * 暂停任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int pauseJob(SysJob job) throws SchedulerException; + + /** + * 恢复任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int resumeJob(SysJob job) throws SchedulerException; + + /** + * 删除任务后,所对应的trigger也将被删除 + * + * @param job 调度信息 + * @return 结果 + */ + public int deleteJob(SysJob job) throws SchedulerException; + + /** + * 批量删除调度信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public void deleteJobByIds(String ids) throws SchedulerException; + + /** + * 任务调度状态修改 + * + * @param job 调度信息 + * @return 结果 + */ + public int changeStatus(SysJob job) throws SchedulerException; + + /** + * 立即运行任务 + * + * @param job 调度信息 + * @return 结果 + */ + public void run(SysJob job) throws SchedulerException; + + /** + * 新增任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int insertJob(SysJob job) throws SchedulerException, TaskException; + + /** + * 更新任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int updateJob(SysJob job) throws SchedulerException, TaskException; + + /** + * 校验cron表达式是否有效 + * + * @param cronExpression 表达式 + * @return 结果 + */ + public boolean checkCronExpressionIsValid(String cronExpression); } \ No newline at end of file diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java index ccd7379b9..2e4ebe325 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java @@ -1,6 +1,7 @@ package com.ruoyi.quartz.service.impl; import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.core.text.Convert; @@ -10,70 +11,64 @@ import com.ruoyi.quartz.service.ISysJobLogService; /** * 定时任务调度日志信息 服务层 - * + * * @author ruoyi */ @Service -public class SysJobLogServiceImpl implements ISysJobLogService -{ +public class SysJobLogServiceImpl implements ISysJobLogService { @Autowired private SysJobLogMapper jobLogMapper; /** * 获取quartz调度器日志的计划任务 - * + * * @param jobLog 调度日志信息 * @return 调度任务日志集合 */ @Override - public List selectJobLogList(SysJobLog jobLog) - { + public List selectJobLogList(SysJobLog jobLog) { return jobLogMapper.selectJobLogList(jobLog); } /** * 通过调度任务日志ID查询调度信息 - * + * * @param jobLogId 调度任务日志ID * @return 调度任务日志对象信息 */ @Override - public SysJobLog selectJobLogById(Long jobLogId) - { + public SysJobLog selectJobLogById(Long jobLogId) { return jobLogMapper.selectJobLogById(jobLogId); } /** * 新增任务日志 - * + * * @param jobLog 调度日志信息 */ @Override - public void addJobLog(SysJobLog jobLog) - { + public void addJobLog(SysJobLog jobLog) { jobLogMapper.insertJobLog(jobLog); } /** * 批量删除调度日志信息 - * + * * @param ids 需要删除的数据ID * @return 结果 */ @Override - public int deleteJobLogByIds(String ids) - { + public int deleteJobLogByIds(String ids) { return jobLogMapper.deleteJobLogByIds(Convert.toStrArray(ids)); } /** * 删除任务日志 - * + * * @param jobId 调度日志ID */ @Override - public int deleteJobLogById(Long jobId) - { + public int deleteJobLogById(Long jobId) { return jobLogMapper.deleteJobLogById(jobId); } @@ -81,8 +76,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService * 清空任务日志 */ @Override - public void cleanJobLog() - { + public void cleanJobLog() { jobLogMapper.cleanJobLog(); } } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java index 95e3623a0..3e3eeba4c 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java @@ -1,255 +1,232 @@ -package com.ruoyi.quartz.service.impl; - -import java.util.List; -import javax.annotation.PostConstruct; -import org.quartz.JobDataMap; -import org.quartz.JobKey; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.constant.ScheduleConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.job.TaskException; -import com.ruoyi.quartz.domain.SysJob; -import com.ruoyi.quartz.mapper.SysJobMapper; -import com.ruoyi.quartz.service.ISysJobService; -import com.ruoyi.quartz.util.CronUtils; -import com.ruoyi.quartz.util.ScheduleUtils; - -/** - * 定时任务调度信息 服务层 - * - * @author ruoyi - */ -@Service -public class SysJobServiceImpl implements ISysJobService -{ - @Autowired - private Scheduler scheduler; - - @Autowired - private SysJobMapper jobMapper; - - /** - * 项目启动时,初始化定时器 - * 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据) - */ - @PostConstruct - public void init() throws SchedulerException, TaskException { - List jobList = jobMapper.selectJobAll(); - for (SysJob job : jobList) - { - updateSchedulerJob(job, job.getJobGroup()); - } - } - - /** - * 获取quartz调度器的计划任务列表 - * - * @param job 调度信息 - * @return - */ - @Override - public List selectJobList(SysJob job) - { - return jobMapper.selectJobList(job); - } - - /** - * 通过调度任务ID查询调度信息 - * - * @param jobId 调度任务ID - * @return 调度任务对象信息 - */ - @Override - public SysJob selectJobById(Long jobId) - { - return jobMapper.selectJobById(jobId); - } - - /** - * 暂停任务 - * - * @param job 调度信息 - */ - @Override - @Transactional - public int pauseJob(SysJob job) throws SchedulerException - { - Long jobId = job.getJobId(); - String jobGroup = job.getJobGroup(); - job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); - int rows = jobMapper.updateJob(job); - if (rows > 0) - { - scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; - } - - /** - * 恢复任务 - * - * @param job 调度信息 - */ - @Override - @Transactional - public int resumeJob(SysJob job) throws SchedulerException - { - Long jobId = job.getJobId(); - String jobGroup = job.getJobGroup(); - job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); - int rows = jobMapper.updateJob(job); - if (rows > 0) - { - scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; - } - - /** - * 删除任务后,所对应的trigger也将被删除 - * - * @param job 调度信息 - */ - @Override - @Transactional - public int deleteJob(SysJob job) throws SchedulerException - { - Long jobId = job.getJobId(); - String jobGroup = job.getJobGroup(); - int rows = jobMapper.deleteJobById(jobId); - if (rows > 0) - { - scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; - } - - /** - * 批量删除调度信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - @Transactional - public void deleteJobByIds(String ids) throws SchedulerException - { - Long[] jobIds = Convert.toLongArray(ids); - for (Long jobId : jobIds) - { - SysJob job = jobMapper.selectJobById(jobId); - deleteJob(job); - } - } - - /** - * 任务调度状态修改 - * - * @param job 调度信息 - */ - @Override - @Transactional - public int changeStatus(SysJob job) throws SchedulerException - { - int rows = 0; - String status = job.getStatus(); - if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) - { - rows = resumeJob(job); - } - else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) - { - rows = pauseJob(job); - } - return rows; - } - - /** - * 立即运行任务 - * - * @param job 调度信息 - */ - @Override - @Transactional - public void run(SysJob job) throws SchedulerException - { - Long jobId = job.getJobId(); - String jobGroup = job.getJobGroup(); - SysJob properties = selectJobById(job.getJobId()); - // 参数 - JobDataMap dataMap = new JobDataMap(); - dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties); - scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap); - } - - /** - * 新增任务 - * - * @param job 调度信息 调度信息 - */ - @Override - @Transactional - public int insertJob(SysJob job) throws SchedulerException, TaskException - { - job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); - int rows = jobMapper.insertJob(job); - if (rows > 0) - { - ScheduleUtils.createScheduleJob(scheduler, job); - } - return rows; - } - - /** - * 更新任务的时间表达式 - * - * @param job 调度信息 - */ - @Override - @Transactional - public int updateJob(SysJob job) throws SchedulerException, TaskException - { - SysJob properties = selectJobById(job.getJobId()); - int rows = jobMapper.updateJob(job); - if (rows > 0) - { - updateSchedulerJob(job, properties.getJobGroup()); - } - return rows; - } - - /** - * 更新任务 - * - * @param job 任务对象 - * @param jobGroup 任务组名 - */ - public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException - { - Long jobId = job.getJobId(); - // 判断是否存在 - JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup); - if (scheduler.checkExists(jobKey)) - { - // 防止创建时存在数据问题 先移除,然后在执行创建操作 - scheduler.deleteJob(jobKey); - } - ScheduleUtils.createScheduleJob(scheduler, job); - } - - /** - * 校验cron表达式是否有效 - * - * @param cronExpression 表达式 - * @return 结果 - */ - @Override - public boolean checkCronExpressionIsValid(String cronExpression) - { - return CronUtils.isValid(cronExpression); - } +package com.ruoyi.quartz.service.impl; + +import java.util.List; +import javax.annotation.PostConstruct; + +import org.quartz.JobDataMap; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.constant.ScheduleConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.job.TaskException; +import com.ruoyi.quartz.domain.SysJob; +import com.ruoyi.quartz.mapper.SysJobMapper; +import com.ruoyi.quartz.service.ISysJobService; +import com.ruoyi.quartz.util.CronUtils; +import com.ruoyi.quartz.util.ScheduleUtils; + +/** + * 定时任务调度信息 服务层 + * + * @author ruoyi + */ +@Service +public class SysJobServiceImpl implements ISysJobService { + @Autowired + private Scheduler scheduler; + + @Autowired + private SysJobMapper jobMapper; + + /** + * 项目启动时,初始化定时器 + * 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据) + */ + @PostConstruct + public void init() throws SchedulerException, TaskException { + List jobList = jobMapper.selectJobAll(); + for (SysJob job : jobList) { + updateSchedulerJob(job, job.getJobGroup()); + } + } + + /** + * 获取quartz调度器的计划任务列表 + * + * @param job 调度信息 + * @return + */ + @Override + public List selectJobList(SysJob job) { + return jobMapper.selectJobList(job); + } + + /** + * 通过调度任务ID查询调度信息 + * + * @param jobId 调度任务ID + * @return 调度任务对象信息 + */ + @Override + public SysJob selectJobById(Long jobId) { + return jobMapper.selectJobById(jobId); + } + + /** + * 暂停任务 + * + * @param job 调度信息 + */ + @Override + @Transactional + public int pauseJob(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); + int rows = jobMapper.updateJob(job); + if (rows > 0) { + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 恢复任务 + * + * @param job 调度信息 + */ + @Override + @Transactional + public int resumeJob(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); + int rows = jobMapper.updateJob(job); + if (rows > 0) { + scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 删除任务后,所对应的trigger也将被删除 + * + * @param job 调度信息 + */ + @Override + @Transactional + public int deleteJob(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + int rows = jobMapper.deleteJobById(jobId); + if (rows > 0) { + scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 批量删除调度信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + @Transactional + public void deleteJobByIds(String ids) throws SchedulerException { + Long[] jobIds = Convert.toLongArray(ids); + for (Long jobId : jobIds) { + SysJob job = jobMapper.selectJobById(jobId); + deleteJob(job); + } + } + + /** + * 任务调度状态修改 + * + * @param job 调度信息 + */ + @Override + @Transactional + public int changeStatus(SysJob job) throws SchedulerException { + int rows = 0; + String status = job.getStatus(); + if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) { + rows = resumeJob(job); + } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) { + rows = pauseJob(job); + } + return rows; + } + + /** + * 立即运行任务 + * + * @param job 调度信息 + */ + @Override + @Transactional + public void run(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + SysJob properties = selectJobById(job.getJobId()); + // 参数 + JobDataMap dataMap = new JobDataMap(); + dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties); + scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap); + } + + /** + * 新增任务 + * + * @param job 调度信息 调度信息 + */ + @Override + @Transactional + public int insertJob(SysJob job) throws SchedulerException, TaskException { + job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); + int rows = jobMapper.insertJob(job); + if (rows > 0) { + ScheduleUtils.createScheduleJob(scheduler, job); + } + return rows; + } + + /** + * 更新任务的时间表达式 + * + * @param job 调度信息 + */ + @Override + @Transactional + public int updateJob(SysJob job) throws SchedulerException, TaskException { + SysJob properties = selectJobById(job.getJobId()); + int rows = jobMapper.updateJob(job); + if (rows > 0) { + updateSchedulerJob(job, properties.getJobGroup()); + } + return rows; + } + + /** + * 更新任务 + * + * @param job 任务对象 + * @param jobGroup 任务组名 + */ + public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException { + Long jobId = job.getJobId(); + // 判断是否存在 + JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup); + if (scheduler.checkExists(jobKey)) { + // 防止创建时存在数据问题 先移除,然后在执行创建操作 + scheduler.deleteJob(jobKey); + } + ScheduleUtils.createScheduleJob(scheduler, job); + } + + /** + * 校验cron表达式是否有效 + * + * @param cronExpression 表达式 + * @return 结果 + */ + @Override + public boolean checkCronExpressionIsValid(String cronExpression) { + return CronUtils.isValid(cronExpression); + } } \ No newline at end of file diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java index 25d1ddd02..b4b94c89d 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java @@ -1,28 +1,24 @@ -package com.ruoyi.quartz.task; - -import org.springframework.stereotype.Component; -import com.ruoyi.common.utils.StringUtils; - -/** - * 定时任务调度测试 - * - * @author ruoyi - */ -@Component("ryTask") -public class RyTask -{ - public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) - { - System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i)); - } - - public void ryParams(String params) - { - System.out.println("执行有参方法:" + params); - } - - public void ryNoParams() - { - System.out.println("执行无参方法"); - } -} +package com.ruoyi.quartz.task; + +import org.springframework.stereotype.Component; +import com.ruoyi.common.utils.StringUtils; + +/** + * 定时任务调度测试 + * + * @author ruoyi + */ +@Component("ryTask") +public class RyTask { + public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) { + System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i)); + } + + public void ryParams(String params) { + System.out.println("执行有参方法:" + params); + } + + public void ryNoParams() { + System.out.println("执行无参方法"); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java index a6f3dc4ee..ad2bd12f3 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java @@ -1,107 +1,97 @@ -package com.ruoyi.quartz.util; - -import java.util.Date; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.ruoyi.common.constant.Constants; -import com.ruoyi.common.constant.ScheduleConstants; -import com.ruoyi.common.utils.ExceptionUtil; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.bean.BeanUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.quartz.domain.SysJob; -import com.ruoyi.quartz.domain.SysJobLog; -import com.ruoyi.quartz.service.ISysJobLogService; - -/** - * 抽象quartz调用 - * - * @author ruoyi - */ -public abstract class AbstractQuartzJob implements Job -{ - private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); - - /** - * 线程本地变量 - */ - private static ThreadLocal threadLocal = new ThreadLocal<>(); - - @Override - public void execute(JobExecutionContext context) throws JobExecutionException - { - SysJob sysJob = new SysJob(); - BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); - try - { - before(context, sysJob); - if (sysJob != null) - { - doExecute(context, sysJob); - } - after(context, sysJob, null); - } - catch (Exception e) - { - log.error("任务执行异常 - :", e); - after(context, sysJob, e); - } - } - - /** - * 执行前 - * - * @param context 工作执行上下文对象 - * @param sysJob 系统计划任务 - */ - protected void before(JobExecutionContext context, SysJob sysJob) - { - threadLocal.set(new Date()); - } - - /** - * 执行后 - * - * @param context 工作执行上下文对象 - * @param sysScheduleJob 系统计划任务 - */ - protected void after(JobExecutionContext context, SysJob sysJob, Exception e) - { - Date startTime = threadLocal.get(); - threadLocal.remove(); - - final SysJobLog sysJobLog = new SysJobLog(); - sysJobLog.setJobName(sysJob.getJobName()); - sysJobLog.setJobGroup(sysJob.getJobGroup()); - sysJobLog.setInvokeTarget(sysJob.getInvokeTarget()); - sysJobLog.setStartTime(startTime); - sysJobLog.setEndTime(new Date()); - long runMs = sysJobLog.getEndTime().getTime() - sysJobLog.getStartTime().getTime(); - sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); - if (e != null) - { - sysJobLog.setStatus(Constants.FAIL); - String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); - sysJobLog.setExceptionInfo(errorMsg); - } - else - { - sysJobLog.setStatus(Constants.SUCCESS); - } - - // 写入数据库当中 - SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog); - } - - /** - * 执行方法,由子类重载 - * - * @param context 工作执行上下文对象 - * @param sysJob 系统计划任务 - * @throws Exception 执行过程中的异常 - */ - protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception; -} +package com.ruoyi.quartz.util; + +import java.util.Date; + +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.constant.ScheduleConstants; +import com.ruoyi.common.utils.ExceptionUtil; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.bean.BeanUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.quartz.domain.SysJob; +import com.ruoyi.quartz.domain.SysJobLog; +import com.ruoyi.quartz.service.ISysJobLogService; + +/** + * 抽象quartz调用 + * + * @author ruoyi + */ +public abstract class AbstractQuartzJob implements Job { + private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); + + /** + * 线程本地变量 + */ + private static ThreadLocal threadLocal = new ThreadLocal<>(); + + @Override + public void execute(JobExecutionContext context) throws JobExecutionException { + SysJob sysJob = new SysJob(); + BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); + try { + before(context, sysJob); + if (sysJob != null) { + doExecute(context, sysJob); + } + after(context, sysJob, null); + } catch (Exception e) { + log.error("任务执行异常 - :", e); + after(context, sysJob, e); + } + } + + /** + * 执行前 + * + * @param context 工作执行上下文对象 + * @param sysJob 系统计划任务 + */ + protected void before(JobExecutionContext context, SysJob sysJob) { + threadLocal.set(new Date()); + } + + /** + * 执行后 + * + * @param context 工作执行上下文对象 + * @param sysScheduleJob 系统计划任务 + */ + protected void after(JobExecutionContext context, SysJob sysJob, Exception e) { + Date startTime = threadLocal.get(); + threadLocal.remove(); + + final SysJobLog sysJobLog = new SysJobLog(); + sysJobLog.setJobName(sysJob.getJobName()); + sysJobLog.setJobGroup(sysJob.getJobGroup()); + sysJobLog.setInvokeTarget(sysJob.getInvokeTarget()); + sysJobLog.setStartTime(startTime); + sysJobLog.setEndTime(new Date()); + long runMs = sysJobLog.getEndTime().getTime() - sysJobLog.getStartTime().getTime(); + sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); + if (e != null) { + sysJobLog.setStatus(Constants.FAIL); + String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); + sysJobLog.setExceptionInfo(errorMsg); + } else { + sysJobLog.setStatus(Constants.SUCCESS); + } + + // 写入数据库当中 + SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog); + } + + /** + * 执行方法,由子类重载 + * + * @param context 工作执行上下文对象 + * @param sysJob 系统计划任务 + * @throws Exception 执行过程中的异常 + */ + protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception; +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/CronUtils.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/CronUtils.java index dd5383979..a91e2505a 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/CronUtils.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/CronUtils.java @@ -2,24 +2,22 @@ package com.ruoyi.quartz.util; import java.text.ParseException; import java.util.Date; + import org.quartz.CronExpression; /** * cron表达式工具类 - * - * @author ruoyi * + * @author ruoyi */ -public class CronUtils -{ +public class CronUtils { /** * 返回一个布尔值代表一个给定的Cron表达式的有效性 * * @param cronExpression Cron表达式 * @return boolean 表达式是否有效 */ - public static boolean isValid(String cronExpression) - { + public static boolean isValid(String cronExpression) { return CronExpression.isValidExpression(cronExpression); } @@ -29,15 +27,11 @@ public class CronUtils * @param cronExpression Cron表达式 * @return String 无效时返回表达式错误描述,如果有效返回null */ - public static String getInvalidMessage(String cronExpression) - { - try - { + public static String getInvalidMessage(String cronExpression) { + try { new CronExpression(cronExpression); return null; - } - catch (ParseException pe) - { + } catch (ParseException pe) { return pe.getMessage(); } } @@ -48,15 +42,11 @@ public class CronUtils * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ - public static Date getNextExecution(String cronExpression) - { - try - { + public static Date getNextExecution(String cronExpression) { + try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); - } - catch (ParseException e) - { + } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/JobInvokeUtil.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/JobInvokeUtil.java index 5519c672f..7e5661a12 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/JobInvokeUtil.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/JobInvokeUtil.java @@ -1,182 +1,159 @@ -package com.ruoyi.quartz.util; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.LinkedList; -import java.util.List; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.quartz.domain.SysJob; - -/** - * 任务执行工具 - * - * @author ruoyi - */ -public class JobInvokeUtil -{ - /** - * 执行方法 - * - * @param sysJob 系统任务 - */ - public static void invokeMethod(SysJob sysJob) throws Exception - { - String invokeTarget = sysJob.getInvokeTarget(); - String beanName = getBeanName(invokeTarget); - String methodName = getMethodName(invokeTarget); - List methodParams = getMethodParams(invokeTarget); - - if (!isValidClassName(beanName)) - { - Object bean = SpringUtils.getBean(beanName); - invokeMethod(bean, methodName, methodParams); - } - else - { - Object bean = Class.forName(beanName).newInstance(); - invokeMethod(bean, methodName, methodParams); - } - } - - /** - * 调用任务方法 - * - * @param bean 目标对象 - * @param methodName 方法名称 - * @param methodParams 方法参数 - */ - private static void invokeMethod(Object bean, String methodName, List methodParams) - throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException - { - if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) - { - Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams)); - method.invoke(bean, getMethodParamsValue(methodParams)); - } - else - { - Method method = bean.getClass().getDeclaredMethod(methodName); - method.invoke(bean); - } - } - - /** - * 校验是否为为class包名 - * - * @param str 名称 - * @return true是 false否 - */ - public static boolean isValidClassName(String invokeTarget) - { - return StringUtils.countMatches(invokeTarget, ".") > 1; - } - - /** - * 获取bean名称 - * - * @param invokeTarget 目标字符串 - * @return bean名称 - */ - public static String getBeanName(String invokeTarget) - { - String beanName = StringUtils.substringBefore(invokeTarget, "("); - return StringUtils.substringBeforeLast(beanName, "."); - } - - /** - * 获取bean方法 - * - * @param invokeTarget 目标字符串 - * @return method方法 - */ - public static String getMethodName(String invokeTarget) - { - String methodName = StringUtils.substringBefore(invokeTarget, "("); - return StringUtils.substringAfterLast(methodName, "."); - } - - /** - * 获取method方法参数相关列表 - * - * @param invokeTarget 目标字符串 - * @return method方法相关参数列表 - */ - public static List getMethodParams(String invokeTarget) - { - String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")"); - if (StringUtils.isEmpty(methodStr)) - { - return null; - } - String[] methodParams = methodStr.split(","); - List classs = new LinkedList<>(); - for (int i = 0; i < methodParams.length; i++) - { - String str = StringUtils.trimToEmpty(methodParams[i]); - // String字符串类型,包含' - if (StringUtils.contains(str, "'")) - { - classs.add(new Object[] { StringUtils.replace(str, "'", ""), String.class }); - } - // boolean布尔类型,等于true或者false - else if (StringUtils.equals(str, "true") || StringUtils.equalsIgnoreCase(str, "false")) - { - classs.add(new Object[] { Boolean.valueOf(str), Boolean.class }); - } - // long长整形,包含L - else if (StringUtils.containsIgnoreCase(str, "L")) - { - classs.add(new Object[] { Long.valueOf(StringUtils.replaceIgnoreCase(str, "L", "")), Long.class }); - } - // double浮点类型,包含D - else if (StringUtils.containsIgnoreCase(str, "D")) - { - classs.add(new Object[] { Double.valueOf(StringUtils.replaceIgnoreCase(str, "D", "")), Double.class }); - } - // 其他类型归类为整形 - else - { - classs.add(new Object[] { Integer.valueOf(str), Integer.class }); - } - } - return classs; - } - - /** - * 获取参数类型 - * - * @param methodParams 参数相关列表 - * @return 参数类型列表 - */ - public static Class[] getMethodParamsType(List methodParams) - { - Class[] classs = new Class[methodParams.size()]; - int index = 0; - for (Object[] os : methodParams) - { - classs[index] = (Class) os[1]; - index++; - } - return classs; - } - - /** - * 获取参数值 - * - * @param methodParams 参数相关列表 - * @return 参数值列表 - */ - public static Object[] getMethodParamsValue(List methodParams) - { - Object[] classs = new Object[methodParams.size()]; - int index = 0; - for (Object[] os : methodParams) - { - classs[index] = (Object) os[0]; - index++; - } - return classs; - } -} +package com.ruoyi.quartz.util; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.quartz.domain.SysJob; + +/** + * 任务执行工具 + * + * @author ruoyi + */ +public class JobInvokeUtil { + /** + * 执行方法 + * + * @param sysJob 系统任务 + */ + public static void invokeMethod(SysJob sysJob) throws Exception { + String invokeTarget = sysJob.getInvokeTarget(); + String beanName = getBeanName(invokeTarget); + String methodName = getMethodName(invokeTarget); + List methodParams = getMethodParams(invokeTarget); + + if (!isValidClassName(beanName)) { + Object bean = SpringUtils.getBean(beanName); + invokeMethod(bean, methodName, methodParams); + } else { + Object bean = Class.forName(beanName).newInstance(); + invokeMethod(bean, methodName, methodParams); + } + } + + /** + * 调用任务方法 + * + * @param bean 目标对象 + * @param methodName 方法名称 + * @param methodParams 方法参数 + */ + private static void invokeMethod(Object bean, String methodName, List methodParams) + throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException { + if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) { + Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams)); + method.invoke(bean, getMethodParamsValue(methodParams)); + } else { + Method method = bean.getClass().getDeclaredMethod(methodName); + method.invoke(bean); + } + } + + /** + * 校验是否为为class包名 + * + * @param str 名称 + * @return true是 false否 + */ + public static boolean isValidClassName(String invokeTarget) { + return StringUtils.countMatches(invokeTarget, ".") > 1; + } + + /** + * 获取bean名称 + * + * @param invokeTarget 目标字符串 + * @return bean名称 + */ + public static String getBeanName(String invokeTarget) { + String beanName = StringUtils.substringBefore(invokeTarget, "("); + return StringUtils.substringBeforeLast(beanName, "."); + } + + /** + * 获取bean方法 + * + * @param invokeTarget 目标字符串 + * @return method方法 + */ + public static String getMethodName(String invokeTarget) { + String methodName = StringUtils.substringBefore(invokeTarget, "("); + return StringUtils.substringAfterLast(methodName, "."); + } + + /** + * 获取method方法参数相关列表 + * + * @param invokeTarget 目标字符串 + * @return method方法相关参数列表 + */ + public static List getMethodParams(String invokeTarget) { + String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")"); + if (StringUtils.isEmpty(methodStr)) { + return null; + } + String[] methodParams = methodStr.split(","); + List classs = new LinkedList<>(); + for (int i = 0; i < methodParams.length; i++) { + String str = StringUtils.trimToEmpty(methodParams[i]); + // String字符串类型,包含' + if (StringUtils.contains(str, "'")) { + classs.add(new Object[]{StringUtils.replace(str, "'", ""), String.class}); + } + // boolean布尔类型,等于true或者false + else if (StringUtils.equals(str, "true") || StringUtils.equalsIgnoreCase(str, "false")) { + classs.add(new Object[]{Boolean.valueOf(str), Boolean.class}); + } + // long长整形,包含L + else if (StringUtils.containsIgnoreCase(str, "L")) { + classs.add(new Object[]{Long.valueOf(StringUtils.replaceIgnoreCase(str, "L", "")), Long.class}); + } + // double浮点类型,包含D + else if (StringUtils.containsIgnoreCase(str, "D")) { + classs.add(new Object[]{Double.valueOf(StringUtils.replaceIgnoreCase(str, "D", "")), Double.class}); + } + // 其他类型归类为整形 + else { + classs.add(new Object[]{Integer.valueOf(str), Integer.class}); + } + } + return classs; + } + + /** + * 获取参数类型 + * + * @param methodParams 参数相关列表 + * @return 参数类型列表 + */ + public static Class[] getMethodParamsType(List methodParams) { + Class[] classs = new Class[methodParams.size()]; + int index = 0; + for (Object[] os : methodParams) { + classs[index] = (Class) os[1]; + index++; + } + return classs; + } + + /** + * 获取参数值 + * + * @param methodParams 参数相关列表 + * @return 参数值列表 + */ + public static Object[] getMethodParamsValue(List methodParams) { + Object[] classs = new Object[methodParams.size()]; + int index = 0; + for (Object[] os : methodParams) { + classs[index] = (Object) os[0]; + index++; + } + return classs; + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzDisallowConcurrentExecution.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzDisallowConcurrentExecution.java index 96a6dcf8e..6d9c550df 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzDisallowConcurrentExecution.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzDisallowConcurrentExecution.java @@ -1,21 +1,18 @@ -package com.ruoyi.quartz.util; - -import org.quartz.DisallowConcurrentExecution; -import org.quartz.JobExecutionContext; -import com.ruoyi.quartz.domain.SysJob; - -/** - * 定时任务处理(禁止并发执行) - * - * @author ruoyi - * - */ -@DisallowConcurrentExecution -public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob -{ - @Override - protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception - { - JobInvokeUtil.invokeMethod(sysJob); - } -} +package com.ruoyi.quartz.util; + +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; +import com.ruoyi.quartz.domain.SysJob; + +/** + * 定时任务处理(禁止并发执行) + * + * @author ruoyi + */ +@DisallowConcurrentExecution +public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob { + @Override + protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception { + JobInvokeUtil.invokeMethod(sysJob); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzJobExecution.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzJobExecution.java index 87a06bc13..733f03e2a 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzJobExecution.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/QuartzJobExecution.java @@ -1,19 +1,16 @@ -package com.ruoyi.quartz.util; - -import org.quartz.JobExecutionContext; -import com.ruoyi.quartz.domain.SysJob; - -/** - * 定时任务处理(允许并发执行) - * - * @author ruoyi - * - */ -public class QuartzJobExecution extends AbstractQuartzJob -{ - @Override - protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception - { - JobInvokeUtil.invokeMethod(sysJob); - } -} +package com.ruoyi.quartz.util; + +import org.quartz.JobExecutionContext; +import com.ruoyi.quartz.domain.SysJob; + +/** + * 定时任务处理(允许并发执行) + * + * @author ruoyi + */ +public class QuartzJobExecution extends AbstractQuartzJob { + @Override + protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception { + JobInvokeUtil.invokeMethod(sysJob); + } +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/ScheduleUtils.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/ScheduleUtils.java index b7c2f5365..b704b9adf 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/ScheduleUtils.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/ScheduleUtils.java @@ -1,113 +1,103 @@ -package com.ruoyi.quartz.util; - -import org.quartz.CronScheduleBuilder; -import org.quartz.CronTrigger; -import org.quartz.Job; -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.JobKey; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.TriggerBuilder; -import org.quartz.TriggerKey; -import com.ruoyi.common.constant.ScheduleConstants; -import com.ruoyi.common.exception.job.TaskException; -import com.ruoyi.common.exception.job.TaskException.Code; -import com.ruoyi.quartz.domain.SysJob; - -/** - * 定时任务工具类 - * - * @author ruoyi - * - */ -public class ScheduleUtils -{ - /** - * 得到quartz任务类 - * - * @param sysJob 执行计划 - * @return 具体执行任务类 - */ - private static Class getQuartzJobClass(SysJob sysJob) - { - boolean isConcurrent = "0".equals(sysJob.getConcurrent()); - return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class; - } - - /** - * 构建任务触发对象 - */ - public static TriggerKey getTriggerKey(Long jobId, String jobGroup) - { - return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); - } - - /** - * 构建任务键对象 - */ - public static JobKey getJobKey(Long jobId, String jobGroup) - { - return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); - } - - /** - * 创建定时任务 - */ - public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException - { - Class jobClass = getQuartzJobClass(job); - // 构建job信息 - Long jobId = job.getJobId(); - String jobGroup = job.getJobGroup(); - JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build(); - - // 表达式调度构建器 - CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); - cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); - - // 按新的cronExpression表达式构建一个新的trigger - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)) - .withSchedule(cronScheduleBuilder).build(); - - // 放入参数,运行时的方法可以获取 - jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); - - // 判断是否存在 - if (scheduler.checkExists(getJobKey(jobId, jobGroup))) - { - // 防止创建时存在数据问题 先移除,然后在执行创建操作 - scheduler.deleteJob(getJobKey(jobId, jobGroup)); - } - - scheduler.scheduleJob(jobDetail, trigger); - - // 暂停任务 - if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) - { - scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - } - - /** - * 设置定时任务策略 - */ - public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) - throws TaskException - { - switch (job.getMisfirePolicy()) - { - case ScheduleConstants.MISFIRE_DEFAULT: - return cb; - case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: - return cb.withMisfireHandlingInstructionIgnoreMisfires(); - case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED: - return cb.withMisfireHandlingInstructionFireAndProceed(); - case ScheduleConstants.MISFIRE_DO_NOTHING: - return cb.withMisfireHandlingInstructionDoNothing(); - default: - throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() - + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR); - } - } +package com.ruoyi.quartz.util; + +import org.quartz.CronScheduleBuilder; +import org.quartz.CronTrigger; +import org.quartz.Job; +import org.quartz.JobBuilder; +import org.quartz.JobDetail; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.TriggerBuilder; +import org.quartz.TriggerKey; +import com.ruoyi.common.constant.ScheduleConstants; +import com.ruoyi.common.exception.job.TaskException; +import com.ruoyi.common.exception.job.TaskException.Code; +import com.ruoyi.quartz.domain.SysJob; + +/** + * 定时任务工具类 + * + * @author ruoyi + */ +public class ScheduleUtils { + /** + * 得到quartz任务类 + * + * @param sysJob 执行计划 + * @return 具体执行任务类 + */ + private static Class getQuartzJobClass(SysJob sysJob) { + boolean isConcurrent = "0".equals(sysJob.getConcurrent()); + return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class; + } + + /** + * 构建任务触发对象 + */ + public static TriggerKey getTriggerKey(Long jobId, String jobGroup) { + return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); + } + + /** + * 构建任务键对象 + */ + public static JobKey getJobKey(Long jobId, String jobGroup) { + return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); + } + + /** + * 创建定时任务 + */ + public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException { + Class jobClass = getQuartzJobClass(job); + // 构建job信息 + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build(); + + // 表达式调度构建器 + CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); + cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); + + // 按新的cronExpression表达式构建一个新的trigger + CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)) + .withSchedule(cronScheduleBuilder).build(); + + // 放入参数,运行时的方法可以获取 + jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); + + // 判断是否存在 + if (scheduler.checkExists(getJobKey(jobId, jobGroup))) { + // 防止创建时存在数据问题 先移除,然后在执行创建操作 + scheduler.deleteJob(getJobKey(jobId, jobGroup)); + } + + scheduler.scheduleJob(jobDetail, trigger); + + // 暂停任务 + if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) { + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + } + + /** + * 设置定时任务策略 + */ + public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) + throws TaskException { + switch (job.getMisfirePolicy()) { + case ScheduleConstants.MISFIRE_DEFAULT: + return cb; + case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: + return cb.withMisfireHandlingInstructionIgnoreMisfires(); + case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED: + return cb.withMisfireHandlingInstructionFireAndProceed(); + case ScheduleConstants.MISFIRE_DO_NOTHING: + return cb.withMisfireHandlingInstructionDoNothing(); + default: + throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR); + } + } } \ No newline at end of file From 5cd1c3e30eba3639f2e66f1f0668eadac91e611c Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 13:25:15 +0800 Subject: [PATCH 08/52] format code --- .../com/ruoyi/system/domain/SysConfig.java | 220 ++--- .../java/com/ruoyi/system/domain/SysDept.java | 370 +++---- .../com/ruoyi/system/domain/SysDictData.java | 351 ++++--- .../com/ruoyi/system/domain/SysDictType.java | 186 ++-- .../ruoyi/system/domain/SysLogininfor.java | 317 +++--- .../java/com/ruoyi/system/domain/SysMenu.java | 402 ++++---- .../com/ruoyi/system/domain/SysNotice.java | 198 ++-- .../com/ruoyi/system/domain/SysOperLog.java | 555 +++++------ .../java/com/ruoyi/system/domain/SysPost.java | 244 ++--- .../java/com/ruoyi/system/domain/SysRole.java | 388 ++++---- .../com/ruoyi/system/domain/SysRoleDept.java | 91 +- .../com/ruoyi/system/domain/SysRoleMenu.java | 91 +- .../java/com/ruoyi/system/domain/SysUser.java | 695 +++++++------ .../ruoyi/system/domain/SysUserOnline.java | 354 +++---- .../com/ruoyi/system/domain/SysUserPost.java | 91 +- .../com/ruoyi/system/domain/SysUserRole.java | 91 +- .../ruoyi/system/mapper/SysConfigMapper.java | 118 +-- .../ruoyi/system/mapper/SysDeptMapper.java | 217 ++--- .../system/mapper/SysDictDataMapper.java | 190 ++-- .../system/mapper/SysDictTypeMapper.java | 166 ++-- .../system/mapper/SysLogininforMapper.java | 84 +- .../ruoyi/system/mapper/SysMenuMapper.java | 248 ++--- .../ruoyi/system/mapper/SysNoticeMapper.java | 102 +- .../ruoyi/system/mapper/SysOperLogMapper.java | 96 +- .../ruoyi/system/mapper/SysPostMapper.java | 166 ++-- .../system/mapper/SysRoleDeptMapper.java | 88 +- .../ruoyi/system/mapper/SysRoleMapper.java | 168 ++-- .../system/mapper/SysRoleMenuMapper.java | 88 +- .../ruoyi/system/mapper/SysUserMapper.java | 248 ++--- .../system/mapper/SysUserOnlineMapper.java | 104 +- .../system/mapper/SysUserPostMapper.java | 88 +- .../system/mapper/SysUserRoleMapper.java | 124 +-- .../system/service/ISysConfigService.java | 136 +-- .../ruoyi/system/service/ISysDeptService.java | 188 ++-- .../system/service/ISysDictDataService.java | 154 +-- .../system/service/ISysDictTypeService.java | 186 ++-- .../system/service/ISysLogininforService.java | 80 +- .../ruoyi/system/service/ISysMenuService.java | 262 ++--- .../system/service/ISysNoticeService.java | 104 +- .../system/service/ISysOperLogService.java | 96 +- .../ruoyi/system/service/ISysPostService.java | 184 ++-- .../ruoyi/system/service/ISysRoleService.java | 318 +++--- .../system/service/ISysUserOnlineService.java | 134 +-- .../ruoyi/system/service/ISysUserService.java | 364 +++---- .../service/impl/SysConfigServiceImpl.java | 228 +++-- .../service/impl/SysDeptServiceImpl.java | 516 +++++----- .../service/impl/SysDictDataServiceImpl.java | 228 +++-- .../service/impl/SysDictTypeServiceImpl.java | 360 ++++--- .../impl/SysLogininforServiceImpl.java | 128 ++- .../service/impl/SysMenuServiceImpl.java | 742 +++++++------- .../service/impl/SysNoticeServiceImpl.java | 159 ++- .../service/impl/SysOperLogServiceImpl.java | 149 ++- .../service/impl/SysPostServiceImpl.java | 345 ++++--- .../service/impl/SysRoleServiceImpl.java | 723 +++++++------- .../impl/SysUserOnlineServiceImpl.java | 220 ++--- .../service/impl/SysUserServiceImpl.java | 909 +++++++++--------- 56 files changed, 6803 insertions(+), 7049 deletions(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java index da884de81..db533cd74 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java @@ -1,110 +1,110 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 参数配置表 sys_config - * - * @author ruoyi - */ -public class SysConfig extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 参数主键 */ - @Excel(name = "参数主键", cellType = ColumnType.NUMERIC) - private Long configId; - - /** 参数名称 */ - @Excel(name = "参数名称") - private String configName; - - /** 参数键名 */ - @Excel(name = "参数键名") - private String configKey; - - /** 参数键值 */ - @Excel(name = "参数键值") - private String configValue; - - /** 系统内置(Y是 N否) */ - @Excel(name = "系统内置", readConverterExp = "Y=是,N=否") - private String configType; - - public Long getConfigId() - { - return configId; - } - - public void setConfigId(Long configId) - { - this.configId = configId; - } - - @NotBlank(message = "参数名称不能为空") - @Size(min = 0, max = 100, message = "参数名称不能超过100个字符") - public String getConfigName() - { - return configName; - } - - public void setConfigName(String configName) - { - this.configName = configName; - } - - @NotBlank(message = "参数键名长度不能为空") - @Size(min = 0, max = 100, message = "参数键名长度不能超过100个字符") - public String getConfigKey() - { - return configKey; - } - - public void setConfigKey(String configKey) - { - this.configKey = configKey; - } - - @NotBlank(message = "参数键值不能为空") - @Size(min = 0, max = 500, message = "参数键值长度不能超过500个字符") - public String getConfigValue() - { - return configValue; - } - - public void setConfigValue(String configValue) - { - this.configValue = configValue; - } - - public String getConfigType() - { - return configType; - } - - public void setConfigType(String configType) - { - this.configType = configType; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("configId", getConfigId()) - .append("configName", getConfigName()) - .append("configKey", getConfigKey()) - .append("configValue", getConfigValue()) - .append("configType", getConfigType()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 参数配置表 sys_config + * + * @author ruoyi + */ +public class SysConfig extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 参数主键 + */ + @Excel(name = "参数主键", cellType = ColumnType.NUMERIC) + private Long configId; + + /** + * 参数名称 + */ + @Excel(name = "参数名称") + private String configName; + + /** + * 参数键名 + */ + @Excel(name = "参数键名") + private String configKey; + + /** + * 参数键值 + */ + @Excel(name = "参数键值") + private String configValue; + + /** + * 系统内置(Y是 N否) + */ + @Excel(name = "系统内置", readConverterExp = "Y=是,N=否") + private String configType; + + public Long getConfigId() { + return configId; + } + + public void setConfigId(Long configId) { + this.configId = configId; + } + + @NotBlank(message = "参数名称不能为空") + @Size(min = 0, max = 100, message = "参数名称不能超过100个字符") + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + @NotBlank(message = "参数键名长度不能为空") + @Size(min = 0, max = 100, message = "参数键名长度不能超过100个字符") + public String getConfigKey() { + return configKey; + } + + public void setConfigKey(String configKey) { + this.configKey = configKey; + } + + @NotBlank(message = "参数键值不能为空") + @Size(min = 0, max = 500, message = "参数键值长度不能超过500个字符") + public String getConfigValue() { + return configValue; + } + + public void setConfigValue(String configValue) { + this.configValue = configValue; + } + + public String getConfigType() { + return configType; + } + + public void setConfigType(String configType) { + this.configType = configType; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("configId", getConfigId()) + .append("configName", getConfigName()) + .append("configKey", getConfigKey()) + .append("configValue", getConfigValue()) + .append("configType", getConfigType()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index 4d86400d1..d872d2cee 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -1,185 +1,185 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 部门表 sys_dept - * - * @author ruoyi - */ -public class SysDept extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 部门ID */ - private Long deptId; - - /** 父部门ID */ - private Long parentId; - - /** 祖级列表 */ - private String ancestors; - - /** 部门名称 */ - private String deptName; - - /** 显示顺序 */ - private String orderNum; - - /** 负责人 */ - private String leader; - - /** 联系电话 */ - private String phone; - - /** 邮箱 */ - private String email; - - /** 部门状态:0正常,1停用 */ - private String status; - - /** 删除标志(0代表存在 2代表删除) */ - private String delFlag; - - /** 父部门名称 */ - private String parentName; - - public Long getDeptId() - { - return deptId; - } - - public void setDeptId(Long deptId) - { - this.deptId = deptId; - } - - public Long getParentId() - { - return parentId; - } - - public void setParentId(Long parentId) - { - this.parentId = parentId; - } - - public String getAncestors() - { - return ancestors; - } - - public void setAncestors(String ancestors) - { - this.ancestors = ancestors; - } - - @NotBlank(message = "部门名称不能为空") - @Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符") - public String getDeptName() - { - return deptName; - } - - public void setDeptName(String deptName) - { - this.deptName = deptName; - } - - @NotBlank(message = "显示顺序不能为空") - public String getOrderNum() - { - return orderNum; - } - - public void setOrderNum(String orderNum) - { - this.orderNum = orderNum; - } - - public String getLeader() - { - return leader; - } - - public void setLeader(String leader) - { - this.leader = leader; - } - - @Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符") - public String getPhone() - { - return phone; - } - - public void setPhone(String phone) - { - this.phone = phone; - } - - @Email(message = "邮箱格式不正确") - @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") - public String getEmail() - { - return email; - } - - public void setEmail(String email) - { - this.email = email; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public String getDelFlag() - { - return delFlag; - } - - public void setDelFlag(String delFlag) - { - this.delFlag = delFlag; - } - - public String getParentName() - { - return parentName; - } - - public void setParentName(String parentName) - { - this.parentName = parentName; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("deptId", getDeptId()) - .append("parentId", getParentId()) - .append("ancestors", getAncestors()) - .append("deptName", getDeptName()) - .append("orderNum", getOrderNum()) - .append("leader", getLeader()) - .append("phone", getPhone()) - .append("email", getEmail()) - .append("status", getStatus()) - .append("delFlag", getDelFlag()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 部门表 sys_dept + * + * @author ruoyi + */ +public class SysDept extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 部门ID + */ + private Long deptId; + + /** + * 父部门ID + */ + private Long parentId; + + /** + * 祖级列表 + */ + private String ancestors; + + /** + * 部门名称 + */ + private String deptName; + + /** + * 显示顺序 + */ + private String orderNum; + + /** + * 负责人 + */ + private String leader; + + /** + * 联系电话 + */ + private String phone; + + /** + * 邮箱 + */ + private String email; + + /** + * 部门状态:0正常,1停用 + */ + private String status; + + /** + * 删除标志(0代表存在 2代表删除) + */ + private String delFlag; + + /** + * 父部门名称 + */ + private String parentName; + + public Long getDeptId() { + return deptId; + } + + public void setDeptId(Long deptId) { + this.deptId = deptId; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public String getAncestors() { + return ancestors; + } + + public void setAncestors(String ancestors) { + this.ancestors = ancestors; + } + + @NotBlank(message = "部门名称不能为空") + @Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符") + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + @NotBlank(message = "显示顺序不能为空") + public String getOrderNum() { + return orderNum; + } + + public void setOrderNum(String orderNum) { + this.orderNum = orderNum; + } + + public String getLeader() { + return leader; + } + + public void setLeader(String leader) { + this.leader = leader; + } + + @Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Email(message = "邮箱格式不正确") + @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDelFlag() { + return delFlag; + } + + public void setDelFlag(String delFlag) { + this.delFlag = delFlag; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("deptId", getDeptId()) + .append("parentId", getParentId()) + .append("ancestors", getAncestors()) + .append("deptName", getDeptName()) + .append("orderNum", getOrderNum()) + .append("leader", getLeader()) + .append("phone", getPhone()) + .append("email", getEmail()) + .append("status", getStatus()) + .append("delFlag", getDelFlag()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java index 4b8146a72..445094f99 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java @@ -1,176 +1,175 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 字典数据表 sys_dict_data - * - * @author ruoyi - */ -public class SysDictData extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 字典编码 */ - @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) - private Long dictCode; - - /** 字典排序 */ - @Excel(name = "字典排序", cellType = ColumnType.NUMERIC) - private Long dictSort; - - /** 字典标签 */ - @Excel(name = "字典标签") - private String dictLabel; - - /** 字典键值 */ - @Excel(name = "字典键值") - private String dictValue; - - /** 字典类型 */ - @Excel(name = "字典类型") - private String dictType; - - /** 样式属性(其他样式扩展) */ - @Excel(name = "字典样式") - private String cssClass; - - /** 表格字典样式 */ - private String listClass; - - /** 是否默认(Y是 N否) */ - @Excel(name = "是否默认", readConverterExp = "Y=是,N=否") - private String isDefault; - - /** 状态(0正常 1停用) */ - @Excel(name = "状态", readConverterExp = "0=正常,1=停用") - private String status; - - public Long getDictCode() - { - return dictCode; - } - - public void setDictCode(Long dictCode) - { - this.dictCode = dictCode; - } - - public Long getDictSort() - { - return dictSort; - } - - public void setDictSort(Long dictSort) - { - this.dictSort = dictSort; - } - - @NotBlank(message = "字典标签不能为空") - @Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符") - public String getDictLabel() - { - return dictLabel; - } - - public void setDictLabel(String dictLabel) - { - this.dictLabel = dictLabel; - } - - @NotBlank(message = "字典键值不能为空") - @Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符") - public String getDictValue() - { - return dictValue; - } - - public void setDictValue(String dictValue) - { - this.dictValue = dictValue; - } - - @NotBlank(message = "字典类型不能为空") - @Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符") - public String getDictType() - { - return dictType; - } - - public void setDictType(String dictType) - { - this.dictType = dictType; - } - - @Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符") - public String getCssClass() - { - return cssClass; - } - - public void setCssClass(String cssClass) - { - this.cssClass = cssClass; - } - - public String getListClass() - { - return listClass; - } - - public void setListClass(String listClass) - { - this.listClass = listClass; - } - - public boolean getDefault() - { - return UserConstants.YES.equals(this.isDefault) ? true : false; - } - - public String getIsDefault() - { - return isDefault; - } - - public void setIsDefault(String isDefault) - { - this.isDefault = isDefault; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("dictCode", getDictCode()) - .append("dictSort", getDictSort()) - .append("dictLabel", getDictLabel()) - .append("dictValue", getDictValue()) - .append("dictType", getDictType()) - .append("cssClass", getCssClass()) - .append("listClass", getListClass()) - .append("isDefault", getIsDefault()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 字典数据表 sys_dict_data + * + * @author ruoyi + */ +public class SysDictData extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 字典编码 + */ + @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) + private Long dictCode; + + /** + * 字典排序 + */ + @Excel(name = "字典排序", cellType = ColumnType.NUMERIC) + private Long dictSort; + + /** + * 字典标签 + */ + @Excel(name = "字典标签") + private String dictLabel; + + /** + * 字典键值 + */ + @Excel(name = "字典键值") + private String dictValue; + + /** + * 字典类型 + */ + @Excel(name = "字典类型") + private String dictType; + + /** + * 样式属性(其他样式扩展) + */ + @Excel(name = "字典样式") + private String cssClass; + + /** + * 表格字典样式 + */ + private String listClass; + + /** + * 是否默认(Y是 N否) + */ + @Excel(name = "是否默认", readConverterExp = "Y=是,N=否") + private String isDefault; + + /** + * 状态(0正常 1停用) + */ + @Excel(name = "状态", readConverterExp = "0=正常,1=停用") + private String status; + + public Long getDictCode() { + return dictCode; + } + + public void setDictCode(Long dictCode) { + this.dictCode = dictCode; + } + + public Long getDictSort() { + return dictSort; + } + + public void setDictSort(Long dictSort) { + this.dictSort = dictSort; + } + + @NotBlank(message = "字典标签不能为空") + @Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符") + public String getDictLabel() { + return dictLabel; + } + + public void setDictLabel(String dictLabel) { + this.dictLabel = dictLabel; + } + + @NotBlank(message = "字典键值不能为空") + @Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符") + public String getDictValue() { + return dictValue; + } + + public void setDictValue(String dictValue) { + this.dictValue = dictValue; + } + + @NotBlank(message = "字典类型不能为空") + @Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符") + public String getDictType() { + return dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + @Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符") + public String getCssClass() { + return cssClass; + } + + public void setCssClass(String cssClass) { + this.cssClass = cssClass; + } + + public String getListClass() { + return listClass; + } + + public void setListClass(String listClass) { + this.listClass = listClass; + } + + public boolean getDefault() { + return UserConstants.YES.equals(this.isDefault) ? true : false; + } + + public String getIsDefault() { + return isDefault; + } + + public void setIsDefault(String isDefault) { + this.isDefault = isDefault; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("dictCode", getDictCode()) + .append("dictSort", getDictSort()) + .append("dictLabel", getDictLabel()) + .append("dictValue", getDictValue()) + .append("dictType", getDictType()) + .append("cssClass", getCssClass()) + .append("listClass", getListClass()) + .append("isDefault", getIsDefault()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java index 8c786b4bc..2a0c851ab 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java @@ -1,93 +1,93 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 字典类型表 sys_dict_type - * - * @author ruoyi - */ -public class SysDictType extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 字典主键 */ - @Excel(name = "字典主键", cellType = ColumnType.NUMERIC) - private Long dictId; - - /** 字典名称 */ - @Excel(name = "字典名称") - private String dictName; - - /** 字典类型 */ - @Excel(name = "字典类型") - private String dictType; - - /** 状态(0正常 1停用) */ - @Excel(name = "状态", readConverterExp = "0=正常,1=停用") - private String status; - - public Long getDictId() - { - return dictId; - } - - public void setDictId(Long dictId) - { - this.dictId = dictId; - } - - @NotBlank(message = "字典名称不能为空") - @Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符") - public String getDictName() - { - return dictName; - } - - public void setDictName(String dictName) - { - this.dictName = dictName; - } - - @NotBlank(message = "字典类型不能为空") - @Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符") - public String getDictType() - { - return dictType; - } - - public void setDictType(String dictType) - { - this.dictType = dictType; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("dictId", getDictId()) - .append("dictName", getDictName()) - .append("dictType", getDictType()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 字典类型表 sys_dict_type + * + * @author ruoyi + */ +public class SysDictType extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 字典主键 + */ + @Excel(name = "字典主键", cellType = ColumnType.NUMERIC) + private Long dictId; + + /** + * 字典名称 + */ + @Excel(name = "字典名称") + private String dictName; + + /** + * 字典类型 + */ + @Excel(name = "字典类型") + private String dictType; + + /** + * 状态(0正常 1停用) + */ + @Excel(name = "状态", readConverterExp = "0=正常,1=停用") + private String status; + + public Long getDictId() { + return dictId; + } + + public void setDictId(Long dictId) { + this.dictId = dictId; + } + + @NotBlank(message = "字典名称不能为空") + @Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符") + public String getDictName() { + return dictName; + } + + public void setDictName(String dictName) { + this.dictName = dictName; + } + + @NotBlank(message = "字典类型不能为空") + @Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符") + public String getDictType() { + return dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("dictId", getDictId()) + .append("dictName", getDictName()) + .append("dictType", getDictType()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java index cf79d99d2..e823cdfda 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java @@ -1,159 +1,160 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import java.util.Date; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 系统访问记录表 sys_logininfor - * - * @author ruoyi - */ -public class SysLogininfor extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** ID */ - @Excel(name = "序号", cellType = ColumnType.NUMERIC) - private Long infoId; - - /** 用户账号 */ - @Excel(name = "用户账号") - private String loginName; - - /** 登录状态 0成功 1失败 */ - @Excel(name = "登录状态", readConverterExp = "0=成功,1=失败") - private String status; - - /** 登录IP地址 */ - @Excel(name = "登录地址") - private String ipaddr; - - /** 登录地点 */ - @Excel(name = "登录地点") - private String loginLocation; - - /** 浏览器类型 */ - @Excel(name = "浏览器") - private String browser; - - /** 操作系统 */ - @Excel(name = "操作系统") - private String os; - - /** 提示消息 */ - @Excel(name = "提示消息") - private String msg; - - /** 访问时间 */ - @Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") - private Date loginTime; - - public Long getInfoId() - { - return infoId; - } - - public void setInfoId(Long infoId) - { - this.infoId = infoId; - } - - public String getLoginName() - { - return loginName; - } - - public void setLoginName(String loginName) - { - this.loginName = loginName; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public String getIpaddr() - { - return ipaddr; - } - - public void setIpaddr(String ipaddr) - { - this.ipaddr = ipaddr; - } - - public String getLoginLocation() - { - return loginLocation; - } - - public void setLoginLocation(String loginLocation) - { - this.loginLocation = loginLocation; - } - - public String getBrowser() - { - return browser; - } - - public void setBrowser(String browser) - { - this.browser = browser; - } - - public String getOs() - { - return os; - } - - public void setOs(String os) - { - this.os = os; - } - - public String getMsg() - { - return msg; - } - - public void setMsg(String msg) - { - this.msg = msg; - } - - public Date getLoginTime() - { - return loginTime; - } - - public void setLoginTime(Date loginTime) - { - this.loginTime = loginTime; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("infoId", getInfoId()) - .append("loginName", getLoginName()) - .append("ipaddr", getIpaddr()) - .append("loginLocation", getLoginLocation()) - .append("browser", getBrowser()) - .append("os", getOs()) - .append("status", getStatus()) - .append("msg", getMsg()) - .append("loginTime", getLoginTime()) - .toString(); - } +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import java.util.Date; + +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 系统访问记录表 sys_logininfor + * + * @author ruoyi + */ +public class SysLogininfor extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * ID + */ + @Excel(name = "序号", cellType = ColumnType.NUMERIC) + private Long infoId; + + /** + * 用户账号 + */ + @Excel(name = "用户账号") + private String loginName; + + /** + * 登录状态 0成功 1失败 + */ + @Excel(name = "登录状态", readConverterExp = "0=成功,1=失败") + private String status; + + /** + * 登录IP地址 + */ + @Excel(name = "登录地址") + private String ipaddr; + + /** + * 登录地点 + */ + @Excel(name = "登录地点") + private String loginLocation; + + /** + * 浏览器类型 + */ + @Excel(name = "浏览器") + private String browser; + + /** + * 操作系统 + */ + @Excel(name = "操作系统") + private String os; + + /** + * 提示消息 + */ + @Excel(name = "提示消息") + private String msg; + + /** + * 访问时间 + */ + @Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") + private Date loginTime; + + public Long getInfoId() { + return infoId; + } + + public void setInfoId(Long infoId) { + this.infoId = infoId; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getIpaddr() { + return ipaddr; + } + + public void setIpaddr(String ipaddr) { + this.ipaddr = ipaddr; + } + + public String getLoginLocation() { + return loginLocation; + } + + public void setLoginLocation(String loginLocation) { + this.loginLocation = loginLocation; + } + + public String getBrowser() { + return browser; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Date getLoginTime() { + return loginTime; + } + + public void setLoginTime(Date loginTime) { + this.loginTime = loginTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("infoId", getInfoId()) + .append("loginName", getLoginName()) + .append("ipaddr", getIpaddr()) + .append("loginLocation", getLoginLocation()) + .append("browser", getBrowser()) + .append("os", getOs()) + .append("status", getStatus()) + .append("msg", getMsg()) + .append("loginTime", getLoginTime()) + .toString(); + } } \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java index 8a0f83f44..76ac12333 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java @@ -1,201 +1,201 @@ -package com.ruoyi.system.domain; - -import java.util.List; -import java.util.ArrayList; -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 菜单权限表 sys_menu - * - * @author ruoyi - */ -public class SysMenu extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 菜单ID */ - private Long menuId; - - /** 菜单名称 */ - private String menuName; - - /** 父菜单名称 */ - private String parentName; - - /** 父菜单ID */ - private Long parentId; - - /** 显示顺序 */ - private String orderNum; - - /** 菜单URL */ - private String url; - - /** 打开方式:menuItem页签 menuBlank新窗口 */ - private String target; - - /** 类型:0目录,1菜单,2按钮 */ - private String menuType; - - /** 菜单状态:0显示,1隐藏 */ - private String visible; - - /** 权限字符串 */ - private String perms; - - /** 菜单图标 */ - private String icon; - - /** 子菜单 */ - private List children = new ArrayList(); - - public Long getMenuId() - { - return menuId; - } - - public void setMenuId(Long menuId) - { - this.menuId = menuId; - } - - @NotBlank(message = "菜单名称不能为空") - @Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符") - public String getMenuName() - { - return menuName; - } - - public void setMenuName(String menuName) - { - this.menuName = menuName; - } - - public String getParentName() - { - return parentName; - } - - public void setParentName(String parentName) - { - this.parentName = parentName; - } - - public Long getParentId() - { - return parentId; - } - - public void setParentId(Long parentId) - { - this.parentId = parentId; - } - - @NotBlank(message = "显示顺序不能为空") - public String getOrderNum() - { - return orderNum; - } - - public void setOrderNum(String orderNum) - { - this.orderNum = orderNum; - } - - @Size(min = 0, max = 200, message = "请求地址不能超过200个字符") - public String getUrl() - { - return url; - } - - public void setUrl(String url) - { - this.url = url; - } - - public String getTarget() - { - return target; - } - - public void setTarget(String target) - { - this.target = target; - } - - @NotBlank(message = "菜单类型不能为空") - public String getMenuType() - { - return menuType; - } - - public void setMenuType(String menuType) - { - this.menuType = menuType; - } - - public String getVisible() - { - return visible; - } - - public void setVisible(String visible) - { - this.visible = visible; - } - - @Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符") - public String getPerms() - { - return perms; - } - - public void setPerms(String perms) - { - this.perms = perms; - } - - public String getIcon() - { - return icon; - } - - public void setIcon(String icon) - { - this.icon = icon; - } - - public List getChildren() - { - return children; - } - - public void setChildren(List children) - { - this.children = children; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("menuId", getMenuId()) - .append("menuName", getMenuName()) - .append("parentId", getParentId()) - .append("orderNum", getOrderNum()) - .append("url", getUrl()) - .append("target", getTarget()) - .append("menuType", getMenuType()) - .append("visible", getVisible()) - .append("perms", getPerms()) - .append("icon", getIcon()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import java.util.List; +import java.util.ArrayList; +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 菜单权限表 sys_menu + * + * @author ruoyi + */ +public class SysMenu extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 菜单ID + */ + private Long menuId; + + /** + * 菜单名称 + */ + private String menuName; + + /** + * 父菜单名称 + */ + private String parentName; + + /** + * 父菜单ID + */ + private Long parentId; + + /** + * 显示顺序 + */ + private String orderNum; + + /** + * 菜单URL + */ + private String url; + + /** + * 打开方式:menuItem页签 menuBlank新窗口 + */ + private String target; + + /** + * 类型:0目录,1菜单,2按钮 + */ + private String menuType; + + /** + * 菜单状态:0显示,1隐藏 + */ + private String visible; + + /** + * 权限字符串 + */ + private String perms; + + /** + * 菜单图标 + */ + private String icon; + + /** + * 子菜单 + */ + private List children = new ArrayList(); + + public Long getMenuId() { + return menuId; + } + + public void setMenuId(Long menuId) { + this.menuId = menuId; + } + + @NotBlank(message = "菜单名称不能为空") + @Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符") + public String getMenuName() { + return menuName; + } + + public void setMenuName(String menuName) { + this.menuName = menuName; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + @NotBlank(message = "显示顺序不能为空") + public String getOrderNum() { + return orderNum; + } + + public void setOrderNum(String orderNum) { + this.orderNum = orderNum; + } + + @Size(min = 0, max = 200, message = "请求地址不能超过200个字符") + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + @NotBlank(message = "菜单类型不能为空") + public String getMenuType() { + return menuType; + } + + public void setMenuType(String menuType) { + this.menuType = menuType; + } + + public String getVisible() { + return visible; + } + + public void setVisible(String visible) { + this.visible = visible; + } + + @Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符") + public String getPerms() { + return perms; + } + + public void setPerms(String perms) { + this.perms = perms; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("menuId", getMenuId()) + .append("menuName", getMenuName()) + .append("parentId", getParentId()) + .append("orderNum", getOrderNum()) + .append("url", getUrl()) + .append("target", getTarget()) + .append("menuType", getMenuType()) + .append("visible", getVisible()) + .append("perms", getPerms()) + .append("icon", getIcon()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java index 7de4d9460..fc6798458 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java @@ -1,99 +1,99 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 通知公告表 sys_notice - * - * @author ruoyi - */ -public class SysNotice extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 公告ID */ - private Long noticeId; - - /** 公告标题 */ - private String noticeTitle; - - /** 公告类型(1通知 2公告) */ - private String noticeType; - - /** 公告内容 */ - private String noticeContent; - - /** 公告状态(0正常 1关闭) */ - private String status; - - public Long getNoticeId() - { - return noticeId; - } - - public void setNoticeId(Long noticeId) - { - this.noticeId = noticeId; - } - - public void setNoticeTitle(String noticeTitle) - { - this.noticeTitle = noticeTitle; - } - - @NotBlank(message = "公告标题不能为空") - @Size(min = 0, max = 50, message = "公告标题不能超过50个字符") - public String getNoticeTitle() - { - return noticeTitle; - } - - public void setNoticeType(String noticeType) - { - this.noticeType = noticeType; - } - - public String getNoticeType() - { - return noticeType; - } - - public void setNoticeContent(String noticeContent) - { - this.noticeContent = noticeContent; - } - - public String getNoticeContent() - { - return noticeContent; - } - - public void setStatus(String status) - { - this.status = status; - } - - public String getStatus() - { - return status; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("noticeId", getNoticeId()) - .append("noticeTitle", getNoticeTitle()) - .append("noticeType", getNoticeType()) - .append("noticeContent", getNoticeContent()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 通知公告表 sys_notice + * + * @author ruoyi + */ +public class SysNotice extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 公告ID + */ + private Long noticeId; + + /** + * 公告标题 + */ + private String noticeTitle; + + /** + * 公告类型(1通知 2公告) + */ + private String noticeType; + + /** + * 公告内容 + */ + private String noticeContent; + + /** + * 公告状态(0正常 1关闭) + */ + private String status; + + public Long getNoticeId() { + return noticeId; + } + + public void setNoticeId(Long noticeId) { + this.noticeId = noticeId; + } + + public void setNoticeTitle(String noticeTitle) { + this.noticeTitle = noticeTitle; + } + + @NotBlank(message = "公告标题不能为空") + @Size(min = 0, max = 50, message = "公告标题不能超过50个字符") + public String getNoticeTitle() { + return noticeTitle; + } + + public void setNoticeType(String noticeType) { + this.noticeType = noticeType; + } + + public String getNoticeType() { + return noticeType; + } + + public void setNoticeContent(String noticeContent) { + this.noticeContent = noticeContent; + } + + public String getNoticeContent() { + return noticeContent; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getStatus() { + return status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("noticeId", getNoticeId()) + .append("noticeTitle", getNoticeTitle()) + .append("noticeType", getNoticeType()) + .append("noticeContent", getNoticeContent()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java index a3a98438e..68d486336 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java @@ -1,277 +1,278 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import java.util.Date; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 操作日志记录表 oper_log - * - * @author ruoyi - */ -public class SysOperLog extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 日志主键 */ - @Excel(name = "操作序号", cellType = ColumnType.NUMERIC) - private Long operId; - - /** 操作模块 */ - @Excel(name = "操作模块") - private String title; - - /** 业务类型(0其它 1新增 2修改 3删除) */ - @Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据") - private Integer businessType; - - /** 业务类型数组 */ - private Integer[] businessTypes; - - /** 请求方法 */ - @Excel(name = "请求方法") - private String method; - - /** 请求方式 */ - @Excel(name = "请求方式") - private String requestMethod; - - /** 操作类别(0其它 1后台用户 2手机端用户) */ - @Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户") - private Integer operatorType; - - /** 操作人员 */ - @Excel(name = "操作人员") - private String operName; - - /** 部门名称 */ - @Excel(name = "部门名称") - private String deptName; - - /** 请求url */ - @Excel(name = "请求地址") - private String operUrl; - - /** 操作地址 */ - @Excel(name = "操作地址") - private String operIp; - - /** 操作地点 */ - @Excel(name = "操作地点") - private String operLocation; - - /** 请求参数 */ - @Excel(name = "请求参数") - private String operParam; - - /** 返回参数 */ - @Excel(name = "返回参数") - private String jsonResult; - - /** 操作状态(0正常 1异常) */ - @Excel(name = "状态", readConverterExp = "0=正常,1=异常") - private Integer status; - - /** 错误消息 */ - @Excel(name = "错误消息") - private String errorMsg; - - /** 操作时间 */ - @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") - private Date operTime; - - public Long getOperId() - { - return operId; - } - - public void setOperId(Long operId) - { - this.operId = operId; - } - - public String getTitle() - { - return title; - } - - public void setTitle(String title) - { - this.title = title; - } - - public Integer getBusinessType() - { - return businessType; - } - - public void setBusinessType(Integer businessType) - { - this.businessType = businessType; - } - - public Integer[] getBusinessTypes() - { - return businessTypes; - } - - public void setBusinessTypes(Integer[] businessTypes) - { - this.businessTypes = businessTypes; - } - - public String getMethod() - { - return method; - } - - public void setMethod(String method) - { - this.method = method; - } - - public String getRequestMethod() - { - return requestMethod; - } - - public void setRequestMethod(String requestMethod) - { - this.requestMethod = requestMethod; - } - - public Integer getOperatorType() - { - return operatorType; - } - - public void setOperatorType(Integer operatorType) - { - this.operatorType = operatorType; - } - - public String getOperName() - { - return operName; - } - - public void setOperName(String operName) - { - this.operName = operName; - } - - public String getDeptName() - { - return deptName; - } - - public void setDeptName(String deptName) - { - this.deptName = deptName; - } - - public String getOperUrl() - { - return operUrl; - } - - public void setOperUrl(String operUrl) - { - this.operUrl = operUrl; - } - - public String getOperIp() - { - return operIp; - } - - public void setOperIp(String operIp) - { - this.operIp = operIp; - } - - public String getOperLocation() - { - return operLocation; - } - - public void setOperLocation(String operLocation) - { - this.operLocation = operLocation; - } - - public String getOperParam() - { - return operParam; - } - - public void setOperParam(String operParam) - { - this.operParam = operParam; - } - - public String getJsonResult() - { - return jsonResult; - } - - public void setJsonResult(String jsonResult) - { - this.jsonResult = jsonResult; - } - - public Integer getStatus() - { - return status; - } - - public void setStatus(Integer status) - { - this.status = status; - } - - public String getErrorMsg() - { - return errorMsg; - } - - public void setErrorMsg(String errorMsg) - { - this.errorMsg = errorMsg; - } - - public Date getOperTime() - { - return operTime; - } - - public void setOperTime(Date operTime) - { - this.operTime = operTime; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("operId", getOperId()) - .append("title", getTitle()) - .append("businessType", getBusinessType()) - .append("businessTypes", getBusinessTypes()) - .append("method", getMethod()) - .append("requestMethod", getRequestMethod()) - .append("operatorType", getOperatorType()) - .append("operName", getOperName()) - .append("deptName", getDeptName()) - .append("operUrl", getOperUrl()) - .append("operIp", getOperIp()) - .append("operLocation", getOperLocation()) - .append("operParam", getOperParam()) - .append("status", getStatus()) - .append("errorMsg", getErrorMsg()) - .append("operTime", getOperTime()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import java.util.Date; + +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 操作日志记录表 oper_log + * + * @author ruoyi + */ +public class SysOperLog extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 日志主键 + */ + @Excel(name = "操作序号", cellType = ColumnType.NUMERIC) + private Long operId; + + /** + * 操作模块 + */ + @Excel(name = "操作模块") + private String title; + + /** + * 业务类型(0其它 1新增 2修改 3删除) + */ + @Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据") + private Integer businessType; + + /** + * 业务类型数组 + */ + private Integer[] businessTypes; + + /** + * 请求方法 + */ + @Excel(name = "请求方法") + private String method; + + /** + * 请求方式 + */ + @Excel(name = "请求方式") + private String requestMethod; + + /** + * 操作类别(0其它 1后台用户 2手机端用户) + */ + @Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户") + private Integer operatorType; + + /** + * 操作人员 + */ + @Excel(name = "操作人员") + private String operName; + + /** + * 部门名称 + */ + @Excel(name = "部门名称") + private String deptName; + + /** + * 请求url + */ + @Excel(name = "请求地址") + private String operUrl; + + /** + * 操作地址 + */ + @Excel(name = "操作地址") + private String operIp; + + /** + * 操作地点 + */ + @Excel(name = "操作地点") + private String operLocation; + + /** + * 请求参数 + */ + @Excel(name = "请求参数") + private String operParam; + + /** + * 返回参数 + */ + @Excel(name = "返回参数") + private String jsonResult; + + /** + * 操作状态(0正常 1异常) + */ + @Excel(name = "状态", readConverterExp = "0=正常,1=异常") + private Integer status; + + /** + * 错误消息 + */ + @Excel(name = "错误消息") + private String errorMsg; + + /** + * 操作时间 + */ + @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") + private Date operTime; + + public Long getOperId() { + return operId; + } + + public void setOperId(Long operId) { + this.operId = operId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getBusinessType() { + return businessType; + } + + public void setBusinessType(Integer businessType) { + this.businessType = businessType; + } + + public Integer[] getBusinessTypes() { + return businessTypes; + } + + public void setBusinessTypes(Integer[] businessTypes) { + this.businessTypes = businessTypes; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getRequestMethod() { + return requestMethod; + } + + public void setRequestMethod(String requestMethod) { + this.requestMethod = requestMethod; + } + + public Integer getOperatorType() { + return operatorType; + } + + public void setOperatorType(Integer operatorType) { + this.operatorType = operatorType; + } + + public String getOperName() { + return operName; + } + + public void setOperName(String operName) { + this.operName = operName; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + public String getOperUrl() { + return operUrl; + } + + public void setOperUrl(String operUrl) { + this.operUrl = operUrl; + } + + public String getOperIp() { + return operIp; + } + + public void setOperIp(String operIp) { + this.operIp = operIp; + } + + public String getOperLocation() { + return operLocation; + } + + public void setOperLocation(String operLocation) { + this.operLocation = operLocation; + } + + public String getOperParam() { + return operParam; + } + + public void setOperParam(String operParam) { + this.operParam = operParam; + } + + public String getJsonResult() { + return jsonResult; + } + + public void setJsonResult(String jsonResult) { + this.jsonResult = jsonResult; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public Date getOperTime() { + return operTime; + } + + public void setOperTime(Date operTime) { + this.operTime = operTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("operId", getOperId()) + .append("title", getTitle()) + .append("businessType", getBusinessType()) + .append("businessTypes", getBusinessTypes()) + .append("method", getMethod()) + .append("requestMethod", getRequestMethod()) + .append("operatorType", getOperatorType()) + .append("operName", getOperName()) + .append("deptName", getDeptName()) + .append("operUrl", getOperUrl()) + .append("operIp", getOperIp()) + .append("operLocation", getOperLocation()) + .append("operParam", getOperParam()) + .append("status", getStatus()) + .append("errorMsg", getErrorMsg()) + .append("operTime", getOperTime()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java index 7a2cb2bad..0e2d434a4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java @@ -1,122 +1,122 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 岗位表 sys_post - * - * @author ruoyi - */ -public class SysPost extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 岗位序号 */ - @Excel(name = "岗位序号", cellType = ColumnType.NUMERIC) - private Long postId; - - /** 岗位编码 */ - @Excel(name = "岗位编码") - private String postCode; - - /** 岗位名称 */ - @Excel(name = "岗位名称") - private String postName; - - /** 岗位排序 */ - @Excel(name = "岗位排序", cellType = ColumnType.NUMERIC) - private String postSort; - - /** 状态(0正常 1停用) */ - @Excel(name = "状态", readConverterExp = "0=正常,1=停用") - private String status; - - /** 用户是否存在此岗位标识 默认不存在 */ - private boolean flag = false; - - public Long getPostId() - { - return postId; - } - - public void setPostId(Long postId) - { - this.postId = postId; - } - - @NotBlank(message = "岗位编码不能为空") - @Size(min = 0, max = 64, message = "岗位编码长度不能超过64个字符") - public String getPostCode() - { - return postCode; - } - - public void setPostCode(String postCode) - { - this.postCode = postCode; - } - - @NotBlank(message = "岗位名称不能为空") - @Size(min = 0, max = 50, message = "岗位名称长度不能超过50个字符") - public String getPostName() - { - return postName; - } - - public void setPostName(String postName) - { - this.postName = postName; - } - - @NotBlank(message = "显示顺序不能为空") - public String getPostSort() - { - return postSort; - } - - public void setPostSort(String postSort) - { - this.postSort = postSort; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public boolean isFlag() - { - return flag; - } - - public void setFlag(boolean flag) - { - this.flag = flag; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("postId", getPostId()) - .append("postCode", getPostCode()) - .append("postName", getPostName()) - .append("postSort", getPostSort()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 岗位表 sys_post + * + * @author ruoyi + */ +public class SysPost extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 岗位序号 + */ + @Excel(name = "岗位序号", cellType = ColumnType.NUMERIC) + private Long postId; + + /** + * 岗位编码 + */ + @Excel(name = "岗位编码") + private String postCode; + + /** + * 岗位名称 + */ + @Excel(name = "岗位名称") + private String postName; + + /** + * 岗位排序 + */ + @Excel(name = "岗位排序", cellType = ColumnType.NUMERIC) + private String postSort; + + /** + * 状态(0正常 1停用) + */ + @Excel(name = "状态", readConverterExp = "0=正常,1=停用") + private String status; + + /** + * 用户是否存在此岗位标识 默认不存在 + */ + private boolean flag = false; + + public Long getPostId() { + return postId; + } + + public void setPostId(Long postId) { + this.postId = postId; + } + + @NotBlank(message = "岗位编码不能为空") + @Size(min = 0, max = 64, message = "岗位编码长度不能超过64个字符") + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } + + @NotBlank(message = "岗位名称不能为空") + @Size(min = 0, max = 50, message = "岗位名称长度不能超过50个字符") + public String getPostName() { + return postName; + } + + public void setPostName(String postName) { + this.postName = postName; + } + + @NotBlank(message = "显示顺序不能为空") + public String getPostSort() { + return postSort; + } + + public void setPostSort(String postSort) { + this.postSort = postSort; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("postId", getPostId()) + .append("postCode", getPostCode()) + .append("postName", getPostName()) + .append("postSort", getPostSort()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index bb3f549e3..5a9bafe7d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -1,196 +1,192 @@ -package com.ruoyi.system.domain; - -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 角色表 sys_role - * - * @author ruoyi - */ -public class SysRole extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 角色ID */ - @Excel(name = "角色序号", cellType = ColumnType.NUMERIC) - private Long roleId; - - /** 角色名称 */ - @Excel(name = "角色名称") - private String roleName; - - /** 角色权限 */ - @Excel(name = "角色权限") - private String roleKey; - - /** 角色排序 */ - @Excel(name = "角色排序", cellType = ColumnType.NUMERIC) - private String roleSort; - - /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) */ - @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限") - private String dataScope; - - /** 角色状态(0正常 1停用) */ - @Excel(name = "角色状态", readConverterExp = "0=正常,1=停用") - private String status; - - /** 删除标志(0代表存在 2代表删除) */ - private String delFlag; - - /** 用户是否存在此角色标识 默认不存在 */ - private boolean flag = false; - - /** 菜单组 */ - private Long[] menuIds; - - /** 部门组(数据权限) */ - private Long[] deptIds; - - public SysRole() - { - - } - - public SysRole(Long roleId) - { - this.roleId = roleId; - } - - public Long getRoleId() - { - return roleId; - } - - public void setRoleId(Long roleId) - { - this.roleId = roleId; - } - - public boolean isAdmin() - { - return isAdmin(this.roleId); - } - - public static boolean isAdmin(Long roleId) - { - return roleId != null && 1L == roleId; - } - - public String getDataScope() - { - return dataScope; - } - - public void setDataScope(String dataScope) - { - this.dataScope = dataScope; - } - - @NotBlank(message = "角色名称不能为空") - @Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符") - public String getRoleName() - { - return roleName; - } - - public void setRoleName(String roleName) - { - this.roleName = roleName; - } - - @NotBlank(message = "权限字符不能为空") - @Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符") - public String getRoleKey() - { - return roleKey; - } - - public void setRoleKey(String roleKey) - { - this.roleKey = roleKey; - } - - @NotBlank(message = "显示顺序不能为空") - public String getRoleSort() - { - return roleSort; - } - - public void setRoleSort(String roleSort) - { - this.roleSort = roleSort; - } - - public String getStatus() - { - return status; - } - - public String getDelFlag() - { - return delFlag; - } - - public void setDelFlag(String delFlag) - { - this.delFlag = delFlag; - } - - public void setStatus(String status) - { - this.status = status; - } - - public boolean isFlag() - { - return flag; - } - - public void setFlag(boolean flag) - { - this.flag = flag; - } - - public Long[] getMenuIds() - { - return menuIds; - } - - public void setMenuIds(Long[] menuIds) - { - this.menuIds = menuIds; - } - - public Long[] getDeptIds() - { - return deptIds; - } - - public void setDeptIds(Long[] deptIds) - { - this.deptIds = deptIds; - } - - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("roleId", getRoleId()) - .append("roleName", getRoleName()) - .append("roleKey", getRoleKey()) - .append("roleSort", getRoleSort()) - .append("dataScope", getDataScope()) - .append("status", getStatus()) - .append("delFlag", getDelFlag()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 角色表 sys_role + * + * @author ruoyi + */ +public class SysRole extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 角色ID + */ + @Excel(name = "角色序号", cellType = ColumnType.NUMERIC) + private Long roleId; + + /** + * 角色名称 + */ + @Excel(name = "角色名称") + private String roleName; + + /** + * 角色权限 + */ + @Excel(name = "角色权限") + private String roleKey; + + /** + * 角色排序 + */ + @Excel(name = "角色排序", cellType = ColumnType.NUMERIC) + private String roleSort; + + /** + * 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) + */ + @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限") + private String dataScope; + + /** + * 角色状态(0正常 1停用) + */ + @Excel(name = "角色状态", readConverterExp = "0=正常,1=停用") + private String status; + + /** + * 删除标志(0代表存在 2代表删除) + */ + private String delFlag; + + /** + * 用户是否存在此角色标识 默认不存在 + */ + private boolean flag = false; + + /** + * 菜单组 + */ + private Long[] menuIds; + + /** + * 部门组(数据权限) + */ + private Long[] deptIds; + + public SysRole() { + + } + + public SysRole(Long roleId) { + this.roleId = roleId; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public boolean isAdmin() { + return isAdmin(this.roleId); + } + + public static boolean isAdmin(Long roleId) { + return roleId != null && 1L == roleId; + } + + public String getDataScope() { + return dataScope; + } + + public void setDataScope(String dataScope) { + this.dataScope = dataScope; + } + + @NotBlank(message = "角色名称不能为空") + @Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符") + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + @NotBlank(message = "权限字符不能为空") + @Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符") + public String getRoleKey() { + return roleKey; + } + + public void setRoleKey(String roleKey) { + this.roleKey = roleKey; + } + + @NotBlank(message = "显示顺序不能为空") + public String getRoleSort() { + return roleSort; + } + + public void setRoleSort(String roleSort) { + this.roleSort = roleSort; + } + + public String getStatus() { + return status; + } + + public String getDelFlag() { + return delFlag; + } + + public void setDelFlag(String delFlag) { + this.delFlag = delFlag; + } + + public void setStatus(String status) { + this.status = status; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + public Long[] getMenuIds() { + return menuIds; + } + + public void setMenuIds(Long[] menuIds) { + this.menuIds = menuIds; + } + + public Long[] getDeptIds() { + return deptIds; + } + + public void setDeptIds(Long[] deptIds) { + this.deptIds = deptIds; + } + + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("roleId", getRoleId()) + .append("roleName", getRoleName()) + .append("roleKey", getRoleKey()) + .append("roleSort", getRoleSort()) + .append("dataScope", getDataScope()) + .append("status", getStatus()) + .append("delFlag", getDelFlag()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleDept.java index 8ed8e473e..aaaa06e4c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleDept.java @@ -1,46 +1,45 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * 角色和部门关联 sys_role_dept - * - * @author ruoyi - */ -public class SysRoleDept -{ - /** 角色ID */ - private Long roleId; - - /** 部门ID */ - private Long deptId; - - public Long getRoleId() - { - return roleId; - } - - public void setRoleId(Long roleId) - { - this.roleId = roleId; - } - - public Long getDeptId() - { - return deptId; - } - - public void setDeptId(Long deptId) - { - this.deptId = deptId; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("roleId", getRoleId()) - .append("deptId", getDeptId()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 角色和部门关联 sys_role_dept + * + * @author ruoyi + */ +public class SysRoleDept { + /** + * 角色ID + */ + private Long roleId; + + /** + * 部门ID + */ + private Long deptId; + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public Long getDeptId() { + return deptId; + } + + public void setDeptId(Long deptId) { + this.deptId = deptId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("roleId", getRoleId()) + .append("deptId", getDeptId()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleMenu.java index 59d286999..af6ac3204 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRoleMenu.java @@ -1,46 +1,45 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * 角色和菜单关联 sys_role_menu - * - * @author ruoyi - */ -public class SysRoleMenu -{ - /** 角色ID */ - private Long roleId; - - /** 菜单ID */ - private Long menuId; - - public Long getRoleId() - { - return roleId; - } - - public void setRoleId(Long roleId) - { - this.roleId = roleId; - } - - public Long getMenuId() - { - return menuId; - } - - public void setMenuId(Long menuId) - { - this.menuId = menuId; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("roleId", getRoleId()) - .append("menuId", getMenuId()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 角色和菜单关联 sys_role_menu + * + * @author ruoyi + */ +public class SysRoleMenu { + /** + * 角色ID + */ + private Long roleId; + + /** + * 菜单ID + */ + private Long menuId; + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public Long getMenuId() { + return menuId; + } + + public void setMenuId(Long menuId) { + this.menuId = menuId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("roleId", getRoleId()) + .append("menuId", getMenuId()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 43994ef36..793e8b287 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -1,351 +1,344 @@ -package com.ruoyi.system.domain; - -import java.util.Date; -import java.util.List; -import javax.validation.constraints.*; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.annotation.Excel.Type; -import com.ruoyi.common.annotation.Excels; -import com.ruoyi.common.core.domain.BaseEntity; - -/** - * 用户对象 sys_user - * - * @author ruoyi - */ -public class SysUser extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 用户ID */ - @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") - private Long userId; - - /** 部门ID */ - @Excel(name = "部门编号", type = Type.IMPORT) - private Long deptId; - - /** 部门父ID */ - private Long parentId; - - /** 角色ID */ - private Long roleId; - - /** 登录名称 */ - @Excel(name = "登录名称") - private String loginName; - - /** 用户名称 */ - @Excel(name = "用户名称") - private String userName; - - /** 用户邮箱 */ - @Excel(name = "用户邮箱") - private String email; - - /** 手机号码 */ - @Excel(name = "手机号码") - private String phonenumber; - - /** 用户性别 */ - @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知") - private String sex; - - /** 用户头像 */ - private String avatar; - - /** 密码 */ - private String password; - - /** 盐加密 */ - private String salt; - - /** 帐号状态(0正常 1停用) */ - @Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用") - private String status; - - /** 删除标志(0代表存在 2代表删除) */ - private String delFlag; - - /** 最后登陆IP */ - @Excel(name = "最后登陆IP", type = Type.EXPORT) - private String loginIp; - - /** 最后登陆时间 */ - @Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT) - private Date loginDate; - - /** 部门对象 */ - @Excels({ - @Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), - @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) - }) - private SysDept dept; - - private List roles; - - /** 角色组 */ - private Long[] roleIds; - - /** 岗位组 */ - private Long[] postIds; - - public SysUser() - { - - } - - public SysUser(Long userId) - { - this.userId = userId; - } - - public Long getUserId() - { - return userId; - } - - public void setUserId(Long userId) - { - this.userId = userId; - } - - public boolean isAdmin() - { - return isAdmin(this.userId); - } - - public static boolean isAdmin(Long userId) - { - return userId != null && 1L == userId; - } - - public Long getDeptId() - { - return deptId; - } - - public void setDeptId(Long deptId) - { - this.deptId = deptId; - } - - public Long getParentId() - { - return parentId; - } - - public void setParentId(Long parentId) - { - this.parentId = parentId; - } - - public Long getRoleId() - { - return roleId; - } - - public void setRoleId(Long roleId) - { - this.roleId = roleId; - } - - @NotBlank(message = "登录账号不能为空") - @Size(min = 0, max = 30, message = "登录账号长度不能超过30个字符") - public String getLoginName() - { - return loginName; - } - - public void setLoginName(String loginName) - { - this.loginName = loginName; - } - - @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") - public String getUserName() - { - return userName; - } - - public void setUserName(String userName) - { - this.userName = userName; - } - - @Email(message = "邮箱格式不正确") - @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") - public String getEmail() - { - return email; - } - - public void setEmail(String email) - { - this.email = email; - } - - @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") - public String getPhonenumber() - { - return phonenumber; - } - - public void setPhonenumber(String phonenumber) - { - this.phonenumber = phonenumber; - } - - public String getSex() - { - return sex; - } - - public void setSex(String sex) - { - this.sex = sex; - } - - public String getAvatar() - { - return avatar; - } - - public void setAvatar(String avatar) - { - this.avatar = avatar; - } - - public String getPassword() - { - return password; - } - - public void setPassword(String password) - { - this.password = password; - } - - public String getSalt() - { - return salt; - } - - public void setSalt(String salt) - { - this.salt = salt; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public String getDelFlag() - { - return delFlag; - } - - public void setDelFlag(String delFlag) - { - this.delFlag = delFlag; - } - - public String getLoginIp() - { - return loginIp; - } - - public void setLoginIp(String loginIp) - { - this.loginIp = loginIp; - } - - public Date getLoginDate() - { - return loginDate; - } - - public void setLoginDate(Date loginDate) - { - this.loginDate = loginDate; - } - - public SysDept getDept() - { - if (dept == null) - { - dept = new SysDept(); - } - return dept; - } - - public void setDept(SysDept dept) - { - this.dept = dept; - } - - public List getRoles() - { - return roles; - } - - public void setRoles(List roles) - { - this.roles = roles; - } - - public Long[] getRoleIds() - { - return roleIds; - } - - public void setRoleIds(Long[] roleIds) - { - this.roleIds = roleIds; - } - - public Long[] getPostIds() - { - return postIds; - } - - public void setPostIds(Long[] postIds) - { - this.postIds = postIds; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("userId", getUserId()) - .append("deptId", getDeptId()) - .append("loginName", getLoginName()) - .append("userName", getUserName()) - .append("email", getEmail()) - .append("phonenumber", getPhonenumber()) - .append("sex", getSex()) - .append("avatar", getAvatar()) - .append("password", getPassword()) - .append("salt", getSalt()) - .append("status", getStatus()) - .append("delFlag", getDelFlag()) - .append("loginIp", getLoginIp()) - .append("loginDate", getLoginDate()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .append("dept", getDept()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import java.util.Date; +import java.util.List; +import javax.validation.constraints.*; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.annotation.Excel.Type; +import com.ruoyi.common.annotation.Excels; +import com.ruoyi.common.core.domain.BaseEntity; + +/** + * 用户对象 sys_user + * + * @author ruoyi + */ +public class SysUser extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") + private Long userId; + + /** + * 部门ID + */ + @Excel(name = "部门编号", type = Type.IMPORT) + private Long deptId; + + /** + * 部门父ID + */ + private Long parentId; + + /** + * 角色ID + */ + private Long roleId; + + /** + * 登录名称 + */ + @Excel(name = "登录名称") + private String loginName; + + /** + * 用户名称 + */ + @Excel(name = "用户名称") + private String userName; + + /** + * 用户邮箱 + */ + @Excel(name = "用户邮箱") + private String email; + + /** + * 手机号码 + */ + @Excel(name = "手机号码") + private String phonenumber; + + /** + * 用户性别 + */ + @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知") + private String sex; + + /** + * 用户头像 + */ + private String avatar; + + /** + * 密码 + */ + private String password; + + /** + * 盐加密 + */ + private String salt; + + /** + * 帐号状态(0正常 1停用) + */ + @Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用") + private String status; + + /** + * 删除标志(0代表存在 2代表删除) + */ + private String delFlag; + + /** + * 最后登陆IP + */ + @Excel(name = "最后登陆IP", type = Type.EXPORT) + private String loginIp; + + /** + * 最后登陆时间 + */ + @Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT) + private Date loginDate; + + /** + * 部门对象 + */ + @Excels({ + @Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), + @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) + }) + private SysDept dept; + + private List roles; + + /** + * 角色组 + */ + private Long[] roleIds; + + /** + * 岗位组 + */ + private Long[] postIds; + + public SysUser() { + + } + + public SysUser(Long userId) { + this.userId = userId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public boolean isAdmin() { + return isAdmin(this.userId); + } + + public static boolean isAdmin(Long userId) { + return userId != null && 1L == userId; + } + + public Long getDeptId() { + return deptId; + } + + public void setDeptId(Long deptId) { + this.deptId = deptId; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + @NotBlank(message = "登录账号不能为空") + @Size(min = 0, max = 30, message = "登录账号长度不能超过30个字符") + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Email(message = "邮箱格式不正确") + @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") + public String getPhonenumber() { + return phonenumber; + } + + public void setPhonenumber(String phonenumber) { + this.phonenumber = phonenumber; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getSalt() { + return salt; + } + + public void setSalt(String salt) { + this.salt = salt; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDelFlag() { + return delFlag; + } + + public void setDelFlag(String delFlag) { + this.delFlag = delFlag; + } + + public String getLoginIp() { + return loginIp; + } + + public void setLoginIp(String loginIp) { + this.loginIp = loginIp; + } + + public Date getLoginDate() { + return loginDate; + } + + public void setLoginDate(Date loginDate) { + this.loginDate = loginDate; + } + + public SysDept getDept() { + if (dept == null) { + dept = new SysDept(); + } + return dept; + } + + public void setDept(SysDept dept) { + this.dept = dept; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public Long[] getRoleIds() { + return roleIds; + } + + public void setRoleIds(Long[] roleIds) { + this.roleIds = roleIds; + } + + public Long[] getPostIds() { + return postIds; + } + + public void setPostIds(Long[] postIds) { + this.postIds = postIds; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("userId", getUserId()) + .append("deptId", getDeptId()) + .append("loginName", getLoginName()) + .append("userName", getUserName()) + .append("email", getEmail()) + .append("phonenumber", getPhonenumber()) + .append("sex", getSex()) + .append("avatar", getAvatar()) + .append("password", getPassword()) + .append("salt", getSalt()) + .append("status", getStatus()) + .append("delFlag", getDelFlag()) + .append("loginIp", getLoginIp()) + .append("loginDate", getLoginDate()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .append("dept", getDept()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java index c5467bb66..3c366abb5 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java @@ -1,177 +1,177 @@ -package com.ruoyi.system.domain; - -import java.util.Date; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.enums.OnlineStatus; - -/** - * 当前在线会话 sys_user_online - * - * @author ruoyi - */ -public class SysUserOnline extends BaseEntity -{ - private static final long serialVersionUID = 1L; - - /** 用户会话id */ - private String sessionId; - - /** 部门名称 */ - private String deptName; - - /** 登录名称 */ - private String loginName; - - /** 登录IP地址 */ - private String ipaddr; - - /** 登录地址 */ - private String loginLocation; - - /** 浏览器类型 */ - private String browser; - - /** 操作系统 */ - private String os; - - /** session创建时间 */ - private Date startTimestamp; - - /** session最后访问时间 */ - private Date lastAccessTime; - - /** 超时时间,单位为分钟 */ - private Long expireTime; - - /** 在线状态 */ - private OnlineStatus status = OnlineStatus.on_line; - - public String getSessionId() - { - return sessionId; - } - - public void setSessionId(String sessionId) - { - this.sessionId = sessionId; - } - - public String getDeptName() - { - return deptName; - } - - public void setDeptName(String deptName) - { - this.deptName = deptName; - } - - public String getLoginName() - { - return loginName; - } - - public void setLoginName(String loginName) - { - this.loginName = loginName; - } - - public String getIpaddr() - { - return ipaddr; - } - - public void setIpaddr(String ipaddr) - { - this.ipaddr = ipaddr; - } - - public String getLoginLocation() - { - return loginLocation; - } - - public void setLoginLocation(String loginLocation) - { - this.loginLocation = loginLocation; - } - - public String getBrowser() - { - return browser; - } - - public void setBrowser(String browser) - { - this.browser = browser; - } - - public String getOs() - { - return os; - } - - public void setOs(String os) - { - this.os = os; - } - - public Date getStartTimestamp() - { - return startTimestamp; - } - - public void setStartTimestamp(Date startTimestamp) - { - this.startTimestamp = startTimestamp; - } - - public Date getLastAccessTime() - { - return lastAccessTime; - } - - public void setLastAccessTime(Date lastAccessTime) - { - this.lastAccessTime = lastAccessTime; - } - - public Long getExpireTime() - { - return expireTime; - } - - public void setExpireTime(Long expireTime) - { - this.expireTime = expireTime; - } - - public OnlineStatus getStatus() - { - return status; - } - - public void setStatus(OnlineStatus status) - { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("sessionId", getSessionId()) - .append("loginName", getLoginName()) - .append("deptName", getDeptName()) - .append("ipaddr", getIpaddr()) - .append("loginLocation", getLoginLocation()) - .append("browser", getBrowser()) - .append("os", getOs()) - .append("status", getStatus()) - .append("startTimestamp", getStartTimestamp()) - .append("lastAccessTime", getLastAccessTime()) - .append("expireTime", getExpireTime()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import java.util.Date; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.core.domain.BaseEntity; +import com.ruoyi.common.enums.OnlineStatus; + +/** + * 当前在线会话 sys_user_online + * + * @author ruoyi + */ +public class SysUserOnline extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 用户会话id + */ + private String sessionId; + + /** + * 部门名称 + */ + private String deptName; + + /** + * 登录名称 + */ + private String loginName; + + /** + * 登录IP地址 + */ + private String ipaddr; + + /** + * 登录地址 + */ + private String loginLocation; + + /** + * 浏览器类型 + */ + private String browser; + + /** + * 操作系统 + */ + private String os; + + /** + * session创建时间 + */ + private Date startTimestamp; + + /** + * session最后访问时间 + */ + private Date lastAccessTime; + + /** + * 超时时间,单位为分钟 + */ + private Long expireTime; + + /** + * 在线状态 + */ + private OnlineStatus status = OnlineStatus.on_line; + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getIpaddr() { + return ipaddr; + } + + public void setIpaddr(String ipaddr) { + this.ipaddr = ipaddr; + } + + public String getLoginLocation() { + return loginLocation; + } + + public void setLoginLocation(String loginLocation) { + this.loginLocation = loginLocation; + } + + public String getBrowser() { + return browser; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + public Date getStartTimestamp() { + return startTimestamp; + } + + public void setStartTimestamp(Date startTimestamp) { + this.startTimestamp = startTimestamp; + } + + public Date getLastAccessTime() { + return lastAccessTime; + } + + public void setLastAccessTime(Date lastAccessTime) { + this.lastAccessTime = lastAccessTime; + } + + public Long getExpireTime() { + return expireTime; + } + + public void setExpireTime(Long expireTime) { + this.expireTime = expireTime; + } + + public OnlineStatus getStatus() { + return status; + } + + public void setStatus(OnlineStatus status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("sessionId", getSessionId()) + .append("loginName", getLoginName()) + .append("deptName", getDeptName()) + .append("ipaddr", getIpaddr()) + .append("loginLocation", getLoginLocation()) + .append("browser", getBrowser()) + .append("os", getOs()) + .append("status", getStatus()) + .append("startTimestamp", getStartTimestamp()) + .append("lastAccessTime", getLastAccessTime()) + .append("expireTime", getExpireTime()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserPost.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserPost.java index 07ceb85cc..eb2ba7b1d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserPost.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserPost.java @@ -1,46 +1,45 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * 用户和岗位关联 sys_user_post - * - * @author ruoyi - */ -public class SysUserPost -{ - /** 用户ID */ - private Long userId; - - /** 岗位ID */ - private Long postId; - - public Long getUserId() - { - return userId; - } - - public void setUserId(Long userId) - { - this.userId = userId; - } - - public Long getPostId() - { - return postId; - } - - public void setPostId(Long postId) - { - this.postId = postId; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("userId", getUserId()) - .append("postId", getPostId()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 用户和岗位关联 sys_user_post + * + * @author ruoyi + */ +public class SysUserPost { + /** + * 用户ID + */ + private Long userId; + + /** + * 岗位ID + */ + private Long postId; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getPostId() { + return postId; + } + + public void setPostId(Long postId) { + this.postId = postId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("userId", getUserId()) + .append("postId", getPostId()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserRole.java index ce2af2bda..6e0073faa 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserRole.java @@ -1,46 +1,45 @@ -package com.ruoyi.system.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * 用户和角色关联 sys_user_role - * - * @author ruoyi - */ -public class SysUserRole -{ - /** 用户ID */ - private Long userId; - - /** 角色ID */ - private Long roleId; - - public Long getUserId() - { - return userId; - } - - public void setUserId(Long userId) - { - this.userId = userId; - } - - public Long getRoleId() - { - return roleId; - } - - public void setRoleId(Long roleId) - { - this.roleId = roleId; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("userId", getUserId()) - .append("roleId", getRoleId()) - .toString(); - } -} +package com.ruoyi.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 用户和角色关联 sys_user_role + * + * @author ruoyi + */ +public class SysUserRole { + /** + * 用户ID + */ + private Long userId; + + /** + * 角色ID + */ + private Long roleId; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("userId", getUserId()) + .append("roleId", getRoleId()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java index 9bc8482cc..db89e9a8b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java @@ -1,60 +1,60 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysConfig; - -/** - * 参数配置 数据层 - * - * @author ruoyi - */ -public interface SysConfigMapper -{ - /** - * 查询参数配置信息 - * - * @param config 参数配置信息 - * @return 参数配置信息 - */ - public SysConfig selectConfig(SysConfig config); - - /** - * 查询参数配置列表 - * - * @param config 参数配置信息 - * @return 参数配置集合 - */ - public List selectConfigList(SysConfig config); - - /** - * 根据键名查询参数配置信息 - * - * @param configKey 参数键名 - * @return 参数配置信息 - */ - public SysConfig checkConfigKeyUnique(String configKey); - - /** - * 新增参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int insertConfig(SysConfig config); - - /** - * 修改参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int updateConfig(SysConfig config); - - /** - * 批量删除参数配置 - * - * @param configIds 需要删除的数据ID - * @return 结果 - */ - public int deleteConfigByIds(String[] configIds); +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysConfig; + +/** + * 参数配置 数据层 + * + * @author ruoyi + */ +public interface SysConfigMapper { + /** + * 查询参数配置信息 + * + * @param config 参数配置信息 + * @return 参数配置信息 + */ + public SysConfig selectConfig(SysConfig config); + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + public List selectConfigList(SysConfig config); + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数键名 + * @return 参数配置信息 + */ + public SysConfig checkConfigKeyUnique(String configKey); + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int insertConfig(SysConfig config); + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int updateConfig(SysConfig config); + + /** + * 批量删除参数配置 + * + * @param configIds 需要删除的数据ID + * @return 结果 + */ + public int deleteConfigByIds(String[] configIds); } \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java index 3dcc9713d..ef2bf6ae4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java @@ -1,108 +1,109 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysDept; - -/** - * 部门管理 数据层 - * - * @author ruoyi - */ -public interface SysDeptMapper -{ - /** - * 查询部门人数 - * - * @param dept 部门信息 - * @return 结果 - */ - public int selectDeptCount(SysDept dept); - - /** - * 查询部门是否存在用户 - * - * @param deptId 部门ID - * @return 结果 - */ - public int checkDeptExistUser(Long deptId); - - /** - * 查询部门管理数据 - * - * @param dept 部门信息 - * @return 部门信息集合 - */ - public List selectDeptList(SysDept dept); - - /** - * 删除部门管理信息 - * - * @param deptId 部门ID - * @return 结果 - */ - public int deleteDeptById(Long deptId); - - /** - * 新增部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int insertDept(SysDept dept); - - /** - * 修改部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int updateDept(SysDept dept); - - /** - * 修改子元素关系 - * - * @param depts 子元素 - * @return 结果 - */ - public int updateDeptChildren(@Param("depts") List depts); - - /** - * 根据部门ID查询信息 - * - * @param deptId 部门ID - * @return 部门信息 - */ - public SysDept selectDeptById(Long deptId); - - /** - * 校验部门名称是否唯一 - * - * @param deptName 部门名称 - * @param parentId 父部门ID - * @return 结果 - */ - public SysDept checkDeptNameUnique(@Param("deptName") String deptName, @Param("parentId") Long parentId); - - /** - * 根据角色ID查询部门 - * - * @param roleId 角色ID - * @return 部门列表 - */ - public List selectRoleDeptTree(Long roleId); - - /** - * 修改所在部门的父级部门状态 - * - * @param dept 部门 - */ - public void updateDeptStatus(SysDept dept); - - /** - * 根据ID查询所有子部门 - * @param deptId 部门ID - * @return 部门列表 - */ - public List selectChildrenDeptById(Long deptId); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.SysDept; + +/** + * 部门管理 数据层 + * + * @author ruoyi + */ +public interface SysDeptMapper { + /** + * 查询部门人数 + * + * @param dept 部门信息 + * @return 结果 + */ + public int selectDeptCount(SysDept dept); + + /** + * 查询部门是否存在用户 + * + * @param deptId 部门ID + * @return 结果 + */ + public int checkDeptExistUser(Long deptId); + + /** + * 查询部门管理数据 + * + * @param dept 部门信息 + * @return 部门信息集合 + */ + public List selectDeptList(SysDept dept); + + /** + * 删除部门管理信息 + * + * @param deptId 部门ID + * @return 结果 + */ + public int deleteDeptById(Long deptId); + + /** + * 新增部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + public int insertDept(SysDept dept); + + /** + * 修改部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + public int updateDept(SysDept dept); + + /** + * 修改子元素关系 + * + * @param depts 子元素 + * @return 结果 + */ + public int updateDeptChildren(@Param("depts") List depts); + + /** + * 根据部门ID查询信息 + * + * @param deptId 部门ID + * @return 部门信息 + */ + public SysDept selectDeptById(Long deptId); + + /** + * 校验部门名称是否唯一 + * + * @param deptName 部门名称 + * @param parentId 父部门ID + * @return 结果 + */ + public SysDept checkDeptNameUnique(@Param("deptName") String deptName, @Param("parentId") Long parentId); + + /** + * 根据角色ID查询部门 + * + * @param roleId 角色ID + * @return 部门列表 + */ + public List selectRoleDeptTree(Long roleId); + + /** + * 修改所在部门的父级部门状态 + * + * @param dept 部门 + */ + public void updateDeptStatus(SysDept dept); + + /** + * 根据ID查询所有子部门 + * + * @param deptId 部门ID + * @return 部门列表 + */ + public List selectChildrenDeptById(Long deptId); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java index ad251fdea..4d327eff8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java @@ -1,95 +1,95 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysDictData; - -/** - * 字典表 数据层 - * - * @author ruoyi - */ -public interface SysDictDataMapper -{ - /** - * 根据条件分页查询字典数据 - * - * @param dictData 字典数据信息 - * @return 字典数据集合信息 - */ - public List selectDictDataList(SysDictData dictData); - - /** - * 根据字典类型查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据集合信息 - */ - public List selectDictDataByType(String dictType); - - /** - * 根据字典类型和字典键值查询字典数据信息 - * - * @param dictType 字典类型 - * @param dictValue 字典键值 - * @return 字典标签 - */ - public String selectDictLabel(@Param("dictType") String dictType, @Param("dictValue") String dictValue); - - /** - * 根据字典数据ID查询信息 - * - * @param dictCode 字典数据ID - * @return 字典数据 - */ - public SysDictData selectDictDataById(Long dictCode); - - /** - * 查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据 - */ - public int countDictDataByType(String dictType); - - /** - * 通过字典ID删除字典数据信息 - * - * @param dictCode 字典数据ID - * @return 结果 - */ - public int deleteDictDataById(Long dictCode); - - /** - * 批量删除字典数据 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteDictDataByIds(String[] ids); - - /** - * 新增字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int insertDictData(SysDictData dictData); - - /** - * 修改字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int updateDictData(SysDictData dictData); - - /** - * 同步修改字典类型 - * - * @param oldDictType 旧字典类型 - * @param newDictType 新旧字典类型 - * @return 结果 - */ - public int updateDictDataType(@Param("oldDictType") String oldDictType, @Param("newDictType") String newDictType); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.SysDictData; + +/** + * 字典表 数据层 + * + * @author ruoyi + */ +public interface SysDictDataMapper { + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + public List selectDictDataList(SysDictData dictData); + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + public List selectDictDataByType(String dictType); + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + public String selectDictLabel(@Param("dictType") String dictType, @Param("dictValue") String dictValue); + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + public SysDictData selectDictDataById(Long dictCode); + + /** + * 查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据 + */ + public int countDictDataByType(String dictType); + + /** + * 通过字典ID删除字典数据信息 + * + * @param dictCode 字典数据ID + * @return 结果 + */ + public int deleteDictDataById(Long dictCode); + + /** + * 批量删除字典数据 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteDictDataByIds(String[] ids); + + /** + * 新增字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int insertDictData(SysDictData dictData); + + /** + * 修改字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int updateDictData(SysDictData dictData); + + /** + * 同步修改字典类型 + * + * @param oldDictType 旧字典类型 + * @param newDictType 新旧字典类型 + * @return 结果 + */ + public int updateDictDataType(@Param("oldDictType") String oldDictType, @Param("newDictType") String newDictType); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java index a1aa3e3b4..b260072a1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java @@ -1,83 +1,83 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysDictType; - -/** - * 字典表 数据层 - * - * @author ruoyi - */ -public interface SysDictTypeMapper -{ - /** - * 根据条件分页查询字典类型 - * - * @param dictType 字典类型信息 - * @return 字典类型集合信息 - */ - public List selectDictTypeList(SysDictType dictType); - - /** - * 根据所有字典类型 - * - * @return 字典类型集合信息 - */ - public List selectDictTypeAll(); - - /** - * 根据字典类型ID查询信息 - * - * @param dictId 字典类型ID - * @return 字典类型 - */ - public SysDictType selectDictTypeById(Long dictId); - - /** - * 根据字典类型查询信息 - * - * @param dictType 字典类型 - * @return 字典类型 - */ - public SysDictType selectDictTypeByType(String dictType); - - /** - * 通过字典ID删除字典信息 - * - * @param dictId 字典ID - * @return 结果 - */ - public int deleteDictTypeById(Long dictId); - - /** - * 批量删除字典类型 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteDictTypeByIds(Long[] ids); - - /** - * 新增字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int insertDictType(SysDictType dictType); - - /** - * 修改字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int updateDictType(SysDictType dictType); - - /** - * 校验字典类型称是否唯一 - * - * @param dictType 字典类型 - * @return 结果 - */ - public SysDictType checkDictTypeUnique(String dictType); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysDictType; + +/** + * 字典表 数据层 + * + * @author ruoyi + */ +public interface SysDictTypeMapper { + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + public List selectDictTypeList(SysDictType dictType); + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + public List selectDictTypeAll(); + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + public SysDictType selectDictTypeById(Long dictId); + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + public SysDictType selectDictTypeByType(String dictType); + + /** + * 通过字典ID删除字典信息 + * + * @param dictId 字典ID + * @return 结果 + */ + public int deleteDictTypeById(Long dictId); + + /** + * 批量删除字典类型 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteDictTypeByIds(Long[] ids); + + /** + * 新增字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int insertDictType(SysDictType dictType); + + /** + * 修改字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int updateDictType(SysDictType dictType); + + /** + * 校验字典类型称是否唯一 + * + * @param dictType 字典类型 + * @return 结果 + */ + public SysDictType checkDictTypeUnique(String dictType); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java index 0efe3d7e8..f750701bd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java @@ -1,42 +1,42 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysLogininfor; - -/** - * 系统访问日志情况信息 数据层 - * - * @author ruoyi - */ -public interface SysLogininforMapper -{ - /** - * 新增系统登录日志 - * - * @param logininfor 访问日志对象 - */ - public void insertLogininfor(SysLogininfor logininfor); - - /** - * 查询系统登录日志集合 - * - * @param logininfor 访问日志对象 - * @return 登录记录集合 - */ - public List selectLogininforList(SysLogininfor logininfor); - - /** - * 批量删除系统登录日志 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteLogininforByIds(String[] ids); - - /** - * 清空系统登录日志 - * - * @return 结果 - */ - public int cleanLogininfor(); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysLogininfor; + +/** + * 系统访问日志情况信息 数据层 + * + * @author ruoyi + */ +public interface SysLogininforMapper { + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + public void insertLogininfor(SysLogininfor logininfor); + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + public List selectLogininforList(SysLogininfor logininfor); + + /** + * 批量删除系统登录日志 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteLogininforByIds(String[] ids); + + /** + * 清空系统登录日志 + * + * @return 结果 + */ + public int cleanLogininfor(); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java index 4b09dda5f..526059e83 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java @@ -1,124 +1,124 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysMenu; - -/** - * 菜单表 数据层 - * - * @author ruoyi - */ -public interface SysMenuMapper -{ - /** - * 查询系统所有菜单(含按钮) - * - * @return 菜单列表 - */ - public List selectMenuAll(); - - /** - * 根据用户ID查询菜单 - * - * @param userId 用户ID - * @return 菜单列表 - */ - public List selectMenuAllByUserId(Long userId); - - /** - * 查询系统正常显示菜单(不含按钮) - * - * @return 菜单列表 - */ - public List selectMenuNormalAll(); - - /** - * 根据用户ID查询菜单 - * - * @param userId 用户ID - * @return 菜单列表 - */ - public List selectMenusByUserId(Long userId); - - /** - * 根据用户ID查询权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - public List selectPermsByUserId(Long userId); - - /** - * 根据角色ID查询菜单 - * - * @param roleId 角色ID - * @return 菜单列表 - */ - public List selectMenuTree(Long roleId); - - /** - * 查询系统菜单列表 - * - * @param menu 菜单信息 - * @return 菜单列表 - */ - public List selectMenuList(SysMenu menu); - - /** - * 查询系统菜单列表 - * - * @param menu 菜单信息 - * @return 菜单列表 - */ - public List selectMenuListByUserId(SysMenu menu); - - /** - * 删除菜单管理信息 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int deleteMenuById(Long menuId); - - /** - * 根据菜单ID查询信息 - * - * @param menuId 菜单ID - * @return 菜单信息 - */ - public SysMenu selectMenuById(Long menuId); - - /** - * 查询菜单数量 - * - * @param parentId 菜单父ID - * @return 结果 - */ - public int selectCountMenuByParentId(Long parentId); - - /** - * 新增菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int insertMenu(SysMenu menu); - - /** - * 修改菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int updateMenu(SysMenu menu); - - /** - * 校验菜单名称是否唯一 - * - * @param menuName 菜单名称 - * @param parentId 父菜单ID - * @return 结果 - */ - public SysMenu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") Long parentId); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.SysMenu; + +/** + * 菜单表 数据层 + * + * @author ruoyi + */ +public interface SysMenuMapper { + /** + * 查询系统所有菜单(含按钮) + * + * @return 菜单列表 + */ + public List selectMenuAll(); + + /** + * 根据用户ID查询菜单 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuAllByUserId(Long userId); + + /** + * 查询系统正常显示菜单(不含按钮) + * + * @return 菜单列表 + */ + public List selectMenuNormalAll(); + + /** + * 根据用户ID查询菜单 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenusByUserId(Long userId); + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + public List selectPermsByUserId(Long userId); + + /** + * 根据角色ID查询菜单 + * + * @param roleId 角色ID + * @return 菜单列表 + */ + public List selectMenuTree(Long roleId); + + /** + * 查询系统菜单列表 + * + * @param menu 菜单信息 + * @return 菜单列表 + */ + public List selectMenuList(SysMenu menu); + + /** + * 查询系统菜单列表 + * + * @param menu 菜单信息 + * @return 菜单列表 + */ + public List selectMenuListByUserId(SysMenu menu); + + /** + * 删除菜单管理信息 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int deleteMenuById(Long menuId); + + /** + * 根据菜单ID查询信息 + * + * @param menuId 菜单ID + * @return 菜单信息 + */ + public SysMenu selectMenuById(Long menuId); + + /** + * 查询菜单数量 + * + * @param parentId 菜单父ID + * @return 结果 + */ + public int selectCountMenuByParentId(Long parentId); + + /** + * 新增菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int insertMenu(SysMenu menu); + + /** + * 修改菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int updateMenu(SysMenu menu); + + /** + * 校验菜单名称是否唯一 + * + * @param menuName 菜单名称 + * @param parentId 父菜单ID + * @return 结果 + */ + public SysMenu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") Long parentId); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java index 1ce1d8cde..dec9ba486 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java @@ -1,52 +1,52 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysNotice; - -/** - * 公告 数据层 - * - * @author ruoyi - */ -public interface SysNoticeMapper -{ - /** - * 查询公告信息 - * - * @param noticeId 公告ID - * @return 公告信息 - */ - public SysNotice selectNoticeById(Long noticeId); - - /** - * 查询公告列表 - * - * @param notice 公告信息 - * @return 公告集合 - */ - public List selectNoticeList(SysNotice notice); - - /** - * 新增公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int insertNotice(SysNotice notice); - - /** - * 修改公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int updateNotice(SysNotice notice); - - /** - * 批量删除公告 - * - * @param noticeIds 需要删除的数据ID - * @return 结果 - */ - public int deleteNoticeByIds(String[] noticeIds); +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysNotice; + +/** + * 公告 数据层 + * + * @author ruoyi + */ +public interface SysNoticeMapper { + /** + * 查询公告信息 + * + * @param noticeId 公告ID + * @return 公告信息 + */ + public SysNotice selectNoticeById(Long noticeId); + + /** + * 查询公告列表 + * + * @param notice 公告信息 + * @return 公告集合 + */ + public List selectNoticeList(SysNotice notice); + + /** + * 新增公告 + * + * @param notice 公告信息 + * @return 结果 + */ + public int insertNotice(SysNotice notice); + + /** + * 修改公告 + * + * @param notice 公告信息 + * @return 结果 + */ + public int updateNotice(SysNotice notice); + + /** + * 批量删除公告 + * + * @param noticeIds 需要删除的数据ID + * @return 结果 + */ + public int deleteNoticeByIds(String[] noticeIds); } \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java index 98ca5d130..3f92aebe5 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java @@ -1,48 +1,48 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysOperLog; - -/** - * 操作日志 数据层 - * - * @author ruoyi - */ -public interface SysOperLogMapper -{ - /** - * 新增操作日志 - * - * @param operLog 操作日志对象 - */ - public void insertOperlog(SysOperLog operLog); - - /** - * 查询系统操作日志集合 - * - * @param operLog 操作日志对象 - * @return 操作日志集合 - */ - public List selectOperLogList(SysOperLog operLog); - - /** - * 批量删除系统操作日志 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteOperLogByIds(String[] ids); - - /** - * 查询操作日志详细 - * - * @param operId 操作ID - * @return 操作日志对象 - */ - public SysOperLog selectOperLogById(Long operId); - - /** - * 清空操作日志 - */ - public void cleanOperLog(); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysOperLog; + +/** + * 操作日志 数据层 + * + * @author ruoyi + */ +public interface SysOperLogMapper { + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + public void insertOperlog(SysOperLog operLog); + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + public List selectOperLogList(SysOperLog operLog); + + /** + * 批量删除系统操作日志 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteOperLogByIds(String[] ids); + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + public SysOperLog selectOperLogById(Long operId); + + /** + * 清空操作日志 + */ + public void cleanOperLog(); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java index a4aab595b..1649802d7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java @@ -1,83 +1,83 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysPost; - -/** - * 岗位信息 数据层 - * - * @author ruoyi - */ -public interface SysPostMapper -{ - /** - * 查询岗位数据集合 - * - * @param post 岗位信息 - * @return 岗位数据集合 - */ - public List selectPostList(SysPost post); - - /** - * 查询所有岗位 - * - * @return 岗位列表 - */ - public List selectPostAll(); - - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - public List selectPostsByUserId(Long userId); - - /** - * 通过岗位ID查询岗位信息 - * - * @param postId 岗位ID - * @return 角色对象信息 - */ - public SysPost selectPostById(Long postId); - - /** - * 批量删除岗位信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deletePostByIds(Long[] ids); - - /** - * 修改岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int updatePost(SysPost post); - - /** - * 新增岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int insertPost(SysPost post); - - /** - * 校验岗位名称 - * - * @param postName 岗位名称 - * @return 结果 - */ - public SysPost checkPostNameUnique(String postName); - - /** - * 校验岗位编码 - * - * @param postCode 岗位编码 - * @return 结果 - */ - public SysPost checkPostCodeUnique(String postCode); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysPost; + +/** + * 岗位信息 数据层 + * + * @author ruoyi + */ +public interface SysPostMapper { + /** + * 查询岗位数据集合 + * + * @param post 岗位信息 + * @return 岗位数据集合 + */ + public List selectPostList(SysPost post); + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + public List selectPostAll(); + + /** + * 根据用户ID查询岗位 + * + * @param userId 用户ID + * @return 岗位列表 + */ + public List selectPostsByUserId(Long userId); + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + public SysPost selectPostById(Long postId); + + /** + * 批量删除岗位信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deletePostByIds(Long[] ids); + + /** + * 修改岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int updatePost(SysPost post); + + /** + * 新增岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int insertPost(SysPost post); + + /** + * 校验岗位名称 + * + * @param postName 岗位名称 + * @return 结果 + */ + public SysPost checkPostNameUnique(String postName); + + /** + * 校验岗位编码 + * + * @param postCode 岗位编码 + * @return 结果 + */ + public SysPost checkPostCodeUnique(String postCode); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java index a4ad4de24..e2615c035 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java @@ -1,44 +1,44 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysRoleDept; - -/** - * 角色与部门关联表 数据层 - * - * @author ruoyi - */ -public interface SysRoleDeptMapper -{ - /** - * 通过角色ID删除角色和部门关联 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleDeptByRoleId(Long roleId); - - /** - * 批量删除角色部门关联信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleDept(Long[] ids); - - /** - * 查询部门使用数量 - * - * @param deptId 部门ID - * @return 结果 - */ - public int selectCountRoleDeptByDeptId(Long deptId); - - /** - * 批量新增角色部门信息 - * - * @param roleDeptList 角色部门列表 - * @return 结果 - */ - public int batchRoleDept(List roleDeptList); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysRoleDept; + +/** + * 角色与部门关联表 数据层 + * + * @author ruoyi + */ +public interface SysRoleDeptMapper { + /** + * 通过角色ID删除角色和部门关联 + * + * @param roleId 角色ID + * @return 结果 + */ + public int deleteRoleDeptByRoleId(Long roleId); + + /** + * 批量删除角色部门关联信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteRoleDept(Long[] ids); + + /** + * 查询部门使用数量 + * + * @param deptId 部门ID + * @return 结果 + */ + public int selectCountRoleDeptByDeptId(Long deptId); + + /** + * 批量新增角色部门信息 + * + * @param roleDeptList 角色部门列表 + * @return 结果 + */ + public int batchRoleDept(List roleDeptList); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java index 8c2ea6501..9a2b1dff3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java @@ -1,84 +1,84 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysRole; - -/** - * 角色表 数据层 - * - * @author ruoyi - */ -public interface SysRoleMapper -{ - /** - * 根据条件分页查询角色数据 - * - * @param role 角色信息 - * @return 角色数据集合信息 - */ - public List selectRoleList(SysRole role); - - /** - * 根据用户ID查询角色 - * - * @param userId 用户ID - * @return 角色列表 - */ - public List selectRolesByUserId(Long userId); - - /** - * 通过角色ID查询角色 - * - * @param roleId 角色ID - * @return 角色对象信息 - */ - public SysRole selectRoleById(Long roleId); - - /** - * 通过角色ID删除角色 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleById(Long roleId); - - /** - * 批量角色用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleByIds(Long[] ids); - - /** - * 修改角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int updateRole(SysRole role); - - /** - * 新增角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int insertRole(SysRole role); - - /** - * 校验角色名称是否唯一 - * - * @param roleName 角色名称 - * @return 角色信息 - */ - public SysRole checkRoleNameUnique(String roleName); - - /** - * 校验角色权限是否唯一 - * - * @param roleKey 角色权限 - * @return 角色信息 - */ - public SysRole checkRoleKeyUnique(String roleKey); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysRole; + +/** + * 角色表 数据层 + * + * @author ruoyi + */ +public interface SysRoleMapper { + /** + * 根据条件分页查询角色数据 + * + * @param role 角色信息 + * @return 角色数据集合信息 + */ + public List selectRoleList(SysRole role); + + /** + * 根据用户ID查询角色 + * + * @param userId 用户ID + * @return 角色列表 + */ + public List selectRolesByUserId(Long userId); + + /** + * 通过角色ID查询角色 + * + * @param roleId 角色ID + * @return 角色对象信息 + */ + public SysRole selectRoleById(Long roleId); + + /** + * 通过角色ID删除角色 + * + * @param roleId 角色ID + * @return 结果 + */ + public int deleteRoleById(Long roleId); + + /** + * 批量角色用户信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteRoleByIds(Long[] ids); + + /** + * 修改角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int updateRole(SysRole role); + + /** + * 新增角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int insertRole(SysRole role); + + /** + * 校验角色名称是否唯一 + * + * @param roleName 角色名称 + * @return 角色信息 + */ + public SysRole checkRoleNameUnique(String roleName); + + /** + * 校验角色权限是否唯一 + * + * @param roleKey 角色权限 + * @return 角色信息 + */ + public SysRole checkRoleKeyUnique(String roleKey); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java index 5ed98f294..c69f9fbf9 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java @@ -1,44 +1,44 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysRoleMenu; - -/** - * 角色与菜单关联表 数据层 - * - * @author ruoyi - */ -public interface SysRoleMenuMapper -{ - /** - * 通过角色ID删除角色和菜单关联 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleMenuByRoleId(Long roleId); - - /** - * 批量删除角色菜单关联信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleMenu(Long[] ids); - - /** - * 查询菜单使用数量 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int selectCountRoleMenuByMenuId(Long menuId); - - /** - * 批量新增角色菜单信息 - * - * @param roleMenuList 角色菜单列表 - * @return 结果 - */ - public int batchRoleMenu(List roleMenuList); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysRoleMenu; + +/** + * 角色与菜单关联表 数据层 + * + * @author ruoyi + */ +public interface SysRoleMenuMapper { + /** + * 通过角色ID删除角色和菜单关联 + * + * @param roleId 角色ID + * @return 结果 + */ + public int deleteRoleMenuByRoleId(Long roleId); + + /** + * 批量删除角色菜单关联信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteRoleMenu(Long[] ids); + + /** + * 查询菜单使用数量 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int selectCountRoleMenuByMenuId(Long menuId); + + /** + * 批量新增角色菜单信息 + * + * @param roleMenuList 角色菜单列表 + * @return 结果 + */ + public int batchRoleMenu(List roleMenuList); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java index ab4a15fe6..51dbdb7bc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java @@ -1,124 +1,124 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysUser; - -/** - * 用户表 数据层 - * - * @author ruoyi - */ -public interface SysUserMapper -{ - /** - * 根据条件分页查询用户列表 - * - * @param sysUser 用户信息 - * @return 用户信息集合信息 - */ - public List selectUserList(SysUser sysUser); - - /** - * 根据条件分页查询未已配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectAllocatedList(SysUser user); - - /** - * 根据条件分页查询未分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectUnallocatedList(SysUser user); - - /** - * 通过用户名查询用户 - * - * @param userName 用户名 - * @return 用户对象信息 - */ - public SysUser selectUserByLoginName(String userName); - - /** - * 通过手机号码查询用户 - * - * @param phoneNumber 手机号码 - * @return 用户对象信息 - */ - public SysUser selectUserByPhoneNumber(String phoneNumber); - - /** - * 通过邮箱查询用户 - * - * @param email 邮箱 - * @return 用户对象信息 - */ - public SysUser selectUserByEmail(String email); - - /** - * 通过用户ID查询用户 - * - * @param userId 用户ID - * @return 用户对象信息 - */ - public SysUser selectUserById(Long userId); - - /** - * 通过用户ID删除用户 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserById(Long userId); - - /** - * 批量删除用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserByIds(Long[] ids); - - /** - * 修改用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int updateUser(SysUser user); - - /** - * 新增用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int insertUser(SysUser user); - - /** - * 校验用户名称是否唯一 - * - * @param loginName 登录名称 - * @return 结果 - */ - public int checkLoginNameUnique(String loginName); - - /** - * 校验手机号码是否唯一 - * - * @param phonenumber 手机号码 - * @return 结果 - */ - public SysUser checkPhoneUnique(String phonenumber); - - /** - * 校验email是否唯一 - * - * @param email 用户邮箱 - * @return 结果 - */ - public SysUser checkEmailUnique(String email); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysUser; + +/** + * 用户表 数据层 + * + * @author ruoyi + */ +public interface SysUserMapper { + /** + * 根据条件分页查询用户列表 + * + * @param sysUser 用户信息 + * @return 用户信息集合信息 + */ + public List selectUserList(SysUser sysUser); + + /** + * 根据条件分页查询未已配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + public List selectAllocatedList(SysUser user); + + /** + * 根据条件分页查询未分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + public List selectUnallocatedList(SysUser user); + + /** + * 通过用户名查询用户 + * + * @param userName 用户名 + * @return 用户对象信息 + */ + public SysUser selectUserByLoginName(String userName); + + /** + * 通过手机号码查询用户 + * + * @param phoneNumber 手机号码 + * @return 用户对象信息 + */ + public SysUser selectUserByPhoneNumber(String phoneNumber); + + /** + * 通过邮箱查询用户 + * + * @param email 邮箱 + * @return 用户对象信息 + */ + public SysUser selectUserByEmail(String email); + + /** + * 通过用户ID查询用户 + * + * @param userId 用户ID + * @return 用户对象信息 + */ + public SysUser selectUserById(Long userId); + + /** + * 通过用户ID删除用户 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserById(Long userId); + + /** + * 批量删除用户信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUserByIds(Long[] ids); + + /** + * 修改用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int updateUser(SysUser user); + + /** + * 新增用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int insertUser(SysUser user); + + /** + * 校验用户名称是否唯一 + * + * @param loginName 登录名称 + * @return 结果 + */ + public int checkLoginNameUnique(String loginName); + + /** + * 校验手机号码是否唯一 + * + * @param phonenumber 手机号码 + * @return 结果 + */ + public SysUser checkPhoneUnique(String phonenumber); + + /** + * 校验email是否唯一 + * + * @param email 用户邮箱 + * @return 结果 + */ + public SysUser checkEmailUnique(String email); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java index c6bf94cd2..807f9b838 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java @@ -1,52 +1,52 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysUserOnline; - -/** - * 在线用户 数据层 - * - * @author ruoyi - */ -public interface SysUserOnlineMapper -{ - /** - * 通过会话序号查询信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public SysUserOnline selectOnlineById(String sessionId); - - /** - * 通过会话序号删除信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public int deleteOnlineById(String sessionId); - - /** - * 保存会话信息 - * - * @param online 会话信息 - * @return 结果 - */ - public int saveOnline(SysUserOnline online); - - /** - * 查询会话集合 - * - * @param userOnline 会话参数 - * @return 会话集合 - */ - public List selectUserOnlineList(SysUserOnline userOnline); - - /** - * 查询过期会话集合 - * - * @param lastAccessTime 过期时间 - * @return 会话集合 - */ - public List selectOnlineByExpired(String lastAccessTime); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysUserOnline; + +/** + * 在线用户 数据层 + * + * @author ruoyi + */ +public interface SysUserOnlineMapper { + /** + * 通过会话序号查询信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + public SysUserOnline selectOnlineById(String sessionId); + + /** + * 通过会话序号删除信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + public int deleteOnlineById(String sessionId); + + /** + * 保存会话信息 + * + * @param online 会话信息 + * @return 结果 + */ + public int saveOnline(SysUserOnline online); + + /** + * 查询会话集合 + * + * @param userOnline 会话参数 + * @return 会话集合 + */ + public List selectUserOnlineList(SysUserOnline userOnline); + + /** + * 查询过期会话集合 + * + * @param lastAccessTime 过期时间 + * @return 会话集合 + */ + public List selectOnlineByExpired(String lastAccessTime); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java index 1f7a1fcbd..468efb990 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java @@ -1,44 +1,44 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import com.ruoyi.system.domain.SysUserPost; - -/** - * 用户与岗位关联表 数据层 - * - * @author ruoyi - */ -public interface SysUserPostMapper -{ - /** - * 通过用户ID删除用户和岗位关联 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserPostByUserId(Long userId); - - /** - * 通过岗位ID查询岗位使用数量 - * - * @param postId 岗位ID - * @return 结果 - */ - public int countUserPostById(Long postId); - - /** - * 批量删除用户和岗位关联 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserPost(Long[] ids); - - /** - * 批量新增用户岗位信息 - * - * @param userPostList 用户角色列表 - * @return 结果 - */ - public int batchUserPost(List userPostList); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.ruoyi.system.domain.SysUserPost; + +/** + * 用户与岗位关联表 数据层 + * + * @author ruoyi + */ +public interface SysUserPostMapper { + /** + * 通过用户ID删除用户和岗位关联 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserPostByUserId(Long userId); + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + public int countUserPostById(Long postId); + + /** + * 批量删除用户和岗位关联 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUserPost(Long[] ids); + + /** + * 批量新增用户岗位信息 + * + * @param userPostList 用户角色列表 + * @return 结果 + */ + public int batchUserPost(List userPostList); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java index 0e2dd8263..020be070f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java @@ -1,62 +1,62 @@ -package com.ruoyi.system.mapper; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysUserRole; - -/** - * 用户与角色关联表 数据层 - * - * @author ruoyi - */ -public interface SysUserRoleMapper -{ - /** - * 通过用户ID删除用户和角色关联 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserRoleByUserId(Long userId); - - /** - * 批量删除用户和角色关联 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserRole(Long[] ids); - - /** - * 通过角色ID查询角色使用数量 - * - * @param roleId 角色ID - * @return 结果 - */ - public int countUserRoleByRoleId(Long roleId); - - /** - * 批量新增用户角色信息 - * - * @param userRoleList 用户角色列表 - * @return 结果 - */ - public int batchUserRole(List userRoleList); - - /** - * 删除用户和角色关联信息 - * - * @param userRole 用户和角色关联信息 - * @return 结果 - */ - public int deleteUserRoleInfo(SysUserRole userRole); - - /** - * 批量取消授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds); -} +package com.ruoyi.system.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.SysUserRole; + +/** + * 用户与角色关联表 数据层 + * + * @author ruoyi + */ +public interface SysUserRoleMapper { + /** + * 通过用户ID删除用户和角色关联 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserRoleByUserId(Long userId); + + /** + * 批量删除用户和角色关联 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUserRole(Long[] ids); + + /** + * 通过角色ID查询角色使用数量 + * + * @param roleId 角色ID + * @return 结果 + */ + public int countUserRoleByRoleId(Long roleId); + + /** + * 批量新增用户角色信息 + * + * @param userRoleList 用户角色列表 + * @return 结果 + */ + public int batchUserRole(List userRoleList); + + /** + * 删除用户和角色关联信息 + * + * @param userRole 用户和角色关联信息 + * @return 结果 + */ + public int deleteUserRoleInfo(SysUserRole userRole); + + /** + * 批量取消授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java index 949bf44c9..54ee4d20e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java @@ -1,68 +1,68 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysConfig; - -/** - * 参数配置 服务层 - * - * @author ruoyi - */ -public interface ISysConfigService -{ - /** - * 查询参数配置信息 - * - * @param configId 参数配置ID - * @return 参数配置信息 - */ - public SysConfig selectConfigById(Long configId); - - /** - * 根据键名查询参数配置信息 - * - * @param configKey 参数键名 - * @return 参数键值 - */ - public String selectConfigByKey(String configKey); - - /** - * 查询参数配置列表 - * - * @param config 参数配置信息 - * @return 参数配置集合 - */ - public List selectConfigList(SysConfig config); - - /** - * 新增参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int insertConfig(SysConfig config); - - /** - * 修改参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int updateConfig(SysConfig config); - - /** - * 批量删除参数配置信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteConfigByIds(String ids); - - /** - * 校验参数键名是否唯一 - * - * @param config 参数信息 - * @return 结果 - */ - public String checkConfigKeyUnique(SysConfig config); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysConfig; + +/** + * 参数配置 服务层 + * + * @author ruoyi + */ +public interface ISysConfigService { + /** + * 查询参数配置信息 + * + * @param configId 参数配置ID + * @return 参数配置信息 + */ + public SysConfig selectConfigById(Long configId); + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数键名 + * @return 参数键值 + */ + public String selectConfigByKey(String configKey); + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + public List selectConfigList(SysConfig config); + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int insertConfig(SysConfig config); + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int updateConfig(SysConfig config); + + /** + * 批量删除参数配置信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteConfigByIds(String ids); + + /** + * 校验参数键名是否唯一 + * + * @param config 参数信息 + * @return 结果 + */ + public String checkConfigKeyUnique(SysConfig config); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java index 6e75df247..1946ece24 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java @@ -1,94 +1,94 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.system.domain.SysDept; -import com.ruoyi.system.domain.SysRole; - -/** - * 部门管理 服务层 - * - * @author ruoyi - */ -public interface ISysDeptService -{ - /** - * 查询部门管理数据 - * - * @param dept 部门信息 - * @return 部门信息集合 - */ - public List selectDeptList(SysDept dept); - - /** - * 查询部门管理树 - * - * @param dept 部门信息 - * @return 所有部门信息 - */ - public List selectDeptTree(SysDept dept); - - /** - * 根据角色ID查询菜单 - * - * @param role 角色对象 - * @return 菜单列表 - */ - public List roleDeptTreeData(SysRole role); - - /** - * 查询部门人数 - * - * @param parentId 父部门ID - * @return 结果 - */ - public int selectDeptCount(Long parentId); - - /** - * 查询部门是否存在用户 - * - * @param deptId 部门ID - * @return 结果 true 存在 false 不存在 - */ - public boolean checkDeptExistUser(Long deptId); - - /** - * 删除部门管理信息 - * - * @param deptId 部门ID - * @return 结果 - */ - public int deleteDeptById(Long deptId); - - /** - * 新增保存部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int insertDept(SysDept dept); - - /** - * 修改保存部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int updateDept(SysDept dept); - - /** - * 根据部门ID查询信息 - * - * @param deptId 部门ID - * @return 部门信息 - */ - public SysDept selectDeptById(Long deptId); - - /** - * 校验部门名称是否唯一 - * - * @param dept 部门信息 - * @return 结果 - */ - public String checkDeptNameUnique(SysDept dept); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.domain.SysRole; + +/** + * 部门管理 服务层 + * + * @author ruoyi + */ +public interface ISysDeptService { + /** + * 查询部门管理数据 + * + * @param dept 部门信息 + * @return 部门信息集合 + */ + public List selectDeptList(SysDept dept); + + /** + * 查询部门管理树 + * + * @param dept 部门信息 + * @return 所有部门信息 + */ + public List selectDeptTree(SysDept dept); + + /** + * 根据角色ID查询菜单 + * + * @param role 角色对象 + * @return 菜单列表 + */ + public List roleDeptTreeData(SysRole role); + + /** + * 查询部门人数 + * + * @param parentId 父部门ID + * @return 结果 + */ + public int selectDeptCount(Long parentId); + + /** + * 查询部门是否存在用户 + * + * @param deptId 部门ID + * @return 结果 true 存在 false 不存在 + */ + public boolean checkDeptExistUser(Long deptId); + + /** + * 删除部门管理信息 + * + * @param deptId 部门ID + * @return 结果 + */ + public int deleteDeptById(Long deptId); + + /** + * 新增保存部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + public int insertDept(SysDept dept); + + /** + * 修改保存部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + public int updateDept(SysDept dept); + + /** + * 根据部门ID查询信息 + * + * @param deptId 部门ID + * @return 部门信息 + */ + public SysDept selectDeptById(Long deptId); + + /** + * 校验部门名称是否唯一 + * + * @param dept 部门信息 + * @return 结果 + */ + public String checkDeptNameUnique(SysDept dept); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java index 68d68d812..7cb1567c8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java @@ -1,77 +1,77 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysDictData; - -/** - * 字典 业务层 - * - * @author ruoyi - */ -public interface ISysDictDataService -{ - /** - * 根据条件分页查询字典数据 - * - * @param dictData 字典数据信息 - * @return 字典数据集合信息 - */ - public List selectDictDataList(SysDictData dictData); - - /** - * 根据字典类型查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据集合信息 - */ - public List selectDictDataByType(String dictType); - - /** - * 根据字典类型和字典键值查询字典数据信息 - * - * @param dictType 字典类型 - * @param dictValue 字典键值 - * @return 字典标签 - */ - public String selectDictLabel(String dictType, String dictValue); - - /** - * 根据字典数据ID查询信息 - * - * @param dictCode 字典数据ID - * @return 字典数据 - */ - public SysDictData selectDictDataById(Long dictCode); - - /** - * 通过字典ID删除字典数据信息 - * - * @param dictCode 字典数据ID - * @return 结果 - */ - public int deleteDictDataById(Long dictCode); - - /** - * 批量删除字典数据 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteDictDataByIds(String ids); - - /** - * 新增保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int insertDictData(SysDictData dictData); - - /** - * 修改保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int updateDictData(SysDictData dictData); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysDictData; + +/** + * 字典 业务层 + * + * @author ruoyi + */ +public interface ISysDictDataService { + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + public List selectDictDataList(SysDictData dictData); + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + public List selectDictDataByType(String dictType); + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + public String selectDictLabel(String dictType, String dictValue); + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + public SysDictData selectDictDataById(Long dictCode); + + /** + * 通过字典ID删除字典数据信息 + * + * @param dictCode 字典数据ID + * @return 结果 + */ + public int deleteDictDataById(Long dictCode); + + /** + * 批量删除字典数据 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteDictDataByIds(String ids); + + /** + * 新增保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int insertDictData(SysDictData dictData); + + /** + * 修改保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int updateDictData(SysDictData dictData); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java index dc22381d0..f8d3e3322 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java @@ -1,93 +1,93 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.system.domain.SysDictType; - -/** - * 字典 业务层 - * - * @author ruoyi - */ -public interface ISysDictTypeService -{ - /** - * 根据条件分页查询字典类型 - * - * @param dictType 字典类型信息 - * @return 字典类型集合信息 - */ - public List selectDictTypeList(SysDictType dictType); - - /** - * 根据所有字典类型 - * - * @return 字典类型集合信息 - */ - public List selectDictTypeAll(); - - /** - * 根据字典类型ID查询信息 - * - * @param dictId 字典类型ID - * @return 字典类型 - */ - public SysDictType selectDictTypeById(Long dictId); - - /** - * 根据字典类型查询信息 - * - * @param dictType 字典类型 - * @return 字典类型 - */ - public SysDictType selectDictTypeByType(String dictType); - - /** - * 通过字典ID删除字典信息 - * - * @param dictId 字典ID - * @return 结果 - */ - public int deleteDictTypeById(Long dictId); - - /** - * 批量删除字典类型 - * - * @param ids 需要删除的数据 - * @return 结果 - * @throws Exception 异常 - */ - public int deleteDictTypeByIds(String ids) throws Exception; - - /** - * 新增保存字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int insertDictType(SysDictType dictType); - - /** - * 修改保存字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int updateDictType(SysDictType dictType); - - /** - * 校验字典类型称是否唯一 - * - * @param dictType 字典类型 - * @return 结果 - */ - public String checkDictTypeUnique(SysDictType dictType); - - /** - * 查询字典类型树 - * - * @param dictType 字典类型 - * @return 所有字典类型 - */ - public List selectDictTree(SysDictType dictType); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.system.domain.SysDictType; + +/** + * 字典 业务层 + * + * @author ruoyi + */ +public interface ISysDictTypeService { + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + public List selectDictTypeList(SysDictType dictType); + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + public List selectDictTypeAll(); + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + public SysDictType selectDictTypeById(Long dictId); + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + public SysDictType selectDictTypeByType(String dictType); + + /** + * 通过字典ID删除字典信息 + * + * @param dictId 字典ID + * @return 结果 + */ + public int deleteDictTypeById(Long dictId); + + /** + * 批量删除字典类型 + * + * @param ids 需要删除的数据 + * @return 结果 + * @throws Exception 异常 + */ + public int deleteDictTypeByIds(String ids) throws Exception; + + /** + * 新增保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int insertDictType(SysDictType dictType); + + /** + * 修改保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int updateDictType(SysDictType dictType); + + /** + * 校验字典类型称是否唯一 + * + * @param dictType 字典类型 + * @return 结果 + */ + public String checkDictTypeUnique(SysDictType dictType); + + /** + * 查询字典类型树 + * + * @param dictType 字典类型 + * @return 所有字典类型 + */ + public List selectDictTree(SysDictType dictType); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java index 8e292c25b..ed013e4f6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java @@ -1,40 +1,40 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysLogininfor; - -/** - * 系统访问日志情况信息 服务层 - * - * @author ruoyi - */ -public interface ISysLogininforService -{ - /** - * 新增系统登录日志 - * - * @param logininfor 访问日志对象 - */ - public void insertLogininfor(SysLogininfor logininfor); - - /** - * 查询系统登录日志集合 - * - * @param logininfor 访问日志对象 - * @return 登录记录集合 - */ - public List selectLogininforList(SysLogininfor logininfor); - - /** - * 批量删除系统登录日志 - * - * @param ids 需要删除的数据 - * @return - */ - public int deleteLogininforByIds(String ids); - - /** - * 清空系统登录日志 - */ - public void cleanLogininfor(); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysLogininfor; + +/** + * 系统访问日志情况信息 服务层 + * + * @author ruoyi + */ +public interface ISysLogininforService { + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + public void insertLogininfor(SysLogininfor logininfor); + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + public List selectLogininforList(SysLogininfor logininfor); + + /** + * 批量删除系统登录日志 + * + * @param ids 需要删除的数据 + * @return + */ + public int deleteLogininforByIds(String ids); + + /** + * 清空系统登录日志 + */ + public void cleanLogininfor(); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java index 04cb8e091..45dbdd9cd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java @@ -1,131 +1,131 @@ -package com.ruoyi.system.service; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.system.domain.SysMenu; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; - -/** - * 菜单 业务层 - * - * @author ruoyi - */ -public interface ISysMenuService -{ - /** - * 根据用户ID查询菜单 - * - * @param user 用户信息 - * @return 菜单列表 - */ - public List selectMenusByUser(SysUser user); - - /** - * 查询系统菜单列表 - * - * @param menu 菜单信息 - * @param userId 用户ID - * @return 菜单列表 - */ - public List selectMenuList(SysMenu menu, Long userId); - - /** - * 查询菜单集合 - * - * @param userId 用户ID - * @return 所有菜单信息 - */ - public List selectMenuAll(Long userId); - - /** - * 根据用户ID查询权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - public Set selectPermsByUserId(Long userId); - - /** - * 根据角色ID查询菜单 - * - * @param role 角色对象 - * @param userId 用户ID - * @return 菜单列表 - */ - public List roleMenuTreeData(SysRole role, Long userId); - - /** - * 查询所有菜单信息 - * - * @param userId 用户ID - * @return 菜单列表 - */ - public List menuTreeData(Long userId); - - /** - * 查询系统所有权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - public Map selectPermsAll(Long userId); - - /** - * 删除菜单管理信息 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int deleteMenuById(Long menuId); - - /** - * 根据菜单ID查询信息 - * - * @param menuId 菜单ID - * @return 菜单信息 - */ - public SysMenu selectMenuById(Long menuId); - - /** - * 查询菜单数量 - * - * @param parentId 菜单父ID - * @return 结果 - */ - public int selectCountMenuByParentId(Long parentId); - - /** - * 查询菜单使用数量 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int selectCountRoleMenuByMenuId(Long menuId); - - /** - * 新增保存菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int insertMenu(SysMenu menu); - - /** - * 修改保存菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int updateMenu(SysMenu menu); - - /** - * 校验菜单名称是否唯一 - * - * @param menu 菜单信息 - * @return 结果 - */ - public String checkMenuNameUnique(SysMenu menu); -} +package com.ruoyi.system.service; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; + +/** + * 菜单 业务层 + * + * @author ruoyi + */ +public interface ISysMenuService { + /** + * 根据用户ID查询菜单 + * + * @param user 用户信息 + * @return 菜单列表 + */ + public List selectMenusByUser(SysUser user); + + /** + * 查询系统菜单列表 + * + * @param menu 菜单信息 + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuList(SysMenu menu, Long userId); + + /** + * 查询菜单集合 + * + * @param userId 用户ID + * @return 所有菜单信息 + */ + public List selectMenuAll(Long userId); + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + public Set selectPermsByUserId(Long userId); + + /** + * 根据角色ID查询菜单 + * + * @param role 角色对象 + * @param userId 用户ID + * @return 菜单列表 + */ + public List roleMenuTreeData(SysRole role, Long userId); + + /** + * 查询所有菜单信息 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List menuTreeData(Long userId); + + /** + * 查询系统所有权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + public Map selectPermsAll(Long userId); + + /** + * 删除菜单管理信息 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int deleteMenuById(Long menuId); + + /** + * 根据菜单ID查询信息 + * + * @param menuId 菜单ID + * @return 菜单信息 + */ + public SysMenu selectMenuById(Long menuId); + + /** + * 查询菜单数量 + * + * @param parentId 菜单父ID + * @return 结果 + */ + public int selectCountMenuByParentId(Long parentId); + + /** + * 查询菜单使用数量 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int selectCountRoleMenuByMenuId(Long menuId); + + /** + * 新增保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int insertMenu(SysMenu menu); + + /** + * 修改保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int updateMenu(SysMenu menu); + + /** + * 校验菜单名称是否唯一 + * + * @param menu 菜单信息 + * @return 结果 + */ + public String checkMenuNameUnique(SysMenu menu); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java index abd6d7afc..7dc902da6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java @@ -1,52 +1,52 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysNotice; - -/** - * 公告 服务层 - * - * @author ruoyi - */ -public interface ISysNoticeService -{ - /** - * 查询公告信息 - * - * @param noticeId 公告ID - * @return 公告信息 - */ - public SysNotice selectNoticeById(Long noticeId); - - /** - * 查询公告列表 - * - * @param notice 公告信息 - * @return 公告集合 - */ - public List selectNoticeList(SysNotice notice); - - /** - * 新增公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int insertNotice(SysNotice notice); - - /** - * 修改公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int updateNotice(SysNotice notice); - - /** - * 删除公告信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteNoticeByIds(String ids); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysNotice; + +/** + * 公告 服务层 + * + * @author ruoyi + */ +public interface ISysNoticeService { + /** + * 查询公告信息 + * + * @param noticeId 公告ID + * @return 公告信息 + */ + public SysNotice selectNoticeById(Long noticeId); + + /** + * 查询公告列表 + * + * @param notice 公告信息 + * @return 公告集合 + */ + public List selectNoticeList(SysNotice notice); + + /** + * 新增公告 + * + * @param notice 公告信息 + * @return 结果 + */ + public int insertNotice(SysNotice notice); + + /** + * 修改公告 + * + * @param notice 公告信息 + * @return 结果 + */ + public int updateNotice(SysNotice notice); + + /** + * 删除公告信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteNoticeByIds(String ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java index 61efe6020..66b45382f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java @@ -1,48 +1,48 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysOperLog; - -/** - * 操作日志 服务层 - * - * @author ruoyi - */ -public interface ISysOperLogService -{ - /** - * 新增操作日志 - * - * @param operLog 操作日志对象 - */ - public void insertOperlog(SysOperLog operLog); - - /** - * 查询系统操作日志集合 - * - * @param operLog 操作日志对象 - * @return 操作日志集合 - */ - public List selectOperLogList(SysOperLog operLog); - - /** - * 批量删除系统操作日志 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteOperLogByIds(String ids); - - /** - * 查询操作日志详细 - * - * @param operId 操作ID - * @return 操作日志对象 - */ - public SysOperLog selectOperLogById(Long operId); - - /** - * 清空操作日志 - */ - public void cleanOperLog(); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysOperLog; + +/** + * 操作日志 服务层 + * + * @author ruoyi + */ +public interface ISysOperLogService { + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + public void insertOperlog(SysOperLog operLog); + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + public List selectOperLogList(SysOperLog operLog); + + /** + * 批量删除系统操作日志 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + public int deleteOperLogByIds(String ids); + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + public SysOperLog selectOperLogById(Long operId); + + /** + * 清空操作日志 + */ + public void cleanOperLog(); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java index bbf7b784f..52f03ef29 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java @@ -1,92 +1,92 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysPost; - -/** - * 岗位信息 服务层 - * - * @author ruoyi - */ -public interface ISysPostService -{ - /** - * 查询岗位信息集合 - * - * @param post 岗位信息 - * @return 岗位信息集合 - */ - public List selectPostList(SysPost post); - - /** - * 查询所有岗位 - * - * @return 岗位列表 - */ - public List selectPostAll(); - - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - public List selectPostsByUserId(Long userId); - - /** - * 通过岗位ID查询岗位信息 - * - * @param postId 岗位ID - * @return 角色对象信息 - */ - public SysPost selectPostById(Long postId); - - /** - * 批量删除岗位信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - * @throws Exception 异常 - */ - public int deletePostByIds(String ids) throws Exception; - - /** - * 新增保存岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int insertPost(SysPost post); - - /** - * 修改保存岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int updatePost(SysPost post); - - /** - * 通过岗位ID查询岗位使用数量 - * - * @param postId 岗位ID - * @return 结果 - */ - public int countUserPostById(Long postId); - - /** - * 校验岗位名称 - * - * @param post 岗位信息 - * @return 结果 - */ - public String checkPostNameUnique(SysPost post); - - /** - * 校验岗位编码 - * - * @param post 岗位信息 - * @return 结果 - */ - public String checkPostCodeUnique(SysPost post); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysPost; + +/** + * 岗位信息 服务层 + * + * @author ruoyi + */ +public interface ISysPostService { + /** + * 查询岗位信息集合 + * + * @param post 岗位信息 + * @return 岗位信息集合 + */ + public List selectPostList(SysPost post); + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + public List selectPostAll(); + + /** + * 根据用户ID查询岗位 + * + * @param userId 用户ID + * @return 岗位列表 + */ + public List selectPostsByUserId(Long userId); + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + public SysPost selectPostById(Long postId); + + /** + * 批量删除岗位信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + * @throws Exception 异常 + */ + public int deletePostByIds(String ids) throws Exception; + + /** + * 新增保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int insertPost(SysPost post); + + /** + * 修改保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int updatePost(SysPost post); + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + public int countUserPostById(Long postId); + + /** + * 校验岗位名称 + * + * @param post 岗位信息 + * @return 结果 + */ + public String checkPostNameUnique(SysPost post); + + /** + * 校验岗位编码 + * + * @param post 岗位信息 + * @return 结果 + */ + public String checkPostCodeUnique(SysPost post); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java index 1d51d6b72..bedf5298e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java @@ -1,159 +1,159 @@ -package com.ruoyi.system.service; - -import java.util.List; -import java.util.Set; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUserRole; - -/** - * 角色业务层 - * - * @author ruoyi - */ -public interface ISysRoleService -{ - /** - * 根据条件分页查询角色数据 - * - * @param role 角色信息 - * @return 角色数据集合信息 - */ - public List selectRoleList(SysRole role); - - /** - * 根据用户ID查询角色 - * - * @param userId 用户ID - * @return 权限列表 - */ - public Set selectRoleKeys(Long userId); - - /** - * 根据用户ID查询角色 - * - * @param userId 用户ID - * @return 角色列表 - */ - public List selectRolesByUserId(Long userId); - - /** - * 查询所有角色 - * - * @return 角色列表 - */ - public List selectRoleAll(); - - /** - * 通过角色ID查询角色 - * - * @param roleId 角色ID - * @return 角色对象信息 - */ - public SysRole selectRoleById(Long roleId); - - /** - * 通过角色ID删除角色 - * - * @param roleId 角色ID - * @return 结果 - */ - public boolean deleteRoleById(Long roleId); - - /** - * 批量删除角色用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - * @throws Exception 异常 - */ - public int deleteRoleByIds(String ids) throws Exception; - - /** - * 新增保存角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int insertRole(SysRole role); - - /** - * 修改保存角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int updateRole(SysRole role); - - /** - * 修改数据权限信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int authDataScope(SysRole role); - - /** - * 校验角色名称是否唯一 - * - * @param role 角色信息 - * @return 结果 - */ - public String checkRoleNameUnique(SysRole role); - - /** - * 校验角色权限是否唯一 - * - * @param role 角色信息 - * @return 结果 - */ - public String checkRoleKeyUnique(SysRole role); - - /** - * 校验角色是否允许操作 - * - * @param role 角色信息 - */ - public void checkRoleAllowed(SysRole role); - - /** - * 通过角色ID查询角色使用数量 - * - * @param roleId 角色ID - * @return 结果 - */ - public int countUserRoleByRoleId(Long roleId); - - /** - * 角色状态修改 - * - * @param role 角色信息 - * @return 结果 - */ - public int changeStatus(SysRole role); - - /** - * 取消授权用户角色 - * - * @param userRole 用户和角色关联信息 - * @return 结果 - */ - public int deleteAuthUser(SysUserRole userRole); - - /** - * 批量取消授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int deleteAuthUsers(Long roleId, String userIds); - - /** - * 批量选择授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int insertAuthUsers(Long roleId, String userIds); -} +package com.ruoyi.system.service; + +import java.util.List; +import java.util.Set; + +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUserRole; + +/** + * 角色业务层 + * + * @author ruoyi + */ +public interface ISysRoleService { + /** + * 根据条件分页查询角色数据 + * + * @param role 角色信息 + * @return 角色数据集合信息 + */ + public List selectRoleList(SysRole role); + + /** + * 根据用户ID查询角色 + * + * @param userId 用户ID + * @return 权限列表 + */ + public Set selectRoleKeys(Long userId); + + /** + * 根据用户ID查询角色 + * + * @param userId 用户ID + * @return 角色列表 + */ + public List selectRolesByUserId(Long userId); + + /** + * 查询所有角色 + * + * @return 角色列表 + */ + public List selectRoleAll(); + + /** + * 通过角色ID查询角色 + * + * @param roleId 角色ID + * @return 角色对象信息 + */ + public SysRole selectRoleById(Long roleId); + + /** + * 通过角色ID删除角色 + * + * @param roleId 角色ID + * @return 结果 + */ + public boolean deleteRoleById(Long roleId); + + /** + * 批量删除角色用户信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + * @throws Exception 异常 + */ + public int deleteRoleByIds(String ids) throws Exception; + + /** + * 新增保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int insertRole(SysRole role); + + /** + * 修改保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int updateRole(SysRole role); + + /** + * 修改数据权限信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int authDataScope(SysRole role); + + /** + * 校验角色名称是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + public String checkRoleNameUnique(SysRole role); + + /** + * 校验角色权限是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + public String checkRoleKeyUnique(SysRole role); + + /** + * 校验角色是否允许操作 + * + * @param role 角色信息 + */ + public void checkRoleAllowed(SysRole role); + + /** + * 通过角色ID查询角色使用数量 + * + * @param roleId 角色ID + * @return 结果 + */ + public int countUserRoleByRoleId(Long roleId); + + /** + * 角色状态修改 + * + * @param role 角色信息 + * @return 结果 + */ + public int changeStatus(SysRole role); + + /** + * 取消授权用户角色 + * + * @param userRole 用户和角色关联信息 + * @return 结果 + */ + public int deleteAuthUser(SysUserRole userRole); + + /** + * 批量取消授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int deleteAuthUsers(Long roleId, String userIds); + + /** + * 批量选择授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int insertAuthUsers(Long roleId, String userIds); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java index 1ed908064..f23b9eb7f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java @@ -1,67 +1,67 @@ -package com.ruoyi.system.service; - -import java.util.Date; -import java.util.List; -import com.ruoyi.system.domain.SysUserOnline; - -/** - * 在线用户 服务层 - * - * @author ruoyi - */ -public interface ISysUserOnlineService -{ - /** - * 通过会话序号查询信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public SysUserOnline selectOnlineById(String sessionId); - - /** - * 通过会话序号删除信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public void deleteOnlineById(String sessionId); - - /** - * 通过会话序号删除信息 - * - * @param sessions 会话ID集合 - * @return 在线用户信息 - */ - public void batchDeleteOnline(List sessions); - - /** - * 保存会话信息 - * - * @param online 会话信息 - */ - public void saveOnline(SysUserOnline online); - - /** - * 查询会话集合 - * - * @param userOnline 分页参数 - * @return 会话集合 - */ - public List selectUserOnlineList(SysUserOnline userOnline); - - /** - * 强退用户 - * - * @param sessionId 会话ID - */ - public void forceLogout(String sessionId); - - /** - * 查询会话集合 - * - * @param expiredDate 有效期 - * @return 会话集合 - */ - public List selectOnlineByExpired(Date expiredDate); -} +package com.ruoyi.system.service; + +import java.util.Date; +import java.util.List; + +import com.ruoyi.system.domain.SysUserOnline; + +/** + * 在线用户 服务层 + * + * @author ruoyi + */ +public interface ISysUserOnlineService { + /** + * 通过会话序号查询信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + public SysUserOnline selectOnlineById(String sessionId); + + /** + * 通过会话序号删除信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + public void deleteOnlineById(String sessionId); + + /** + * 通过会话序号删除信息 + * + * @param sessions 会话ID集合 + * @return 在线用户信息 + */ + public void batchDeleteOnline(List sessions); + + /** + * 保存会话信息 + * + * @param online 会话信息 + */ + public void saveOnline(SysUserOnline online); + + /** + * 查询会话集合 + * + * @param userOnline 分页参数 + * @return 会话集合 + */ + public List selectUserOnlineList(SysUserOnline userOnline); + + /** + * 强退用户 + * + * @param sessionId 会话ID + */ + public void forceLogout(String sessionId); + + /** + * 查询会话集合 + * + * @param expiredDate 有效期 + * @return 会话集合 + */ + public List selectOnlineByExpired(Date expiredDate); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index 8ab240a1c..629b6f825 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -1,182 +1,182 @@ -package com.ruoyi.system.service; - -import java.util.List; -import com.ruoyi.system.domain.SysUser; - -/** - * 用户 业务层 - * - * @author ruoyi - */ -public interface ISysUserService -{ - /** - * 根据条件分页查询用户列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectUserList(SysUser user); - - /** - * 根据条件分页查询已分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectAllocatedList(SysUser user); - - /** - * 根据条件分页查询未分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectUnallocatedList(SysUser user); - - /** - * 通过用户名查询用户 - * - * @param userName 用户名 - * @return 用户对象信息 - */ - public SysUser selectUserByLoginName(String userName); - - /** - * 通过手机号码查询用户 - * - * @param phoneNumber 手机号码 - * @return 用户对象信息 - */ - public SysUser selectUserByPhoneNumber(String phoneNumber); - - /** - * 通过邮箱查询用户 - * - * @param email 邮箱 - * @return 用户对象信息 - */ - public SysUser selectUserByEmail(String email); - - /** - * 通过用户ID查询用户 - * - * @param userId 用户ID - * @return 用户对象信息 - */ - public SysUser selectUserById(Long userId); - - /** - * 通过用户ID删除用户 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserById(Long userId); - - /** - * 批量删除用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - * @throws Exception 异常 - */ - public int deleteUserByIds(String ids) throws Exception; - - /** - * 保存用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int insertUser(SysUser user); - - /** - * 保存用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int updateUser(SysUser user); - - /** - * 修改用户详细信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int updateUserInfo(SysUser user); - - /** - * 修改用户密码信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int resetUserPwd(SysUser user); - - /** - * 校验用户名称是否唯一 - * - * @param loginName 登录名称 - * @return 结果 - */ - public String checkLoginNameUnique(String loginName); - - /** - * 校验手机号码是否唯一 - * - * @param user 用户信息 - * @return 结果 - */ - public String checkPhoneUnique(SysUser user); - - /** - * 校验email是否唯一 - * - * @param user 用户信息 - * @return 结果 - */ - public String checkEmailUnique(SysUser user); - - /** - * 校验用户是否允许操作 - * - * @param user 用户信息 - */ - public void checkUserAllowed(SysUser user); - - /** - * 根据用户ID查询用户所属角色组 - * - * @param userId 用户ID - * @return 结果 - */ - public String selectUserRoleGroup(Long userId); - - /** - * 根据用户ID查询用户所属岗位组 - * - * @param userId 用户ID - * @return 结果 - */ - public String selectUserPostGroup(Long userId); - - /** - * 导入用户数据 - * - * @param userList 用户数据列表 - * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 - * @param operName 操作用户 - * @return 结果 - */ - public String importUser(List userList, Boolean isUpdateSupport, String operName); - - /** - * 用户状态修改 - * - * @param user 用户信息 - * @return 结果 - */ - public int changeStatus(SysUser user); -} +package com.ruoyi.system.service; + +import java.util.List; + +import com.ruoyi.system.domain.SysUser; + +/** + * 用户 业务层 + * + * @author ruoyi + */ +public interface ISysUserService { + /** + * 根据条件分页查询用户列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + public List selectUserList(SysUser user); + + /** + * 根据条件分页查询已分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + public List selectAllocatedList(SysUser user); + + /** + * 根据条件分页查询未分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + public List selectUnallocatedList(SysUser user); + + /** + * 通过用户名查询用户 + * + * @param userName 用户名 + * @return 用户对象信息 + */ + public SysUser selectUserByLoginName(String userName); + + /** + * 通过手机号码查询用户 + * + * @param phoneNumber 手机号码 + * @return 用户对象信息 + */ + public SysUser selectUserByPhoneNumber(String phoneNumber); + + /** + * 通过邮箱查询用户 + * + * @param email 邮箱 + * @return 用户对象信息 + */ + public SysUser selectUserByEmail(String email); + + /** + * 通过用户ID查询用户 + * + * @param userId 用户ID + * @return 用户对象信息 + */ + public SysUser selectUserById(Long userId); + + /** + * 通过用户ID删除用户 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserById(Long userId); + + /** + * 批量删除用户信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + * @throws Exception 异常 + */ + public int deleteUserByIds(String ids) throws Exception; + + /** + * 保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int insertUser(SysUser user); + + /** + * 保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int updateUser(SysUser user); + + /** + * 修改用户详细信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int updateUserInfo(SysUser user); + + /** + * 修改用户密码信息 + * + * @param user 用户信息 + * @return 结果 + */ + public int resetUserPwd(SysUser user); + + /** + * 校验用户名称是否唯一 + * + * @param loginName 登录名称 + * @return 结果 + */ + public String checkLoginNameUnique(String loginName); + + /** + * 校验手机号码是否唯一 + * + * @param user 用户信息 + * @return 结果 + */ + public String checkPhoneUnique(SysUser user); + + /** + * 校验email是否唯一 + * + * @param user 用户信息 + * @return 结果 + */ + public String checkEmailUnique(SysUser user); + + /** + * 校验用户是否允许操作 + * + * @param user 用户信息 + */ + public void checkUserAllowed(SysUser user); + + /** + * 根据用户ID查询用户所属角色组 + * + * @param userId 用户ID + * @return 结果 + */ + public String selectUserRoleGroup(Long userId); + + /** + * 根据用户ID查询用户所属岗位组 + * + * @param userId 用户ID + * @return 结果 + */ + public String selectUserPostGroup(Long userId); + + /** + * 导入用户数据 + * + * @param userList 用户数据列表 + * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 + * @param operName 操作用户 + * @return 结果 + */ + public String importUser(List userList, Boolean isUpdateSupport, String operName); + + /** + * 用户状态修改 + * + * @param user 用户信息 + * @return 结果 + */ + public int changeStatus(SysUser user); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java index 8b2a02d0a..7e95d33d7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java @@ -1,118 +1,110 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysConfig; -import com.ruoyi.system.mapper.SysConfigMapper; -import com.ruoyi.system.service.ISysConfigService; - -/** - * 参数配置 服务层实现 - * - * @author ruoyi - */ -@Service -public class SysConfigServiceImpl implements ISysConfigService -{ - @Autowired - private SysConfigMapper configMapper; - - /** - * 查询参数配置信息 - * - * @param configId 参数配置ID - * @return 参数配置信息 - */ - @Override - public SysConfig selectConfigById(Long configId) - { - SysConfig config = new SysConfig(); - config.setConfigId(configId); - return configMapper.selectConfig(config); - } - - /** - * 根据键名查询参数配置信息 - * - * @param configKey 参数key - * @return 参数键值 - */ - @Override - public String selectConfigByKey(String configKey) - { - SysConfig config = new SysConfig(); - config.setConfigKey(configKey); - SysConfig retConfig = configMapper.selectConfig(config); - return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : ""; - } - - /** - * 查询参数配置列表 - * - * @param config 参数配置信息 - * @return 参数配置集合 - */ - @Override - public List selectConfigList(SysConfig config) - { - return configMapper.selectConfigList(config); - } - - /** - * 新增参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - @Override - public int insertConfig(SysConfig config) - { - return configMapper.insertConfig(config); - } - - /** - * 修改参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - @Override - public int updateConfig(SysConfig config) - { - return configMapper.updateConfig(config); - } - - /** - * 批量删除参数配置对象 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - public int deleteConfigByIds(String ids) - { - return configMapper.deleteConfigByIds(Convert.toStrArray(ids)); - } - - /** - * 校验参数键名是否唯一 - * - * @param config 参数配置信息 - * @return 结果 - */ - @Override - public String checkConfigKeyUnique(SysConfig config) - { - Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); - SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); - if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) - { - return UserConstants.CONFIG_KEY_NOT_UNIQUE; - } - return UserConstants.CONFIG_KEY_UNIQUE; - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysConfig; +import com.ruoyi.system.mapper.SysConfigMapper; +import com.ruoyi.system.service.ISysConfigService; + +/** + * 参数配置 服务层实现 + * + * @author ruoyi + */ +@Service +public class SysConfigServiceImpl implements ISysConfigService { + @Autowired + private SysConfigMapper configMapper; + + /** + * 查询参数配置信息 + * + * @param configId 参数配置ID + * @return 参数配置信息 + */ + @Override + public SysConfig selectConfigById(Long configId) { + SysConfig config = new SysConfig(); + config.setConfigId(configId); + return configMapper.selectConfig(config); + } + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数key + * @return 参数键值 + */ + @Override + public String selectConfigByKey(String configKey) { + SysConfig config = new SysConfig(); + config.setConfigKey(configKey); + SysConfig retConfig = configMapper.selectConfig(config); + return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : ""; + } + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + @Override + public List selectConfigList(SysConfig config) { + return configMapper.selectConfigList(config); + } + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public int insertConfig(SysConfig config) { + return configMapper.insertConfig(config); + } + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public int updateConfig(SysConfig config) { + return configMapper.updateConfig(config); + } + + /** + * 批量删除参数配置对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteConfigByIds(String ids) { + return configMapper.deleteConfigByIds(Convert.toStrArray(ids)); + } + + /** + * 校验参数键名是否唯一 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public String checkConfigKeyUnique(SysConfig config) { + Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); + SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); + if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) { + return UserConstants.CONFIG_KEY_NOT_UNIQUE; + } + return UserConstants.CONFIG_KEY_UNIQUE; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 422b33643..10799d5ab 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -1,271 +1,245 @@ -package com.ruoyi.system.service.impl; - -import java.util.ArrayList; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.annotation.DataScope; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysDept; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.mapper.SysDeptMapper; -import com.ruoyi.system.service.ISysDeptService; - -/** - * 部门管理 服务实现 - * - * @author ruoyi - */ -@Service -public class SysDeptServiceImpl implements ISysDeptService -{ - @Autowired - private SysDeptMapper deptMapper; - - /** - * 查询部门管理数据 - * - * @param dept 部门信息 - * @return 部门信息集合 - */ - @Override - @DataScope(deptAlias = "d") - public List selectDeptList(SysDept dept) - { - return deptMapper.selectDeptList(dept); - } - - /** - * 查询部门管理树 - * - * @param dept 部门信息 - * @return 所有部门信息 - */ - @Override - @DataScope(deptAlias = "d") - public List selectDeptTree(SysDept dept) - { - List deptList = deptMapper.selectDeptList(dept); - List ztrees = initZtree(deptList); - return ztrees; - } - - /** - * 根据角色ID查询部门(数据权限) - * - * @param role 角色对象 - * @return 部门列表(数据权限) - */ - @Override - public List roleDeptTreeData(SysRole role) - { - Long roleId = role.getRoleId(); - List ztrees = new ArrayList(); - List deptList = selectDeptList(new SysDept()); - if (StringUtils.isNotNull(roleId)) - { - List roleDeptList = deptMapper.selectRoleDeptTree(roleId); - ztrees = initZtree(deptList, roleDeptList); - } - else - { - ztrees = initZtree(deptList); - } - return ztrees; - } - - /** - * 对象转部门树 - * - * @param deptList 部门列表 - * @return 树结构列表 - */ - public List initZtree(List deptList) - { - return initZtree(deptList, null); - } - - /** - * 对象转部门树 - * - * @param deptList 部门列表 - * @param roleDeptList 角色已存在菜单列表 - * @return 树结构列表 - */ - public List initZtree(List deptList, List roleDeptList) - { - - List ztrees = new ArrayList(); - boolean isCheck = StringUtils.isNotNull(roleDeptList); - for (SysDept dept : deptList) - { - if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) - { - Ztree ztree = new Ztree(); - ztree.setId(dept.getDeptId()); - ztree.setpId(dept.getParentId()); - ztree.setName(dept.getDeptName()); - ztree.setTitle(dept.getDeptName()); - if (isCheck) - { - ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName())); - } - ztrees.add(ztree); - } - } - return ztrees; - } - - /** - * 查询部门人数 - * - * @param parentId 部门ID - * @return 结果 - */ - @Override - public int selectDeptCount(Long parentId) - { - SysDept dept = new SysDept(); - dept.setParentId(parentId); - return deptMapper.selectDeptCount(dept); - } - - /** - * 查询部门是否存在用户 - * - * @param deptId 部门ID - * @return 结果 true 存在 false 不存在 - */ - @Override - public boolean checkDeptExistUser(Long deptId) - { - int result = deptMapper.checkDeptExistUser(deptId); - return result > 0 ? true : false; - } - - /** - * 删除部门管理信息 - * - * @param deptId 部门ID - * @return 结果 - */ - @Override - public int deleteDeptById(Long deptId) - { - return deptMapper.deleteDeptById(deptId); - } - - /** - * 新增保存部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - @Override - public int insertDept(SysDept dept) - { - SysDept info = deptMapper.selectDeptById(dept.getParentId()); - // 如果父节点不为"正常"状态,则不允许新增子节点 - if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) - { - throw new BusinessException("部门停用,不允许新增"); - } - dept.setAncestors(info.getAncestors() + "," + dept.getParentId()); - return deptMapper.insertDept(dept); - } - - /** - * 修改保存部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - @Override - @Transactional - public int updateDept(SysDept dept) - { - SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId()); - SysDept oldDept = selectDeptById(dept.getDeptId()); - if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) - { - String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId(); - String oldAncestors = oldDept.getAncestors(); - dept.setAncestors(newAncestors); - updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors); - } - int result = deptMapper.updateDept(dept); - if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) - { - // 如果该部门是启用状态,则启用该部门的所有上级部门 - updateParentDeptStatus(dept); - } - return result; - } - - /** - * 修改该部门的父级部门状态 - * - * @param dept 当前部门 - */ - private void updateParentDeptStatus(SysDept dept) - { - String updateBy = dept.getUpdateBy(); - dept = deptMapper.selectDeptById(dept.getDeptId()); - dept.setUpdateBy(updateBy); - deptMapper.updateDeptStatus(dept); - } - - /** - * 修改子元素关系 - * - * @param deptId 被修改的部门ID - * @param newAncestors 新的父ID集合 - * @param oldAncestors 旧的父ID集合 - */ - public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) - { - List children = deptMapper.selectChildrenDeptById(deptId); - for (SysDept child : children) - { - child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors)); - } - if (children.size() > 0) - { - deptMapper.updateDeptChildren(children); - } - } - - /** - * 根据部门ID查询信息 - * - * @param deptId 部门ID - * @return 部门信息 - */ - @Override - public SysDept selectDeptById(Long deptId) - { - return deptMapper.selectDeptById(deptId); - } - - /** - * 校验部门名称是否唯一 - * - * @param dept 部门信息 - * @return 结果 - */ - @Override - public String checkDeptNameUnique(SysDept dept) - { - Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId(); - SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); - if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) - { - return UserConstants.DEPT_NAME_NOT_UNIQUE; - } - return UserConstants.DEPT_NAME_UNIQUE; - } -} +package com.ruoyi.system.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.mapper.SysDeptMapper; +import com.ruoyi.system.service.ISysDeptService; + +/** + * 部门管理 服务实现 + * + * @author ruoyi + */ +@Service +public class SysDeptServiceImpl implements ISysDeptService { + @Autowired + private SysDeptMapper deptMapper; + + /** + * 查询部门管理数据 + * + * @param dept 部门信息 + * @return 部门信息集合 + */ + @Override + @DataScope(deptAlias = "d") + public List selectDeptList(SysDept dept) { + return deptMapper.selectDeptList(dept); + } + + /** + * 查询部门管理树 + * + * @param dept 部门信息 + * @return 所有部门信息 + */ + @Override + @DataScope(deptAlias = "d") + public List selectDeptTree(SysDept dept) { + List deptList = deptMapper.selectDeptList(dept); + List ztrees = initZtree(deptList); + return ztrees; + } + + /** + * 根据角色ID查询部门(数据权限) + * + * @param role 角色对象 + * @return 部门列表(数据权限) + */ + @Override + public List roleDeptTreeData(SysRole role) { + Long roleId = role.getRoleId(); + List ztrees = new ArrayList(); + List deptList = selectDeptList(new SysDept()); + if (StringUtils.isNotNull(roleId)) { + List roleDeptList = deptMapper.selectRoleDeptTree(roleId); + ztrees = initZtree(deptList, roleDeptList); + } else { + ztrees = initZtree(deptList); + } + return ztrees; + } + + /** + * 对象转部门树 + * + * @param deptList 部门列表 + * @return 树结构列表 + */ + public List initZtree(List deptList) { + return initZtree(deptList, null); + } + + /** + * 对象转部门树 + * + * @param deptList 部门列表 + * @param roleDeptList 角色已存在菜单列表 + * @return 树结构列表 + */ + public List initZtree(List deptList, List roleDeptList) { + + List ztrees = new ArrayList(); + boolean isCheck = StringUtils.isNotNull(roleDeptList); + for (SysDept dept : deptList) { + if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) { + Ztree ztree = new Ztree(); + ztree.setId(dept.getDeptId()); + ztree.setpId(dept.getParentId()); + ztree.setName(dept.getDeptName()); + ztree.setTitle(dept.getDeptName()); + if (isCheck) { + ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName())); + } + ztrees.add(ztree); + } + } + return ztrees; + } + + /** + * 查询部门人数 + * + * @param parentId 部门ID + * @return 结果 + */ + @Override + public int selectDeptCount(Long parentId) { + SysDept dept = new SysDept(); + dept.setParentId(parentId); + return deptMapper.selectDeptCount(dept); + } + + /** + * 查询部门是否存在用户 + * + * @param deptId 部门ID + * @return 结果 true 存在 false 不存在 + */ + @Override + public boolean checkDeptExistUser(Long deptId) { + int result = deptMapper.checkDeptExistUser(deptId); + return result > 0 ? true : false; + } + + /** + * 删除部门管理信息 + * + * @param deptId 部门ID + * @return 结果 + */ + @Override + public int deleteDeptById(Long deptId) { + return deptMapper.deleteDeptById(deptId); + } + + /** + * 新增保存部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + @Override + public int insertDept(SysDept dept) { + SysDept info = deptMapper.selectDeptById(dept.getParentId()); + // 如果父节点不为"正常"状态,则不允许新增子节点 + if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) { + throw new BusinessException("部门停用,不允许新增"); + } + dept.setAncestors(info.getAncestors() + "," + dept.getParentId()); + return deptMapper.insertDept(dept); + } + + /** + * 修改保存部门信息 + * + * @param dept 部门信息 + * @return 结果 + */ + @Override + @Transactional + public int updateDept(SysDept dept) { + SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId()); + SysDept oldDept = selectDeptById(dept.getDeptId()); + if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) { + String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId(); + String oldAncestors = oldDept.getAncestors(); + dept.setAncestors(newAncestors); + updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors); + } + int result = deptMapper.updateDept(dept); + if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) { + // 如果该部门是启用状态,则启用该部门的所有上级部门 + updateParentDeptStatus(dept); + } + return result; + } + + /** + * 修改该部门的父级部门状态 + * + * @param dept 当前部门 + */ + private void updateParentDeptStatus(SysDept dept) { + String updateBy = dept.getUpdateBy(); + dept = deptMapper.selectDeptById(dept.getDeptId()); + dept.setUpdateBy(updateBy); + deptMapper.updateDeptStatus(dept); + } + + /** + * 修改子元素关系 + * + * @param deptId 被修改的部门ID + * @param newAncestors 新的父ID集合 + * @param oldAncestors 旧的父ID集合 + */ + public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) { + List children = deptMapper.selectChildrenDeptById(deptId); + for (SysDept child : children) { + child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors)); + } + if (children.size() > 0) { + deptMapper.updateDeptChildren(children); + } + } + + /** + * 根据部门ID查询信息 + * + * @param deptId 部门ID + * @return 部门信息 + */ + @Override + public SysDept selectDeptById(Long deptId) { + return deptMapper.selectDeptById(deptId); + } + + /** + * 校验部门名称是否唯一 + * + * @param dept 部门信息 + * @return 结果 + */ + @Override + public String checkDeptNameUnique(SysDept dept) { + Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId(); + SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); + if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) { + return UserConstants.DEPT_NAME_NOT_UNIQUE; + } + return UserConstants.DEPT_NAME_UNIQUE; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java index 502e03f43..28c9ddca7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java @@ -1,118 +1,110 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.system.domain.SysDictData; -import com.ruoyi.system.mapper.SysDictDataMapper; -import com.ruoyi.system.service.ISysDictDataService; - -/** - * 字典 业务层处理 - * - * @author ruoyi - */ -@Service -public class SysDictDataServiceImpl implements ISysDictDataService -{ - @Autowired - private SysDictDataMapper dictDataMapper; - - /** - * 根据条件分页查询字典数据 - * - * @param dictData 字典数据信息 - * @return 字典数据集合信息 - */ - @Override - public List selectDictDataList(SysDictData dictData) - { - return dictDataMapper.selectDictDataList(dictData); - } - - /** - * 根据字典类型查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据集合信息 - */ - @Override - public List selectDictDataByType(String dictType) - { - return dictDataMapper.selectDictDataByType(dictType); - } - - /** - * 根据字典类型和字典键值查询字典数据信息 - * - * @param dictType 字典类型 - * @param dictValue 字典键值 - * @return 字典标签 - */ - @Override - public String selectDictLabel(String dictType, String dictValue) - { - return dictDataMapper.selectDictLabel(dictType, dictValue); - } - - /** - * 根据字典数据ID查询信息 - * - * @param dictCode 字典数据ID - * @return 字典数据 - */ - @Override - public SysDictData selectDictDataById(Long dictCode) - { - return dictDataMapper.selectDictDataById(dictCode); - } - - /** - * 通过字典ID删除字典数据信息 - * - * @param dictCode 字典数据ID - * @return 结果 - */ - @Override - public int deleteDictDataById(Long dictCode) - { - return dictDataMapper.deleteDictDataById(dictCode); - } - - /** - * 批量删除字典数据 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - @Override - public int deleteDictDataByIds(String ids) - { - return dictDataMapper.deleteDictDataByIds(Convert.toStrArray(ids)); - } - - /** - * 新增保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - @Override - public int insertDictData(SysDictData dictData) - { - return dictDataMapper.insertDictData(dictData); - } - - /** - * 修改保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - @Override - public int updateDictData(SysDictData dictData) - { - return dictDataMapper.updateDictData(dictData); - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.system.domain.SysDictData; +import com.ruoyi.system.mapper.SysDictDataMapper; +import com.ruoyi.system.service.ISysDictDataService; + +/** + * 字典 业务层处理 + * + * @author ruoyi + */ +@Service +public class SysDictDataServiceImpl implements ISysDictDataService { + @Autowired + private SysDictDataMapper dictDataMapper; + + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + @Override + public List selectDictDataList(SysDictData dictData) { + return dictDataMapper.selectDictDataList(dictData); + } + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + @Override + public List selectDictDataByType(String dictType) { + return dictDataMapper.selectDictDataByType(dictType); + } + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + @Override + public String selectDictLabel(String dictType, String dictValue) { + return dictDataMapper.selectDictLabel(dictType, dictValue); + } + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + @Override + public SysDictData selectDictDataById(Long dictCode) { + return dictDataMapper.selectDictDataById(dictCode); + } + + /** + * 通过字典ID删除字典数据信息 + * + * @param dictCode 字典数据ID + * @return 结果 + */ + @Override + public int deleteDictDataById(Long dictCode) { + return dictDataMapper.deleteDictDataById(dictCode); + } + + /** + * 批量删除字典数据 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + @Override + public int deleteDictDataByIds(String ids) { + return dictDataMapper.deleteDictDataByIds(Convert.toStrArray(ids)); + } + + /** + * 新增保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + @Override + public int insertDictData(SysDictData dictData) { + return dictDataMapper.insertDictData(dictData); + } + + /** + * 修改保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + @Override + public int updateDictData(SysDictData dictData) { + return dictDataMapper.updateDictData(dictData); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java index 34ca02bae..322d04b88 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java @@ -1,188 +1,172 @@ -package com.ruoyi.system.service.impl; - -import java.util.ArrayList; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysDictType; -import com.ruoyi.system.mapper.SysDictDataMapper; -import com.ruoyi.system.mapper.SysDictTypeMapper; -import com.ruoyi.system.service.ISysDictTypeService; - -/** - * 字典 业务层处理 - * - * @author ruoyi - */ -@Service -public class SysDictTypeServiceImpl implements ISysDictTypeService -{ - @Autowired - private SysDictTypeMapper dictTypeMapper; - - @Autowired - private SysDictDataMapper dictDataMapper; - - /** - * 根据条件分页查询字典类型 - * - * @param dictType 字典类型信息 - * @return 字典类型集合信息 - */ - @Override - public List selectDictTypeList(SysDictType dictType) - { - return dictTypeMapper.selectDictTypeList(dictType); - } - - /** - * 根据所有字典类型 - * - * @return 字典类型集合信息 - */ - @Override - public List selectDictTypeAll() - { - return dictTypeMapper.selectDictTypeAll(); - } - - /** - * 根据字典类型ID查询信息 - * - * @param dictId 字典类型ID - * @return 字典类型 - */ - @Override - public SysDictType selectDictTypeById(Long dictId) - { - return dictTypeMapper.selectDictTypeById(dictId); - } - - /** - * 根据字典类型查询信息 - * - * @param dictType 字典类型 - * @return 字典类型 - */ - public SysDictType selectDictTypeByType(String dictType) - { - return dictTypeMapper.selectDictTypeByType(dictType); - } - - /** - * 通过字典ID删除字典信息 - * - * @param dictId 字典ID - * @return 结果 - */ - @Override - public int deleteDictTypeById(Long dictId) - { - return dictTypeMapper.deleteDictTypeById(dictId); - } - - /** - * 批量删除字典类型 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - @Override - public int deleteDictTypeByIds(String ids) throws BusinessException - { - Long[] dictIds = Convert.toLongArray(ids); - for (Long dictId : dictIds) - { - SysDictType dictType = selectDictTypeById(dictId); - if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) - { - throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName())); - } - } - - return dictTypeMapper.deleteDictTypeByIds(dictIds); - } - - /** - * 新增保存字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - @Override - public int insertDictType(SysDictType dictType) - { - return dictTypeMapper.insertDictType(dictType); - } - - /** - * 修改保存字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - @Override - @Transactional - public int updateDictType(SysDictType dictType) - { - SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId()); - dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType()); - return dictTypeMapper.updateDictType(dictType); - } - - /** - * 校验字典类型称是否唯一 - * - * @param dict 字典类型 - * @return 结果 - */ - @Override - public String checkDictTypeUnique(SysDictType dict) - { - Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); - SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); - if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) - { - return UserConstants.DICT_TYPE_NOT_UNIQUE; - } - return UserConstants.DICT_TYPE_UNIQUE; - } - - /** - * 查询字典类型树 - * - * @param dictType 字典类型 - * @return 所有字典类型 - */ - public List selectDictTree(SysDictType dictType) - { - List ztrees = new ArrayList(); - List dictList = dictTypeMapper.selectDictTypeList(dictType); - for (SysDictType dict : dictList) - { - if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) - { - Ztree ztree = new Ztree(); - ztree.setId(dict.getDictId()); - ztree.setName(transDictName(dict)); - ztree.setTitle(dict.getDictType()); - ztrees.add(ztree); - } - } - return ztrees; - } - - public String transDictName(SysDictType dictType) - { - StringBuffer sb = new StringBuffer(); - sb.append("(" + dictType.getDictName() + ")"); - sb.append("   " + dictType.getDictType()); - return sb.toString(); - } -} +package com.ruoyi.system.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysDictType; +import com.ruoyi.system.mapper.SysDictDataMapper; +import com.ruoyi.system.mapper.SysDictTypeMapper; +import com.ruoyi.system.service.ISysDictTypeService; + +/** + * 字典 业务层处理 + * + * @author ruoyi + */ +@Service +public class SysDictTypeServiceImpl implements ISysDictTypeService { + @Autowired + private SysDictTypeMapper dictTypeMapper; + + @Autowired + private SysDictDataMapper dictDataMapper; + + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + @Override + public List selectDictTypeList(SysDictType dictType) { + return dictTypeMapper.selectDictTypeList(dictType); + } + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + @Override + public List selectDictTypeAll() { + return dictTypeMapper.selectDictTypeAll(); + } + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + @Override + public SysDictType selectDictTypeById(Long dictId) { + return dictTypeMapper.selectDictTypeById(dictId); + } + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + public SysDictType selectDictTypeByType(String dictType) { + return dictTypeMapper.selectDictTypeByType(dictType); + } + + /** + * 通过字典ID删除字典信息 + * + * @param dictId 字典ID + * @return 结果 + */ + @Override + public int deleteDictTypeById(Long dictId) { + return dictTypeMapper.deleteDictTypeById(dictId); + } + + /** + * 批量删除字典类型 + * + * @param ids 需要删除的数据 + * @return 结果 + */ + @Override + public int deleteDictTypeByIds(String ids) throws BusinessException { + Long[] dictIds = Convert.toLongArray(ids); + for (Long dictId : dictIds) { + SysDictType dictType = selectDictTypeById(dictId); + if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) { + throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName())); + } + } + + return dictTypeMapper.deleteDictTypeByIds(dictIds); + } + + /** + * 新增保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + @Override + public int insertDictType(SysDictType dictType) { + return dictTypeMapper.insertDictType(dictType); + } + + /** + * 修改保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + @Override + @Transactional + public int updateDictType(SysDictType dictType) { + SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId()); + dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType()); + return dictTypeMapper.updateDictType(dictType); + } + + /** + * 校验字典类型称是否唯一 + * + * @param dict 字典类型 + * @return 结果 + */ + @Override + public String checkDictTypeUnique(SysDictType dict) { + Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); + SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); + if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) { + return UserConstants.DICT_TYPE_NOT_UNIQUE; + } + return UserConstants.DICT_TYPE_UNIQUE; + } + + /** + * 查询字典类型树 + * + * @param dictType 字典类型 + * @return 所有字典类型 + */ + public List selectDictTree(SysDictType dictType) { + List ztrees = new ArrayList(); + List dictList = dictTypeMapper.selectDictTypeList(dictType); + for (SysDictType dict : dictList) { + if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) { + Ztree ztree = new Ztree(); + ztree.setId(dict.getDictId()); + ztree.setName(transDictName(dict)); + ztree.setTitle(dict.getDictType()); + ztrees.add(ztree); + } + } + return ztrees; + } + + public String transDictName(SysDictType dictType) { + StringBuffer sb = new StringBuffer(); + sb.append("(" + dictType.getDictName() + ")"); + sb.append("   " + dictType.getDictType()); + return sb.toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java index 3f183d62c..09d2bc1da 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java @@ -1,66 +1,62 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.system.domain.SysLogininfor; -import com.ruoyi.system.mapper.SysLogininforMapper; -import com.ruoyi.system.service.ISysLogininforService; - -/** - * 系统访问日志情况信息 服务层处理 - * - * @author ruoyi - */ -@Service -public class SysLogininforServiceImpl implements ISysLogininforService -{ - - @Autowired - private SysLogininforMapper logininforMapper; - - /** - * 新增系统登录日志 - * - * @param logininfor 访问日志对象 - */ - @Override - public void insertLogininfor(SysLogininfor logininfor) - { - logininforMapper.insertLogininfor(logininfor); - } - - /** - * 查询系统登录日志集合 - * - * @param logininfor 访问日志对象 - * @return 登录记录集合 - */ - @Override - public List selectLogininforList(SysLogininfor logininfor) - { - return logininforMapper.selectLogininforList(logininfor); - } - - /** - * 批量删除系统登录日志 - * - * @param ids 需要删除的数据 - * @return - */ - @Override - public int deleteLogininforByIds(String ids) - { - return logininforMapper.deleteLogininforByIds(Convert.toStrArray(ids)); - } - - /** - * 清空系统登录日志 - */ - @Override - public void cleanLogininfor() - { - logininforMapper.cleanLogininfor(); - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.system.domain.SysLogininfor; +import com.ruoyi.system.mapper.SysLogininforMapper; +import com.ruoyi.system.service.ISysLogininforService; + +/** + * 系统访问日志情况信息 服务层处理 + * + * @author ruoyi + */ +@Service +public class SysLogininforServiceImpl implements ISysLogininforService { + + @Autowired + private SysLogininforMapper logininforMapper; + + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + @Override + public void insertLogininfor(SysLogininfor logininfor) { + logininforMapper.insertLogininfor(logininfor); + } + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + @Override + public List selectLogininforList(SysLogininfor logininfor) { + return logininforMapper.selectLogininforList(logininfor); + } + + /** + * 批量删除系统登录日志 + * + * @param ids 需要删除的数据 + * @return + */ + @Override + public int deleteLogininforByIds(String ids) { + return logininforMapper.deleteLogininforByIds(Convert.toStrArray(ids)); + } + + /** + * 清空系统登录日志 + */ + @Override + public void cleanLogininfor() { + logininforMapper.cleanLogininfor(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index ce6a65e73..52e4a7b61 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -1,395 +1,347 @@ -package com.ruoyi.system.service.impl; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysMenu; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.mapper.SysMenuMapper; -import com.ruoyi.system.mapper.SysRoleMenuMapper; -import com.ruoyi.system.service.ISysMenuService; - -/** - * 菜单 业务层处理 - * - * @author ruoyi - */ -@Service -public class SysMenuServiceImpl implements ISysMenuService -{ - public static final String PREMISSION_STRING = "perms[\"{0}\"]"; - - @Autowired - private SysMenuMapper menuMapper; - - @Autowired - private SysRoleMenuMapper roleMenuMapper; - - /** - * 根据用户查询菜单 - * - * @param user 用户信息 - * @return 菜单列表 - */ - @Override - public List selectMenusByUser(SysUser user) - { - List menus = new LinkedList(); - // 管理员显示所有菜单信息 - if (user.isAdmin()) - { - menus = menuMapper.selectMenuNormalAll(); - } - else - { - menus = menuMapper.selectMenusByUserId(user.getUserId()); - } - return getChildPerms(menus, 0); - } - - /** - * 查询菜单集合 - * - * @return 所有菜单信息 - */ - @Override - public List selectMenuList(SysMenu menu, Long userId) - { - List menuList = null; - if (SysUser.isAdmin(userId)) - { - menuList = menuMapper.selectMenuList(menu); - } - else - { - menu.getParams().put("userId", userId); - menuList = menuMapper.selectMenuListByUserId(menu); - } - return menuList; - } - - /** - * 查询菜单集合 - * - * @return 所有菜单信息 - */ - @Override - public List selectMenuAll(Long userId) - { - List menuList = null; - if (SysUser.isAdmin(userId)) - { - menuList = menuMapper.selectMenuAll(); - } - else - { - menuList = menuMapper.selectMenuAllByUserId(userId); - } - return menuList; - } - - /** - * 根据用户ID查询权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - @Override - public Set selectPermsByUserId(Long userId) - { - List perms = menuMapper.selectPermsByUserId(userId); - Set permsSet = new HashSet<>(); - for (String perm : perms) - { - if (StringUtils.isNotEmpty(perm)) - { - permsSet.addAll(Arrays.asList(perm.trim().split(","))); - } - } - return permsSet; - } - - /** - * 根据角色ID查询菜单 - * - * @param role 角色对象 - * @return 菜单列表 - */ - @Override - public List roleMenuTreeData(SysRole role, Long userId) - { - Long roleId = role.getRoleId(); - List ztrees = new ArrayList(); - List menuList = selectMenuAll(userId); - if (StringUtils.isNotNull(roleId)) - { - List roleMenuList = menuMapper.selectMenuTree(roleId); - ztrees = initZtree(menuList, roleMenuList, true); - } - else - { - ztrees = initZtree(menuList, null, true); - } - return ztrees; - } - - /** - * 查询所有菜单 - * - * @return 菜单列表 - */ - @Override - public List menuTreeData(Long userId) - { - List menuList = selectMenuAll(userId); - List ztrees = initZtree(menuList); - return ztrees; - } - - /** - * 查询系统所有权限 - * - * @return 权限列表 - */ - @Override - public LinkedHashMap selectPermsAll(Long userId) - { - LinkedHashMap section = new LinkedHashMap<>(); - List permissions = selectMenuAll(userId); - if (StringUtils.isNotEmpty(permissions)) - { - for (SysMenu menu : permissions) - { - section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms())); - } - } - return section; - } - - /** - * 对象转菜单树 - * - * @param menuList 菜单列表 - * @return 树结构列表 - */ - public List initZtree(List menuList) - { - return initZtree(menuList, null, false); - } - - /** - * 对象转菜单树 - * - * @param menuList 菜单列表 - * @param roleMenuList 角色已存在菜单列表 - * @param permsFlag 是否需要显示权限标识 - * @return 树结构列表 - */ - public List initZtree(List menuList, List roleMenuList, boolean permsFlag) - { - List ztrees = new ArrayList(); - boolean isCheck = StringUtils.isNotNull(roleMenuList); - for (SysMenu menu : menuList) - { - Ztree ztree = new Ztree(); - ztree.setId(menu.getMenuId()); - ztree.setpId(menu.getParentId()); - ztree.setName(transMenuName(menu, permsFlag)); - ztree.setTitle(menu.getMenuName()); - if (isCheck) - { - ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms())); - } - ztrees.add(ztree); - } - return ztrees; - } - - public String transMenuName(SysMenu menu, boolean permsFlag) - { - StringBuffer sb = new StringBuffer(); - sb.append(menu.getMenuName()); - if (permsFlag) - { - sb.append("   " + menu.getPerms() + ""); - } - return sb.toString(); - } - - /** - * 删除菜单管理信息 - * - * @param menuId 菜单ID - * @return 结果 - */ - @Override - public int deleteMenuById(Long menuId) - { - return menuMapper.deleteMenuById(menuId); - } - - /** - * 根据菜单ID查询信息 - * - * @param menuId 菜单ID - * @return 菜单信息 - */ - @Override - public SysMenu selectMenuById(Long menuId) - { - return menuMapper.selectMenuById(menuId); - } - - /** - * 查询子菜单数量 - * - * @param parentId 父级菜单ID - * @return 结果 - */ - @Override - public int selectCountMenuByParentId(Long parentId) - { - return menuMapper.selectCountMenuByParentId(parentId); - } - - /** - * 查询菜单使用数量 - * - * @param menuId 菜单ID - * @return 结果 - */ - @Override - public int selectCountRoleMenuByMenuId(Long menuId) - { - return roleMenuMapper.selectCountRoleMenuByMenuId(menuId); - } - - /** - * 新增保存菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - @Override - public int insertMenu(SysMenu menu) - { - return menuMapper.insertMenu(menu); - } - - /** - * 修改保存菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - @Override - public int updateMenu(SysMenu menu) - { - return menuMapper.updateMenu(menu); - } - - /** - * 校验菜单名称是否唯一 - * - * @param menu 菜单信息 - * @return 结果 - */ - @Override - public String checkMenuNameUnique(SysMenu menu) - { - Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); - SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); - if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) - { - return UserConstants.MENU_NAME_NOT_UNIQUE; - } - return UserConstants.MENU_NAME_UNIQUE; - } - - /** - * 根据父节点的ID获取所有子节点 - * - * @param list 分类表 - * @param parentId 传入的父节点ID - * @return String - */ - public List getChildPerms(List list, int parentId) - { - List returnList = new ArrayList(); - for (Iterator iterator = list.iterator(); iterator.hasNext();) - { - SysMenu t = (SysMenu) iterator.next(); - // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点 - if (t.getParentId() == parentId) - { - recursionFn(list, t); - returnList.add(t); - } - } - return returnList; - } - - /** - * 递归列表 - * - * @param list - * @param t - */ - private void recursionFn(List list, SysMenu t) - { - // 得到子节点列表 - List childList = getChildList(list, t); - t.setChildren(childList); - for (SysMenu tChild : childList) - { - if (hasChild(list, tChild)) - { - // 判断是否有子节点 - Iterator it = childList.iterator(); - while (it.hasNext()) - { - SysMenu n = (SysMenu) it.next(); - recursionFn(list, n); - } - } - } - } - - /** - * 得到子节点列表 - */ - private List getChildList(List list, SysMenu t) - { - List tlist = new ArrayList(); - Iterator it = list.iterator(); - while (it.hasNext()) - { - SysMenu n = (SysMenu) it.next(); - if (n.getParentId().longValue() == t.getMenuId().longValue()) - { - tlist.add(n); - } - } - return tlist; - } - - /** - * 判断是否有子节点 - */ - private boolean hasChild(List list, SysMenu t) - { - return getChildList(list, t).size() > 0 ? true : false; - } -} +package com.ruoyi.system.service.impl; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.mapper.SysMenuMapper; +import com.ruoyi.system.mapper.SysRoleMenuMapper; +import com.ruoyi.system.service.ISysMenuService; + +/** + * 菜单 业务层处理 + * + * @author ruoyi + */ +@Service +public class SysMenuServiceImpl implements ISysMenuService { + public static final String PREMISSION_STRING = "perms[\"{0}\"]"; + + @Autowired + private SysMenuMapper menuMapper; + + @Autowired + private SysRoleMenuMapper roleMenuMapper; + + /** + * 根据用户查询菜单 + * + * @param user 用户信息 + * @return 菜单列表 + */ + @Override + public List selectMenusByUser(SysUser user) { + List menus = new LinkedList(); + // 管理员显示所有菜单信息 + if (user.isAdmin()) { + menus = menuMapper.selectMenuNormalAll(); + } else { + menus = menuMapper.selectMenusByUserId(user.getUserId()); + } + return getChildPerms(menus, 0); + } + + /** + * 查询菜单集合 + * + * @return 所有菜单信息 + */ + @Override + public List selectMenuList(SysMenu menu, Long userId) { + List menuList = null; + if (SysUser.isAdmin(userId)) { + menuList = menuMapper.selectMenuList(menu); + } else { + menu.getParams().put("userId", userId); + menuList = menuMapper.selectMenuListByUserId(menu); + } + return menuList; + } + + /** + * 查询菜单集合 + * + * @return 所有菜单信息 + */ + @Override + public List selectMenuAll(Long userId) { + List menuList = null; + if (SysUser.isAdmin(userId)) { + menuList = menuMapper.selectMenuAll(); + } else { + menuList = menuMapper.selectMenuAllByUserId(userId); + } + return menuList; + } + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + @Override + public Set selectPermsByUserId(Long userId) { + List perms = menuMapper.selectPermsByUserId(userId); + Set permsSet = new HashSet<>(); + for (String perm : perms) { + if (StringUtils.isNotEmpty(perm)) { + permsSet.addAll(Arrays.asList(perm.trim().split(","))); + } + } + return permsSet; + } + + /** + * 根据角色ID查询菜单 + * + * @param role 角色对象 + * @return 菜单列表 + */ + @Override + public List roleMenuTreeData(SysRole role, Long userId) { + Long roleId = role.getRoleId(); + List ztrees = new ArrayList(); + List menuList = selectMenuAll(userId); + if (StringUtils.isNotNull(roleId)) { + List roleMenuList = menuMapper.selectMenuTree(roleId); + ztrees = initZtree(menuList, roleMenuList, true); + } else { + ztrees = initZtree(menuList, null, true); + } + return ztrees; + } + + /** + * 查询所有菜单 + * + * @return 菜单列表 + */ + @Override + public List menuTreeData(Long userId) { + List menuList = selectMenuAll(userId); + List ztrees = initZtree(menuList); + return ztrees; + } + + /** + * 查询系统所有权限 + * + * @return 权限列表 + */ + @Override + public LinkedHashMap selectPermsAll(Long userId) { + LinkedHashMap section = new LinkedHashMap<>(); + List permissions = selectMenuAll(userId); + if (StringUtils.isNotEmpty(permissions)) { + for (SysMenu menu : permissions) { + section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms())); + } + } + return section; + } + + /** + * 对象转菜单树 + * + * @param menuList 菜单列表 + * @return 树结构列表 + */ + public List initZtree(List menuList) { + return initZtree(menuList, null, false); + } + + /** + * 对象转菜单树 + * + * @param menuList 菜单列表 + * @param roleMenuList 角色已存在菜单列表 + * @param permsFlag 是否需要显示权限标识 + * @return 树结构列表 + */ + public List initZtree(List menuList, List roleMenuList, boolean permsFlag) { + List ztrees = new ArrayList(); + boolean isCheck = StringUtils.isNotNull(roleMenuList); + for (SysMenu menu : menuList) { + Ztree ztree = new Ztree(); + ztree.setId(menu.getMenuId()); + ztree.setpId(menu.getParentId()); + ztree.setName(transMenuName(menu, permsFlag)); + ztree.setTitle(menu.getMenuName()); + if (isCheck) { + ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms())); + } + ztrees.add(ztree); + } + return ztrees; + } + + public String transMenuName(SysMenu menu, boolean permsFlag) { + StringBuffer sb = new StringBuffer(); + sb.append(menu.getMenuName()); + if (permsFlag) { + sb.append("   " + menu.getPerms() + ""); + } + return sb.toString(); + } + + /** + * 删除菜单管理信息 + * + * @param menuId 菜单ID + * @return 结果 + */ + @Override + public int deleteMenuById(Long menuId) { + return menuMapper.deleteMenuById(menuId); + } + + /** + * 根据菜单ID查询信息 + * + * @param menuId 菜单ID + * @return 菜单信息 + */ + @Override + public SysMenu selectMenuById(Long menuId) { + return menuMapper.selectMenuById(menuId); + } + + /** + * 查询子菜单数量 + * + * @param parentId 父级菜单ID + * @return 结果 + */ + @Override + public int selectCountMenuByParentId(Long parentId) { + return menuMapper.selectCountMenuByParentId(parentId); + } + + /** + * 查询菜单使用数量 + * + * @param menuId 菜单ID + * @return 结果 + */ + @Override + public int selectCountRoleMenuByMenuId(Long menuId) { + return roleMenuMapper.selectCountRoleMenuByMenuId(menuId); + } + + /** + * 新增保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + @Override + public int insertMenu(SysMenu menu) { + return menuMapper.insertMenu(menu); + } + + /** + * 修改保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + @Override + public int updateMenu(SysMenu menu) { + return menuMapper.updateMenu(menu); + } + + /** + * 校验菜单名称是否唯一 + * + * @param menu 菜单信息 + * @return 结果 + */ + @Override + public String checkMenuNameUnique(SysMenu menu) { + Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); + SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); + if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) { + return UserConstants.MENU_NAME_NOT_UNIQUE; + } + return UserConstants.MENU_NAME_UNIQUE; + } + + /** + * 根据父节点的ID获取所有子节点 + * + * @param list 分类表 + * @param parentId 传入的父节点ID + * @return String + */ + public List getChildPerms(List list, int parentId) { + List returnList = new ArrayList(); + for (Iterator iterator = list.iterator(); iterator.hasNext(); ) { + SysMenu t = (SysMenu) iterator.next(); + // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点 + if (t.getParentId() == parentId) { + recursionFn(list, t); + returnList.add(t); + } + } + return returnList; + } + + /** + * 递归列表 + * + * @param list + * @param t + */ + private void recursionFn(List list, SysMenu t) { + // 得到子节点列表 + List childList = getChildList(list, t); + t.setChildren(childList); + for (SysMenu tChild : childList) { + if (hasChild(list, tChild)) { + // 判断是否有子节点 + Iterator it = childList.iterator(); + while (it.hasNext()) { + SysMenu n = (SysMenu) it.next(); + recursionFn(list, n); + } + } + } + } + + /** + * 得到子节点列表 + */ + private List getChildList(List list, SysMenu t) { + List tlist = new ArrayList(); + Iterator it = list.iterator(); + while (it.hasNext()) { + SysMenu n = (SysMenu) it.next(); + if (n.getParentId().longValue() == t.getMenuId().longValue()) { + tlist.add(n); + } + } + return tlist; + } + + /** + * 判断是否有子节点 + */ + private boolean hasChild(List list, SysMenu t) { + return getChildList(list, t).size() > 0 ? true : false; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java index 0f4814d0a..6d76b75fd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java @@ -1,82 +1,77 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.system.domain.SysNotice; -import com.ruoyi.system.mapper.SysNoticeMapper; -import com.ruoyi.system.service.ISysNoticeService; - -/** - * 公告 服务层实现 - * - * @author ruoyi - * @date 2018-06-25 - */ -@Service -public class SysNoticeServiceImpl implements ISysNoticeService -{ - @Autowired - private SysNoticeMapper noticeMapper; - - /** - * 查询公告信息 - * - * @param noticeId 公告ID - * @return 公告信息 - */ - @Override - public SysNotice selectNoticeById(Long noticeId) - { - return noticeMapper.selectNoticeById(noticeId); - } - - /** - * 查询公告列表 - * - * @param notice 公告信息 - * @return 公告集合 - */ - @Override - public List selectNoticeList(SysNotice notice) - { - return noticeMapper.selectNoticeList(notice); - } - - /** - * 新增公告 - * - * @param notice 公告信息 - * @return 结果 - */ - @Override - public int insertNotice(SysNotice notice) - { - return noticeMapper.insertNotice(notice); - } - - /** - * 修改公告 - * - * @param notice 公告信息 - * @return 结果 - */ - @Override - public int updateNotice(SysNotice notice) - { - return noticeMapper.updateNotice(notice); - } - - /** - * 删除公告对象 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - public int deleteNoticeByIds(String ids) - { - return noticeMapper.deleteNoticeByIds(Convert.toStrArray(ids)); - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.system.domain.SysNotice; +import com.ruoyi.system.mapper.SysNoticeMapper; +import com.ruoyi.system.service.ISysNoticeService; + +/** + * 公告 服务层实现 + * + * @author ruoyi + * @date 2018-06-25 + */ +@Service +public class SysNoticeServiceImpl implements ISysNoticeService { + @Autowired + private SysNoticeMapper noticeMapper; + + /** + * 查询公告信息 + * + * @param noticeId 公告ID + * @return 公告信息 + */ + @Override + public SysNotice selectNoticeById(Long noticeId) { + return noticeMapper.selectNoticeById(noticeId); + } + + /** + * 查询公告列表 + * + * @param notice 公告信息 + * @return 公告集合 + */ + @Override + public List selectNoticeList(SysNotice notice) { + return noticeMapper.selectNoticeList(notice); + } + + /** + * 新增公告 + * + * @param notice 公告信息 + * @return 结果 + */ + @Override + public int insertNotice(SysNotice notice) { + return noticeMapper.insertNotice(notice); + } + + /** + * 修改公告 + * + * @param notice 公告信息 + * @return 结果 + */ + @Override + public int updateNotice(SysNotice notice) { + return noticeMapper.updateNotice(notice); + } + + /** + * 删除公告对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteNoticeByIds(String ids) { + return noticeMapper.deleteNoticeByIds(Convert.toStrArray(ids)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java index c79668b2e..69ff4450e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java @@ -1,77 +1,72 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.mapper.SysOperLogMapper; -import com.ruoyi.system.service.ISysOperLogService; - -/** - * 操作日志 服务层处理 - * - * @author ruoyi - */ -@Service -public class SysOperLogServiceImpl implements ISysOperLogService -{ - @Autowired - private SysOperLogMapper operLogMapper; - - /** - * 新增操作日志 - * - * @param operLog 操作日志对象 - */ - @Override - public void insertOperlog(SysOperLog operLog) - { - operLogMapper.insertOperlog(operLog); - } - - /** - * 查询系统操作日志集合 - * - * @param operLog 操作日志对象 - * @return 操作日志集合 - */ - @Override - public List selectOperLogList(SysOperLog operLog) - { - return operLogMapper.selectOperLogList(operLog); - } - - /** - * 批量删除系统操作日志 - * - * @param ids 需要删除的数据 - * @return - */ - @Override - public int deleteOperLogByIds(String ids) - { - return operLogMapper.deleteOperLogByIds(Convert.toStrArray(ids)); - } - - /** - * 查询操作日志详细 - * - * @param operId 操作ID - * @return 操作日志对象 - */ - @Override - public SysOperLog selectOperLogById(Long operId) - { - return operLogMapper.selectOperLogById(operId); - } - - /** - * 清空操作日志 - */ - @Override - public void cleanOperLog() - { - operLogMapper.cleanOperLog(); - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.system.domain.SysOperLog; +import com.ruoyi.system.mapper.SysOperLogMapper; +import com.ruoyi.system.service.ISysOperLogService; + +/** + * 操作日志 服务层处理 + * + * @author ruoyi + */ +@Service +public class SysOperLogServiceImpl implements ISysOperLogService { + @Autowired + private SysOperLogMapper operLogMapper; + + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + @Override + public void insertOperlog(SysOperLog operLog) { + operLogMapper.insertOperlog(operLog); + } + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + @Override + public List selectOperLogList(SysOperLog operLog) { + return operLogMapper.selectOperLogList(operLog); + } + + /** + * 批量删除系统操作日志 + * + * @param ids 需要删除的数据 + * @return + */ + @Override + public int deleteOperLogByIds(String ids) { + return operLogMapper.deleteOperLogByIds(Convert.toStrArray(ids)); + } + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + @Override + public SysOperLog selectOperLogById(Long operId) { + return operLogMapper.selectOperLogById(operId); + } + + /** + * 清空操作日志 + */ + @Override + public void cleanOperLog() { + operLogMapper.cleanOperLog(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java index 885b89240..95117e28c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java @@ -1,181 +1,164 @@ -package com.ruoyi.system.service.impl; - -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.mapper.SysPostMapper; -import com.ruoyi.system.mapper.SysUserPostMapper; -import com.ruoyi.system.service.ISysPostService; - -/** - * 岗位信息 服务层处理 - * - * @author ruoyi - */ -@Service -public class SysPostServiceImpl implements ISysPostService -{ - @Autowired - private SysPostMapper postMapper; - - @Autowired - private SysUserPostMapper userPostMapper; - - /** - * 查询岗位信息集合 - * - * @param post 岗位信息 - * @return 岗位信息集合 - */ - @Override - public List selectPostList(SysPost post) - { - return postMapper.selectPostList(post); - } - - /** - * 查询所有岗位 - * - * @return 岗位列表 - */ - @Override - public List selectPostAll() - { - return postMapper.selectPostAll(); - } - - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - @Override - public List selectPostsByUserId(Long userId) - { - List userPosts = postMapper.selectPostsByUserId(userId); - List posts = postMapper.selectPostAll(); - for (SysPost post : posts) - { - for (SysPost userRole : userPosts) - { - if (post.getPostId().longValue() == userRole.getPostId().longValue()) - { - post.setFlag(true); - break; - } - } - } - return posts; - } - - /** - * 通过岗位ID查询岗位信息 - * - * @param postId 岗位ID - * @return 角色对象信息 - */ - @Override - public SysPost selectPostById(Long postId) - { - return postMapper.selectPostById(postId); - } - - /** - * 批量删除岗位信息 - * - * @param ids 需要删除的数据ID - * @throws Exception - */ - @Override - public int deletePostByIds(String ids) throws BusinessException - { - Long[] postIds = Convert.toLongArray(ids); - for (Long postId : postIds) - { - SysPost post = selectPostById(postId); - if (countUserPostById(postId) > 0) - { - throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName())); - } - } - return postMapper.deletePostByIds(postIds); - } - - /** - * 新增保存岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - @Override - public int insertPost(SysPost post) - { - return postMapper.insertPost(post); - } - - /** - * 修改保存岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - @Override - public int updatePost(SysPost post) - { - return postMapper.updatePost(post); - } - - /** - * 通过岗位ID查询岗位使用数量 - * - * @param postId 岗位ID - * @return 结果 - */ - @Override - public int countUserPostById(Long postId) - { - return userPostMapper.countUserPostById(postId); - } - - /** - * 校验岗位名称是否唯一 - * - * @param post 岗位信息 - * @return 结果 - */ - @Override - public String checkPostNameUnique(SysPost post) - { - Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); - SysPost info = postMapper.checkPostNameUnique(post.getPostName()); - if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) - { - return UserConstants.POST_NAME_NOT_UNIQUE; - } - return UserConstants.POST_NAME_UNIQUE; - } - - /** - * 校验岗位编码是否唯一 - * - * @param post 岗位信息 - * @return 结果 - */ - @Override - public String checkPostCodeUnique(SysPost post) - { - Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); - SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); - if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) - { - return UserConstants.POST_CODE_NOT_UNIQUE; - } - return UserConstants.POST_CODE_UNIQUE; - } -} +package com.ruoyi.system.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.mapper.SysPostMapper; +import com.ruoyi.system.mapper.SysUserPostMapper; +import com.ruoyi.system.service.ISysPostService; + +/** + * 岗位信息 服务层处理 + * + * @author ruoyi + */ +@Service +public class SysPostServiceImpl implements ISysPostService { + @Autowired + private SysPostMapper postMapper; + + @Autowired + private SysUserPostMapper userPostMapper; + + /** + * 查询岗位信息集合 + * + * @param post 岗位信息 + * @return 岗位信息集合 + */ + @Override + public List selectPostList(SysPost post) { + return postMapper.selectPostList(post); + } + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + @Override + public List selectPostAll() { + return postMapper.selectPostAll(); + } + + /** + * 根据用户ID查询岗位 + * + * @param userId 用户ID + * @return 岗位列表 + */ + @Override + public List selectPostsByUserId(Long userId) { + List userPosts = postMapper.selectPostsByUserId(userId); + List posts = postMapper.selectPostAll(); + for (SysPost post : posts) { + for (SysPost userRole : userPosts) { + if (post.getPostId().longValue() == userRole.getPostId().longValue()) { + post.setFlag(true); + break; + } + } + } + return posts; + } + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + @Override + public SysPost selectPostById(Long postId) { + return postMapper.selectPostById(postId); + } + + /** + * 批量删除岗位信息 + * + * @param ids 需要删除的数据ID + * @throws Exception + */ + @Override + public int deletePostByIds(String ids) throws BusinessException { + Long[] postIds = Convert.toLongArray(ids); + for (Long postId : postIds) { + SysPost post = selectPostById(postId); + if (countUserPostById(postId) > 0) { + throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName())); + } + } + return postMapper.deletePostByIds(postIds); + } + + /** + * 新增保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public int insertPost(SysPost post) { + return postMapper.insertPost(post); + } + + /** + * 修改保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public int updatePost(SysPost post) { + return postMapper.updatePost(post); + } + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + @Override + public int countUserPostById(Long postId) { + return userPostMapper.countUserPostById(postId); + } + + /** + * 校验岗位名称是否唯一 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public String checkPostNameUnique(SysPost post) { + Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); + SysPost info = postMapper.checkPostNameUnique(post.getPostName()); + if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { + return UserConstants.POST_NAME_NOT_UNIQUE; + } + return UserConstants.POST_NAME_UNIQUE; + } + + /** + * 校验岗位编码是否唯一 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public String checkPostCodeUnique(SysPost post) { + Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); + SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); + if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { + return UserConstants.POST_CODE_NOT_UNIQUE; + } + return UserConstants.POST_CODE_UNIQUE; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index 0f51e474e..fc696fa82 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -1,379 +1,344 @@ -package com.ruoyi.system.service.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.annotation.DataScope; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.spring.SpringUtils; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysRoleDept; -import com.ruoyi.system.domain.SysRoleMenu; -import com.ruoyi.system.domain.SysUserRole; -import com.ruoyi.system.mapper.SysRoleDeptMapper; -import com.ruoyi.system.mapper.SysRoleMapper; -import com.ruoyi.system.mapper.SysRoleMenuMapper; -import com.ruoyi.system.mapper.SysUserRoleMapper; -import com.ruoyi.system.service.ISysRoleService; - -/** - * 角色 业务层处理 - * - * @author ruoyi - */ -@Service -public class SysRoleServiceImpl implements ISysRoleService -{ - @Autowired - private SysRoleMapper roleMapper; - - @Autowired - private SysRoleMenuMapper roleMenuMapper; - - @Autowired - private SysUserRoleMapper userRoleMapper; - - @Autowired - private SysRoleDeptMapper roleDeptMapper; - - /** - * 根据条件分页查询角色数据 - * - * @param role 角色信息 - * @return 角色数据集合信息 - */ - @Override - @DataScope(deptAlias = "d") - public List selectRoleList(SysRole role) - { - return roleMapper.selectRoleList(role); - } - - /** - * 根据用户ID查询权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - @Override - public Set selectRoleKeys(Long userId) - { - List perms = roleMapper.selectRolesByUserId(userId); - Set permsSet = new HashSet<>(); - for (SysRole perm : perms) - { - if (StringUtils.isNotNull(perm)) - { - permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); - } - } - return permsSet; - } - - /** - * 根据用户ID查询角色 - * - * @param userId 用户ID - * @return 角色列表 - */ - @Override - public List selectRolesByUserId(Long userId) - { - List userRoles = roleMapper.selectRolesByUserId(userId); - List roles = selectRoleAll(); - for (SysRole role : roles) - { - for (SysRole userRole : userRoles) - { - if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) - { - role.setFlag(true); - break; - } - } - } - return roles; - } - - /** - * 查询所有角色 - * - * @return 角色列表 - */ - @Override - public List selectRoleAll() - { - return SpringUtils.getAopProxy(this).selectRoleList(new SysRole()); - } - - /** - * 通过角色ID查询角色 - * - * @param roleId 角色ID - * @return 角色对象信息 - */ - @Override - public SysRole selectRoleById(Long roleId) - { - return roleMapper.selectRoleById(roleId); - } - - /** - * 通过角色ID删除角色 - * - * @param roleId 角色ID - * @return 结果 - */ - @Override - public boolean deleteRoleById(Long roleId) - { - return roleMapper.deleteRoleById(roleId) > 0 ? true : false; - } - - /** - * 批量删除角色信息 - * - * @param ids 需要删除的数据ID - * @throws Exception - */ - @Override - public int deleteRoleByIds(String ids) throws BusinessException - { - Long[] roleIds = Convert.toLongArray(ids); - for (Long roleId : roleIds) - { - checkRoleAllowed(new SysRole(roleId)); - SysRole role = selectRoleById(roleId); - if (countUserRoleByRoleId(roleId) > 0) - { - throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName())); - } - } - return roleMapper.deleteRoleByIds(roleIds); - } - - /** - * 新增保存角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - @Transactional - public int insertRole(SysRole role) - { - // 新增角色信息 - roleMapper.insertRole(role); - return insertRoleMenu(role); - } - - /** - * 修改保存角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - @Transactional - public int updateRole(SysRole role) - { - // 修改角色信息 - roleMapper.updateRole(role); - // 删除角色与菜单关联 - roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId()); - return insertRoleMenu(role); - } - - /** - * 修改数据权限信息 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - @Transactional - public int authDataScope(SysRole role) - { - // 修改角色信息 - roleMapper.updateRole(role); - // 删除角色与部门关联 - roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId()); - // 新增角色和部门信息(数据权限) - return insertRoleDept(role); - } - - /** - * 新增角色菜单信息 - * - * @param role 角色对象 - */ - public int insertRoleMenu(SysRole role) - { - int rows = 1; - // 新增用户与角色管理 - List list = new ArrayList(); - for (Long menuId : role.getMenuIds()) - { - SysRoleMenu rm = new SysRoleMenu(); - rm.setRoleId(role.getRoleId()); - rm.setMenuId(menuId); - list.add(rm); - } - if (list.size() > 0) - { - rows = roleMenuMapper.batchRoleMenu(list); - } - return rows; - } - - /** - * 新增角色部门信息(数据权限) - * - * @param role 角色对象 - */ - public int insertRoleDept(SysRole role) - { - int rows = 1; - // 新增角色与部门(数据权限)管理 - List list = new ArrayList(); - for (Long deptId : role.getDeptIds()) - { - SysRoleDept rd = new SysRoleDept(); - rd.setRoleId(role.getRoleId()); - rd.setDeptId(deptId); - list.add(rd); - } - if (list.size() > 0) - { - rows = roleDeptMapper.batchRoleDept(list); - } - return rows; - } - - /** - * 校验角色名称是否唯一 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - public String checkRoleNameUnique(SysRole role) - { - Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); - SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); - if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) - { - return UserConstants.ROLE_NAME_NOT_UNIQUE; - } - return UserConstants.ROLE_NAME_UNIQUE; - } - - /** - * 校验角色权限是否唯一 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - public String checkRoleKeyUnique(SysRole role) - { - Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); - SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); - if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) - { - return UserConstants.ROLE_KEY_NOT_UNIQUE; - } - return UserConstants.ROLE_KEY_UNIQUE; - } - - /** - * 校验角色是否允许操作 - * - * @param role 角色信息 - */ - public void checkRoleAllowed(SysRole role) - { - if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) - { - throw new BusinessException("不允许操作超级管理员角色"); - } - } - - /** - * 通过角色ID查询角色使用数量 - * - * @param roleId 角色ID - * @return 结果 - */ - @Override - public int countUserRoleByRoleId(Long roleId) - { - return userRoleMapper.countUserRoleByRoleId(roleId); - } - - /** - * 角色状态修改 - * - * @param role 角色信息 - * @return 结果 - */ - @Override - public int changeStatus(SysRole role) - { - return roleMapper.updateRole(role); - } - - /** - * 取消授权用户角色 - * - * @param userRole 用户和角色关联信息 - * @return 结果 - */ - @Override - public int deleteAuthUser(SysUserRole userRole) - { - return userRoleMapper.deleteUserRoleInfo(userRole); - } - - /** - * 批量取消授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int deleteAuthUsers(Long roleId, String userIds) - { - return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds)); - } - - /** - * 批量选择授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int insertAuthUsers(Long roleId, String userIds) - { - Long[] users = Convert.toLongArray(userIds); - // 新增用户与角色管理 - List list = new ArrayList(); - for (Long userId : users) - { - SysUserRole ur = new SysUserRole(); - ur.setUserId(userId); - ur.setRoleId(roleId); - list.add(ur); - } - return userRoleMapper.batchUserRole(list); - } -} +package com.ruoyi.system.service.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysRoleDept; +import com.ruoyi.system.domain.SysRoleMenu; +import com.ruoyi.system.domain.SysUserRole; +import com.ruoyi.system.mapper.SysRoleDeptMapper; +import com.ruoyi.system.mapper.SysRoleMapper; +import com.ruoyi.system.mapper.SysRoleMenuMapper; +import com.ruoyi.system.mapper.SysUserRoleMapper; +import com.ruoyi.system.service.ISysRoleService; + +/** + * 角色 业务层处理 + * + * @author ruoyi + */ +@Service +public class SysRoleServiceImpl implements ISysRoleService { + @Autowired + private SysRoleMapper roleMapper; + + @Autowired + private SysRoleMenuMapper roleMenuMapper; + + @Autowired + private SysUserRoleMapper userRoleMapper; + + @Autowired + private SysRoleDeptMapper roleDeptMapper; + + /** + * 根据条件分页查询角色数据 + * + * @param role 角色信息 + * @return 角色数据集合信息 + */ + @Override + @DataScope(deptAlias = "d") + public List selectRoleList(SysRole role) { + return roleMapper.selectRoleList(role); + } + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + @Override + public Set selectRoleKeys(Long userId) { + List perms = roleMapper.selectRolesByUserId(userId); + Set permsSet = new HashSet<>(); + for (SysRole perm : perms) { + if (StringUtils.isNotNull(perm)) { + permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); + } + } + return permsSet; + } + + /** + * 根据用户ID查询角色 + * + * @param userId 用户ID + * @return 角色列表 + */ + @Override + public List selectRolesByUserId(Long userId) { + List userRoles = roleMapper.selectRolesByUserId(userId); + List roles = selectRoleAll(); + for (SysRole role : roles) { + for (SysRole userRole : userRoles) { + if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { + role.setFlag(true); + break; + } + } + } + return roles; + } + + /** + * 查询所有角色 + * + * @return 角色列表 + */ + @Override + public List selectRoleAll() { + return SpringUtils.getAopProxy(this).selectRoleList(new SysRole()); + } + + /** + * 通过角色ID查询角色 + * + * @param roleId 角色ID + * @return 角色对象信息 + */ + @Override + public SysRole selectRoleById(Long roleId) { + return roleMapper.selectRoleById(roleId); + } + + /** + * 通过角色ID删除角色 + * + * @param roleId 角色ID + * @return 结果 + */ + @Override + public boolean deleteRoleById(Long roleId) { + return roleMapper.deleteRoleById(roleId) > 0 ? true : false; + } + + /** + * 批量删除角色信息 + * + * @param ids 需要删除的数据ID + * @throws Exception + */ + @Override + public int deleteRoleByIds(String ids) throws BusinessException { + Long[] roleIds = Convert.toLongArray(ids); + for (Long roleId : roleIds) { + checkRoleAllowed(new SysRole(roleId)); + SysRole role = selectRoleById(roleId); + if (countUserRoleByRoleId(roleId) > 0) { + throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName())); + } + } + return roleMapper.deleteRoleByIds(roleIds); + } + + /** + * 新增保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int insertRole(SysRole role) { + // 新增角色信息 + roleMapper.insertRole(role); + return insertRoleMenu(role); + } + + /** + * 修改保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int updateRole(SysRole role) { + // 修改角色信息 + roleMapper.updateRole(role); + // 删除角色与菜单关联 + roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId()); + return insertRoleMenu(role); + } + + /** + * 修改数据权限信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int authDataScope(SysRole role) { + // 修改角色信息 + roleMapper.updateRole(role); + // 删除角色与部门关联 + roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId()); + // 新增角色和部门信息(数据权限) + return insertRoleDept(role); + } + + /** + * 新增角色菜单信息 + * + * @param role 角色对象 + */ + public int insertRoleMenu(SysRole role) { + int rows = 1; + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long menuId : role.getMenuIds()) { + SysRoleMenu rm = new SysRoleMenu(); + rm.setRoleId(role.getRoleId()); + rm.setMenuId(menuId); + list.add(rm); + } + if (list.size() > 0) { + rows = roleMenuMapper.batchRoleMenu(list); + } + return rows; + } + + /** + * 新增角色部门信息(数据权限) + * + * @param role 角色对象 + */ + public int insertRoleDept(SysRole role) { + int rows = 1; + // 新增角色与部门(数据权限)管理 + List list = new ArrayList(); + for (Long deptId : role.getDeptIds()) { + SysRoleDept rd = new SysRoleDept(); + rd.setRoleId(role.getRoleId()); + rd.setDeptId(deptId); + list.add(rd); + } + if (list.size() > 0) { + rows = roleDeptMapper.batchRoleDept(list); + } + return rows; + } + + /** + * 校验角色名称是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public String checkRoleNameUnique(SysRole role) { + Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); + SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); + if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { + return UserConstants.ROLE_NAME_NOT_UNIQUE; + } + return UserConstants.ROLE_NAME_UNIQUE; + } + + /** + * 校验角色权限是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public String checkRoleKeyUnique(SysRole role) { + Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); + SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); + if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { + return UserConstants.ROLE_KEY_NOT_UNIQUE; + } + return UserConstants.ROLE_KEY_UNIQUE; + } + + /** + * 校验角色是否允许操作 + * + * @param role 角色信息 + */ + public void checkRoleAllowed(SysRole role) { + if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) { + throw new BusinessException("不允许操作超级管理员角色"); + } + } + + /** + * 通过角色ID查询角色使用数量 + * + * @param roleId 角色ID + * @return 结果 + */ + @Override + public int countUserRoleByRoleId(Long roleId) { + return userRoleMapper.countUserRoleByRoleId(roleId); + } + + /** + * 角色状态修改 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public int changeStatus(SysRole role) { + return roleMapper.updateRole(role); + } + + /** + * 取消授权用户角色 + * + * @param userRole 用户和角色关联信息 + * @return 结果 + */ + @Override + public int deleteAuthUser(SysUserRole userRole) { + return userRoleMapper.deleteUserRoleInfo(userRole); + } + + /** + * 批量取消授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int deleteAuthUsers(Long roleId, String userIds) { + return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds)); + } + + /** + * 批量选择授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int insertAuthUsers(Long roleId, String userIds) { + Long[] users = Convert.toLongArray(userIds); + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long userId : users) { + SysUserRole ur = new SysUserRole(); + ur.setUserId(userId); + ur.setRoleId(roleId); + list.add(ur); + } + return userRoleMapper.batchUserRole(list); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java index b9d6f1d24..7dde6550c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java @@ -1,115 +1,105 @@ -package com.ruoyi.system.service.impl; - -import java.util.Date; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.mapper.SysUserOnlineMapper; -import com.ruoyi.system.service.ISysUserOnlineService; - -/** - * 在线用户 服务层处理 - * - * @author ruoyi - */ -@Service -public class SysUserOnlineServiceImpl implements ISysUserOnlineService -{ - @Autowired - private SysUserOnlineMapper userOnlineDao; - - /** - * 通过会话序号查询信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - @Override - public SysUserOnline selectOnlineById(String sessionId) - { - return userOnlineDao.selectOnlineById(sessionId); - } - - /** - * 通过会话序号删除信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - @Override - public void deleteOnlineById(String sessionId) - { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) - { - userOnlineDao.deleteOnlineById(sessionId); - } - } - - /** - * 通过会话序号删除信息 - * - * @param sessions 会话ID集合 - * @return 在线用户信息 - */ - @Override - public void batchDeleteOnline(List sessions) - { - for (String sessionId : sessions) - { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) - { - userOnlineDao.deleteOnlineById(sessionId); - } - } - } - - /** - * 保存会话信息 - * - * @param online 会话信息 - */ - @Override - public void saveOnline(SysUserOnline online) - { - userOnlineDao.saveOnline(online); - } - - /** - * 查询会话集合 - * - * @param userOnline 在线用户 - */ - @Override - public List selectUserOnlineList(SysUserOnline userOnline) - { - return userOnlineDao.selectUserOnlineList(userOnline); - } - - /** - * 强退用户 - * - * @param sessionId 会话ID - */ - @Override - public void forceLogout(String sessionId) - { - userOnlineDao.deleteOnlineById(sessionId); - } - - /** - * 查询会话集合 - * - * @param expiredDate 失效日期 - */ - @Override - public List selectOnlineByExpired(Date expiredDate) - { - String lastAccessTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiredDate); - return userOnlineDao.selectOnlineByExpired(lastAccessTime); - } -} +package com.ruoyi.system.service.impl; + +import java.util.Date; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.mapper.SysUserOnlineMapper; +import com.ruoyi.system.service.ISysUserOnlineService; + +/** + * 在线用户 服务层处理 + * + * @author ruoyi + */ +@Service +public class SysUserOnlineServiceImpl implements ISysUserOnlineService { + @Autowired + private SysUserOnlineMapper userOnlineDao; + + /** + * 通过会话序号查询信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + @Override + public SysUserOnline selectOnlineById(String sessionId) { + return userOnlineDao.selectOnlineById(sessionId); + } + + /** + * 通过会话序号删除信息 + * + * @param sessionId 会话ID + * @return 在线用户信息 + */ + @Override + public void deleteOnlineById(String sessionId) { + SysUserOnline userOnline = selectOnlineById(sessionId); + if (StringUtils.isNotNull(userOnline)) { + userOnlineDao.deleteOnlineById(sessionId); + } + } + + /** + * 通过会话序号删除信息 + * + * @param sessions 会话ID集合 + * @return 在线用户信息 + */ + @Override + public void batchDeleteOnline(List sessions) { + for (String sessionId : sessions) { + SysUserOnline userOnline = selectOnlineById(sessionId); + if (StringUtils.isNotNull(userOnline)) { + userOnlineDao.deleteOnlineById(sessionId); + } + } + } + + /** + * 保存会话信息 + * + * @param online 会话信息 + */ + @Override + public void saveOnline(SysUserOnline online) { + userOnlineDao.saveOnline(online); + } + + /** + * 查询会话集合 + * + * @param userOnline 在线用户 + */ + @Override + public List selectUserOnlineList(SysUserOnline userOnline) { + return userOnlineDao.selectUserOnlineList(userOnline); + } + + /** + * 强退用户 + * + * @param sessionId 会话ID + */ + @Override + public void forceLogout(String sessionId) { + userOnlineDao.deleteOnlineById(sessionId); + } + + /** + * 查询会话集合 + * + * @param expiredDate 失效日期 + */ + @Override + public List selectOnlineByExpired(Date expiredDate) { + String lastAccessTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiredDate); + return userOnlineDao.selectOnlineByExpired(lastAccessTime); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 29ade1579..67ec8eaf8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -1,480 +1,429 @@ -package com.ruoyi.system.service.impl; - -import java.util.ArrayList; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.annotation.DataScope; -import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.common.exception.BusinessException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.security.Md5Utils; -import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.domain.SysUserPost; -import com.ruoyi.system.domain.SysUserRole; -import com.ruoyi.system.mapper.SysPostMapper; -import com.ruoyi.system.mapper.SysRoleMapper; -import com.ruoyi.system.mapper.SysUserMapper; -import com.ruoyi.system.mapper.SysUserPostMapper; -import com.ruoyi.system.mapper.SysUserRoleMapper; -import com.ruoyi.system.service.ISysConfigService; -import com.ruoyi.system.service.ISysUserService; - -/** - * 用户 业务层处理 - * - * @author ruoyi - */ -@Service -public class SysUserServiceImpl implements ISysUserService -{ - private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); - - @Autowired - private SysUserMapper userMapper; - - @Autowired - private SysRoleMapper roleMapper; - - @Autowired - private SysPostMapper postMapper; - - @Autowired - private SysUserPostMapper userPostMapper; - - @Autowired - private SysUserRoleMapper userRoleMapper; - - @Autowired - private ISysConfigService configService; - - /** - * 根据条件分页查询用户列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - @Override - @DataScope(deptAlias = "d", userAlias = "u") - public List selectUserList(SysUser user) - { - return userMapper.selectUserList(user); - } - - /** - * 根据条件分页查询已分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - @DataScope(deptAlias = "d", userAlias = "u") - public List selectAllocatedList(SysUser user) - { - return userMapper.selectAllocatedList(user); - } - - /** - * 根据条件分页查询未分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - @DataScope(deptAlias = "d", userAlias = "u") - public List selectUnallocatedList(SysUser user) - { - return userMapper.selectUnallocatedList(user); - } - - /** - * 通过用户名查询用户 - * - * @param userName 用户名 - * @return 用户对象信息 - */ - @Override - public SysUser selectUserByLoginName(String userName) - { - return userMapper.selectUserByLoginName(userName); - } - - /** - * 通过手机号码查询用户 - * - * @param phoneNumber 手机号码 - * @return 用户对象信息 - */ - @Override - public SysUser selectUserByPhoneNumber(String phoneNumber) - { - return userMapper.selectUserByPhoneNumber(phoneNumber); - } - - /** - * 通过邮箱查询用户 - * - * @param email 邮箱 - * @return 用户对象信息 - */ - @Override - public SysUser selectUserByEmail(String email) - { - return userMapper.selectUserByEmail(email); - } - - /** - * 通过用户ID查询用户 - * - * @param userId 用户ID - * @return 用户对象信息 - */ - @Override - public SysUser selectUserById(Long userId) - { - return userMapper.selectUserById(userId); - } - - /** - * 通过用户ID删除用户 - * - * @param userId 用户ID - * @return 结果 - */ - @Override - public int deleteUserById(Long userId) - { - // 删除用户与角色关联 - userRoleMapper.deleteUserRoleByUserId(userId); - // 删除用户与岗位表 - userPostMapper.deleteUserPostByUserId(userId); - return userMapper.deleteUserById(userId); - } - - /** - * 批量删除用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - public int deleteUserByIds(String ids) throws BusinessException - { - Long[] userIds = Convert.toLongArray(ids); - for (Long userId : userIds) - { - checkUserAllowed(new SysUser(userId)); - } - return userMapper.deleteUserByIds(userIds); - } - - /** - * 新增保存用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - @Override - @Transactional - public int insertUser(SysUser user) - { - // 新增用户信息 - int rows = userMapper.insertUser(user); - // 新增用户岗位关联 - insertUserPost(user); - // 新增用户与角色管理 - insertUserRole(user); - return rows; - } - - /** - * 修改保存用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - @Override - @Transactional - public int updateUser(SysUser user) - { - Long userId = user.getUserId(); - // 删除用户与角色关联 - userRoleMapper.deleteUserRoleByUserId(userId); - // 新增用户与角色管理 - insertUserRole(user); - // 删除用户与岗位关联 - userPostMapper.deleteUserPostByUserId(userId); - // 新增用户与岗位管理 - insertUserPost(user); - return userMapper.updateUser(user); - } - - /** - * 修改用户个人详细信息 - * - * @param user 用户信息 - * @return 结果 - */ - @Override - public int updateUserInfo(SysUser user) - { - return userMapper.updateUser(user); - } - - /** - * 修改用户密码 - * - * @param user 用户信息 - * @return 结果 - */ - @Override - public int resetUserPwd(SysUser user) - { - return updateUserInfo(user); - } - - /** - * 新增用户角色信息 - * - * @param user 用户对象 - */ - public void insertUserRole(SysUser user) - { - Long[] roles = user.getRoleIds(); - if (StringUtils.isNotNull(roles)) - { - // 新增用户与角色管理 - List list = new ArrayList(); - for (Long roleId : roles) - { - SysUserRole ur = new SysUserRole(); - ur.setUserId(user.getUserId()); - ur.setRoleId(roleId); - list.add(ur); - } - if (list.size() > 0) - { - userRoleMapper.batchUserRole(list); - } - } - } - - /** - * 新增用户岗位信息 - * - * @param user 用户对象 - */ - public void insertUserPost(SysUser user) - { - Long[] posts = user.getPostIds(); - if (StringUtils.isNotNull(posts)) - { - // 新增用户与岗位管理 - List list = new ArrayList(); - for (Long postId : posts) - { - SysUserPost up = new SysUserPost(); - up.setUserId(user.getUserId()); - up.setPostId(postId); - list.add(up); - } - if (list.size() > 0) - { - userPostMapper.batchUserPost(list); - } - } - } - - /** - * 校验登录名称是否唯一 - * - * @param loginName 用户名 - * @return - */ - @Override - public String checkLoginNameUnique(String loginName) - { - int count = userMapper.checkLoginNameUnique(loginName); - if (count > 0) - { - return UserConstants.USER_NAME_NOT_UNIQUE; - } - return UserConstants.USER_NAME_UNIQUE; - } - - /** - * 校验用户名称是否唯一 - * - * @param user 用户信息 - * @return - */ - @Override - public String checkPhoneUnique(SysUser user) - { - Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); - SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); - if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) - { - return UserConstants.USER_PHONE_NOT_UNIQUE; - } - return UserConstants.USER_PHONE_UNIQUE; - } - - /** - * 校验email是否唯一 - * - * @param user 用户信息 - * @return - */ - @Override - public String checkEmailUnique(SysUser user) - { - Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); - SysUser info = userMapper.checkEmailUnique(user.getEmail()); - if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) - { - return UserConstants.USER_EMAIL_NOT_UNIQUE; - } - return UserConstants.USER_EMAIL_UNIQUE; - } - - /** - * 校验用户是否允许操作 - * - * @param user 用户信息 - */ - public void checkUserAllowed(SysUser user) - { - if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) - { - throw new BusinessException("不允许操作超级管理员用户"); - } - } - - /** - * 查询用户所属角色组 - * - * @param userId 用户ID - * @return 结果 - */ - @Override - public String selectUserRoleGroup(Long userId) - { - List list = roleMapper.selectRolesByUserId(userId); - StringBuffer idsStr = new StringBuffer(); - for (SysRole role : list) - { - idsStr.append(role.getRoleName()).append(","); - } - if (StringUtils.isNotEmpty(idsStr.toString())) - { - return idsStr.substring(0, idsStr.length() - 1); - } - return idsStr.toString(); - } - - /** - * 查询用户所属岗位组 - * - * @param userId 用户ID - * @return 结果 - */ - @Override - public String selectUserPostGroup(Long userId) - { - List list = postMapper.selectPostsByUserId(userId); - StringBuffer idsStr = new StringBuffer(); - for (SysPost post : list) - { - idsStr.append(post.getPostName()).append(","); - } - if (StringUtils.isNotEmpty(idsStr.toString())) - { - return idsStr.substring(0, idsStr.length() - 1); - } - return idsStr.toString(); - } - - /** - * 导入用户数据 - * - * @param userList 用户数据列表 - * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 - * @param operName 操作用户 - * @return 结果 - */ - @Override - public String importUser(List userList, Boolean isUpdateSupport, String operName) - { - if (StringUtils.isNull(userList) || userList.size() == 0) - { - throw new BusinessException("导入用户数据不能为空!"); - } - int successNum = 0; - int failureNum = 0; - StringBuilder successMsg = new StringBuilder(); - StringBuilder failureMsg = new StringBuilder(); - String password = configService.selectConfigByKey("sys.user.initPassword"); - for (SysUser user : userList) - { - try - { - // 验证是否存在这个用户 - SysUser u = userMapper.selectUserByLoginName(user.getLoginName()); - if (StringUtils.isNull(u)) - { - user.setPassword(Md5Utils.hash(user.getLoginName() + password)); - user.setCreateBy(operName); - this.insertUser(user); - successNum++; - successMsg.append("
" + successNum + "、账号 " + user.getLoginName() + " 导入成功"); - } - else if (isUpdateSupport) - { - user.setUpdateBy(operName); - this.updateUser(user); - successNum++; - successMsg.append("
" + successNum + "、账号 " + user.getLoginName() + " 更新成功"); - } - else - { - failureNum++; - failureMsg.append("
" + failureNum + "、账号 " + user.getLoginName() + " 已存在"); - } - } - catch (Exception e) - { - failureNum++; - String msg = "
" + failureNum + "、账号 " + user.getLoginName() + " 导入失败:"; - failureMsg.append(msg + e.getMessage()); - log.error(msg, e); - } - } - if (failureNum > 0) - { - failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); - throw new BusinessException(failureMsg.toString()); - } - else - { - successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); - } - return successMsg.toString(); - } - - /** - * 用户状态修改 - * - * @param user 用户信息 - * @return 结果 - */ - @Override - public int changeStatus(SysUser user) - { - return userMapper.updateUser(user); - } -} +package com.ruoyi.system.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.exception.BusinessException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.security.Md5Utils; +import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.domain.SysUserPost; +import com.ruoyi.system.domain.SysUserRole; +import com.ruoyi.system.mapper.SysPostMapper; +import com.ruoyi.system.mapper.SysRoleMapper; +import com.ruoyi.system.mapper.SysUserMapper; +import com.ruoyi.system.mapper.SysUserPostMapper; +import com.ruoyi.system.mapper.SysUserRoleMapper; +import com.ruoyi.system.service.ISysConfigService; +import com.ruoyi.system.service.ISysUserService; + +/** + * 用户 业务层处理 + * + * @author ruoyi + */ +@Service +public class SysUserServiceImpl implements ISysUserService { + private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); + + @Autowired + private SysUserMapper userMapper; + + @Autowired + private SysRoleMapper roleMapper; + + @Autowired + private SysPostMapper postMapper; + + @Autowired + private SysUserPostMapper userPostMapper; + + @Autowired + private SysUserRoleMapper userRoleMapper; + + @Autowired + private ISysConfigService configService; + + /** + * 根据条件分页查询用户列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @Override + @DataScope(deptAlias = "d", userAlias = "u") + public List selectUserList(SysUser user) { + return userMapper.selectUserList(user); + } + + /** + * 根据条件分页查询已分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @DataScope(deptAlias = "d", userAlias = "u") + public List selectAllocatedList(SysUser user) { + return userMapper.selectAllocatedList(user); + } + + /** + * 根据条件分页查询未分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @DataScope(deptAlias = "d", userAlias = "u") + public List selectUnallocatedList(SysUser user) { + return userMapper.selectUnallocatedList(user); + } + + /** + * 通过用户名查询用户 + * + * @param userName 用户名 + * @return 用户对象信息 + */ + @Override + public SysUser selectUserByLoginName(String userName) { + return userMapper.selectUserByLoginName(userName); + } + + /** + * 通过手机号码查询用户 + * + * @param phoneNumber 手机号码 + * @return 用户对象信息 + */ + @Override + public SysUser selectUserByPhoneNumber(String phoneNumber) { + return userMapper.selectUserByPhoneNumber(phoneNumber); + } + + /** + * 通过邮箱查询用户 + * + * @param email 邮箱 + * @return 用户对象信息 + */ + @Override + public SysUser selectUserByEmail(String email) { + return userMapper.selectUserByEmail(email); + } + + /** + * 通过用户ID查询用户 + * + * @param userId 用户ID + * @return 用户对象信息 + */ + @Override + public SysUser selectUserById(Long userId) { + return userMapper.selectUserById(userId); + } + + /** + * 通过用户ID删除用户 + * + * @param userId 用户ID + * @return 结果 + */ + @Override + public int deleteUserById(Long userId) { + // 删除用户与角色关联 + userRoleMapper.deleteUserRoleByUserId(userId); + // 删除用户与岗位表 + userPostMapper.deleteUserPostByUserId(userId); + return userMapper.deleteUserById(userId); + } + + /** + * 批量删除用户信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteUserByIds(String ids) throws BusinessException { + Long[] userIds = Convert.toLongArray(ids); + for (Long userId : userIds) { + checkUserAllowed(new SysUser(userId)); + } + return userMapper.deleteUserByIds(userIds); + } + + /** + * 新增保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + @Transactional + public int insertUser(SysUser user) { + // 新增用户信息 + int rows = userMapper.insertUser(user); + // 新增用户岗位关联 + insertUserPost(user); + // 新增用户与角色管理 + insertUserRole(user); + return rows; + } + + /** + * 修改保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + @Transactional + public int updateUser(SysUser user) { + Long userId = user.getUserId(); + // 删除用户与角色关联 + userRoleMapper.deleteUserRoleByUserId(userId); + // 新增用户与角色管理 + insertUserRole(user); + // 删除用户与岗位关联 + userPostMapper.deleteUserPostByUserId(userId); + // 新增用户与岗位管理 + insertUserPost(user); + return userMapper.updateUser(user); + } + + /** + * 修改用户个人详细信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int updateUserInfo(SysUser user) { + return userMapper.updateUser(user); + } + + /** + * 修改用户密码 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int resetUserPwd(SysUser user) { + return updateUserInfo(user); + } + + /** + * 新增用户角色信息 + * + * @param user 用户对象 + */ + public void insertUserRole(SysUser user) { + Long[] roles = user.getRoleIds(); + if (StringUtils.isNotNull(roles)) { + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long roleId : roles) { + SysUserRole ur = new SysUserRole(); + ur.setUserId(user.getUserId()); + ur.setRoleId(roleId); + list.add(ur); + } + if (list.size() > 0) { + userRoleMapper.batchUserRole(list); + } + } + } + + /** + * 新增用户岗位信息 + * + * @param user 用户对象 + */ + public void insertUserPost(SysUser user) { + Long[] posts = user.getPostIds(); + if (StringUtils.isNotNull(posts)) { + // 新增用户与岗位管理 + List list = new ArrayList(); + for (Long postId : posts) { + SysUserPost up = new SysUserPost(); + up.setUserId(user.getUserId()); + up.setPostId(postId); + list.add(up); + } + if (list.size() > 0) { + userPostMapper.batchUserPost(list); + } + } + } + + /** + * 校验登录名称是否唯一 + * + * @param loginName 用户名 + * @return + */ + @Override + public String checkLoginNameUnique(String loginName) { + int count = userMapper.checkLoginNameUnique(loginName); + if (count > 0) { + return UserConstants.USER_NAME_NOT_UNIQUE; + } + return UserConstants.USER_NAME_UNIQUE; + } + + /** + * 校验用户名称是否唯一 + * + * @param user 用户信息 + * @return + */ + @Override + public String checkPhoneUnique(SysUser user) { + Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); + SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); + if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { + return UserConstants.USER_PHONE_NOT_UNIQUE; + } + return UserConstants.USER_PHONE_UNIQUE; + } + + /** + * 校验email是否唯一 + * + * @param user 用户信息 + * @return + */ + @Override + public String checkEmailUnique(SysUser user) { + Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); + SysUser info = userMapper.checkEmailUnique(user.getEmail()); + if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { + return UserConstants.USER_EMAIL_NOT_UNIQUE; + } + return UserConstants.USER_EMAIL_UNIQUE; + } + + /** + * 校验用户是否允许操作 + * + * @param user 用户信息 + */ + public void checkUserAllowed(SysUser user) { + if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) { + throw new BusinessException("不允许操作超级管理员用户"); + } + } + + /** + * 查询用户所属角色组 + * + * @param userId 用户ID + * @return 结果 + */ + @Override + public String selectUserRoleGroup(Long userId) { + List list = roleMapper.selectRolesByUserId(userId); + StringBuffer idsStr = new StringBuffer(); + for (SysRole role : list) { + idsStr.append(role.getRoleName()).append(","); + } + if (StringUtils.isNotEmpty(idsStr.toString())) { + return idsStr.substring(0, idsStr.length() - 1); + } + return idsStr.toString(); + } + + /** + * 查询用户所属岗位组 + * + * @param userId 用户ID + * @return 结果 + */ + @Override + public String selectUserPostGroup(Long userId) { + List list = postMapper.selectPostsByUserId(userId); + StringBuffer idsStr = new StringBuffer(); + for (SysPost post : list) { + idsStr.append(post.getPostName()).append(","); + } + if (StringUtils.isNotEmpty(idsStr.toString())) { + return idsStr.substring(0, idsStr.length() - 1); + } + return idsStr.toString(); + } + + /** + * 导入用户数据 + * + * @param userList 用户数据列表 + * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 + * @param operName 操作用户 + * @return 结果 + */ + @Override + public String importUser(List userList, Boolean isUpdateSupport, String operName) { + if (StringUtils.isNull(userList) || userList.size() == 0) { + throw new BusinessException("导入用户数据不能为空!"); + } + int successNum = 0; + int failureNum = 0; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + String password = configService.selectConfigByKey("sys.user.initPassword"); + for (SysUser user : userList) { + try { + // 验证是否存在这个用户 + SysUser u = userMapper.selectUserByLoginName(user.getLoginName()); + if (StringUtils.isNull(u)) { + user.setPassword(Md5Utils.hash(user.getLoginName() + password)); + user.setCreateBy(operName); + this.insertUser(user); + successNum++; + successMsg.append("
" + successNum + "、账号 " + user.getLoginName() + " 导入成功"); + } else if (isUpdateSupport) { + user.setUpdateBy(operName); + this.updateUser(user); + successNum++; + successMsg.append("
" + successNum + "、账号 " + user.getLoginName() + " 更新成功"); + } else { + failureNum++; + failureMsg.append("
" + failureNum + "、账号 " + user.getLoginName() + " 已存在"); + } + } catch (Exception e) { + failureNum++; + String msg = "
" + failureNum + "、账号 " + user.getLoginName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + } + if (failureNum > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); + throw new BusinessException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } + + /** + * 用户状态修改 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int changeStatus(SysUser user) { + return userMapper.updateUser(user); + } +} From a20583bf46e2d67c66063b9b81f86aa2d592f229 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 14:53:44 +0800 Subject: [PATCH 09/52] jpa,querydsl,lombok --- pom.xml | 560 +++++++++--------- .../src/main/resources/application-druid.yml | 162 +++-- .../src/main/resources/application.yml | 271 +++++---- ruoyi-common/pom.xml | 211 +++---- .../core/domain/BaseDatabaseEntity.java | 123 ++++ .../common/core/domain/enums/ActiveState.java | 54 ++ .../common/core/domain/enums/BaseEnum.java | 16 + .../common/core/domain/enums/DeleteState.java | 62 ++ .../enums/converter/ActiveStateConverter.java | 19 + .../enums/converter/DeleteStateConverter.java | 19 + .../ActiveStatePropertyEditor.java | 18 + .../DeleteStatePropertyEditor.java | 18 + ruoyi-system/pom.xml | 67 +-- .../repository/base/BaseRepository.java | 13 + .../service/impl/SysRoleServiceImpl.java | 3 - 15 files changed, 1003 insertions(+), 613 deletions(-) create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseDatabaseEntity.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/ActiveState.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/BaseEnum.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/DeleteState.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/ActiveStateConverter.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/DeleteStateConverter.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/ActiveStatePropertyEditor.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/DeleteStatePropertyEditor.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java diff --git a/pom.xml b/pom.xml index bc8ac248d..3aec97dd3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,266 +1,296 @@ - - - 4.0.0 - - com.ruoyi - ruoyi - 4.1.0 - - ruoyi - http://www.ruoyi.vip - 若依管理系统 - - - 4.1.0 - UTF-8 - UTF-8 - 1.8 - 1.4.1 - 2.0.0 - 1.3.2 - 1.1.14 - 1.19 - 2.3.2 - 2.9.2 - 1.2.5 - 1.2.60 - 3.9.1 - 2.5 - 1.3.3 - 3.17 - 1.7 - - - - - - - - - org.springframework.boot - spring-boot-dependencies - 2.2.1.RELEASE - pom - import - - - - - com.alibaba - druid-spring-boot-starter - ${druid.version} - - - - - com.github.penggle - kaptcha - ${kaptcha.version} - - - - - org.apache.shiro - shiro-core - ${shiro.version} - - - - - org.apache.shiro - shiro-spring - ${shiro.version} - - - - - org.apache.shiro - shiro-ehcache - ${shiro.version} - - - - - com.github.theborakompanioni - thymeleaf-extras-shiro - ${thymeleaf.extras.shiro.version} - - - - - eu.bitwalker - UserAgentUtils - ${bitwalker.version} - - - - - com.github.pagehelper - pagehelper-spring-boot-starter - ${pagehelper.boot.version} - - - - - com.github.oshi - oshi-core - ${oshi.version} - - - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - io.swagger - swagger-annotations - - - io.swagger - swagger-models - - - - - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - - - commons-io - commons-io - ${commons.io.version} - - - - - commons-fileupload - commons-fileupload - ${commons.fileupload.version} - - - - - org.apache.poi - poi-ooxml - ${poi.version} - - - - - org.apache.velocity - velocity - ${velocity.version} - - - - - com.alibaba - fastjson - ${fastjson.version} - - - - - com.ruoyi - ruoyi-quartz - ${ruoyi.version} - - - - - com.ruoyi - ruoyi-generator - ${ruoyi.version} - - - - - com.ruoyi - ruoyi-framework - ${ruoyi.version} - - - - - com.ruoyi - ruoyi-system - ${ruoyi.version} - - - - - com.ruoyi - ruoyi-common - ${ruoyi.version} - - - - - - - ruoyi-admin - ruoyi-framework - ruoyi-system - ruoyi-quartz - ruoyi-generator - ruoyi-common - - pom - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${java.version} - ${java.version} - ${project.build.sourceEncoding} - - - - - - - - public - aliyun nexus - http://maven.aliyun.com/nexus/content/groups/public/ - - true - - - - - - - public - aliyun nexus - http://maven.aliyun.com/nexus/content/groups/public/ - - true - - - false - - - - + + + 4.0.0 + + com.ruoyi + ruoyi + 4.1.0 + + ruoyi + http://www.ruoyi.vip + 若依管理系统 + + + 4.1.0 + UTF-8 + UTF-8 + 1.8 + 1.4.1 + 2.0.0 + 1.3.2 + 1.1.14 + 1.19 + 2.3.2 + 2.9.2 + 1.2.5 + 1.2.60 + 3.9.1 + 2.5 + 1.3.3 + 3.17 + 1.7 + 4.2.1 + + + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.2.1.RELEASE + pom + import + + + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + + com.github.penggle + kaptcha + ${kaptcha.version} + + + + + org.apache.shiro + shiro-core + ${shiro.version} + + + + + org.apache.shiro + shiro-spring + ${shiro.version} + + + + + org.apache.shiro + shiro-ehcache + ${shiro.version} + + + + + com.github.theborakompanioni + thymeleaf-extras-shiro + ${thymeleaf.extras.shiro.version} + + + + + eu.bitwalker + UserAgentUtils + ${bitwalker.version} + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + ${pagehelper.boot.version} + + + + + com.github.oshi + oshi-core + ${oshi.version} + + + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + io.swagger + swagger-annotations + + + io.swagger + swagger-models + + + + + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + + + commons-io + commons-io + ${commons.io.version} + + + + + commons-fileupload + commons-fileupload + ${commons.fileupload.version} + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + + org.apache.velocity + velocity + ${velocity.version} + + + + + com.alibaba + fastjson + ${fastjson.version} + + + + + com.ruoyi + ruoyi-quartz + ${ruoyi.version} + + + + + com.ruoyi + ruoyi-generator + ${ruoyi.version} + + + + + com.ruoyi + ruoyi-framework + ${ruoyi.version} + + + + + com.ruoyi + ruoyi-system + ${ruoyi.version} + + + + + com.ruoyi + ruoyi-common + ${ruoyi.version} + + + + + + + + + ruoyi-admin + ruoyi-framework + ruoyi-system + ruoyi-quartz + ruoyi-generator + ruoyi-common + + pom + + + + + + com.querydsl + querydsl-jpa + ${querydsl.version} + + + + + + + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + + process + + + target/generated-sources/java + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + com.querydsl + querydsl-apt + ${querydsl.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + + + + public + aliyun nexus + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + + + + + public + aliyun nexus + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + false + + + + \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index 1df30d82c..7bc159b84 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -1,83 +1,79 @@ -#flyway会自动建立该数据库 -db: - # mysql, oracle, sqlserver - type: mysql - name: ry - username: root - password: root -# 数据源配置 -spring: - datasource: - type: com.alibaba.druid.pool.DruidDataSource - driverClassName: com.mysql.cj.jdbc.Driver - druid: - # 主库数据源 - master: - url: jdbc:mysql://localhost:3306/${db.name}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 - username: ${db.username} - password: ${db.password} - # 从库数据源 - slave: - # 从数据源开关/默认关闭 - enabled: false - url: - username: - password: - # 初始连接数 - initialSize: 5 - # 最小连接池数量 - minIdle: 10 - # 最大连接池数量 - maxActive: 20 - # 配置获取连接等待超时的时间 - maxWait: 60000 - # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 - timeBetweenEvictionRunsMillis: 60000 - # 配置一个连接在池中最小生存的时间,单位是毫秒 - minEvictableIdleTimeMillis: 300000 - # 配置一个连接在池中最大生存的时间,单位是毫秒 - maxEvictableIdleTimeMillis: 900000 - # 配置检测连接是否有效 - validationQuery: SELECT 1 FROM DUAL - testWhileIdle: true - testOnBorrow: false - testOnReturn: false - webStatFilter: - enabled: true - statViewServlet: - enabled: true - # 设置白名单,不填则允许所有访问 - allow: - url-pattern: /druid/* - # 控制台管理用户名和密码 - login-username: - login-password: - filter: - stat: - enabled: true - # 慢SQL记录 - log-slow-sql: true - slow-sql-millis: 1000 - merge-sql: true - wall: - config: - multi-statement-allow: true - - flyway: - enabled: true - url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 - user: ${db.username} - password: ${db.password} - #需要目标数据库已经存在,不自动升级 - baseline-on-migrate: false - encoding: utf-8 - clean-on-validation-error: false - clean-disabled: true - #数据库自动迁移的位置 - locations: classpath:db/migration/${db.type} - # 需要管理的数据库 - schemas: ${db.name} - quartz: - job-store-type: jdbc - jdbc: - initialize-schema: never \ No newline at end of file +#flyway会自动建立该数据库 +db: + # mysql, oracle, sqlserver + type: mysql + name: ry + username: root + password: root +# 数据源配置 +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/${db.name}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: ${db.username} + password: ${db.password} + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: + login-password: + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + + flyway: + enabled: true + url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + user: ${db.username} + password: ${db.password} + #需要目标数据库已经存在,不自动升级 + baseline-on-migrate: false + encoding: utf-8 + clean-on-validation-error: false + clean-disabled: true + #数据库自动迁移的位置 + locations: classpath:db/migration/${db.type} + # 需要管理的数据库 + schemas: ${db.name} \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index e9460a605..10efc5c1a 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -1,130 +1,141 @@ -# 项目相关配置 -ruoyi: - # 名称 - name: RuoYi - # 版本 - version: 4.1.0 - # 版权年份 - copyrightYear: 2019 - # 实例演示开关 - demoEnabled: true - # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath) - profile: D:/ruoyi/uploadPath - # 获取ip地址开关 - addressEnabled: true - -# 开发环境配置 -server: - # 服务器的HTTP端口,默认为80 - port: 80 - servlet: - # 应用的访问路径 - context-path: / - tomcat: - # tomcat的URI编码 - uri-encoding: UTF-8 - # tomcat最大线程数,默认为200 - max-threads: 800 - # Tomcat启动初始化的线程数,默认值25 - min-spare-threads: 30 - -# 日志配置 -logging: - level: - root: warn - com.ruoyi: debug - -# 用户配置 -user: - password: - # 密码错误{maxRetryCount}次锁定10分钟 - maxRetryCount: 5 - -# Spring配置 -spring: - # 模板引擎 - thymeleaf: - mode: HTML - encoding: utf-8 - # 禁用缓存 - cache: false - # 资源信息 - messages: - # 国际化资源文件路径 - basename: static/i18n/messages - jackson: - time-zone: GMT+8 - date-format: yyyy-MM-dd HH:mm:ss - profiles: - active: druid - # 文件上传 - servlet: - multipart: - # 单个文件大小 - max-file-size: 10MB - # 设置总上传的文件大小 - max-request-size: 20MB - # 服务模块 - devtools: - restart: - # 热部署开关 - enabled: true - -# MyBatis -mybatis: - # 搜索指定包别名 - typeAliasesPackage: com.ruoyi.**.domain - # 配置mapper的扫描,找到所有的mapper.xml映射文件 - mapperLocations: classpath*:mapper/**/*Mapper.xml - # 加载全局的配置文件 - configLocation: classpath:mybatis/mybatis-config.xml - -# PageHelper分页插件 -pagehelper: - helperDialect: mysql - reasonable: true - supportMethodsArguments: true - params: count=countSql - -# Shiro -shiro: - user: - # 登录地址 - loginUrl: /login - # 权限认证失败地址 - unauthorizedUrl: /unauth - # 首页地址 - indexUrl: /index - # 验证码开关 - captchaEnabled: true - # 验证码类型 math 数组计算 char 字符 - captchaType: math - cookie: - # 设置Cookie的域名 默认空,即当前访问的域名 - domain: - # 设置cookie的有效访问路径 - path: / - # 设置HttpOnly属性 - httpOnly: true - # 设置Cookie的过期时间,天为单位 - maxAge: 30 - session: - # Session超时时间,-1代表永不过期(默认30分钟) - expireTime: 30 - # 同步session到数据库的周期(默认1分钟) - dbSyncPeriod: 1 - # 相隔多久检查一次session的有效性,默认就是10分钟 - validationInterval: 10 - # 同一个用户最大会话数,比如2的意思是同一个账号允许最多同时两个人登录(默认-1不限制) - maxSession: -1 - # 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户 - kickoutAfter: false - -# 防止XSS攻击 -xss: - # 过滤开关 - enabled: true - # 排除链接(多个用逗号分隔) - excludes: /system/notice/* - # 匹配链接 - urlPatterns: /system/*,/monitor/*,/tool/* +# 项目相关配置 +ruoyi: + # 名称 + name: RuoYi + # 版本 + version: 4.1.0 + # 版权年份 + copyrightYear: 2019 + # 实例演示开关 + demoEnabled: true + # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath) + profile: D:/ruoyi/uploadPath + # 获取ip地址开关 + addressEnabled: true + +# 开发环境配置 +server: + # 服务器的HTTP端口,默认为80 + port: 80 + servlet: + # 应用的访问路径 + context-path: / + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + # tomcat最大线程数,默认为200 + max-threads: 800 + # Tomcat启动初始化的线程数,默认值25 + min-spare-threads: 30 + +# 日志配置 +logging: + level: + root: warn + com.ruoyi: debug + com.ruoyi.quartz.mapper: warn + +# 用户配置 +user: + password: + # 密码错误{maxRetryCount}次锁定10分钟 + maxRetryCount: 5 + +# Spring配置 +spring: + # 模板引擎 + thymeleaf: + mode: HTML + encoding: utf-8 + # 禁用缓存 + cache: false + # 资源信息 + messages: + # 国际化资源文件路径 + basename: static/i18n/messages + jackson: + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss + profiles: + active: druid + # 文件上传 + servlet: + multipart: + # 单个文件大小 + max-file-size: 10MB + # 设置总上传的文件大小 + max-request-size: 20MB + # 服务模块 + devtools: + restart: + # 热部署开关 + enabled: true + jpa: + hibernate: + ddl-auto: update + use-new-id-generator-mappings: true + show-sql: false + database-platform: org.hibernate.dialect.MySQL55Dialect + open-in-view: false + properties: + hibernate: + format_sql: false + +# MyBatis +mybatis: + # 搜索指定包别名 + typeAliasesPackage: com.ruoyi.**.domain + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapperLocations: classpath*:mapper/**/*Mapper.xml + # 加载全局的配置文件 + configLocation: classpath:mybatis/mybatis-config.xml + +# PageHelper分页插件 +pagehelper: + helperDialect: mysql + reasonable: true + supportMethodsArguments: true + params: count=countSql + +# Shiro +shiro: + user: + # 登录地址 + loginUrl: /login + # 权限认证失败地址 + unauthorizedUrl: /unauth + # 首页地址 + indexUrl: /index + # 验证码开关 + captchaEnabled: true + # 验证码类型 math 数组计算 char 字符 + captchaType: math + cookie: + # 设置Cookie的域名 默认空,即当前访问的域名 + domain: + # 设置cookie的有效访问路径 + path: / + # 设置HttpOnly属性 + httpOnly: true + # 设置Cookie的过期时间,天为单位 + maxAge: 30 + session: + # Session超时时间,-1代表永不过期(默认30分钟) + expireTime: 30 + # 同步session到数据库的周期(默认1分钟) + dbSyncPeriod: 1 + # 相隔多久检查一次session的有效性,默认就是10分钟 + validationInterval: 10 + # 同一个用户最大会话数,比如2的意思是同一个账号允许最多同时两个人登录(默认-1不限制) + maxSession: -1 + # 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户 + kickoutAfter: false + +# 防止XSS攻击 +xss: + # 过滤开关 + enabled: true + # 排除链接(多个用逗号分隔) + excludes: /system/notice/* + # 匹配链接 + urlPatterns: /system/*,/monitor/*,/tool/* diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index 4ad87e34a..bcf10818a 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -1,100 +1,113 @@ - - - - ruoyi - com.ruoyi - 4.1.0 - - 4.0.0 - - ruoyi-common - - - common通用工具 - - - - - - - org.springframework - spring-context-support - - - - - org.springframework - spring-web - - - - - org.apache.shiro - shiro-core - - - - - com.github.pagehelper - pagehelper-spring-boot-starter - - - - - javax.validation - validation-api - - - - - org.apache.commons - commons-lang3 - - - - - com.fasterxml.jackson.core - jackson-databind - - - - - com.alibaba - fastjson - - - - - commons-io - commons-io - - - - - commons-fileupload - commons-fileupload - - - - - org.apache.poi - poi-ooxml - - - - - org.yaml - snakeyaml - - - - - javax.servlet - javax.servlet-api - - - - + + + + ruoyi + com.ruoyi + 4.1.0 + + 4.0.0 + + ruoyi-common + + + common通用工具 + + + + + + + org.springframework + spring-context-support + + + + + org.springframework + spring-web + + + + + org.apache.shiro + shiro-core + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + + + + + javax.validation + validation-api + + + + + org.apache.commons + commons-lang3 + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + com.alibaba + fastjson + + + + + commons-io + commons-io + + + + + commons-fileupload + commons-fileupload + + + + + org.apache.poi + poi-ooxml + + + + + org.yaml + snakeyaml + + + + + javax.servlet + javax.servlet-api + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.projectlombok + lombok + provided + + + + \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseDatabaseEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseDatabaseEntity.java new file mode 100644 index 000000000..bf774eb38 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseDatabaseEntity.java @@ -0,0 +1,123 @@ +package com.ruoyi.common.core.domain; + +import com.ruoyi.common.core.domain.enums.ActiveState; +import com.ruoyi.common.core.domain.enums.DeleteState; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseDatabaseEntity implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @CreatedDate + @Column(updatable = false) + private Date createDate; + + @CreatedBy + @Column(updatable = false) + private Long createBy; + + @LastModifiedDate + private Date updateDate; + + @LastModifiedBy + private Long updateBy; + + /** + * 删除状态 + */ + private DeleteState deleteState = DeleteState.NOT_DELETED; + + /** + * 启用状态 + */ + private ActiveState activeState = ActiveState.enabled; + + @Version + private Integer version; + + private String remark; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public Long getCreateBy() { + return createBy; + } + + public void setCreateBy(Long createBy) { + this.createBy = createBy; + } + + public Date getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + public Long getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(Long updateBy) { + this.updateBy = updateBy; + } + + public DeleteState getDeleteState() { + return deleteState; + } + + public void setDeleteState(DeleteState deleteState) { + this.deleteState = deleteState; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public ActiveState getActiveState() { + return activeState; + } + + public void setActiveState(ActiveState activeState) { + this.activeState = activeState; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/ActiveState.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/ActiveState.java new file mode 100644 index 000000000..ff3204329 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/ActiveState.java @@ -0,0 +1,54 @@ +package com.ruoyi.common.core.domain.enums; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.util.Arrays; + +@JsonFormat(shape = JsonFormat.Shape.OBJECT) +public enum ActiveState implements BaseEnum{ + + enabled(1,"活跃"), + disabled(2,"不活跃"), + ; + + private Integer state; + private String desc; + + ActiveState(Integer state, String desc) { + this.state = state; + this.desc = desc; + } + + public Integer getState() { + return state; + } + + public void setState(Integer state) { + this.state = state; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + @Override + public String en() { + return null; + } + + @Override + public String zh() { + return null; + } + + public static ActiveState of(Integer value){ + return Arrays.stream(ActiveState.values()) + .filter(activeState -> activeState.getState().equals(value)) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/BaseEnum.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/BaseEnum.java new file mode 100644 index 000000000..b7e104da7 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/BaseEnum.java @@ -0,0 +1,16 @@ +package com.ruoyi.common.core.domain.enums; + +public interface BaseEnum { + + /** + * 英文显示 + * @return + */ + String en(); + + /** + * 汉语显示 + * @return + */ + String zh(); +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/DeleteState.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/DeleteState.java new file mode 100644 index 000000000..efaf732ed --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/DeleteState.java @@ -0,0 +1,62 @@ +package com.ruoyi.common.core.domain.enums; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.util.Arrays; + +@JsonFormat(shape = JsonFormat.Shape.OBJECT) +public enum DeleteState implements BaseEnum { + NOT_DELETED(0, "未删除","Not Deleted"), + DELETED(1, "已删除", "Deleted"), + ; + private Integer state; + private String desc; + private String en; + + public Integer getState() { + return state; + } + + public void setState(Integer state) { + this.state = state; + } + + DeleteState(Integer state, String desc, String en) { + this.state = state; + this.desc = desc; + this.en = en; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static DeleteState of(Integer state){ + return Arrays.stream(DeleteState.values()) + .filter(deleteState -> deleteState.getState().equals(state)) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + } + + public String getEn() { + return en; + } + + public void setEn(String en) { + this.en = en; + } + + @Override + public String en() { + return en; + } + + @Override + public String zh() { + return desc; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/ActiveStateConverter.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/ActiveStateConverter.java new file mode 100644 index 000000000..eb2369b5a --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/ActiveStateConverter.java @@ -0,0 +1,19 @@ +package com.ruoyi.common.core.domain.enums.converter; + +import com.ruoyi.common.core.domain.enums.ActiveState; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +@Converter(autoApply = true) +public class ActiveStateConverter implements AttributeConverter { + @Override + public Integer convertToDatabaseColumn(ActiveState activeState) { + return null; + } + + @Override + public ActiveState convertToEntityAttribute(Integer integer) { + return null; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/DeleteStateConverter.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/DeleteStateConverter.java new file mode 100644 index 000000000..f01687319 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/converter/DeleteStateConverter.java @@ -0,0 +1,19 @@ +package com.ruoyi.common.core.domain.enums.converter; + +import com.ruoyi.common.core.domain.enums.DeleteState; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +@Converter(autoApply = true) +public class DeleteStateConverter implements AttributeConverter { + @Override + public Integer convertToDatabaseColumn(DeleteState attribute) { + return null == attribute ? null : attribute.getState(); + } + + @Override + public DeleteState convertToEntityAttribute(Integer dbData) { + return DeleteState.of(dbData); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/ActiveStatePropertyEditor.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/ActiveStatePropertyEditor.java new file mode 100644 index 000000000..dc68d5636 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/ActiveStatePropertyEditor.java @@ -0,0 +1,18 @@ +package com.ruoyi.common.core.domain.enums.propertyeditor; + +import com.ruoyi.common.core.domain.enums.ActiveState; + +import java.beans.PropertyEditorSupport; + +public class ActiveStatePropertyEditor extends PropertyEditorSupport { + + @Override + public void setAsText(String text) throws IllegalArgumentException { + try{ + Integer enumValue = Integer.parseInt(text); + setValue(ActiveState.of(enumValue)); + }catch (NumberFormatException e){ + e.printStackTrace(); + } + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/DeleteStatePropertyEditor.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/DeleteStatePropertyEditor.java new file mode 100644 index 000000000..27764345c --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/enums/propertyeditor/DeleteStatePropertyEditor.java @@ -0,0 +1,18 @@ +package com.ruoyi.common.core.domain.enums.propertyeditor; + +import com.ruoyi.common.core.domain.enums.DeleteState; + +import java.beans.PropertyEditorSupport; + +public class DeleteStatePropertyEditor extends PropertyEditorSupport { + + @Override + public void setAsText(String text) throws IllegalArgumentException { + try{ + Integer enumValue = Integer.parseInt(text); + setValue(DeleteState.of(enumValue)); + }catch (NumberFormatException e){ + e.printStackTrace(); + } + } +} diff --git a/ruoyi-system/pom.xml b/ruoyi-system/pom.xml index 47e579df4..6e61b7671 100644 --- a/ruoyi-system/pom.xml +++ b/ruoyi-system/pom.xml @@ -1,34 +1,35 @@ - - - - ruoyi - com.ruoyi - 4.1.0 - - 4.0.0 - - ruoyi-system - - - system系统模块 - - - - - - - mysql - mysql-connector-java - - - - - com.ruoyi - ruoyi-common - - - - + + + + ruoyi + com.ruoyi + 4.1.0 + + 4.0.0 + + ruoyi-system + + + system系统模块 + + + + + + + mysql + mysql-connector-java + + + + + com.ruoyi + ruoyi-common + + + + + \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java new file mode 100644 index 000000000..9ea8c41d3 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java @@ -0,0 +1,13 @@ +package com.ruoyi.system.repository.base; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface BaseRepository extends JpaRepository, + JpaSpecificationExecutor, + QuerydslPredicateExecutor { + +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index fc696fa82..ff77fb8ac 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -162,7 +162,6 @@ public class SysRoleServiceImpl implements ISysRoleService { /** * 修改保存角色信息 - * * @param role 角色信息 * @return 结果 */ @@ -178,7 +177,6 @@ public class SysRoleServiceImpl implements ISysRoleService { /** * 修改数据权限信息 - * * @param role 角色信息 * @return 结果 */ @@ -195,7 +193,6 @@ public class SysRoleServiceImpl implements ISysRoleService { /** * 新增角色菜单信息 - * * @param role 角色对象 */ public int insertRoleMenu(SysRole role) { From f2527bd631fad404ce033c86d96f2b2009fc298c Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 22 Nov 2019 15:04:28 +0800 Subject: [PATCH 10/52] log-level --- ruoyi-admin/src/main/resources/application.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 10efc5c1a..1ed586e7e 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -34,6 +34,7 @@ logging: root: warn com.ruoyi: debug com.ruoyi.quartz.mapper: warn + com.ruoyi.system.mapper: warn # 用户配置 user: From 64c083628f8ee69f91febae60baed34979b097b1 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 3 Dec 2019 16:49:21 +0800 Subject: [PATCH 11/52] jpa --- .../com/ruoyi/framework/config/JpaConfig.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java new file mode 100644 index 000000000..fea933cb0 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java @@ -0,0 +1,29 @@ +package com.ruoyi.framework.config; + +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import java.util.Optional; + +@Configuration +@EnableJpaRepositories(basePackages = "com.ruoyi") +@EnableJpaAuditing +public class JpaConfig { + + @Bean + public AuditorAware auditorAware(){ + return () ->{ + SysUser sysUser = ShiroUtils.getSysUser(); + if(sysUser != null){ + return Optional.of(sysUser.getUserId()); + } + return Optional.empty(); + }; + } + +} \ No newline at end of file From c0879a9d08e736873b5b35514b0f2718f6b3413b Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 3 Dec 2019 16:50:36 +0800 Subject: [PATCH 12/52] =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- business/pom.xml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 business/pom.xml diff --git a/business/pom.xml b/business/pom.xml new file mode 100644 index 000000000..814edde33 --- /dev/null +++ b/business/pom.xml @@ -0,0 +1,23 @@ + + + + ruoyi + com.ruoyi + 4.1.0 + + 4.0.0 + + business + + + + + + com.ruoyi + ruoyi-framework + + + + \ No newline at end of file From b1c12963005cb305278d46a153d2b701269d7cfa Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 3 Dec 2019 16:51:30 +0800 Subject: [PATCH 13/52] =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 1 + ruoyi-admin/pom.xml | 3 ++- ruoyi-admin/src/main/resources/application-druid.yml | 2 +- .../main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 3aec97dd3..40a273eca 100644 --- a/pom.xml +++ b/pom.xml @@ -216,6 +216,7 @@ ruoyi-quartz ruoyi-generator ruoyi-common + business pom diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 19b0f1da7..d71c6e6fd 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -58,7 +58,8 @@ com.ruoyi - ruoyi-framework + business + ${ruoyi.version} diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index 7bc159b84..564816d0b 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -2,7 +2,7 @@ db: # mysql, oracle, sqlserver type: mysql - name: ry + name: framework username: root password: root # 数据源配置 diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java index 554bdd59a..198f417cd 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java @@ -86,7 +86,7 @@ public class DataScopeAspect { * * @param joinPoint 切点 * @param user 用户 - * @param alias 别名 + * @param deptAlias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { StringBuilder sqlString = new StringBuilder(); From 291fa661fbf6af265d51ac0dc44e1523f095490a Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 3 Dec 2019 18:15:38 +0800 Subject: [PATCH 14/52] =?UTF-8?q?=E8=81=8C=E4=BD=8Ddao=E5=B1=82=E6=94=B9?= =?UTF-8?q?=E7=94=A8jpa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysPostController.java | 32 +++---- .../controller/system/SysUserController.java | 2 +- .../src/main/resources/application.yml | 2 +- .../core/controller/BaseController.java | 68 +++++++++++--- .../ruoyi/common/core/domain/BaseEntity.java | 28 +++++- .../com/ruoyi/framework/config/JpaConfig.java | 5 +- .../java/com/ruoyi/system/domain/SysPost.java | 25 ++++-- .../java/com/ruoyi/system/domain/SysUser.java | 18 ++++ .../system/repository/SysPostRepository.java | 15 ++++ .../ruoyi/system/service/ISysPostService.java | 21 ++--- .../service/impl/SysPostServiceImpl.java | 89 +++++++++++-------- 11 files changed, 210 insertions(+), 95 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java index 7af40d1d9..c0587fbaf 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java @@ -1,17 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; @@ -22,6 +10,14 @@ import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.service.ISysPostService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; /** * 岗位信息操作处理 @@ -47,8 +43,8 @@ public class SysPostController extends BaseController { @ResponseBody public TableDataInfo list(SysPost post) { startPage(); - List list = postService.selectPostList(post); - return getDataTable(list); + Page page = postService.selectPostList(post, getPageRequest()); + return getDataTable(page); } @Log(title = "岗位管理", businessType = BusinessType.EXPORT) @@ -56,9 +52,9 @@ public class SysPostController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysPost post) { - List list = postService.selectPostList(post); + Page list = postService.selectPostList(post, Pageable.unpaged()); ExcelUtil util = new ExcelUtil(SysPost.class); - return util.exportExcel(list, "岗位数据"); + return util.exportExcel(list.getContent(), "岗位数据"); } @RequiresPermissions("system:post:remove") @@ -95,7 +91,7 @@ public class SysPostController extends BaseController { return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } post.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(postService.insertPost(post)); + return success(postService.insertPost(post)); } /** @@ -121,7 +117,7 @@ public class SysPostController extends BaseController { return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } post.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(postService.updatePost(post)); + return success(postService.updatePost(post)); } /** diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index 441f0cd99..3b2cd42d2 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -132,7 +132,7 @@ public class SysUserController extends BaseController { public String edit(@PathVariable("userId") Long userId, ModelMap mmap) { mmap.put("user", userService.selectUserById(userId)); mmap.put("roles", roleService.selectRolesByUserId(userId)); - mmap.put("posts", postService.selectPostsByUserId(userId)); +// mmap.put("posts", postService.selectPostsByUserId(userId)); return prefix + "/edit"; } diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 1ed586e7e..4ea546a4e 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -75,7 +75,7 @@ spring: hibernate: ddl-auto: update use-new-id-generator-mappings: true - show-sql: false + show-sql: true database-platform: org.hibernate.dialect.MySQL55Dialect open-in-view: false properties: diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java index a25558746..66fcbbacf 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java @@ -1,16 +1,5 @@ package com.ruoyi.common.core.controller; -import java.beans.PropertyEditorSupport; -import java.util.Date; -import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ruoyi.common.core.domain.AjaxResult; @@ -22,6 +11,20 @@ import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.sql.SqlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.beans.PropertyEditorSupport; +import java.util.Date; +import java.util.List; /** * web层通用数据处理 @@ -91,6 +94,43 @@ public class BaseController { return rspData; } + /** + * 设置请求分页数据 + */ + protected Pageable getPageRequest() { + PageDomain pageDomain = TableSupport.buildPageRequest(); + Integer pageNum = pageDomain.getPageNum(); + Integer pageSize = pageDomain.getPageSize(); + if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { + String attribute = pageDomain.getOrderByColumn(); + if(StringUtils.isNotEmpty(attribute)){ + Sort.Order order = null; + if("desc".equals(pageDomain.getIsAsc())){ + order = Sort.Order.desc(attribute); + }else{ + order = Sort.Order.asc(attribute); + } + return PageRequest.of(pageNum-1, pageSize, Sort.by(order)); + }else{ + return PageRequest.of(pageNum-1, pageSize); + } + }else{ + return PageRequest.of(0,10); + } + } + + /** + * 响应请求分页数据 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + protected TableDataInfo getDataTable(org.springframework.data.domain.Page page) { + TableDataInfo rspData = new TableDataInfo(); + rspData.setCode(0); + rspData.setRows(page.getContent()); + rspData.setTotal(page.getTotalElements()); + return rspData; + } + /** * 响应返回结果 * @@ -118,6 +158,12 @@ public class BaseController { return AjaxResult.success(); } + public AjaxResult success(T data) { + AjaxResult result = AjaxResult.success(); + result.put("data", data); + return result; + } + /** * 返回失败消息 */ diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java index 093fee410..4ed5f8051 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java @@ -1,44 +1,67 @@ package com.ruoyi.common.core.domain; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.hibernate.annotations.DynamicUpdate; +import org.hibernate.annotations.SelectBeforeUpdate; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import javax.persistence.Transient; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonFormat; - /** * Entity基类 * * @author ruoyi */ +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@SelectBeforeUpdate +@DynamicUpdate public class BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; /** * 搜索值 */ + @Transient private String searchValue; /** * 创建者 */ + @CreatedBy + @Column(updatable = false) private String createBy; /** * 创建时间 */ + @CreatedDate + @Column(updatable = false) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 更新者 */ + @LastModifiedBy private String updateBy; /** * 更新时间 */ + @LastModifiedDate @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; @@ -50,6 +73,7 @@ public class BaseEntity implements Serializable { /** * 请求参数 */ + @Transient private Map params; public String getSearchValue() { diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java index fea933cb0..9249e9e9c 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/JpaConfig.java @@ -16,14 +16,13 @@ import java.util.Optional; public class JpaConfig { @Bean - public AuditorAware auditorAware(){ + public AuditorAware auditorAware(){ return () ->{ SysUser sysUser = ShiroUtils.getSysUser(); if(sysUser != null){ - return Optional.of(sysUser.getUserId()); + return Optional.of(sysUser.getUserId().toString()); } return Optional.empty(); }; } - } \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java index 0e2d434a4..33c3a45bc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java @@ -1,24 +1,32 @@ package com.ruoyi.system.domain; -import javax.validation.constraints.*; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; /** * 岗位表 sys_post * * @author ruoyi */ +@Entity +@Table(name = "sys_post") public class SysPost extends BaseEntity { + private static final long serialVersionUID = 1L; /** * 岗位序号 */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) @Excel(name = "岗位序号", cellType = ColumnType.NUMERIC) private Long postId; @@ -38,7 +46,7 @@ public class SysPost extends BaseEntity { * 岗位排序 */ @Excel(name = "岗位排序", cellType = ColumnType.NUMERIC) - private String postSort; + private Integer postSort; /** * 状态(0正常 1停用) @@ -49,6 +57,7 @@ public class SysPost extends BaseEntity { /** * 用户是否存在此岗位标识 默认不存在 */ + @Transient private boolean flag = false; public Long getPostId() { @@ -79,12 +88,12 @@ public class SysPost extends BaseEntity { this.postName = postName; } - @NotBlank(message = "显示顺序不能为空") - public String getPostSort() { + @NotNull(message = "显示顺序不能为空") + public Integer getPostSort() { return postSort; } - public void setPostSort(String postSort) { + public void setPostSort(Integer postSort) { this.postSort = postSort; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 793e8b287..223915a5c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.util.Date; import java.util.List; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; import javax.validation.constraints.*; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -121,6 +124,13 @@ public class SysUser extends BaseEntity { private List roles; + @ManyToMany + @JoinTable(name = "sys_user_post", + inverseJoinColumns = @JoinColumn(name = "post_id", referencedColumnName = "post_id"), + joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id")) + @org.hibernate.annotations.ForeignKey(name = "none") + private List posts; + /** * 角色组 */ @@ -316,6 +326,14 @@ public class SysUser extends BaseEntity { this.postIds = postIds; } + public List getPosts() { + return posts; + } + + public void setPosts(List posts) { + this.posts = posts; + } + @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java new file mode 100644 index 000000000..abcb506d1 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysPostRepository extends BaseRepository { + + int countByPostId(Long postId); + + SysPost findFirstByPostName(String postName); + + SysPost findFirstByPostCode(String postCode); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java index 52f03ef29..cc25483d0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysPostService.java @@ -1,8 +1,10 @@ package com.ruoyi.system.service; -import java.util.List; - import com.ruoyi.system.domain.SysPost; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; /** * 岗位信息 服务层 @@ -14,9 +16,10 @@ public interface ISysPostService { * 查询岗位信息集合 * * @param post 岗位信息 + * @param pageRequest * @return 岗位信息集合 */ - public List selectPostList(SysPost post); + public Page selectPostList(SysPost post, Pageable pageRequest); /** * 查询所有岗位 @@ -25,14 +28,6 @@ public interface ISysPostService { */ public List selectPostAll(); - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - public List selectPostsByUserId(Long userId); - /** * 通过岗位ID查询岗位信息 * @@ -56,7 +51,7 @@ public interface ISysPostService { * @param post 岗位信息 * @return 结果 */ - public int insertPost(SysPost post); + public SysPost insertPost(SysPost post); /** * 修改保存岗位信息 @@ -64,7 +59,7 @@ public interface ISysPostService { * @param post 岗位信息 * @return 结果 */ - public int updatePost(SysPost post); + public SysPost updatePost(SysPost post); /** * 通过岗位ID查询岗位使用数量 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java index 95117e28c..14ab39ab2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java @@ -1,17 +1,26 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.mapper.SysPostMapper; import com.ruoyi.system.mapper.SysUserPostMapper; +import com.ruoyi.system.repository.SysPostRepository; import com.ruoyi.system.service.ISysPostService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.List; /** * 岗位信息 服务层处理 @@ -20,8 +29,9 @@ import com.ruoyi.system.service.ISysPostService; */ @Service public class SysPostServiceImpl implements ISysPostService { + @Autowired - private SysPostMapper postMapper; + private SysPostRepository sysPostRepository; @Autowired private SysUserPostMapper userPostMapper; @@ -30,11 +40,31 @@ public class SysPostServiceImpl implements ISysPostService { * 查询岗位信息集合 * * @param post 岗位信息 + * @param pageRequest * @return 岗位信息集合 */ @Override - public List selectPostList(SysPost post) { - return postMapper.selectPostList(post); + public Page selectPostList(SysPost post, Pageable pageRequest) { + return sysPostRepository.findAll(getSpecification(post), pageRequest); + } + + private Specification getSpecification(SysPost sysPost){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysPost.getPostName())){ + predicates.add(criteriaBuilder.like(root.get("postName").as(String.class), "%" + sysPost.getPostName() + "%")); + } + if(StringUtils.isNotEmpty(sysPost.getPostCode())){ + predicates.add(criteriaBuilder.like(root.get("postCode").as(String.class), "%" + sysPost.getPostName() + "%")); + } + if(StringUtils.isNotEmpty(sysPost.getStatus())){ + predicates.add(criteriaBuilder.equal(root.get("status").as(String.class), sysPost.getStatus())); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; } /** @@ -44,28 +74,7 @@ public class SysPostServiceImpl implements ISysPostService { */ @Override public List selectPostAll() { - return postMapper.selectPostAll(); - } - - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - @Override - public List selectPostsByUserId(Long userId) { - List userPosts = postMapper.selectPostsByUserId(userId); - List posts = postMapper.selectPostAll(); - for (SysPost post : posts) { - for (SysPost userRole : userPosts) { - if (post.getPostId().longValue() == userRole.getPostId().longValue()) { - post.setFlag(true); - break; - } - } - } - return posts; + return sysPostRepository.findAll(); } /** @@ -76,7 +85,7 @@ public class SysPostServiceImpl implements ISysPostService { */ @Override public SysPost selectPostById(Long postId) { - return postMapper.selectPostById(postId); + return sysPostRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("未知的数据id:"+postId)); } /** @@ -86,6 +95,7 @@ public class SysPostServiceImpl implements ISysPostService { * @throws Exception */ @Override + @Transactional public int deletePostByIds(String ids) throws BusinessException { Long[] postIds = Convert.toLongArray(ids); for (Long postId : postIds) { @@ -93,8 +103,9 @@ public class SysPostServiceImpl implements ISysPostService { if (countUserPostById(postId) > 0) { throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName())); } + sysPostRepository.deleteById(postId); } - return postMapper.deletePostByIds(postIds); + return postIds.length; } /** @@ -103,9 +114,10 @@ public class SysPostServiceImpl implements ISysPostService { * @param post 岗位信息 * @return 结果 */ + @Transactional @Override - public int insertPost(SysPost post) { - return postMapper.insertPost(post); + public SysPost insertPost(SysPost post) { + return sysPostRepository.save(post); } /** @@ -114,9 +126,10 @@ public class SysPostServiceImpl implements ISysPostService { * @param post 岗位信息 * @return 结果 */ + @Transactional @Override - public int updatePost(SysPost post) { - return postMapper.updatePost(post); + public SysPost updatePost(SysPost post) { + return sysPostRepository.save(post); } /** @@ -139,7 +152,7 @@ public class SysPostServiceImpl implements ISysPostService { @Override public String checkPostNameUnique(SysPost post) { Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); - SysPost info = postMapper.checkPostNameUnique(post.getPostName()); + SysPost info = sysPostRepository.findFirstByPostName(post.getPostName()); if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { return UserConstants.POST_NAME_NOT_UNIQUE; } @@ -155,7 +168,7 @@ public class SysPostServiceImpl implements ISysPostService { @Override public String checkPostCodeUnique(SysPost post) { Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); - SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); + SysPost info = sysPostRepository.findFirstByPostCode(post.getPostCode()); if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { return UserConstants.POST_CODE_NOT_UNIQUE; } From 5929ee0571940db03f6d03e4e3a5347e6bde52f3 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 9 Dec 2019 18:48:57 +0800 Subject: [PATCH 15/52] =?UTF-8?q?=E8=81=8C=E4=BD=8Ddao=E5=B1=82=E6=94=B9?= =?UTF-8?q?=E7=94=A8jpa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysDeptController.java | 24 ++-- .../controller/system/SysRoleController.java | 24 ++-- .../controller/system/SysUserController.java | 34 +++--- .../ruoyi/common/core/domain/BaseEntity.java | 3 + .../java/com/ruoyi/system/domain/SysDept.java | 51 ++++---- .../java/com/ruoyi/system/domain/SysPost.java | 16 +++ .../java/com/ruoyi/system/domain/SysRole.java | 26 +++-- .../java/com/ruoyi/system/domain/SysUser.java | 49 ++++++-- .../system/repository/SysDeptRepository.java | 11 ++ .../system/repository/SysRoleRepository.java | 9 ++ .../system/repository/SysUserRepository.java | 16 +++ .../ruoyi/system/service/ISysUserService.java | 12 +- .../service/impl/SysDeptServiceImpl.java | 22 ++-- .../service/impl/SysUserServiceImpl.java | 110 ++++++++++++------ 14 files changed, 264 insertions(+), 143 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java index 59b6b9ab6..ac3813926 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java @@ -1,28 +1,23 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.enums.BusinessType; -import com.ruoyi.common.utils.StringUtils; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.service.ISysDeptService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 部门信息 @@ -81,9 +76,6 @@ public class SysDeptController extends BaseController { @GetMapping("/edit/{deptId}") public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) { SysDept dept = deptService.selectDeptById(deptId); - if (StringUtils.isNotNull(dept) && 100L == deptId) { - dept.setParentName("无"); - } mmap.put("dept", dept); return prefix + "/edit"; } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 82a9eb845..2918a6390 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -1,17 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; @@ -25,6 +13,14 @@ import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 角色信息 @@ -215,9 +211,7 @@ public class SysRoleController extends BaseController { @PostMapping("/authUser/allocatedList") @ResponseBody public TableDataInfo allocatedList(SysUser user) { - startPage(); - List list = userService.selectAllocatedList(user); - return getDataTable(list); + return getDataTable(userService.selectAllocatedList(user, getPageRequest())); } /** diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index 3b2cd42d2..aa3f1e9fa 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -1,18 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; @@ -26,6 +13,17 @@ import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.service.ISysPostService; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; /** * 用户信息 @@ -59,9 +57,7 @@ public class SysUserController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysUser user) { - startPage(); - List list = userService.selectUserList(user); - return getDataTable(list); + return getDataTable(userService.selectUserList(user, getPageRequest())); } @Log(title = "用户管理", businessType = BusinessType.EXPORT) @@ -69,9 +65,9 @@ public class SysUserController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysUser user) { - List list = userService.selectUserList(user); + Page page = userService.selectUserList(user, Pageable.unpaged()); ExcelUtil util = new ExcelUtil(SysUser.class); - return util.exportExcel(list, "用户数据"); + return util.exportExcel(page.getContent(), "用户数据"); } @Log(title = "用户管理", businessType = BusinessType.IMPORT) @@ -122,7 +118,7 @@ public class SysUserController extends BaseController { user.setSalt(ShiroUtils.randomSalt()); user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); user.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(userService.insertUser(user)); + return success(userService.insertUser(user)); } /** diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java index 4ed5f8051..e4def64d1 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java @@ -29,6 +29,9 @@ import java.util.Map; @DynamicUpdate public class BaseEntity implements Serializable { + public static final String NOT_DELETED = "0"; + public static final String DELETED = "1"; + private static final long serialVersionUID = 1L; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index d872d2cee..366c82fd0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -1,29 +1,31 @@ package com.ruoyi.system.domain; -import javax.validation.constraints.*; - +import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; +import org.hibernate.annotations.ForeignKey; + +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; /** * 部门表 sys_dept * * @author ruoyi */ +@Entity +@Table(name = "sys_dept") public class SysDept extends BaseEntity { private static final long serialVersionUID = 1L; /** * 部门ID */ + @Id private Long deptId; - /** - * 父部门ID - */ - private Long parentId; - /** * 祖级列表 */ @@ -64,10 +66,10 @@ public class SysDept extends BaseEntity { */ private String delFlag; - /** - * 父部门名称 - */ - private String parentName; + @ManyToOne + @JoinColumn(name = "parent_id") + @ForeignKey(name = "none") + private SysDept parent; public Long getDeptId() { return deptId; @@ -77,14 +79,6 @@ public class SysDept extends BaseEntity { this.deptId = deptId; } - public Long getParentId() { - return parentId; - } - - public void setParentId(Long parentId) { - this.parentId = parentId; - } - public String getAncestors() { return ancestors; } @@ -155,19 +149,18 @@ public class SysDept extends BaseEntity { this.delFlag = delFlag; } - public String getParentName() { - return parentName; + public SysDept getParent() { + return parent; } - public void setParentName(String parentName) { - this.parentName = parentName; + public void setParent(SysDept parent) { + this.parent = parent; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("deptId", getDeptId()) - .append("parentId", getParentId()) .append("ancestors", getAncestors()) .append("deptName", getDeptName()) .append("orderNum", getOrderNum()) @@ -182,4 +175,12 @@ public class SysDept extends BaseEntity { .append("updateTime", getUpdateTime()) .toString(); } + + @Transient + public Long getParentId() { + if(this.parent == null){ + return null; + } + return parent.getDeptId(); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java index 33c3a45bc..b51c8f6b1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java @@ -60,6 +60,22 @@ public class SysPost extends BaseEntity { @Transient private boolean flag = false; +// @JsonIgnore +// @ManyToMany(fetch = FetchType.LAZY) +// @JoinTable(name = "sys_user_post", +// inverseJoinColumns = @JoinColumn(name = "post_id", referencedColumnName = "post_id"), +// joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id")) +// @org.hibernate.annotations.ForeignKey(name = "none") +// private List users; + +// public List getUsers() { +// return users; +// } +// +// public void setUsers(List users) { +// this.users = users; +// } + public Long getPostId() { return postId; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 5a9bafe7d..8dfcea9d5 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -1,24 +1,33 @@ package com.ruoyi.system.domain; -import javax.validation.constraints.*; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; /** * 角色表 sys_role * * @author ruoyi */ +@Entity +@Table(name = "sys_role") public class SysRole extends BaseEntity { private static final long serialVersionUID = 1L; /** * 角色ID */ + @Id @Excel(name = "角色序号", cellType = ColumnType.NUMERIC) private Long roleId; @@ -38,7 +47,7 @@ public class SysRole extends BaseEntity { * 角色排序 */ @Excel(name = "角色排序", cellType = ColumnType.NUMERIC) - private String roleSort; + private Integer roleSort; /** * 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) @@ -60,6 +69,7 @@ public class SysRole extends BaseEntity { /** * 用户是否存在此角色标识 默认不存在 */ + @Transient private boolean flag = false; /** @@ -124,12 +134,12 @@ public class SysRole extends BaseEntity { this.roleKey = roleKey; } - @NotBlank(message = "显示顺序不能为空") - public String getRoleSort() { + @NotNull(message = "显示顺序不能为空") + public Integer getRoleSort() { return roleSort; } - public void setRoleSort(String roleSort) { + public void setRoleSort(Integer roleSort) { this.roleSort = roleSort; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 223915a5c..a29a1f5bc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -1,19 +1,20 @@ package com.ruoyi.system.domain; -import java.util.Date; -import java.util.List; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.validation.constraints.*; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.annotation.Excel.Type; import com.ruoyi.common.annotation.Excels; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.ForeignKey; + +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.Date; +import java.util.List; /** * 用户对象 sys_user @@ -120,8 +121,16 @@ public class SysUser extends BaseEntity { @Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) }) + @ManyToOne + @JoinColumn(name = "dept_id", referencedColumnName = "dept_id") + @ForeignKey(name = "none") private SysDept dept; + @ManyToMany + @JoinTable(name = "sys_user_role", + joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id")) + @ForeignKey(name = "none") private List roles; @ManyToMany @@ -141,6 +150,12 @@ public class SysUser extends BaseEntity { */ private Long[] postIds; + @Transient + private Date startTime; + + @Transient + private Date endTime; + public SysUser() { } @@ -334,6 +349,22 @@ public class SysUser extends BaseEntity { this.posts = posts; } + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java new file mode 100644 index 000000000..c596281a7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java @@ -0,0 +1,11 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysDeptRepository extends BaseRepository { + + int countByDelFlagAndParent(String delFlag, SysDept parent); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java new file mode 100644 index 000000000..09c5c7ce5 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java @@ -0,0 +1,9 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysRoleRepository extends BaseRepository { +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java new file mode 100644 index 000000000..c9bcb3fb7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -0,0 +1,16 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysUserRepository extends BaseRepository { + + SysUser findFirstByDelFlagAndLoginName(String delFlag, String loginName); + + SysUser findFirstByDelFlagAndAndPhonenumber(String delFlag, String phone); + + SysUser findFirstByDelFlagAndEmail(String delFlag, String email); + +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index 629b6f825..66269b6c8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -1,8 +1,10 @@ package com.ruoyi.system.service; -import java.util.List; - import com.ruoyi.system.domain.SysUser; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; /** * 用户 业务层 @@ -14,17 +16,19 @@ public interface ISysUserService { * 根据条件分页查询用户列表 * * @param user 用户信息 + * @param pageRequest * @return 用户信息集合信息 */ - public List selectUserList(SysUser user); + public Page selectUserList(SysUser user, Pageable pageRequest); /** * 根据条件分页查询已分配用户角色列表 * * @param user 用户信息 + * @param pageRequest * @return 用户信息集合信息 */ - public List selectAllocatedList(SysUser user); + public Page selectAllocatedList(SysUser user, Pageable pageRequest); /** * 根据条件分页查询未分配用户角色列表 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 10799d5ab..3bf60ca0c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -1,20 +1,22 @@ package com.ruoyi.system.service.impl; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.mapper.SysDeptMapper; +import com.ruoyi.system.repository.SysDeptRepository; import com.ruoyi.system.service.ISysDeptService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; /** * 部门管理 服务实现 @@ -25,6 +27,8 @@ import com.ruoyi.system.service.ISysDeptService; public class SysDeptServiceImpl implements ISysDeptService { @Autowired private SysDeptMapper deptMapper; + @Autowired + private SysDeptRepository sysDeptRepository; /** * 查询部门管理数据 @@ -117,9 +121,9 @@ public class SysDeptServiceImpl implements ISysDeptService { */ @Override public int selectDeptCount(Long parentId) { - SysDept dept = new SysDept(); - dept.setParentId(parentId); - return deptMapper.selectDeptCount(dept); + SysDept parent = new SysDept(); + parent.setDeptId(parentId); + return sysDeptRepository.countByDelFlagAndParent(BaseEntity.NOT_DELETED, parent); } /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 67ec8eaf8..fa2fad4b2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -1,31 +1,33 @@ package com.ruoyi.system.service.impl; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; -import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.domain.SysUserPost; -import com.ruoyi.system.domain.SysUserRole; -import com.ruoyi.system.mapper.SysPostMapper; -import com.ruoyi.system.mapper.SysRoleMapper; -import com.ruoyi.system.mapper.SysUserMapper; -import com.ruoyi.system.mapper.SysUserPostMapper; -import com.ruoyi.system.mapper.SysUserRoleMapper; +import com.ruoyi.system.domain.*; +import com.ruoyi.system.mapper.*; +import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; /** * 用户 业务层处理 @@ -39,6 +41,9 @@ public class SysUserServiceImpl implements ISysUserService { @Autowired private SysUserMapper userMapper; + @Autowired + private SysUserRepository sysUserRepository; + @Autowired private SysRoleMapper roleMapper; @@ -58,23 +63,56 @@ public class SysUserServiceImpl implements ISysUserService { * 根据条件分页查询用户列表 * * @param user 用户信息 + * @param pageRequest * @return 用户信息集合信息 */ @Override @DataScope(deptAlias = "d", userAlias = "u") - public List selectUserList(SysUser user) { - return userMapper.selectUserList(user); + public Page selectUserList(SysUser user, Pageable pageRequest) { + return sysUserRepository.findAll(getSpecification(user), pageRequest); + } + + private Specification getSpecification(SysUser sysUser){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysUser.getDelFlag())){ + predicates.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), sysUser.getDelFlag())); + } + if(StringUtils.isNotEmpty(sysUser.getLoginName())){ + predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + sysUser.getLoginName() + "%")); + } + if(StringUtils.isNotEmpty(sysUser.getStatus())){ + predicates.add(criteriaBuilder.equal(root.get("status").as(String.class), sysUser.getStatus())); + } + if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){ + predicates.add(criteriaBuilder.like(root.get("phonenumber").as(String.class), "%" + sysUser.getPhonenumber() + "%")); + } + if(sysUser.getStartTime() != null){ + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Date.class), sysUser.getStartTime())); + } + if(sysUser.getEndTime() != null){ + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("endTime").as(Date.class), sysUser.getEndTime())); + } + if(sysUser.getDept() != null){ + predicates.add(criteriaBuilder.equal(root.get("dept").get("id").as(Long.class), sysUser.getDept().getDeptId())); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; } /** * 根据条件分页查询已分配用户角色列表 * * @param user 用户信息 + * @param pageRequest * @return 用户信息集合信息 */ @DataScope(deptAlias = "d", userAlias = "u") - public List selectAllocatedList(SysUser user) { - return userMapper.selectAllocatedList(user); + public Page selectAllocatedList(SysUser user, Pageable pageRequest) { + return sysUserRepository.findAll(getSpecification(user), pageRequest); } /** @@ -96,7 +134,7 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public SysUser selectUserByLoginName(String userName) { - return userMapper.selectUserByLoginName(userName); + return sysUserRepository.findFirstByDelFlagAndLoginName(BaseEntity.NOT_DELETED, userName); } /** @@ -107,7 +145,7 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public SysUser selectUserByPhoneNumber(String phoneNumber) { - return userMapper.selectUserByPhoneNumber(phoneNumber); + return sysUserRepository.findFirstByDelFlagAndAndPhonenumber(BaseEntity.NOT_DELETED, phoneNumber); } /** @@ -118,7 +156,7 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public SysUser selectUserByEmail(String email) { - return userMapper.selectUserByEmail(email); + return sysUserRepository.findFirstByDelFlagAndEmail(BaseEntity.NOT_DELETED, email); } /** @@ -129,7 +167,7 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public SysUser selectUserById(Long userId) { - return userMapper.selectUserById(userId); + return sysUserRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("无效的数据")); } /** @@ -138,13 +176,11 @@ public class SysUserServiceImpl implements ISysUserService { * @param userId 用户ID * @return 结果 */ + @Transactional @Override public int deleteUserById(Long userId) { - // 删除用户与角色关联 - userRoleMapper.deleteUserRoleByUserId(userId); - // 删除用户与岗位表 - userPostMapper.deleteUserPostByUserId(userId); - return userMapper.deleteUserById(userId); + sysUserRepository.deleteById(userId); + return 1; } /** @@ -153,13 +189,15 @@ public class SysUserServiceImpl implements ISysUserService { * @param ids 需要删除的数据ID * @return 结果 */ + @Transactional @Override public int deleteUserByIds(String ids) throws BusinessException { Long[] userIds = Convert.toLongArray(ids); for (Long userId : userIds) { checkUserAllowed(new SysUser(userId)); + deleteUserById(userId); } - return userMapper.deleteUserByIds(userIds); + return userIds.length; } /** @@ -170,14 +208,10 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override @Transactional - public int insertUser(SysUser user) { + public SysUser insertUser(SysUser user) { // 新增用户信息 int rows = userMapper.insertUser(user); - // 新增用户岗位关联 - insertUserPost(user); - // 新增用户与角色管理 - insertUserRole(user); - return rows; + return sysUserRepository.save(user); } /** From 6547c800355b937730fa65ee8d1183829ff67d7b Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 9 Dec 2019 18:49:52 +0800 Subject: [PATCH 16/52] =?UTF-8?q?=E8=81=8C=E4=BD=8Ddao=E5=B1=82=E6=94=B9?= =?UTF-8?q?=E7=94=A8jpa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/ruoyi/system/service/ISysUserService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index 66269b6c8..e2faf41d2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -93,7 +93,7 @@ public interface ISysUserService { * @param user 用户信息 * @return 结果 */ - public int insertUser(SysUser user); + public SysUser insertUser(SysUser user); /** * 保存用户信息 From 5bcf7b043592f56b8721ea5fab5346df4bd9b30f Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 10:02:15 +0800 Subject: [PATCH 17/52] =?UTF-8?q?=E7=94=A8=E6=88=B7dao=E5=B1=82=E6=94=B9?= =?UTF-8?q?=E7=94=A8jpa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/SysProfileController.java | 41 ++++------ .../controller/system/SysUserController.java | 10 +-- .../migration/mysql/V001__init_sys_tables.sql | 16 +--- .../framework/aspectj/DataScopeAspect.java | 4 +- .../java/com/ruoyi/system/domain/SysDept.java | 1 + .../java/com/ruoyi/system/domain/SysRole.java | 6 +- .../java/com/ruoyi/system/domain/SysUser.java | 81 +++---------------- .../ruoyi/system/service/ISysUserService.java | 4 +- .../service/impl/SysUserServiceImpl.java | 58 ++----------- 9 files changed, 45 insertions(+), 176 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java index 21a65838d..91b0a01fb 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java @@ -1,16 +1,5 @@ package com.ruoyi.web.controller.system; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.config.Global; import com.ruoyi.common.core.controller.BaseController; @@ -22,6 +11,13 @@ import com.ruoyi.framework.shiro.service.SysPasswordService; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.service.ISysUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; /** * 个人信息 业务处理 @@ -78,11 +74,9 @@ public class SysProfileController extends BaseController { if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) { user.setSalt(ShiroUtils.randomSalt()); user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt())); - if (userService.resetUserPwd(user) > 0) { - ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); - return success(); - } - return error(); + user = userService.resetUserPwd(user); + ShiroUtils.setSysUser(user); + return success(); } else { return error("修改密码失败,旧密码错误"); } @@ -120,11 +114,9 @@ public class SysProfileController extends BaseController { currentUser.setEmail(user.getEmail()); currentUser.setPhonenumber(user.getPhonenumber()); currentUser.setSex(user.getSex()); - if (userService.updateUserInfo(currentUser) > 0) { - ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); - return success(); - } - return error(); + userService.updateUserInfo(currentUser); + ShiroUtils.setSysUser(currentUser); + return success(); } /** @@ -139,10 +131,9 @@ public class SysProfileController extends BaseController { if (!file.isEmpty()) { String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file); currentUser.setAvatar(avatar); - if (userService.updateUserInfo(currentUser) > 0) { - ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId())); - return success(); - } + userService.updateUserInfo(currentUser); + ShiroUtils.setSysUser(currentUser); + return success(); } return error(); } catch (Exception e) { diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index aa3f1e9fa..b2ac94c4a 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -166,13 +166,11 @@ public class SysUserController extends BaseController { userService.checkUserAllowed(user); user.setSalt(ShiroUtils.randomSalt()); user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); - if (userService.resetUserPwd(user) > 0) { - if (ShiroUtils.getUserId() == user.getUserId()) { - ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); - } - return success(); + userService.resetUserPwd(user); + if (ShiroUtils.getUserId() == user.getUserId()) { + ShiroUtils.setSysUser(userService.selectUserById(user.getUserId())); } - return error(); + return success(); } @RequiresPermissions("system:user:remove") diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql index 293c38404..e29a927cc 100644 --- a/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql @@ -23,17 +23,7 @@ create table sys_dept ( -- ---------------------------- -- 初始化-部门表数据 -- ---------------------------- -insert into sys_dept values(100, 0, '0', '若依科技', 0, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(101, 100, '0,100', '深圳总公司', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(102, 100, '0,100', '长沙分公司', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(103, 101, '0,100,101', '研发部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(104, 101, '0,100,101', '市场部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(105, 101, '0,100,101', '测试部门', 3, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(106, 101, '0,100,101', '财务部门', 4, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(107, 101, '0,100,101', '运维部门', 5, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(108, 102, '0,100,102', '市场部门', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -insert into sys_dept values(109, 102, '0,100,102', '财务部门', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); - +insert into sys_dept values(1, NULL, NULL, '根', 0, 'Admin', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -- ---------------------------- -- 2、用户信息表 @@ -66,8 +56,8 @@ create table sys_user ( -- ---------------------------- -- 初始化-用户信息表数据 -- ---------------------------- -insert into sys_user values(1, 103, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', '29c67a30398638269fe600f73a054934', '111111', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); -insert into sys_user values(2, 105, 'ry', '若依', '00', 'ry@qq.com', '15666666666', '1', '', '8e6d98b90472783cc73c17047ddccf36', '222222', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '测试员'); +insert into sys_user values(1, 1, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', '29c67a30398638269fe600f73a054934', '111111', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员'); +insert into sys_user values(2, 1, 'ry', '若依', '00', 'ry@qq.com', '15666666666', '1', '', '8e6d98b90472783cc73c17047ddccf36', '222222', '0', '0', '127.0.0.1', '2018-03-16 11-33-00', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '测试员'); -- ---------------------------- diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java index 198f417cd..88c1b52fe 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java @@ -101,11 +101,11 @@ public class DataScopeAspect { " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId())); } else if (DATA_SCOPE_DEPT.equals(dataScope)) { - sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); + sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDept().getDeptId())); } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", - deptAlias, user.getDeptId(), user.getDeptId())); + deptAlias, user.getDept().getDeptId(), user.getDept().getDeptId())); } else if (DATA_SCOPE_SELF.equals(dataScope)) { if (StringUtils.isNotBlank(userAlias)) { sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index 366c82fd0..0fc996671 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -24,6 +24,7 @@ public class SysDept extends BaseEntity { * 部门ID */ @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long deptId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 8dfcea9d5..92c65a5a9 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -6,10 +6,7 @@ import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; +import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @@ -28,6 +25,7 @@ public class SysRole extends BaseEntity { * 角色ID */ @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) @Excel(name = "角色序号", cellType = ColumnType.NUMERIC) private Long roleId; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index a29a1f5bc..568c51564 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -21,31 +21,19 @@ import java.util.List; * * @author ruoyi */ +@Entity +@Table(name = "sys_user") public class SysUser extends BaseEntity { private static final long serialVersionUID = 1L; /** * 用户ID */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") private Long userId; - /** - * 部门ID - */ - @Excel(name = "部门编号", type = Type.IMPORT) - private Long deptId; - - /** - * 部门父ID - */ - private Long parentId; - - /** - * 角色ID - */ - private Long roleId; - /** * 登录名称 */ @@ -122,34 +110,24 @@ public class SysUser extends BaseEntity { @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) }) @ManyToOne - @JoinColumn(name = "dept_id", referencedColumnName = "dept_id") + @JoinColumn(name = "dept_id", referencedColumnName = "deptId") @ForeignKey(name = "none") private SysDept dept; @ManyToMany @JoinTable(name = "sys_user_role", - joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"), - inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id")) + joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId"), + inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId")) @ForeignKey(name = "none") private List roles; @ManyToMany @JoinTable(name = "sys_user_post", - inverseJoinColumns = @JoinColumn(name = "post_id", referencedColumnName = "post_id"), - joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id")) + inverseJoinColumns = @JoinColumn(name = "postId", referencedColumnName = "postId"), + joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId")) @org.hibernate.annotations.ForeignKey(name = "none") private List posts; - /** - * 角色组 - */ - private Long[] roleIds; - - /** - * 岗位组 - */ - private Long[] postIds; - @Transient private Date startTime; @@ -180,30 +158,6 @@ public class SysUser extends BaseEntity { return userId != null && 1L == userId; } - public Long getDeptId() { - return deptId; - } - - public void setDeptId(Long deptId) { - this.deptId = deptId; - } - - public Long getParentId() { - return parentId; - } - - public void setParentId(Long parentId) { - this.parentId = parentId; - } - - public Long getRoleId() { - return roleId; - } - - public void setRoleId(Long roleId) { - this.roleId = roleId; - } - @NotBlank(message = "登录账号不能为空") @Size(min = 0, max = 30, message = "登录账号长度不能超过30个字符") public String getLoginName() { @@ -325,22 +279,6 @@ public class SysUser extends BaseEntity { this.roles = roles; } - public Long[] getRoleIds() { - return roleIds; - } - - public void setRoleIds(Long[] roleIds) { - this.roleIds = roleIds; - } - - public Long[] getPostIds() { - return postIds; - } - - public void setPostIds(Long[] postIds) { - this.postIds = postIds; - } - public List getPosts() { return posts; } @@ -369,7 +307,6 @@ public class SysUser extends BaseEntity { public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("userId", getUserId()) - .append("deptId", getDeptId()) .append("loginName", getLoginName()) .append("userName", getUserName()) .append("email", getEmail()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index e2faf41d2..feabee225 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -109,7 +109,7 @@ public interface ISysUserService { * @param user 用户信息 * @return 结果 */ - public int updateUserInfo(SysUser user); + public SysUser updateUserInfo(SysUser user); /** * 修改用户密码信息 @@ -117,7 +117,7 @@ public interface ISysUserService { * @param user 用户信息 * @return 结果 */ - public int resetUserPwd(SysUser user); + public SysUser resetUserPwd(SysUser user); /** * 校验用户名称是否唯一 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index fa2fad4b2..6a60005b3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -7,7 +7,9 @@ import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; -import com.ruoyi.system.domain.*; +import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.mapper.*; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; @@ -226,12 +228,8 @@ public class SysUserServiceImpl implements ISysUserService { Long userId = user.getUserId(); // 删除用户与角色关联 userRoleMapper.deleteUserRoleByUserId(userId); - // 新增用户与角色管理 - insertUserRole(user); // 删除用户与岗位关联 userPostMapper.deleteUserPostByUserId(userId); - // 新增用户与岗位管理 - insertUserPost(user); return userMapper.updateUser(user); } @@ -242,8 +240,8 @@ public class SysUserServiceImpl implements ISysUserService { * @return 结果 */ @Override - public int updateUserInfo(SysUser user) { - return userMapper.updateUser(user); + public SysUser updateUserInfo(SysUser user) { + return sysUserRepository.save(user); } /** @@ -253,54 +251,10 @@ public class SysUserServiceImpl implements ISysUserService { * @return 结果 */ @Override - public int resetUserPwd(SysUser user) { + public SysUser resetUserPwd(SysUser user) { return updateUserInfo(user); } - /** - * 新增用户角色信息 - * - * @param user 用户对象 - */ - public void insertUserRole(SysUser user) { - Long[] roles = user.getRoleIds(); - if (StringUtils.isNotNull(roles)) { - // 新增用户与角色管理 - List list = new ArrayList(); - for (Long roleId : roles) { - SysUserRole ur = new SysUserRole(); - ur.setUserId(user.getUserId()); - ur.setRoleId(roleId); - list.add(ur); - } - if (list.size() > 0) { - userRoleMapper.batchUserRole(list); - } - } - } - - /** - * 新增用户岗位信息 - * - * @param user 用户对象 - */ - public void insertUserPost(SysUser user) { - Long[] posts = user.getPostIds(); - if (StringUtils.isNotNull(posts)) { - // 新增用户与岗位管理 - List list = new ArrayList(); - for (Long postId : posts) { - SysUserPost up = new SysUserPost(); - up.setUserId(user.getUserId()); - up.setPostId(postId); - list.add(up); - } - if (list.size() > 0) { - userPostMapper.batchUserPost(list); - } - } - } - /** * 校验登录名称是否唯一 * From 5a12961c84a2c8910cf9bb413112b700b3e37cbf Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 11:06:11 +0800 Subject: [PATCH 18/52] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/templates/system/user/edit.html | 454 +++++++++--------- 1 file changed, 227 insertions(+), 227 deletions(-) diff --git a/ruoyi-admin/src/main/resources/templates/system/user/edit.html b/ruoyi-admin/src/main/resources/templates/system/user/edit.html index 246beef21..4fab1a35b 100644 --- a/ruoyi-admin/src/main/resources/templates/system/user/edit.html +++ b/ruoyi-admin/src/main/resources/templates/system/user/edit.html @@ -1,228 +1,228 @@ - - - - - - - -

-
- - -

基本信息

-
-
-
- -
- -
-
-
-
-
- -
-
- - -
-
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-

其他信息

-
-
-
- -
- -
-
-
-
-
-
-
-
-   - -
-
- - - - + + + + + + + +
+
+ + +

基本信息

+
+
+
+ +
+ +
+
+
+
+
+ +
+
+ + +
+
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+

其他信息

+
+
+
+ +
+ +
+
+
+
+
+
+
+
+   + +
+
+ + + + \ No newline at end of file From c9c91386d545af5d9a5f6876f002c8283690ba7c Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 11:09:04 +0800 Subject: [PATCH 19/52] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ruoyi-admin/pom.xml | 7 + .../ruoyi/web/core/config/WebmvcConfig.java | 37 ++ .../src/main/resources/application-druid.yml | 3 +- ...s_tables.sql => v001__init_sys_tables.sql} | 3 +- ...ables.sql => v002__init_quartz_tables.sql} | 0 .../resources/templates/system/user/add.html | 512 +++++++++--------- .../java/com/ruoyi/system/domain/SysDept.java | 13 + .../service/impl/SysUserServiceImpl.java | 7 +- 8 files changed, 322 insertions(+), 260 deletions(-) create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/web/core/config/WebmvcConfig.java rename ruoyi-admin/src/main/resources/db/migration/mysql/{V001__init_sys_tables.sql => v001__init_sys_tables.sql} (99%) rename ruoyi-admin/src/main/resources/db/migration/mysql/{V002__init_quartz_tables.sql => v002__init_quartz_tables.sql} (100%) diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index d71c6e6fd..b81d1950f 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -79,6 +79,13 @@ org.flywaydb flyway-core + + + + com.fasterxml.jackson.datatype + jackson-datatype-hibernate5 + 2.10.1 + diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/WebmvcConfig.java b/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/WebmvcConfig.java new file mode 100644 index 000000000..5d6ad6859 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/WebmvcConfig.java @@ -0,0 +1,37 @@ +package com.ruoyi.web.core.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +public class WebmvcConfig implements WebMvcConfigurer { + + @Override + public void extendMessageConverters(List> converters) { + for ( HttpMessageConverter converter : converters ) { + if ( converter instanceof MappingJackson2HttpMessageConverter) { + MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter; + ObjectMapper objectMapper = jacksonConverter.getObjectMapper(); + + //--- register hibernateModule in MappingJackson2HttpMessageConverter.objectMapper + Hibernate5Module hibernate5Module = new Hibernate5Module(); + hibernate5Module.disable(Hibernate5Module.Feature.FORCE_LAZY_LOADING); + hibernate5Module.enable(Hibernate5Module.Feature.WRITE_MISSING_ENTITIES_AS_NULL); + hibernate5Module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION); + objectMapper.registerModule(hibernate5Module); + + //--- other configurations + jacksonConverter.setPrettyPrint( true ); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + } + } + } +} diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index 564816d0b..b848b4f9e 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -76,4 +76,5 @@ spring: #数据库自动迁移的位置 locations: classpath:db/migration/${db.type} # 需要管理的数据库 - schemas: ${db.name} \ No newline at end of file + schemas: ${db.name} + sql-migration-prefix: v \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql similarity index 99% rename from ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql rename to ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql index e29a927cc..8e935dc7f 100644 --- a/ruoyi-admin/src/main/resources/db/migration/mysql/V001__init_sys_tables.sql +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql @@ -5,6 +5,7 @@ drop table if exists sys_dept; create table sys_dept ( dept_id bigint(20) not null auto_increment comment '部门id', parent_id bigint(20) default 0 comment '父部门id', + code varchar(128) not null comment '部门编码', ancestors varchar(50) default '' comment '祖级列表', dept_name varchar(30) default '' comment '部门名称', order_num int(4) default 0 comment '显示顺序', @@ -23,7 +24,7 @@ create table sys_dept ( -- ---------------------------- -- 初始化-部门表数据 -- ---------------------------- -insert into sys_dept values(1, NULL, NULL, '根', 0, 'Admin', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); +insert into sys_dept values(1, NULL, '001', NULL, '根', 0, 'Admin', '15888888888', 'ry@qq.com', '0', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00'); -- ---------------------------- -- 2、用户信息表 diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/v002__init_quartz_tables.sql similarity index 100% rename from ruoyi-admin/src/main/resources/db/migration/mysql/V002__init_quartz_tables.sql rename to ruoyi-admin/src/main/resources/db/migration/mysql/v002__init_quartz_tables.sql diff --git a/ruoyi-admin/src/main/resources/templates/system/user/add.html b/ruoyi-admin/src/main/resources/templates/system/user/add.html index f75a0d3d7..23292b640 100644 --- a/ruoyi-admin/src/main/resources/templates/system/user/add.html +++ b/ruoyi-admin/src/main/resources/templates/system/user/add.html @@ -1,257 +1,257 @@ - - - - - - - -
-
- -

基本信息

-
-
-
- -
- -
-
-
-
-
- -
-
- - -
-
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- -
-
-
-
-

其他信息

-
-
-
- -
- -
-
-
-
-
-
- -
-
-   - -
-
- - - - + + + + + + + +
+
+ +

基本信息

+
+
+
+ +
+ +
+
+
+
+
+ +
+
+ + +
+
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+
+
+
+

其他信息

+
+
+
+ +
+ +
+
+
+
+
+
+ +
+
+   + +
+
+ + + + \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index 0fc996671..9b0315a0a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -27,6 +27,11 @@ public class SysDept extends BaseEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long deptId; + /** + * 编码,父001 -> 子001001 -> 孙 001001001 格式编码 + */ + private String code; + /** * 祖级列表 */ @@ -158,6 +163,14 @@ public class SysDept extends BaseEntity { this.parent = parent; } + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 6a60005b3..cf5374e41 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -97,8 +97,11 @@ public class SysUserServiceImpl implements ISysUserService { if(sysUser.getEndTime() != null){ predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("endTime").as(Date.class), sysUser.getEndTime())); } - if(sysUser.getDept() != null){ - predicates.add(criteriaBuilder.equal(root.get("dept").get("id").as(Long.class), sysUser.getDept().getDeptId())); + if(sysUser.getDept() != null && sysUser.getDept().getDeptId() != null){ + predicates.add(criteriaBuilder.equal(root.get("dept").get("deptId").as(Long.class), sysUser.getDept().getDeptId())); + } + if(sysUser.getDept() != null && StringUtils.isNotEmpty(sysUser.getDept().getCode())){ + predicates.add(criteriaBuilder.equal(root.get("dept").get("code").as(String.class), "%" + sysUser.getDept().getCode() + "%")); } return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } From ecfdd916bf915dd940cee7329a75cf4703c094e2 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 13:15:54 +0800 Subject: [PATCH 20/52] =?UTF-8?q?=E9=83=A8=E9=97=A8=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysDeptController.java | 16 +- .../resources/templates/system/dept/add.html | 256 +++++++++--------- .../resources/templates/system/dept/dept.html | 221 ++++++++------- .../java/com/ruoyi/system/domain/SysDept.java | 45 ++- .../java/com/ruoyi/system/domain/SysRole.java | 16 ++ .../system/repository/SysDeptRepository.java | 18 ++ .../system/repository/SysRoleRepository.java | 1 + .../system/repository/SysUserRepository.java | 2 + .../ruoyi/system/service/ISysDeptService.java | 20 +- .../service/impl/SysDeptServiceImpl.java | 143 ++++++---- 10 files changed, 408 insertions(+), 330 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java index ac3813926..00f0cfc8f 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java @@ -5,6 +5,7 @@ import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.Ztree; +import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysDept; @@ -41,9 +42,8 @@ public class SysDeptController extends BaseController { @RequiresPermissions("system:dept:list") @PostMapping("/list") @ResponseBody - public List list(SysDept dept) { - List deptList = deptService.selectDeptList(dept); - return deptList; + public TableDataInfo list(SysDept dept) { + return getDataTable(deptService.selectDeptList(dept, getPageRequest())); } /** @@ -67,7 +67,7 @@ public class SysDeptController extends BaseController { return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); } dept.setCreateBy(ShiroUtils.getLoginName()); - return toAjax(deptService.insertDept(dept)); + return success(deptService.insertDept(dept)); } /** @@ -94,7 +94,8 @@ public class SysDeptController extends BaseController { return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); } dept.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(deptService.updateDept(dept)); + deptService.updateDept(dept); + return success(); } /** @@ -105,13 +106,14 @@ public class SysDeptController extends BaseController { @GetMapping("/remove/{deptId}") @ResponseBody public AjaxResult remove(@PathVariable("deptId") Long deptId) { - if (deptService.selectDeptCount(deptId) > 0) { + if (deptService.countChildren(deptId) > 0) { return AjaxResult.warn("存在下级部门,不允许删除"); } if (deptService.checkDeptExistUser(deptId)) { return AjaxResult.warn("部门存在用户,不允许删除"); } - return toAjax(deptService.deleteDeptById(deptId)); + deptService.deleteDeptById(deptId); + return success(); } /** diff --git a/ruoyi-admin/src/main/resources/templates/system/dept/add.html b/ruoyi-admin/src/main/resources/templates/system/dept/add.html index 3ce6aae14..d2eb00949 100644 --- a/ruoyi-admin/src/main/resources/templates/system/dept/add.html +++ b/ruoyi-admin/src/main/resources/templates/system/dept/add.html @@ -1,128 +1,128 @@ - - - - - - -
-
- -
- -
-
- - -
-
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
-
- - -
-
-
-
-
- - - - + + + + + + +
+
+ +
+ +
+
+ + +
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+
+ + +
+
+
+
+
+ + + + diff --git a/ruoyi-admin/src/main/resources/templates/system/dept/dept.html b/ruoyi-admin/src/main/resources/templates/system/dept/dept.html index 6663d1848..0959635a6 100644 --- a/ruoyi-admin/src/main/resources/templates/system/dept/dept.html +++ b/ruoyi-admin/src/main/resources/templates/system/dept/dept.html @@ -1,112 +1,111 @@ - - - - - - -
-
-
-
-
-
    -
  • - 部门名称: -
  • -
  • - 部门状态: -
  • -
  • -  搜索 -  重置 -
  • -
-
-
-
- - -
-
-
-
-
- - - + + + + + + +
+
+
+
+
+
    +
  • + 部门名称: +
  • +
  • + 部门状态: +
  • +
  • +  搜索 +  重置 +
  • +
+
+
+
+ + +
+
+
+
+
+ + + \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index 9b0315a0a..b06c23569 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -9,6 +9,7 @@ import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import java.util.Objects; /** * 部门表 sys_dept @@ -18,6 +19,11 @@ import javax.validation.constraints.Size; @Entity @Table(name = "sys_dept") public class SysDept extends BaseEntity { + + public static final Long ROOT_ID = 1L; + public static final String STATUS_NORMAL = "0"; + public static final String STATUS_DISABLED = "1"; + private static final long serialVersionUID = 1L; /** @@ -32,11 +38,6 @@ public class SysDept extends BaseEntity { */ private String code; - /** - * 祖级列表 - */ - private String ancestors; - /** * 部门名称 */ @@ -70,7 +71,7 @@ public class SysDept extends BaseEntity { /** * 删除标志(0代表存在 2代表删除) */ - private String delFlag; + private String delFlag = NOT_DELETED; @ManyToOne @JoinColumn(name = "parent_id") @@ -85,14 +86,6 @@ public class SysDept extends BaseEntity { this.deptId = deptId; } - public String getAncestors() { - return ancestors; - } - - public void setAncestors(String ancestors) { - this.ancestors = ancestors; - } - @NotBlank(message = "部门名称不能为空") @Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符") public String getDeptName() { @@ -175,7 +168,7 @@ public class SysDept extends BaseEntity { public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("deptId", getDeptId()) - .append("ancestors", getAncestors()) + .append("code", getCode()) .append("deptName", getDeptName()) .append("orderNum", getOrderNum()) .append("leader", getLeader()) @@ -197,4 +190,26 @@ public class SysDept extends BaseEntity { } return parent.getDeptId(); } + + public SysDept(){ + super(); + } + + public SysDept(Long deptId){ + this(); + setDeptId(deptId); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SysDept dept = (SysDept) o; + return Objects.equals(deptId, dept.deptId); + } + + @Override + public int hashCode() { + return Objects.hash(deptId); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 92c65a5a9..563af6a7d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -10,6 +10,7 @@ import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; +import java.util.List; /** * 角色表 sys_role @@ -80,6 +81,13 @@ public class SysRole extends BaseEntity { */ private Long[] deptIds; + @OneToMany + @JoinTable(name = "sys_role_dept", + joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"), + inverseJoinColumns = @JoinColumn(name = "deptId", referencedColumnName = "deptId")) + @org.hibernate.annotations.ForeignKey(name = "none") + private List depts; + public SysRole() { } @@ -181,6 +189,14 @@ public class SysRole extends BaseEntity { this.deptIds = deptIds; } + public List getDepts() { + return depts; + } + + public void setDepts(List depts) { + this.depts = depts; + } + public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("roleId", getRoleId()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java index c596281a7..511a5fba6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java @@ -2,10 +2,28 @@ package com.ruoyi.system.repository; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface SysDeptRepository extends BaseRepository { int countByDelFlagAndParent(String delFlag, SysDept parent); + + int countByDelFlagAndDeptId(String delFlag, Long deptId); + + SysDept findFirstByDelFlagAndDeptNameAndParent(String delFlag, String deptName, SysDept parent); + + @Modifying + @Query("update SysDept d set d.delFlag = ?1 where d.deptId = ?2") + void updateDelFlagByDeptId(String delFlag, Long deptId); + + @Modifying + @Query("update SysDept d set d.status = ?1 where d.deptId = ?2") + void updateStatusByDeptId(String status, Long deptId); + + int countByParent(SysDept parent); + + SysDept findFirstByParentOrderByCodeDesc(SysDept parent); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java index 09c5c7ce5..ec810ce66 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java @@ -6,4 +6,5 @@ import org.springframework.stereotype.Repository; @Repository public interface SysRoleRepository extends BaseRepository { + } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java index c9bcb3fb7..a9f81ca08 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -1,5 +1,6 @@ package com.ruoyi.system.repository; +import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; @@ -13,4 +14,5 @@ public interface SysUserRepository extends BaseRepository { SysUser findFirstByDelFlagAndEmail(String delFlag, String email); + int countByDelFlagAndDept(String delFlag, SysDept dept); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java index 1946ece24..9373bb839 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java @@ -1,10 +1,12 @@ package com.ruoyi.system.service; -import java.util.List; - import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysRole; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; /** * 部门管理 服务层 @@ -18,7 +20,7 @@ public interface ISysDeptService { * @param dept 部门信息 * @return 部门信息集合 */ - public List selectDeptList(SysDept dept); + public Page selectDeptList(SysDept dept, Pageable pageable); /** * 查询部门管理树 @@ -37,12 +39,12 @@ public interface ISysDeptService { public List roleDeptTreeData(SysRole role); /** - * 查询部门人数 + * 查询下级部门数量 * - * @param parentId 父部门ID + * @param deptId 部门ID * @return 结果 */ - public int selectDeptCount(Long parentId); + public int countChildren(Long deptId); /** * 查询部门是否存在用户 @@ -58,7 +60,7 @@ public interface ISysDeptService { * @param deptId 部门ID * @return 结果 */ - public int deleteDeptById(Long deptId); + public void deleteDeptById(Long deptId); /** * 新增保存部门信息 @@ -66,7 +68,7 @@ public interface ISysDeptService { * @param dept 部门信息 * @return 结果 */ - public int insertDept(SysDept dept); + public SysDept insertDept(SysDept dept); /** * 修改保存部门信息 @@ -74,7 +76,7 @@ public interface ISysDeptService { * @param dept 部门信息 * @return 结果 */ - public int updateDept(SysDept dept); + public SysDept updateDept(SysDept dept); /** * 根据部门ID查询信息 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 3bf60ca0c..6d69b8ec4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -8,13 +8,21 @@ import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.mapper.SysDeptMapper; import com.ruoyi.system.repository.SysDeptRepository; +import com.ruoyi.system.repository.SysRoleRepository; +import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysDeptService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; @@ -25,10 +33,12 @@ import java.util.List; */ @Service public class SysDeptServiceImpl implements ISysDeptService { - @Autowired - private SysDeptMapper deptMapper; @Autowired private SysDeptRepository sysDeptRepository; + @Autowired + private SysUserRepository sysUserRepository; + @Autowired + private SysRoleRepository sysRoleRepository; /** * 查询部门管理数据 @@ -38,8 +48,30 @@ public class SysDeptServiceImpl implements ISysDeptService { */ @Override @DataScope(deptAlias = "d") - public List selectDeptList(SysDept dept) { - return deptMapper.selectDeptList(dept); + public Page selectDeptList(SysDept dept, Pageable pageable) { + return sysDeptRepository.findAll(getSpecification(dept), pageable); + } + + private Specification getSpecification(SysDept sysDept){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysDept.getDelFlag())){ + predicates.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), sysDept.getDelFlag())); + } + if(StringUtils.isNotEmpty(sysDept.getStatus())){ + predicates.add(criteriaBuilder.equal(root.get("status").as(String.class), sysDept.getStatus())); + } + if(StringUtils.isNotEmpty(sysDept.getDeptName())){ + predicates.add(criteriaBuilder.equal(root.get("deptName").as(String.class), "%" + sysDept.getDeptName() + "%")); + } + if(sysDept.getParent() != null && sysDept.getParent().getDeptId() != null){ + predicates.add(criteriaBuilder.equal(root.get("parent").get("deptId").as(Long.class), sysDept.getParent().getDeptId())); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; } /** @@ -51,7 +83,7 @@ public class SysDeptServiceImpl implements ISysDeptService { @Override @DataScope(deptAlias = "d") public List selectDeptTree(SysDept dept) { - List deptList = deptMapper.selectDeptList(dept); + List deptList = sysDeptRepository.findAll(getSpecification(dept)); List ztrees = initZtree(deptList); return ztrees; } @@ -65,11 +97,12 @@ public class SysDeptServiceImpl implements ISysDeptService { @Override public List roleDeptTreeData(SysRole role) { Long roleId = role.getRoleId(); - List ztrees = new ArrayList(); - List deptList = selectDeptList(new SysDept()); + List ztrees; + List deptList = sysDeptRepository.findAll(getSpecification(new SysDept())); if (StringUtils.isNotNull(roleId)) { - List roleDeptList = deptMapper.selectRoleDeptTree(roleId); - ztrees = initZtree(deptList, roleDeptList); + SysRole sysRole = sysRoleRepository.findById(roleId).get(); + List sysDepts = sysRole.getDepts(); + ztrees = initZtree(deptList, sysDepts); } else { ztrees = initZtree(deptList); } @@ -93,8 +126,7 @@ public class SysDeptServiceImpl implements ISysDeptService { * @param roleDeptList 角色已存在菜单列表 * @return 树结构列表 */ - public List initZtree(List deptList, List roleDeptList) { - + public List initZtree(List deptList, List roleDeptList) { List ztrees = new ArrayList(); boolean isCheck = StringUtils.isNotNull(roleDeptList); for (SysDept dept : deptList) { @@ -105,7 +137,7 @@ public class SysDeptServiceImpl implements ISysDeptService { ztree.setName(dept.getDeptName()); ztree.setTitle(dept.getDeptName()); if (isCheck) { - ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName())); + ztree.setChecked(roleDeptList.contains(new SysDept(dept.getDeptId()))); } ztrees.add(ztree); } @@ -114,16 +146,14 @@ public class SysDeptServiceImpl implements ISysDeptService { } /** - * 查询部门人数 + * 查询下级部门数量 * - * @param parentId 部门ID + * @param deptId 部门ID * @return 结果 */ @Override - public int selectDeptCount(Long parentId) { - SysDept parent = new SysDept(); - parent.setDeptId(parentId); - return sysDeptRepository.countByDelFlagAndParent(BaseEntity.NOT_DELETED, parent); + public int countChildren(Long deptId) { + return sysDeptRepository.countByDelFlagAndParent(BaseEntity.NOT_DELETED, new SysDept(deptId)); } /** @@ -134,8 +164,7 @@ public class SysDeptServiceImpl implements ISysDeptService { */ @Override public boolean checkDeptExistUser(Long deptId) { - int result = deptMapper.checkDeptExistUser(deptId); - return result > 0 ? true : false; + return sysUserRepository.countByDelFlagAndDept(BaseEntity.NOT_DELETED, new SysDept(deptId)) > 0; } /** @@ -144,9 +173,10 @@ public class SysDeptServiceImpl implements ISysDeptService { * @param deptId 部门ID * @return 结果 */ + @Transactional @Override - public int deleteDeptById(Long deptId) { - return deptMapper.deleteDeptById(deptId); + public void deleteDeptById(Long deptId) { + sysDeptRepository.updateDelFlagByDeptId(BaseEntity.DELETED, deptId); } /** @@ -155,15 +185,16 @@ public class SysDeptServiceImpl implements ISysDeptService { * @param dept 部门信息 * @return 结果 */ + @Transactional @Override - public int insertDept(SysDept dept) { - SysDept info = deptMapper.selectDeptById(dept.getParentId()); + public SysDept insertDept(SysDept dept) { + SysDept info = sysDeptRepository.findById(dept.getParentId()).get(); // 如果父节点不为"正常"状态,则不允许新增子节点 if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) { throw new BusinessException("部门停用,不允许新增"); } - dept.setAncestors(info.getAncestors() + "," + dept.getParentId()); - return deptMapper.insertDept(dept); + setDeptCode(dept); + return sysDeptRepository.save(dept); } /** @@ -174,21 +205,14 @@ public class SysDeptServiceImpl implements ISysDeptService { */ @Override @Transactional - public int updateDept(SysDept dept) { - SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId()); - SysDept oldDept = selectDeptById(dept.getDeptId()); - if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) { - String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId(); - String oldAncestors = oldDept.getAncestors(); - dept.setAncestors(newAncestors); - updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors); - } - int result = deptMapper.updateDept(dept); + public SysDept updateDept(SysDept dept) { + setDeptCode(dept); + sysDeptRepository.save(dept); if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) { // 如果该部门是启用状态,则启用该部门的所有上级部门 updateParentDeptStatus(dept); } - return result; + return dept; } /** @@ -197,28 +221,13 @@ public class SysDeptServiceImpl implements ISysDeptService { * @param dept 当前部门 */ private void updateParentDeptStatus(SysDept dept) { - String updateBy = dept.getUpdateBy(); - dept = deptMapper.selectDeptById(dept.getDeptId()); - dept.setUpdateBy(updateBy); - deptMapper.updateDeptStatus(dept); + SysDept parent = null; + while ( (parent = dept.getParent()) != null ){ + sysDeptRepository.updateStatusByDeptId(SysDept.STATUS_NORMAL, dept.getDeptId()); + dept = parent; + } } - /** - * 修改子元素关系 - * - * @param deptId 被修改的部门ID - * @param newAncestors 新的父ID集合 - * @param oldAncestors 旧的父ID集合 - */ - public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) { - List children = deptMapper.selectChildrenDeptById(deptId); - for (SysDept child : children) { - child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors)); - } - if (children.size() > 0) { - deptMapper.updateDeptChildren(children); - } - } /** * 根据部门ID查询信息 @@ -228,7 +237,7 @@ public class SysDeptServiceImpl implements ISysDeptService { */ @Override public SysDept selectDeptById(Long deptId) { - return deptMapper.selectDeptById(deptId); + return sysDeptRepository.findById(deptId).orElseThrow(() -> new IllegalArgumentException("无效的数据")); } /** @@ -240,10 +249,24 @@ public class SysDeptServiceImpl implements ISysDeptService { @Override public String checkDeptNameUnique(SysDept dept) { Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId(); - SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); + SysDept info = sysDeptRepository.findFirstByDelFlagAndDeptNameAndParent(BaseEntity.NOT_DELETED, dept.getDeptName(), dept.getParent()); if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) { return UserConstants.DEPT_NAME_NOT_UNIQUE; } return UserConstants.DEPT_NAME_UNIQUE; } + + public void setDeptCode(SysDept dept){ + SysDept parent = dept.getParent(); + String parentCode = parent.getCode(); + SysDept max = sysDeptRepository.findFirstByParentOrderByCodeDesc(parent); + int next = 001; + if(max != null){ + String maxCode = max.getCode(); + String sequence = maxCode.substring(maxCode.length() - 3); + next = Integer.parseInt(sequence) + 1; + } + String code = String.format("%s%03d", parentCode, next); + dept.setCode(code); + } } From ce3dcf90cccb69e9690fda939aae1effacd0a1f8 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 13:32:59 +0800 Subject: [PATCH 21/52] =?UTF-8?q?=E9=83=A8=E9=97=A8=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ruoyi/web/controller/system/SysDeptController.java | 6 +++--- .../src/main/resources/templates/system/dept/dept.html | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java index 00f0cfc8f..c92644841 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java @@ -5,7 +5,6 @@ import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.Ztree; -import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysDept; @@ -13,6 +12,7 @@ import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.service.ISysDeptService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.annotation.Validated; @@ -42,8 +42,8 @@ public class SysDeptController extends BaseController { @RequiresPermissions("system:dept:list") @PostMapping("/list") @ResponseBody - public TableDataInfo list(SysDept dept) { - return getDataTable(deptService.selectDeptList(dept, getPageRequest())); + public List list(SysDept dept) { + return deptService.selectDeptList(dept, Pageable.unpaged()).getContent(); } /** diff --git a/ruoyi-admin/src/main/resources/templates/system/dept/dept.html b/ruoyi-admin/src/main/resources/templates/system/dept/dept.html index 0959635a6..646b07575 100644 --- a/ruoyi-admin/src/main/resources/templates/system/dept/dept.html +++ b/ruoyi-admin/src/main/resources/templates/system/dept/dept.html @@ -56,6 +56,7 @@ code: "deptId", parentCode: "parentId", uniqueId: "deptId", + rootIdValue: null, url: prefix + "/list", createUrl: prefix + "/add/{id}", updateUrl: prefix + "/edit/{id}", From 7a7d9d7218704c713de573721bca385c1e4e05ea Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 13:35:26 +0800 Subject: [PATCH 22/52] =?UTF-8?q?=E9=83=A8=E9=97=A8=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/templates/system/dept/edit.html | 280 +++++++++--------- 1 file changed, 140 insertions(+), 140 deletions(-) diff --git a/ruoyi-admin/src/main/resources/templates/system/dept/edit.html b/ruoyi-admin/src/main/resources/templates/system/dept/edit.html index f21db0843..cde8c9302 100644 --- a/ruoyi-admin/src/main/resources/templates/system/dept/edit.html +++ b/ruoyi-admin/src/main/resources/templates/system/dept/edit.html @@ -1,140 +1,140 @@ - - - - - - -
-
- - -
- -
-
- - -
-
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
-
- - -
-
-
-
-
- - - - + + + + + + +
+
+ + +
+ +
+
+ + +
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+
+ + +
+
+
+
+
+ + + + From 74c61350c35603f9d658d1b68af9a8b858e06000 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 10 Dec 2019 14:57:36 +0800 Subject: [PATCH 23/52] =?UTF-8?q?=E9=83=A8=E9=97=A8=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 6d69b8ec4..084fc6aac 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -101,8 +101,7 @@ public class SysDeptServiceImpl implements ISysDeptService { List deptList = sysDeptRepository.findAll(getSpecification(new SysDept())); if (StringUtils.isNotNull(roleId)) { SysRole sysRole = sysRoleRepository.findById(roleId).get(); - List sysDepts = sysRole.getDepts(); - ztrees = initZtree(deptList, sysDepts); + ztrees = initZtree(deptList, sysRole.getDepts()); } else { ztrees = initZtree(deptList); } From 6cdc94cd3407cae245092fce7d211d1355ad96f8 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 16 Dec 2019 14:26:28 +0800 Subject: [PATCH 24/52] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysUserController.java | 6 ++--- .../src/main/resources/application.yml | 2 +- .../resources/templates/system/user/edit.html | 4 ++-- .../java/com/ruoyi/system/domain/SysPost.java | 22 +++++++++++++++++++ .../java/com/ruoyi/system/domain/SysRole.java | 16 +++++++++++++- .../java/com/ruoyi/system/domain/SysUser.java | 19 ++++++++-------- .../system/repository/SysUserRepository.java | 7 ++++++ .../ruoyi/system/service/ISysUserService.java | 2 ++ .../service/impl/SysPostServiceImpl.java | 8 +++---- .../service/impl/SysUserServiceImpl.java | 5 +++++ 10 files changed, 71 insertions(+), 20 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index b2ac94c4a..b52358a60 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -126,9 +126,9 @@ public class SysUserController extends BaseController { */ @GetMapping("/edit/{userId}") public String edit(@PathVariable("userId") Long userId, ModelMap mmap) { - mmap.put("user", userService.selectUserById(userId)); - mmap.put("roles", roleService.selectRolesByUserId(userId)); -// mmap.put("posts", postService.selectPostsByUserId(userId)); + mmap.put("user", userService.selectUserWithRolesAndPostsById(userId)); + mmap.put("roles", roleService.selectRoleAll()); + mmap.put("posts", postService.selectPostAll()); return prefix + "/edit"; } diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 4ea546a4e..4c3b3f5ee 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -70,7 +70,7 @@ spring: devtools: restart: # 热部署开关 - enabled: true + enabled: false jpa: hibernate: ddl-auto: update diff --git a/ruoyi-admin/src/main/resources/templates/system/user/edit.html b/ruoyi-admin/src/main/resources/templates/system/user/edit.html index 4fab1a35b..4da21b3ba 100644 --- a/ruoyi-admin/src/main/resources/templates/system/user/edit.html +++ b/ruoyi-admin/src/main/resources/templates/system/user/edit.html @@ -76,7 +76,7 @@
@@ -98,7 +98,7 @@
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java index b51c8f6b1..e68feaf6a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java @@ -10,6 +10,7 @@ import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; +import java.util.Objects; /** * 岗位表 sys_post @@ -144,4 +145,25 @@ public class SysPost extends BaseEntity { .append("remark", getRemark()) .toString(); } + + public SysPost() { + } + + public SysPost(Long postId){ + super(); + setPostId(postId); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SysPost sysPost = (SysPost) o; + return Objects.equals(postId, sysPost.postId); + } + + @Override + public int hashCode() { + return Objects.hash(postId); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 563af6a7d..5bb8376aa 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -11,6 +11,7 @@ import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; +import java.util.Objects; /** * 角色表 sys_role @@ -81,7 +82,7 @@ public class SysRole extends BaseEntity { */ private Long[] deptIds; - @OneToMany + @OneToMany(fetch = FetchType.LAZY) @JoinTable(name = "sys_role_dept", joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"), inverseJoinColumns = @JoinColumn(name = "deptId", referencedColumnName = "deptId")) @@ -213,4 +214,17 @@ public class SysRole extends BaseEntity { .append("remark", getRemark()) .toString(); } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SysRole sysRole = (SysRole) o; + return Objects.equals(roleId, sysRole.roleId); + } + + @Override + public int hashCode() { + return Objects.hash(roleId); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 568c51564..945037be0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -14,7 +14,8 @@ import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; /** * 用户对象 sys_user @@ -114,19 +115,19 @@ public class SysUser extends BaseEntity { @ForeignKey(name = "none") private SysDept dept; - @ManyToMany + @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId")) @ForeignKey(name = "none") - private List roles; + private Set roles = new HashSet<>(); - @ManyToMany + @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "sys_user_post", inverseJoinColumns = @JoinColumn(name = "postId", referencedColumnName = "postId"), joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId")) @org.hibernate.annotations.ForeignKey(name = "none") - private List posts; + private Set posts = new HashSet<>(); @Transient private Date startTime; @@ -271,19 +272,19 @@ public class SysUser extends BaseEntity { this.dept = dept; } - public List getRoles() { + public Set getRoles() { return roles; } - public void setRoles(List roles) { + public void setRoles(Set roles) { this.roles = roles; } - public List getPosts() { + public Set getPosts() { return posts; } - public void setPosts(List posts) { + public void setPosts(Set posts) { this.posts = posts; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java index a9f81ca08..506a0259e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -1,8 +1,10 @@ package com.ruoyi.system.repository; import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.stereotype.Repository; @Repository @@ -15,4 +17,9 @@ public interface SysUserRepository extends BaseRepository { SysUser findFirstByDelFlagAndEmail(String delFlag, String email); int countByDelFlagAndDept(String delFlag, SysDept dept); + + int countByDelFlagAndPostsContaining(String delFlag, SysPost sysPost); + + @EntityGraph(attributePaths = {"roles", "posts"}) + SysUser findSysUserByDelFlagAndUserId(String delFlag, Long userId); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index feabee225..b41a5cc6e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -70,6 +70,8 @@ public interface ISysUserService { */ public SysUser selectUserById(Long userId); + public SysUser selectUserWithRolesAndPostsById(Long userId); + /** * 通过用户ID删除用户 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java index 14ab39ab2..cca258cd6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java @@ -1,12 +1,13 @@ package com.ruoyi.system.service.impl; import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.mapper.SysUserPostMapper; import com.ruoyi.system.repository.SysPostRepository; +import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysPostService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -32,9 +33,8 @@ public class SysPostServiceImpl implements ISysPostService { @Autowired private SysPostRepository sysPostRepository; - @Autowired - private SysUserPostMapper userPostMapper; + private SysUserRepository sysUserRepository; /** * 查询岗位信息集合 @@ -140,7 +140,7 @@ public class SysPostServiceImpl implements ISysPostService { */ @Override public int countUserPostById(Long postId) { - return userPostMapper.countUserPostById(postId); + return sysUserRepository.countByDelFlagAndPostsContaining(BaseEntity.NOT_DELETED, new SysPost(postId)); } /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index cf5374e41..744882985 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -175,6 +175,11 @@ public class SysUserServiceImpl implements ISysUserService { return sysUserRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("无效的数据")); } + @Override + public SysUser selectUserWithRolesAndPostsById(Long userId) { + return sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + } + /** * 通过用户ID删除用户 * From 9c77b4eb3bfbb6d5707a529d7a64a09e37ebf047 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 16 Dec 2019 15:09:45 +0800 Subject: [PATCH 25/52] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/SysProfileController.java | 17 +- .../controller/system/SysRoleController.java | 4 +- .../controller/system/SysUserController.java | 5 +- .../templates/system/role/selectUser.html | 238 +++++++++--------- .../system/repository/SysUserRepository.java | 14 ++ .../ruoyi/system/service/ISysUserService.java | 22 +- .../service/impl/SysUserServiceImpl.java | 100 +++----- 7 files changed, 184 insertions(+), 216 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java index 91b0a01fb..0a29c97bb 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java @@ -9,6 +9,7 @@ import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileUploadUtils; import com.ruoyi.framework.shiro.service.SysPasswordService; import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.service.ISysUserService; import org.slf4j.Logger; @@ -42,13 +43,23 @@ public class SysProfileController extends BaseController { */ @GetMapping() public String profile(ModelMap mmap) { - SysUser user = ShiroUtils.getSysUser(); + SysUser user = userService.selectUserWithRolesAndPostsById(ShiroUtils.getUserId()); mmap.put("user", user); - mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId())); - mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId())); + mmap.put("postGroup", concat(user)); return prefix + "/profile"; } + private String concat(SysUser user){ + StringBuffer idsStr = new StringBuffer(); + for (SysPost post : user.getPosts()) { + idsStr.append(post.getPostName()).append(","); + } + if (StringUtils.isNotEmpty(idsStr.toString())) { + return idsStr.substring(0, idsStr.length() - 1); + } + return idsStr.toString(); + } + @GetMapping("/checkPassword") @ResponseBody public boolean checkPassword(String password) { diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 2918a6390..d15bc9096 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -250,9 +250,7 @@ public class SysRoleController extends BaseController { @PostMapping("/authUser/unallocatedList") @ResponseBody public TableDataInfo unallocatedList(SysUser user) { - startPage(); - List list = userService.selectUnallocatedList(user); - return getDataTable(list); + return getDataTable(userService.selectUnallocatedList(user, getPageRequest())); } /** diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index b52358a60..2d893867e 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -147,7 +147,7 @@ public class SysUserController extends BaseController { return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); } user.setUpdateBy(ShiroUtils.getLoginName()); - return toAjax(userService.updateUser(user)); + return success(userService.updateUser(user)); } @RequiresPermissions("system:user:resetPwd") @@ -221,6 +221,7 @@ public class SysUserController extends BaseController { @ResponseBody public AjaxResult changeStatus(SysUser user) { userService.checkUserAllowed(user); - return toAjax(userService.changeStatus(user)); + userService.changeStatus(user); + return success(); } } \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/templates/system/role/selectUser.html b/ruoyi-admin/src/main/resources/templates/system/role/selectUser.html index 25b50675d..16e9b4dad 100644 --- a/ruoyi-admin/src/main/resources/templates/system/role/selectUser.html +++ b/ruoyi-admin/src/main/resources/templates/system/role/selectUser.html @@ -1,120 +1,120 @@ - - - - - - - -
-
-
-
- -
- -
-
-
- -
-
-
-
-
- - - + + + + + + + +
+
+
+
+ +
+ +
+
+
+ +
+
+
+
+
+ + + \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java index 506a0259e..2a10e307b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -5,6 +5,8 @@ import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository @@ -22,4 +24,16 @@ public interface SysUserRepository extends BaseRepository { @EntityGraph(attributePaths = {"roles", "posts"}) SysUser findSysUserByDelFlagAndUserId(String delFlag, Long userId); + + int countByLoginName(String loginName); + + SysUser findFirstByPhonenumber(String phone); + + SysUser findFirstByEmail(String email); + + SysUser findFirstByLoginName(String loginName); + + @Modifying + @Query("update SysUser u set u.status = ?1 where u.userId = ?2") + void changeStatus(String status, Long userId); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index b41a5cc6e..9af23ec75 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -36,7 +36,7 @@ public interface ISysUserService { * @param user 用户信息 * @return 用户信息集合信息 */ - public List selectUnallocatedList(SysUser user); + public Page selectUnallocatedList(SysUser user, Pageable pageable); /** * 通过用户名查询用户 @@ -103,7 +103,7 @@ public interface ISysUserService { * @param user 用户信息 * @return 结果 */ - public int updateUser(SysUser user); + public SysUser updateUser(SysUser user); /** * 修改用户详细信息 @@ -152,22 +152,6 @@ public interface ISysUserService { */ public void checkUserAllowed(SysUser user); - /** - * 根据用户ID查询用户所属角色组 - * - * @param userId 用户ID - * @return 结果 - */ - public String selectUserRoleGroup(Long userId); - - /** - * 根据用户ID查询用户所属岗位组 - * - * @param userId 用户ID - * @return 结果 - */ - public String selectUserPostGroup(Long userId); - /** * 导入用户数据 * @@ -184,5 +168,5 @@ public interface ISysUserService { * @param user 用户信息 * @return 结果 */ - public int changeStatus(SysUser user); + public void changeStatus(SysUser user); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 744882985..2473176b0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -7,10 +7,9 @@ import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; -import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.mapper.*; +import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; @@ -30,6 +29,7 @@ import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Set; /** * 用户 业务层处理 @@ -46,18 +46,6 @@ public class SysUserServiceImpl implements ISysUserService { @Autowired private SysUserRepository sysUserRepository; - @Autowired - private SysRoleMapper roleMapper; - - @Autowired - private SysPostMapper postMapper; - - @Autowired - private SysUserPostMapper userPostMapper; - - @Autowired - private SysUserRoleMapper userRoleMapper; - @Autowired private ISysConfigService configService; @@ -123,12 +111,29 @@ public class SysUserServiceImpl implements ISysUserService { /** * 根据条件分页查询未分配用户角色列表 * - * @param user 用户信息 + * @param sysUser 用户信息 * @return 用户信息集合信息 */ @DataScope(deptAlias = "d", userAlias = "u") - public List selectUnallocatedList(SysUser user) { - return userMapper.selectUnallocatedList(user); + public Page selectUnallocatedList(SysUser sysUser, Pageable pageable) { + return sysUserRepository.findAll(new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysUser.getLoginName())){ + predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + sysUser.getLoginName() + "%")); + } + if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){ + predicates.add(criteriaBuilder.like(root.get("phonenumber").as(String.class), "%" + sysUser.getPhonenumber() + "%")); + } + if(sysUser.getRoles() != null && sysUser.getRoles().size() == 1){ + SysRole role = sysUser.getRoles().iterator().next(); + Predicate notMember = criteriaBuilder.isNotMember(role, root.get("roles").as(Set.class)); + predicates.add(notMember); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }, pageable); } /** @@ -219,8 +224,6 @@ public class SysUserServiceImpl implements ISysUserService { @Override @Transactional public SysUser insertUser(SysUser user) { - // 新增用户信息 - int rows = userMapper.insertUser(user); return sysUserRepository.save(user); } @@ -232,13 +235,8 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override @Transactional - public int updateUser(SysUser user) { - Long userId = user.getUserId(); - // 删除用户与角色关联 - userRoleMapper.deleteUserRoleByUserId(userId); - // 删除用户与岗位关联 - userPostMapper.deleteUserPostByUserId(userId); - return userMapper.updateUser(user); + public SysUser updateUser(SysUser user) { + return sysUserRepository.save(user); } /** @@ -271,7 +269,7 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public String checkLoginNameUnique(String loginName) { - int count = userMapper.checkLoginNameUnique(loginName); + int count = sysUserRepository.countByLoginName(loginName); if (count > 0) { return UserConstants.USER_NAME_NOT_UNIQUE; } @@ -287,7 +285,7 @@ public class SysUserServiceImpl implements ISysUserService { @Override public String checkPhoneUnique(SysUser user) { Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); - SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); + SysUser info = sysUserRepository.findFirstByPhonenumber(user.getPhonenumber()); if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { return UserConstants.USER_PHONE_NOT_UNIQUE; } @@ -303,7 +301,7 @@ public class SysUserServiceImpl implements ISysUserService { @Override public String checkEmailUnique(SysUser user) { Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); - SysUser info = userMapper.checkEmailUnique(user.getEmail()); + SysUser info = sysUserRepository.findFirstByEmail(user.getEmail()); if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { return UserConstants.USER_EMAIL_NOT_UNIQUE; } @@ -321,44 +319,6 @@ public class SysUserServiceImpl implements ISysUserService { } } - /** - * 查询用户所属角色组 - * - * @param userId 用户ID - * @return 结果 - */ - @Override - public String selectUserRoleGroup(Long userId) { - List list = roleMapper.selectRolesByUserId(userId); - StringBuffer idsStr = new StringBuffer(); - for (SysRole role : list) { - idsStr.append(role.getRoleName()).append(","); - } - if (StringUtils.isNotEmpty(idsStr.toString())) { - return idsStr.substring(0, idsStr.length() - 1); - } - return idsStr.toString(); - } - - /** - * 查询用户所属岗位组 - * - * @param userId 用户ID - * @return 结果 - */ - @Override - public String selectUserPostGroup(Long userId) { - List list = postMapper.selectPostsByUserId(userId); - StringBuffer idsStr = new StringBuffer(); - for (SysPost post : list) { - idsStr.append(post.getPostName()).append(","); - } - if (StringUtils.isNotEmpty(idsStr.toString())) { - return idsStr.substring(0, idsStr.length() - 1); - } - return idsStr.toString(); - } - /** * 导入用户数据 * @@ -380,7 +340,7 @@ public class SysUserServiceImpl implements ISysUserService { for (SysUser user : userList) { try { // 验证是否存在这个用户 - SysUser u = userMapper.selectUserByLoginName(user.getLoginName()); + SysUser u = sysUserRepository.findFirstByLoginName(user.getLoginName()); if (StringUtils.isNull(u)) { user.setPassword(Md5Utils.hash(user.getLoginName() + password)); user.setCreateBy(operName); @@ -419,7 +379,7 @@ public class SysUserServiceImpl implements ISysUserService { * @return 结果 */ @Override - public int changeStatus(SysUser user) { - return userMapper.updateUser(user); + public void changeStatus(SysUser user) { + sysUserRepository.changeStatus(user.getStatus(), user.getUserId()); } } From 742a11a2e77c60432f6d1f7147b60c68cb08adee Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 16 Dec 2019 15:46:37 +0800 Subject: [PATCH 26/52] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../monitor/SysUserOnlineController.java | 18 ++--- .../migration/mysql/v001__init_sys_tables.sql | 4 +- .../converter/OnlineStatusConverter.java | 19 +++++ .../ruoyi/system/domain/SysUserOnline.java | 16 +++-- .../repository/SysUserOnlineRepository.java | 14 ++++ .../system/service/ISysUserOnlineService.java | 10 +-- .../impl/SysUserOnlineServiceImpl.java | 69 ++++++++++++------- .../service/impl/SysUserServiceImpl.java | 4 -- 8 files changed, 102 insertions(+), 52 deletions(-) create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/enums/converter/OnlineStatusConverter.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java index 5ba8700cb..d1b82f6d8 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java @@ -1,15 +1,5 @@ package com.ruoyi.web.controller.monitor; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -21,6 +11,10 @@ import com.ruoyi.framework.shiro.session.OnlineSessionDAO; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysUserOnline; import com.ruoyi.system.service.ISysUserOnlineService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; /** * 在线用户监控 @@ -48,9 +42,7 @@ public class SysUserOnlineController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysUserOnline userOnline) { - startPage(); - List list = userOnlineService.selectUserOnlineList(userOnline); - return getDataTable(list); + return getDataTable(userOnlineService.selectUserOnlineList(userOnline, getPageRequest())); } @RequiresPermissions("monitor:online:batchForceLogout") diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql index 8e935dc7f..b05ec4360 100644 --- a/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/v001__init_sys_tables.sql @@ -547,7 +547,7 @@ create table sys_logininfor ( -- ---------------------------- drop table if exists sys_user_online; create table sys_user_online ( - sessionId varchar(50) default '' comment '用户会话id', + session_id varchar(50) default '' comment '用户会话id', login_name varchar(50) default '' comment '登录账号', dept_name varchar(50) default '' comment '部门名称', ipaddr varchar(50) default '' comment '登录IP地址', @@ -558,7 +558,7 @@ create table sys_user_online ( start_timestamp datetime comment 'session创建时间', last_access_time datetime comment 'session最后访问时间', expire_time int(5) default 0 comment '超时时间,单位为分钟', - primary key (sessionId) + primary key (session_id) ) engine=innodb comment = '在线用户记录'; diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/converter/OnlineStatusConverter.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/converter/OnlineStatusConverter.java new file mode 100644 index 000000000..993e687ea --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/converter/OnlineStatusConverter.java @@ -0,0 +1,19 @@ +package com.ruoyi.common.enums.converter; + +import com.ruoyi.common.enums.OnlineStatus; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +@Converter(autoApply = true) +public class OnlineStatusConverter implements AttributeConverter { + @Override + public String convertToDatabaseColumn(OnlineStatus attribute) { + return attribute == null ? null : attribute.name(); + } + + @Override + public OnlineStatus convertToEntityAttribute(String dbData) { + return OnlineStatus.valueOf(dbData); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java index 3c366abb5..165418f5e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUserOnline.java @@ -1,23 +1,29 @@ package com.ruoyi.system.domain; -import java.util.Date; - +import com.ruoyi.common.enums.OnlineStatus; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; -import com.ruoyi.common.enums.OnlineStatus; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; +import java.util.Date; /** * 当前在线会话 sys_user_online * * @author ruoyi */ -public class SysUserOnline extends BaseEntity { +@Entity +@Table(name = "sys_user_online") +public class SysUserOnline implements Serializable { private static final long serialVersionUID = 1L; /** * 用户会话id */ + @Id private String sessionId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java new file mode 100644 index 000000000..fa15604e8 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java @@ -0,0 +1,14 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +import java.util.Date; +import java.util.List; + +@Repository +public interface SysUserOnlineRepository extends BaseRepository { + + List findByLastAccessTimeLessThanEqual(Date date); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java index f23b9eb7f..488a03588 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java @@ -1,10 +1,12 @@ package com.ruoyi.system.service; +import com.ruoyi.system.domain.SysUserOnline; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + import java.util.Date; import java.util.List; -import com.ruoyi.system.domain.SysUserOnline; - /** * 在线用户 服务层 * @@ -40,7 +42,7 @@ public interface ISysUserOnlineService { * * @param online 会话信息 */ - public void saveOnline(SysUserOnline online); + public SysUserOnline saveOnline(SysUserOnline online); /** * 查询会话集合 @@ -48,7 +50,7 @@ public interface ISysUserOnlineService { * @param userOnline 分页参数 * @return 会话集合 */ - public List selectUserOnlineList(SysUserOnline userOnline); + public Page selectUserOnlineList(SysUserOnline userOnline, Pageable pageable); /** * 强退用户 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java index 7dde6550c..e4e06e24d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java @@ -1,15 +1,23 @@ package com.ruoyi.system.service.impl; -import java.util.Date; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.mapper.SysUserOnlineMapper; +import com.ruoyi.system.repository.SysUserOnlineRepository; import com.ruoyi.system.service.ISysUserOnlineService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; /** * 在线用户 服务层处理 @@ -18,8 +26,9 @@ import com.ruoyi.system.service.ISysUserOnlineService; */ @Service public class SysUserOnlineServiceImpl implements ISysUserOnlineService { + @Autowired - private SysUserOnlineMapper userOnlineDao; + private SysUserOnlineRepository sysUserOnlineRepository; /** * 通过会话序号查询信息 @@ -29,7 +38,7 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { */ @Override public SysUserOnline selectOnlineById(String sessionId) { - return userOnlineDao.selectOnlineById(sessionId); + return sysUserOnlineRepository.findById(sessionId).orElse(null); } /** @@ -38,12 +47,10 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { * @param sessionId 会话ID * @return 在线用户信息 */ + @Transactional @Override public void deleteOnlineById(String sessionId) { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) { - userOnlineDao.deleteOnlineById(sessionId); - } + sysUserOnlineRepository.deleteById(sessionId); } /** @@ -52,13 +59,11 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { * @param sessions 会话ID集合 * @return 在线用户信息 */ + @Transactional @Override public void batchDeleteOnline(List sessions) { for (String sessionId : sessions) { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) { - userOnlineDao.deleteOnlineById(sessionId); - } + deleteOnlineById(sessionId); } } @@ -68,8 +73,8 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { * @param online 会话信息 */ @Override - public void saveOnline(SysUserOnline online) { - userOnlineDao.saveOnline(online); + public SysUserOnline saveOnline(SysUserOnline online) { + return sysUserOnlineRepository.save(online); } /** @@ -78,8 +83,24 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { * @param userOnline 在线用户 */ @Override - public List selectUserOnlineList(SysUserOnline userOnline) { - return userOnlineDao.selectUserOnlineList(userOnline); + public Page selectUserOnlineList(SysUserOnline userOnline, Pageable pageable) { + return sysUserOnlineRepository.findAll(getSpecification(userOnline), pageable); + } + + private Specification getSpecification(SysUserOnline userOnline){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(userOnline.getIpaddr())){ + predicates.add(criteriaBuilder.like(root.get("ipaddr").as(String.class), "%" + userOnline.getIpaddr() + "%")); + } + if(StringUtils.isNotEmpty(userOnline.getLoginName())){ + predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + userOnline.getLoginName() + "%")); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; } /** @@ -87,9 +108,10 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { * * @param sessionId 会话ID */ + @Transactional @Override public void forceLogout(String sessionId) { - userOnlineDao.deleteOnlineById(sessionId); + deleteOnlineById(sessionId); } /** @@ -99,7 +121,6 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService { */ @Override public List selectOnlineByExpired(Date expiredDate) { - String lastAccessTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiredDate); - return userOnlineDao.selectOnlineByExpired(lastAccessTime); + return sysUserOnlineRepository.findByLastAccessTimeLessThanEqual(expiredDate); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 2473176b0..63c6e2fdb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -9,7 +9,6 @@ import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; @@ -40,9 +39,6 @@ import java.util.Set; public class SysUserServiceImpl implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); - @Autowired - private SysUserMapper userMapper; - @Autowired private SysUserRepository sysUserRepository; From 5472ac1232b19ae348ba490349fea747e312c0c0 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Mon, 16 Dec 2019 16:20:39 +0800 Subject: [PATCH 27/52] =?UTF-8?q?=E8=8F=9C=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/ruoyi/system/domain/SysMenu.java | 32 ++++++++----------- .../system/repository/SysMenuRepository.java | 10 ++++++ .../service/impl/SysMenuServiceImpl.java | 21 +++++------- 3 files changed, 32 insertions(+), 31 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java index 76ac12333..25dbac935 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java @@ -1,24 +1,30 @@ package com.ruoyi.system.domain; -import java.util.List; -import java.util.ArrayList; -import javax.validation.constraints.*; - +import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.core.domain.BaseEntity; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.ArrayList; +import java.util.List; /** * 菜单权限表 sys_menu * * @author ruoyi */ +@Entity +@Table(name = "sys_menu") public class SysMenu extends BaseEntity { private static final long serialVersionUID = 1L; /** * 菜单ID */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long menuId; /** @@ -26,11 +32,6 @@ public class SysMenu extends BaseEntity { */ private String menuName; - /** - * 父菜单名称 - */ - private String parentName; - /** * 父菜单ID */ @@ -74,6 +75,9 @@ public class SysMenu extends BaseEntity { /** * 子菜单 */ + @OneToMany + @JoinColumn(name = "parentId") + @org.hibernate.annotations.ForeignKey(name = "none") private List children = new ArrayList(); public Long getMenuId() { @@ -94,14 +98,6 @@ public class SysMenu extends BaseEntity { this.menuName = menuName; } - public String getParentName() { - return parentName; - } - - public void setParentName(String parentName) { - this.parentName = parentName; - } - public Long getParentId() { return parentId; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java new file mode 100644 index 000000000..0cba758b7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java @@ -0,0 +1,10 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysMenuRepository extends BaseRepository { + +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index 52e4a7b61..b1fe4c1a4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -1,17 +1,5 @@ package com.ruoyi.system.service.impl; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.utils.StringUtils; @@ -20,7 +8,13 @@ import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.mapper.SysMenuMapper; import com.ruoyi.system.mapper.SysRoleMenuMapper; +import com.ruoyi.system.repository.SysMenuRepository; import com.ruoyi.system.service.ISysMenuService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.MessageFormat; +import java.util.*; /** * 菜单 业务层处理 @@ -33,9 +27,10 @@ public class SysMenuServiceImpl implements ISysMenuService { @Autowired private SysMenuMapper menuMapper; - @Autowired private SysRoleMenuMapper roleMenuMapper; + @Autowired + private SysMenuRepository sysMenuRepository; /** * 根据用户查询菜单 From c2d2596347025f998244c3171c1f526248f73461 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 15:35:36 +0800 Subject: [PATCH 28/52] =?UTF-8?q?=E8=8F=9C=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../java/com/ruoyi/system/domain/SysMenu.java | 39 ++++++++++++------- .../system/repository/SysMenuRepository.java | 4 ++ .../service/impl/SysMenuServiceImpl.java | 29 +++++++++++--- 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/pom.xml b/pom.xml index d98f3b407..66f94d2a5 100644 --- a/pom.xml +++ b/pom.xml @@ -203,7 +203,7 @@ ruoyi-common ${ruoyi.version} - + diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java index 25dbac935..34f3c6dde 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java @@ -20,6 +20,13 @@ import java.util.List; public class SysMenu extends BaseEntity { private static final long serialVersionUID = 1L; + public static final String MENU_VISIABLE = "0"; + public static final String MENU_INVISIABLE = "1"; + public static final String MENU_TYPE_PRIMARY = "M"; + public static final String MENU_TYPE_SECONDARY = "C"; + public static final String MENU_TYPE_PERMS = "F"; + public static final Long ROOT_ID = null; + /** * 菜单ID */ @@ -32,11 +39,6 @@ public class SysMenu extends BaseEntity { */ private String menuName; - /** - * 父菜单ID - */ - private Long parentId; - /** * 显示顺序 */ @@ -72,12 +74,15 @@ public class SysMenu extends BaseEntity { */ private String icon; + @ManyToOne + @JoinColumn(name = "parentId", referencedColumnName = "menuId") + @org.hibernate.annotations.ForeignKey(name = "none") + private SysMenu parent; + /** * 子菜单 */ - @OneToMany - @JoinColumn(name = "parentId") - @org.hibernate.annotations.ForeignKey(name = "none") + @Transient private List children = new ArrayList(); public Long getMenuId() { @@ -98,12 +103,12 @@ public class SysMenu extends BaseEntity { this.menuName = menuName; } + @Transient public Long getParentId() { - return parentId; - } - - public void setParentId(Long parentId) { - this.parentId = parentId; + if(parent != null){ + return parent.getMenuId(); + } + return null; } @NotBlank(message = "显示顺序不能为空") @@ -174,6 +179,14 @@ public class SysMenu extends BaseEntity { this.children = children; } + public SysMenu getParent() { + return parent; + } + + public void setParent(SysMenu parent) { + this.parent = parent; + } + @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java index 0cba758b7..83a0d9158 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java @@ -4,7 +4,11 @@ import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; +import java.util.Collection; +import java.util.List; + @Repository public interface SysMenuRepository extends BaseRepository { + List findAllByMenuTypeInAndVisibleOrderByOrderNum(Collection types, String visiable); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index b1fe4c1a4..04cf292d3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -1,5 +1,6 @@ package com.ruoyi.system.service.impl; +import com.google.common.collect.Lists; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.utils.StringUtils; @@ -11,8 +12,11 @@ import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.repository.SysMenuRepository; import com.ruoyi.system.service.ISysMenuService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import java.sql.Types; import java.text.MessageFormat; import java.util.*; @@ -31,6 +35,8 @@ public class SysMenuServiceImpl implements ISysMenuService { private SysRoleMenuMapper roleMenuMapper; @Autowired private SysMenuRepository sysMenuRepository; + @Autowired + private JdbcTemplate jdbcTemplate; /** * 根据用户查询菜单 @@ -43,11 +49,22 @@ public class SysMenuServiceImpl implements ISysMenuService { List menus = new LinkedList(); // 管理员显示所有菜单信息 if (user.isAdmin()) { - menus = menuMapper.selectMenuNormalAll(); + menus = sysMenuRepository.findAllByMenuTypeInAndVisibleOrderByOrderNum( + Lists.newArrayList(SysMenu.MENU_TYPE_PRIMARY, SysMenu.MENU_TYPE_SECONDARY), SysMenu.MENU_VISIABLE); } else { - menus = menuMapper.selectMenusByUserId(user.getUserId()); + String sql = "select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time " + + " from sys_menu m " + + " left join sys_role_menu rm on m.menu_id = rm.menu_id " + + " left join sys_user_role ur on rm.role_id = ur.role_id " + + " LEFT JOIN sys_role ro on ur.role_id = ro.role_id " + + " where ur.user_id = ? and m.menu_type in (?, ?) and m.visible = ? AND ro.status = 0 " + + " order by m.parent_id, m.order_num "; + menus = jdbcTemplate.query(sql, + new Object[]{user.getUserId(), SysMenu.MENU_TYPE_PRIMARY, SysMenu.MENU_TYPE_SECONDARY, SysMenu.MENU_VISIABLE}, + new int[]{Types.BIGINT, Types.CHAR, Types.CHAR, Types.CHAR}, + new BeanPropertyRowMapper()); } - return getChildPerms(menus, 0); + return getChildPerms(menus, SysMenu.ROOT_ID); } /** @@ -283,12 +300,12 @@ public class SysMenuServiceImpl implements ISysMenuService { * @param parentId 传入的父节点ID * @return String */ - public List getChildPerms(List list, int parentId) { + public List getChildPerms(List list, Long parentId) { List returnList = new ArrayList(); for (Iterator iterator = list.iterator(); iterator.hasNext(); ) { SysMenu t = (SysMenu) iterator.next(); // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点 - if (t.getParentId() == parentId) { + if((parentId == null && t.getParentId() == null) || (parentId != null && t.getParentId() != null && parentId.equals(t.getParentId()))){ recursionFn(list, t); returnList.add(t); } @@ -326,7 +343,7 @@ public class SysMenuServiceImpl implements ISysMenuService { Iterator it = list.iterator(); while (it.hasNext()) { SysMenu n = (SysMenu) it.next(); - if (n.getParentId().longValue() == t.getMenuId().longValue()) { + if (t.getMenuId().equals(n.getParentId())) { tlist.add(n); } } From 706d220aba5b52a18bfa59915b506f20bce83098 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 15:43:29 +0800 Subject: [PATCH 29/52] =?UTF-8?q?=E8=8F=9C=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/SysMenuServiceImpl.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index 04cf292d3..c4cfc1192 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -12,10 +12,15 @@ import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.repository.SysMenuRepository; import com.ruoyi.system.service.ISysMenuService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; import java.sql.Types; import java.text.MessageFormat; import java.util.*; @@ -76,7 +81,7 @@ public class SysMenuServiceImpl implements ISysMenuService { public List selectMenuList(SysMenu menu, Long userId) { List menuList = null; if (SysUser.isAdmin(userId)) { - menuList = menuMapper.selectMenuList(menu); + menuList = sysMenuRepository.findAll(getSpecification(menu)); } else { menu.getParams().put("userId", userId); menuList = menuMapper.selectMenuListByUserId(menu); @@ -84,6 +89,23 @@ public class SysMenuServiceImpl implements ISysMenuService { return menuList; } + private Specification getSpecification(SysMenu sysMenu){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysMenu.getMenuName())){ + predicates.add(criteriaBuilder.like(root.get("menuName").as(String.class), "%" + sysMenu.getMenuName() + "%")); + } + if(StringUtils.isNotEmpty(sysMenu.getVisible())){ + predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), sysMenu.getVisible())); + } + query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class))); + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; + } + /** * 查询菜单集合 * From 33b08246cec95fdeed27182abbb62147e59dd79e Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 16:56:22 +0800 Subject: [PATCH 30/52] =?UTF-8?q?=E8=8F=9C=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/ruoyi/system/domain/SysMenu.java | 13 ++++ .../java/com/ruoyi/system/domain/SysRole.java | 42 ++++------ .../system/repository/SysMenuRepository.java | 1 + .../service/impl/SysDeptServiceImpl.java | 2 - .../service/impl/SysMenuServiceImpl.java | 76 ++++++++++++++----- .../service/impl/SysRoleServiceImpl.java | 40 ++-------- .../service/impl/SysUserServiceImpl.java | 10 +-- 7 files changed, 95 insertions(+), 89 deletions(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java index 34f3c6dde..d0130d2af 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java @@ -9,6 +9,7 @@ import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.List; +import java.util.Set; /** * 菜单权限表 sys_menu @@ -79,6 +80,10 @@ public class SysMenu extends BaseEntity { @org.hibernate.annotations.ForeignKey(name = "none") private SysMenu parent; + @ManyToMany(fetch = FetchType.LAZY, mappedBy = "menus") + @org.hibernate.annotations.ForeignKey(name = "none") + private Set roles; + /** * 子菜单 */ @@ -187,6 +192,14 @@ public class SysMenu extends BaseEntity { this.parent = parent; } + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } + @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 5bb8376aa..ed99d6f7d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -12,6 +12,7 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; import java.util.Objects; +import java.util.Set; /** * 角色表 sys_role @@ -72,16 +73,6 @@ public class SysRole extends BaseEntity { @Transient private boolean flag = false; - /** - * 菜单组 - */ - private Long[] menuIds; - - /** - * 部门组(数据权限) - */ - private Long[] deptIds; - @OneToMany(fetch = FetchType.LAZY) @JoinTable(name = "sys_role_dept", joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"), @@ -89,6 +80,13 @@ public class SysRole extends BaseEntity { @org.hibernate.annotations.ForeignKey(name = "none") private List depts; + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "sys_role_menu", + joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"), + inverseJoinColumns = @JoinColumn(name = "menuId", referencedColumnName = "menuId")) + @org.hibernate.annotations.ForeignKey(name = "none") + private Set menus; + public SysRole() { } @@ -174,22 +172,6 @@ public class SysRole extends BaseEntity { this.flag = flag; } - public Long[] getMenuIds() { - return menuIds; - } - - public void setMenuIds(Long[] menuIds) { - this.menuIds = menuIds; - } - - public Long[] getDeptIds() { - return deptIds; - } - - public void setDeptIds(Long[] deptIds) { - this.deptIds = deptIds; - } - public List getDepts() { return depts; } @@ -198,6 +180,14 @@ public class SysRole extends BaseEntity { this.depts = depts; } + public Set getMenus() { + return menus; + } + + public void setMenus(Set menus) { + this.menus = menus; + } + public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("roleId", getRoleId()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java index 83a0d9158..67a6d05e2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java @@ -11,4 +11,5 @@ import java.util.List; public interface SysMenuRepository extends BaseRepository { List findAllByMenuTypeInAndVisibleOrderByOrderNum(Collection types, String visiable); + } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 084fc6aac..339c74176 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -47,7 +47,6 @@ public class SysDeptServiceImpl implements ISysDeptService { * @return 部门信息集合 */ @Override - @DataScope(deptAlias = "d") public Page selectDeptList(SysDept dept, Pageable pageable) { return sysDeptRepository.findAll(getSpecification(dept), pageable); } @@ -81,7 +80,6 @@ public class SysDeptServiceImpl implements ISysDeptService { * @return 所有部门信息 */ @Override - @DataScope(deptAlias = "d") public List selectDeptTree(SysDept dept) { List deptList = sysDeptRepository.findAll(getSpecification(dept)); List ztrees = initZtree(deptList); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index c4cfc1192..1d302dcda 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -2,6 +2,7 @@ package com.ruoyi.system.service.impl; import com.google.common.collect.Lists; import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysMenu; @@ -10,18 +11,14 @@ import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.mapper.SysMenuMapper; import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.repository.SysMenuRepository; +import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; -import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import java.sql.Types; +import javax.persistence.criteria.*; import java.text.MessageFormat; import java.util.*; @@ -41,6 +38,8 @@ public class SysMenuServiceImpl implements ISysMenuService { @Autowired private SysMenuRepository sysMenuRepository; @Autowired + private SysUserRepository sysUserRepository; + @Autowired private JdbcTemplate jdbcTemplate; /** @@ -57,17 +56,29 @@ public class SysMenuServiceImpl implements ISysMenuService { menus = sysMenuRepository.findAllByMenuTypeInAndVisibleOrderByOrderNum( Lists.newArrayList(SysMenu.MENU_TYPE_PRIMARY, SysMenu.MENU_TYPE_SECONDARY), SysMenu.MENU_VISIABLE); } else { - String sql = "select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time " + - " from sys_menu m " + - " left join sys_role_menu rm on m.menu_id = rm.menu_id " + - " left join sys_user_role ur on rm.role_id = ur.role_id " + - " LEFT JOIN sys_role ro on ur.role_id = ro.role_id " + - " where ur.user_id = ? and m.menu_type in (?, ?) and m.visible = ? AND ro.status = 0 " + - " order by m.parent_id, m.order_num "; - menus = jdbcTemplate.query(sql, - new Object[]{user.getUserId(), SysMenu.MENU_TYPE_PRIMARY, SysMenu.MENU_TYPE_SECONDARY, SysMenu.MENU_VISIABLE}, - new int[]{Types.BIGINT, Types.CHAR, Types.CHAR, Types.CHAR}, - new BeanPropertyRowMapper()); + user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, user.getUserId()); + Set roles = user.getRoles(); + menus = sysMenuRepository.findAll(new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(!roles.isEmpty()){ + for(SysRole role : roles){ + predicates.add(criteriaBuilder.isMember(role, root.get("roles"))); + } + } + + Expression type = root.get("menuType").as(String.class); + CriteriaBuilder.In in = criteriaBuilder.in(type); + in.value(SysMenu.MENU_TYPE_PRIMARY); + in.value(SysMenu.MENU_TYPE_SECONDARY); + predicates.add(in); + + predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), SysMenu.MENU_VISIABLE)); + query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class))); + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }); } return getChildPerms(menus, SysMenu.ROOT_ID); } @@ -81,15 +92,16 @@ public class SysMenuServiceImpl implements ISysMenuService { public List selectMenuList(SysMenu menu, Long userId) { List menuList = null; if (SysUser.isAdmin(userId)) { - menuList = sysMenuRepository.findAll(getSpecification(menu)); + menuList = sysMenuRepository.findAll(getSpecificationForAdmin(menu)); } else { - menu.getParams().put("userId", userId); - menuList = menuMapper.selectMenuListByUserId(menu); + SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + Set roles = user.getRoles(); + menuList = sysMenuRepository.findAll(getSpecification(menu, roles)); } return menuList; } - private Specification getSpecification(SysMenu sysMenu){ + private Specification getSpecificationForAdmin(SysMenu sysMenu){ return new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { @@ -106,6 +118,28 @@ public class SysMenuServiceImpl implements ISysMenuService { }; } + private Specification getSpecification(SysMenu sysMenu, Set roles){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(!roles.isEmpty()){ + for(SysRole role : roles){ + predicates.add(criteriaBuilder.isMember(role, root.get("roles"))); + } + } + if(StringUtils.isNotEmpty(sysMenu.getMenuName())){ + predicates.add(criteriaBuilder.like(root.get("menuName").as(String.class), "%" + sysMenu.getMenuName() + "%")); + } + if(StringUtils.isNotEmpty(sysMenu.getVisible())){ + predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), sysMenu.getVisible())); + } + query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class))); + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; + } + /** * 查询菜单集合 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index ff77fb8ac..d0d59a39a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -1,29 +1,22 @@ package com.ruoyi.system.service.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.domain.SysRoleDept; -import com.ruoyi.system.domain.SysRoleMenu; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.mapper.SysRoleDeptMapper; import com.ruoyi.system.mapper.SysRoleMapper; import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.mapper.SysUserRoleMapper; import com.ruoyi.system.service.ISysRoleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; /** * 角色 业务层处理 @@ -51,7 +44,6 @@ public class SysRoleServiceImpl implements ISysRoleService { * @return 角色数据集合信息 */ @Override - @DataScope(deptAlias = "d") public List selectRoleList(SysRole role) { return roleMapper.selectRoleList(role); } @@ -197,17 +189,6 @@ public class SysRoleServiceImpl implements ISysRoleService { */ public int insertRoleMenu(SysRole role) { int rows = 1; - // 新增用户与角色管理 - List list = new ArrayList(); - for (Long menuId : role.getMenuIds()) { - SysRoleMenu rm = new SysRoleMenu(); - rm.setRoleId(role.getRoleId()); - rm.setMenuId(menuId); - list.add(rm); - } - if (list.size() > 0) { - rows = roleMenuMapper.batchRoleMenu(list); - } return rows; } @@ -218,17 +199,6 @@ public class SysRoleServiceImpl implements ISysRoleService { */ public int insertRoleDept(SysRole role) { int rows = 1; - // 新增角色与部门(数据权限)管理 - List list = new ArrayList(); - for (Long deptId : role.getDeptIds()) { - SysRoleDept rd = new SysRoleDept(); - rd.setRoleId(role.getRoleId()); - rd.setDeptId(deptId); - list.add(rd); - } - if (list.size() > 0) { - rows = roleDeptMapper.batchRoleDept(list); - } return rows; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 63c6e2fdb..a423d3905 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -1,6 +1,5 @@ package com.ruoyi.system.service.impl; -import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; @@ -53,7 +52,6 @@ public class SysUserServiceImpl implements ISysUserService { * @return 用户信息集合信息 */ @Override - @DataScope(deptAlias = "d", userAlias = "u") public Page selectUserList(SysUser user, Pageable pageRequest) { return sysUserRepository.findAll(getSpecification(user), pageRequest); } @@ -99,7 +97,6 @@ public class SysUserServiceImpl implements ISysUserService { * @param pageRequest * @return 用户信息集合信息 */ - @DataScope(deptAlias = "d", userAlias = "u") public Page selectAllocatedList(SysUser user, Pageable pageRequest) { return sysUserRepository.findAll(getSpecification(user), pageRequest); } @@ -110,7 +107,6 @@ public class SysUserServiceImpl implements ISysUserService { * @param sysUser 用户信息 * @return 用户信息集合信息 */ - @DataScope(deptAlias = "d", userAlias = "u") public Page selectUnallocatedList(SysUser sysUser, Pageable pageable) { return sysUserRepository.findAll(new Specification() { @Override @@ -252,9 +248,13 @@ public class SysUserServiceImpl implements ISysUserService { * @param user 用户信息 * @return 结果 */ + @Transactional @Override public SysUser resetUserPwd(SysUser user) { - return updateUserInfo(user); + SysUser db = sysUserRepository.findById(user.getUserId()).get(); + db.setSalt(user.getSalt()); + db.setPassword(user.getPassword()); + return db; } /** From 49b1567ec04085c94038ef8d4c7fd885677bb92c Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 17:21:29 +0800 Subject: [PATCH 31/52] =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/templates/system/user/edit.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruoyi-admin/src/main/resources/templates/system/user/edit.html b/ruoyi-admin/src/main/resources/templates/system/user/edit.html index 4da21b3ba..b64f71d3e 100644 --- a/ruoyi-admin/src/main/resources/templates/system/user/edit.html +++ b/ruoyi-admin/src/main/resources/templates/system/user/edit.html @@ -188,8 +188,8 @@ var roleIds = $.form.selectCheckeds("role"); var postIds = $.form.selectSelects("post"); data.push({"name": "status", "value": status}); - data.push({"name": "roleIds", "value": roleIds}); - data.push({"name": "postIds", "value": postIds}); + data.push({"name": "roles", "value": roleIds}); + data.push({"name": "posts", "value": postIds}); $.operate.saveTab(prefix + "/edit", data); } } From 945dba8885f15b57e8e16e04985168176aae712f Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 17:36:53 +0800 Subject: [PATCH 32/52] =?UTF-8?q?=E8=A7=92=E8=89=B2=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysRoleController.java | 1 + .../controller/system/SysUserController.java | 4 +- .../resources/templates/system/role/edit.html | 318 +++++++++--------- .../resources/templates/system/user/add.html | 4 +- .../ruoyi/framework/aspectj/LogAspect.java | 33 +- .../java/com/ruoyi/system/domain/SysRole.java | 2 +- .../service/impl/SysMenuServiceImpl.java | 6 +- .../service/impl/SysRoleServiceImpl.java | 16 +- 8 files changed, 196 insertions(+), 188 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index d15bc9096..7d4ea2c56 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -4,6 +4,7 @@ import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index 2d893867e..2661a3dc6 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -4,6 +4,7 @@ import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; @@ -147,7 +148,8 @@ public class SysUserController extends BaseController { return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); } user.setUpdateBy(ShiroUtils.getLoginName()); - return success(userService.updateUser(user)); + userService.updateUser(user); + return success(); } @RequiresPermissions("system:user:resetPwd") diff --git a/ruoyi-admin/src/main/resources/templates/system/role/edit.html b/ruoyi-admin/src/main/resources/templates/system/role/edit.html index 063968e32..9d69115dc 100644 --- a/ruoyi-admin/src/main/resources/templates/system/role/edit.html +++ b/ruoyi-admin/src/main/resources/templates/system/role/edit.html @@ -1,159 +1,159 @@ - - - - - - - -
-
- -
- -
- -
-
-
- -
- - 控制器中定义的权限字符,如:@RequiresRoles("") -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
-
- - - - - + + + + + + + +
+
+ +
+ +
+ +
+
+
+ +
+ + 控制器中定义的权限字符,如:@RequiresRoles("") +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+ + + + + diff --git a/ruoyi-admin/src/main/resources/templates/system/user/add.html b/ruoyi-admin/src/main/resources/templates/system/user/add.html index 23292b640..be1db31b5 100644 --- a/ruoyi-admin/src/main/resources/templates/system/user/add.html +++ b/ruoyi-admin/src/main/resources/templates/system/user/add.html @@ -216,8 +216,8 @@ var roleIds = $.form.selectCheckeds("role"); var postIds = $.form.selectSelects("post"); data.push({"name": "status", "value": status}); - data.push({"name": "roleIds", "value": roleIds}); - data.push({"name": "postIds", "value": postIds}); + data.push({"name": "roles", "value": roleIds}); + data.push({"name": "posts", "value": postIds}); $.operate.saveTab(prefix + "/add", data); } } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java index 1720e4830..fa33d3f8d 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/LogAspect.java @@ -1,18 +1,5 @@ package com.ruoyi.framework.aspectj; -import java.lang.reflect.Method; -import java.util.Map; - -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.Signature; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.AfterThrowing; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessStatus; import com.ruoyi.common.json.JSON; @@ -23,6 +10,21 @@ import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysOperLog; import com.ruoyi.system.domain.SysUser; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; +import java.util.Map; /** * 操作日志记录处理 @@ -34,6 +36,9 @@ import com.ruoyi.system.domain.SysUser; public class LogAspect { private static final Logger log = LoggerFactory.getLogger(LogAspect.class); + @Autowired + private MappingJackson2HttpMessageConverter converter; + // 配置织入点 @Pointcut("@annotation(com.ruoyi.common.annotation.Log)") public void logPointCut() { @@ -78,7 +83,7 @@ public class LogAspect { String ip = ShiroUtils.getIp(); operLog.setOperIp(ip); // 返回参数 - operLog.setJsonResult(JSON.marshal(jsonResult)); + operLog.setJsonResult(converter.getObjectMapper().writeValueAsString(jsonResult)); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); if (currentUser != null) { diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index ed99d6f7d..0dd028a41 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -65,7 +65,7 @@ public class SysRole extends BaseEntity { /** * 删除标志(0代表存在 2代表删除) */ - private String delFlag; + private String delFlag = BaseEntity.NOT_DELETED; /** * 用户是否存在此角色标识 默认不存在 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index 1d302dcda..ceb801714 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -149,9 +149,11 @@ public class SysMenuServiceImpl implements ISysMenuService { public List selectMenuAll(Long userId) { List menuList = null; if (SysUser.isAdmin(userId)) { - menuList = menuMapper.selectMenuAll(); + menuList = sysMenuRepository.findAll(); } else { - menuList = menuMapper.selectMenuAllByUserId(userId); + SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + Set roles = user.getRoles(); + menuList = sysMenuRepository.findAll(getSpecification(new SysMenu(), roles)); } return menuList; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index d0d59a39a..8bb25b489 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -9,8 +9,8 @@ import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.mapper.SysRoleDeptMapper; import com.ruoyi.system.mapper.SysRoleMapper; -import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.mapper.SysUserRoleMapper; +import com.ruoyi.system.repository.SysRoleRepository; import com.ruoyi.system.service.ISysRoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -28,15 +28,15 @@ public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; - @Autowired - private SysRoleMenuMapper roleMenuMapper; - @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; + @Autowired + private SysRoleRepository sysRoleRepository; + /** * 根据条件分页查询角色数据 * @@ -105,7 +105,7 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override public SysRole selectRoleById(Long roleId) { - return roleMapper.selectRoleById(roleId); + return sysRoleRepository.findById(roleId).get(); } /** @@ -161,10 +161,8 @@ public class SysRoleServiceImpl implements ISysRoleService { @Transactional public int updateRole(SysRole role) { // 修改角色信息 - roleMapper.updateRole(role); - // 删除角色与菜单关联 - roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId()); - return insertRoleMenu(role); + sysRoleRepository.save(role); + return 1; } /** From 9c1b232c8705d9cf9a1c718fb69a06d526630844 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Tue, 24 Dec 2019 18:14:24 +0800 Subject: [PATCH 33/52] =?UTF-8?q?=E8=A7=92=E8=89=B2=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/ruoyi/system/domain/SysUser.java | 4 ++++ .../com/ruoyi/system/service/impl/SysUserServiceImpl.java | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 945037be0..1749361fa 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -7,7 +7,9 @@ import com.ruoyi.common.annotation.Excels; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.ForeignKey; +import org.hibernate.annotations.SelectBeforeUpdate; import javax.persistence.*; import javax.validation.constraints.Email; @@ -24,6 +26,8 @@ import java.util.Set; */ @Entity @Table(name = "sys_user") +@DynamicUpdate +@SelectBeforeUpdate public class SysUser extends BaseEntity { private static final long serialVersionUID = 1L; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index a423d3905..941006e4c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -13,6 +13,7 @@ import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -228,7 +229,9 @@ public class SysUserServiceImpl implements ISysUserService { @Override @Transactional public SysUser updateUser(SysUser user) { - return sysUserRepository.save(user); + SysUser db = sysUserRepository.findById(user.getUserId()).get(); + BeanUtils.copyProperties(user, db, "delFlag", "loginDate", "loginIp", "salt", "password", "avatar"); + return sysUserRepository.save(db); } /** From da44e6929578711bacd392ba53b38340ae715271 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 10:33:36 +0800 Subject: [PATCH 34/52] =?UTF-8?q?=E8=8F=9C=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysMenuController.java | 6 ++- .../java/com/ruoyi/system/domain/SysMenu.java | 21 +++++++++ .../system/repository/SysMenuRepository.java | 6 +++ .../system/repository/SysRoleRepository.java | 2 + .../ruoyi/system/service/ISysMenuService.java | 4 +- .../service/impl/SysMenuServiceImpl.java | 47 ++++++++++--------- 6 files changed, 59 insertions(+), 27 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java index e8e7e41d2..734382749 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java @@ -99,7 +99,8 @@ public class SysMenuController extends BaseController { } menu.setCreateBy(ShiroUtils.getLoginName()); ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(menuService.insertMenu(menu)); + menuService.insertMenu(menu); + return success(); } /** @@ -124,7 +125,8 @@ public class SysMenuController extends BaseController { } menu.setUpdateBy(ShiroUtils.getLoginName()); ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(menuService.updateMenu(menu)); + menuService.updateMenu(menu); + return success(); } /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java index d0130d2af..0a595f532 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysMenu.java @@ -9,6 +9,7 @@ import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Set; /** @@ -220,4 +221,24 @@ public class SysMenu extends BaseEntity { .append("remark", getRemark()) .toString(); } + + public SysMenu(Long menuId) { + this.menuId = menuId; + } + + public SysMenu() { + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SysMenu sysMenu = (SysMenu) o; + return Objects.equals(menuId, sysMenu.menuId); + } + + @Override + public int hashCode() { + return Objects.hash(menuId); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java index 67a6d05e2..cc08f3047 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java @@ -1,6 +1,7 @@ package com.ruoyi.system.repository; import com.ruoyi.system.domain.SysMenu; +import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; @@ -12,4 +13,9 @@ public interface SysMenuRepository extends BaseRepository { List findAllByMenuTypeInAndVisibleOrderByOrderNum(Collection types, String visiable); + List findAllByRolesContaining(SysRole sysRole); + + int countByParent(SysMenu sysMenu); + + SysMenu findFirstByMenuNameAndParent(String menuName, SysMenu parent); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java index ec810ce66..750bad2b1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java @@ -1,5 +1,6 @@ package com.ruoyi.system.repository; +import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; @@ -7,4 +8,5 @@ import org.springframework.stereotype.Repository; @Repository public interface SysRoleRepository extends BaseRepository { + int countByMenusContaining(SysMenu menu); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java index 45dbdd9cd..6635ff6c5 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysMenuService.java @@ -111,7 +111,7 @@ public interface ISysMenuService { * @param menu 菜单信息 * @return 结果 */ - public int insertMenu(SysMenu menu); + public SysMenu insertMenu(SysMenu menu); /** * 修改保存菜单信息 @@ -119,7 +119,7 @@ public interface ISysMenuService { * @param menu 菜单信息 * @return 结果 */ - public int updateMenu(SysMenu menu); + public SysMenu updateMenu(SysMenu menu); /** * 校验菜单名称是否唯一 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index ceb801714..5bc139905 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -8,15 +8,14 @@ import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.mapper.SysMenuMapper; -import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.repository.SysMenuRepository; +import com.ruoyi.system.repository.SysRoleRepository; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; -import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import javax.persistence.criteria.*; import java.text.MessageFormat; @@ -31,16 +30,12 @@ import java.util.*; public class SysMenuServiceImpl implements ISysMenuService { public static final String PREMISSION_STRING = "perms[\"{0}\"]"; - @Autowired - private SysMenuMapper menuMapper; - @Autowired - private SysRoleMenuMapper roleMenuMapper; @Autowired private SysMenuRepository sysMenuRepository; @Autowired private SysUserRepository sysUserRepository; @Autowired - private JdbcTemplate jdbcTemplate; + private SysRoleRepository sysRoleRepository; /** * 根据用户查询菜单 @@ -166,9 +161,12 @@ public class SysMenuServiceImpl implements ISysMenuService { */ @Override public Set selectPermsByUserId(Long userId) { - List perms = menuMapper.selectPermsByUserId(userId); + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + Set roles = sysUser.getRoles(); + List menus = sysMenuRepository.findAll(getSpecification(new SysMenu(), roles)); Set permsSet = new HashSet<>(); - for (String perm : perms) { + for(SysMenu sysMenu : menus){ + String perm = sysMenu.getPerms(); if (StringUtils.isNotEmpty(perm)) { permsSet.addAll(Arrays.asList(perm.trim().split(","))); } @@ -188,8 +186,8 @@ public class SysMenuServiceImpl implements ISysMenuService { List ztrees = new ArrayList(); List menuList = selectMenuAll(userId); if (StringUtils.isNotNull(roleId)) { - List roleMenuList = menuMapper.selectMenuTree(roleId); - ztrees = initZtree(menuList, roleMenuList, true); + List menus = sysMenuRepository.findAllByRolesContaining(new SysRole(roleId)); + ztrees = initZtree(menuList, menus, true); } else { ztrees = initZtree(menuList, null, true); } @@ -243,7 +241,7 @@ public class SysMenuServiceImpl implements ISysMenuService { * @param permsFlag 是否需要显示权限标识 * @return 树结构列表 */ - public List initZtree(List menuList, List roleMenuList, boolean permsFlag) { + public List initZtree(List menuList, List roleMenuList, boolean permsFlag) { List ztrees = new ArrayList(); boolean isCheck = StringUtils.isNotNull(roleMenuList); for (SysMenu menu : menuList) { @@ -253,7 +251,7 @@ public class SysMenuServiceImpl implements ISysMenuService { ztree.setName(transMenuName(menu, permsFlag)); ztree.setTitle(menu.getMenuName()); if (isCheck) { - ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms())); + ztree.setChecked(roleMenuList.contains(menu)); } ztrees.add(ztree); } @@ -277,7 +275,8 @@ public class SysMenuServiceImpl implements ISysMenuService { */ @Override public int deleteMenuById(Long menuId) { - return menuMapper.deleteMenuById(menuId); + sysMenuRepository.deleteById(menuId); + return 1; } /** @@ -288,7 +287,7 @@ public class SysMenuServiceImpl implements ISysMenuService { */ @Override public SysMenu selectMenuById(Long menuId) { - return menuMapper.selectMenuById(menuId); + return sysMenuRepository.findById(menuId).get(); } /** @@ -299,7 +298,7 @@ public class SysMenuServiceImpl implements ISysMenuService { */ @Override public int selectCountMenuByParentId(Long parentId) { - return menuMapper.selectCountMenuByParentId(parentId); + return sysMenuRepository.countByParent(new SysMenu(parentId)); } /** @@ -310,7 +309,7 @@ public class SysMenuServiceImpl implements ISysMenuService { */ @Override public int selectCountRoleMenuByMenuId(Long menuId) { - return roleMenuMapper.selectCountRoleMenuByMenuId(menuId); + return sysRoleRepository.countByMenusContaining(new SysMenu(menuId)); } /** @@ -319,9 +318,10 @@ public class SysMenuServiceImpl implements ISysMenuService { * @param menu 菜单信息 * @return 结果 */ + @Transactional @Override - public int insertMenu(SysMenu menu) { - return menuMapper.insertMenu(menu); + public SysMenu insertMenu(SysMenu menu) { + return sysMenuRepository.save(menu); } /** @@ -330,9 +330,10 @@ public class SysMenuServiceImpl implements ISysMenuService { * @param menu 菜单信息 * @return 结果 */ + @Transactional @Override - public int updateMenu(SysMenu menu) { - return menuMapper.updateMenu(menu); + public SysMenu updateMenu(SysMenu menu) { + return sysMenuRepository.save(menu); } /** @@ -344,7 +345,7 @@ public class SysMenuServiceImpl implements ISysMenuService { @Override public String checkMenuNameUnique(SysMenu menu) { Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); - SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); + SysMenu info = sysMenuRepository.findFirstByMenuNameAndParent(menu.getMenuName(), new SysMenu(menu.getParentId())); if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) { return UserConstants.MENU_NAME_NOT_UNIQUE; } From c686ff5021e51d5da692e5ea11c959a915e81954 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 14:40:15 +0800 Subject: [PATCH 35/52] =?UTF-8?q?Querydsl=E6=9E=84=E5=BB=BA=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E7=B1=BB=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../utils/querydsl/ExpressionUtils.java | 66 +++++++++++++++++++ .../shiro/session/OnlineSessionDAO.java | 26 +++++--- .../system/service/base/BaseService.java | 30 +++++++++ .../service/impl/SysUserServiceImpl.java | 37 ++++++++++- 4 files changed, 148 insertions(+), 11 deletions(-) create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java new file mode 100644 index 000000000..2ab49348b --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java @@ -0,0 +1,66 @@ +package com.ruoyi.common.utils.querydsl; + +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.ComparableExpression; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.StringPath; + +/** + * QueryDsl 构建查询条件的工具类 + */ +public class ExpressionUtils { + + /** + * 构建 like 查询条件 + * @param path 对应的属性 + * @param value 对应的值 + * @return + */ + public static BooleanExpression buildLike(StringPath path, String value){ + return path.like("%" + value + "%"); + } + + /** + * 构建 等于 查询 + * @param path + * @param value + * @param + * @return + */ + public static > BooleanExpression buildEqual(ComparableExpression path, T value){ + return path.eq(value); + } + + /** + * 构建 等于 查询 + * @param path + * @param value + * @param + * @return + */ + public static > BooleanExpression buildEqual(NumberPath path, T value){ + return path.eq(value); + } + + /** + * 构建 大于等于 查询 + * @param path + * @param value + * @param + * @return + */ + public static > BooleanExpression buildGreaterThanOrEqualTo(ComparableExpression path, T value){ + return path.goe(value); + } + + /** + * 构建 小于等于 查询 + * @param path + * @param value + * @param + * @return + */ + public static > BooleanExpression buildLessThanOrEqualTo(ComparableExpression path, T value){ + return path.loe(value); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java index 8c7702e80..49da39d17 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionDAO.java @@ -1,17 +1,19 @@ package com.ruoyi.framework.shiro.session; -import java.io.Serializable; -import java.util.Date; - -import org.apache.shiro.session.Session; -import org.apache.shiro.session.UnknownSessionException; -import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import com.ruoyi.common.enums.OnlineStatus; import com.ruoyi.framework.manager.AsyncManager; import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.framework.shiro.service.SysShiroService; +import org.apache.shiro.session.Session; +import org.apache.shiro.session.UnknownSessionException; +import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import java.io.Serializable; +import java.util.Date; /** * 针对自定义的ShiroSession的db操作 @@ -19,6 +21,8 @@ import com.ruoyi.framework.shiro.service.SysShiroService; * @author ruoyi */ public class OnlineSessionDAO extends EnterpriseCacheSessionDAO { + + private static final Logger logger = LoggerFactory.getLogger(OnlineSessionDAO.class); /** * 同步session到数据库的周期 单位为毫秒(默认1分钟) */ @@ -100,6 +104,10 @@ public class OnlineSessionDAO extends EnterpriseCacheSessionDAO { return; } onlineSession.setStatus(OnlineStatus.off_line); - sysShiroService.deleteSession(onlineSession); + try{ + sysShiroService.deleteSession(onlineSession); + }catch (Exception e){ + logger.info("delete OnlineSession error : {}", e); + } } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java new file mode 100644 index 000000000..08db4ee12 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java @@ -0,0 +1,30 @@ +package com.ruoyi.system.service.base; + +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.ComparableExpression; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.StringPath; +import com.ruoyi.common.utils.querydsl.ExpressionUtils; + +public class BaseService { + + protected BooleanExpression buildLike(StringPath path, String value){ + return ExpressionUtils.buildLike(path, value); + } + + protected > BooleanExpression buildEqual(ComparableExpression path, T value){ + return ExpressionUtils.buildEqual(path, value); + } + + protected > BooleanExpression buildEqual(NumberPath path, T value){ + return ExpressionUtils.buildEqual(path, value); + } + + protected > BooleanExpression buildGreaterThanOrEqualTo(ComparableExpression path, T value){ + return ExpressionUtils.buildGreaterThanOrEqualTo(path, value); + } + + protected > BooleanExpression buildLessThanOrEqualTo(ComparableExpression path, T value){ + return ExpressionUtils.buildLessThanOrEqualTo(path, value); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 941006e4c..c290729c2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -1,16 +1,19 @@ package com.ruoyi.system.service.impl; +import com.querydsl.core.types.ExpressionUtils; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; +import com.ruoyi.system.domain.QSysUser; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; +import com.ruoyi.system.service.base.BaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; @@ -36,7 +39,7 @@ import java.util.Set; * @author ruoyi */ @Service -public class SysUserServiceImpl implements ISysUserService { +public class SysUserServiceImpl extends BaseService implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); @Autowired @@ -54,7 +57,37 @@ public class SysUserServiceImpl implements ISysUserService { */ @Override public Page selectUserList(SysUser user, Pageable pageRequest) { - return sysUserRepository.findAll(getSpecification(user), pageRequest); + return sysUserRepository.findAll(getPredicate(user), pageRequest); + } + + private com.querydsl.core.types.Predicate getPredicate(SysUser sysUser){ + QSysUser qSysUser = QSysUser.sysUser; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysUser.getDelFlag())){ + predicates.add(qSysUser.delFlag.eq(sysUser.getDelFlag())); + } + if(StringUtils.isNotEmpty(sysUser.getLoginName())){ + predicates.add(buildLike(qSysUser.loginName, sysUser.getLoginName())); + } + if(StringUtils.isNotEmpty(sysUser.getStatus())){ + predicates.add(buildEqual(qSysUser.status, sysUser.getStatus())); + } + if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){ + predicates.add(buildLike(qSysUser.phonenumber, sysUser.getPhonenumber())); + } + if(sysUser.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysUser.createTime, sysUser.getStartTime())); + } + if(sysUser.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysUser.createTime, sysUser.getEndTime())); + } + if(sysUser.getDept() != null && sysUser.getDept().getDeptId() != null){ + predicates.add(buildEqual(qSysUser.dept.deptId, sysUser.getDept().getDeptId())); + } + if(sysUser.getDept() != null && StringUtils.isNotEmpty(sysUser.getDept().getCode())){ + predicates.add(buildLike(qSysUser.dept.code, sysUser.getDept().getCode())); + } + return ExpressionUtils.allOf(predicates); } private Specification getSpecification(SysUser sysUser){ From d15fa052ecba6c168f7b081b9961f01947a6a6af Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 15:31:58 +0800 Subject: [PATCH 36/52] =?UTF-8?q?=E8=A7=92=E8=89=B2=E7=AE=A1=E7=90=86?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysRoleController.java | 14 +- .../ruoyi/common/core/domain/BaseEntity.java | 22 +++ .../java/com/ruoyi/system/domain/SysUser.java | 20 --- .../system/repository/SysRoleRepository.java | 14 ++ .../system/repository/SysUserRepository.java | 3 + .../ruoyi/system/service/ISysRoleService.java | 16 +- .../service/impl/SysDeptServiceImpl.java | 2 +- .../service/impl/SysRoleServiceImpl.java | 164 +++++++++--------- 8 files changed, 139 insertions(+), 116 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 7d4ea2c56..64e219830 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -4,7 +4,6 @@ import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; @@ -16,6 +15,7 @@ import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.annotation.Validated; @@ -49,9 +49,7 @@ public class SysRoleController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysRole role) { - startPage(); - List list = roleService.selectRoleList(role); - return getDataTable(list); + return getDataTable(roleService.selectRoleList(role, getPageRequest())); } @Log(title = "角色管理", businessType = BusinessType.EXPORT) @@ -59,7 +57,7 @@ public class SysRoleController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysRole role) { - List list = roleService.selectRoleList(role); + List list = roleService.selectRoleList(role, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysRole.class); return util.exportExcel(list, "角色数据"); } @@ -87,7 +85,8 @@ public class SysRoleController extends BaseController { } role.setCreateBy(ShiroUtils.getLoginName()); ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(roleService.insertRole(role)); + roleService.insertRole(role); + return success(); } @@ -116,7 +115,8 @@ public class SysRoleController extends BaseController { } role.setUpdateBy(ShiroUtils.getLoginName()); ShiroUtils.clearCachedAuthorizationInfo(); - return toAjax(roleService.updateRole(role)); + roleService.updateRole(role); + return success(); } /** diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java index e4def64d1..531510fe8 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java @@ -79,6 +79,12 @@ public class BaseEntity implements Serializable { @Transient private Map params; + @Transient + private Date startTime; + + @Transient + private Date endTime; + public String getSearchValue() { return searchValue; } @@ -137,4 +143,20 @@ public class BaseEntity implements Serializable { public void setParams(Map params) { this.params = params; } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java index 1749361fa..574530f47 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysUser.java @@ -133,11 +133,7 @@ public class SysUser extends BaseEntity { @org.hibernate.annotations.ForeignKey(name = "none") private Set posts = new HashSet<>(); - @Transient - private Date startTime; - @Transient - private Date endTime; public SysUser() { @@ -292,22 +288,6 @@ public class SysUser extends BaseEntity { this.posts = posts; } - public Date getStartTime() { - return startTime; - } - - public void setStartTime(Date startTime) { - this.startTime = startTime; - } - - public Date getEndTime() { - return endTime; - } - - public void setEndTime(Date endTime) { - this.endTime = endTime; - } - @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java index 750bad2b1..554487390 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java @@ -3,10 +3,24 @@ package com.ruoyi.system.repository; import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface SysRoleRepository extends BaseRepository { int countByMenusContaining(SysMenu menu); + + SysRole findFirstByRoleName(String roleName); + + SysRole findFirstByRoleKey(String roleKey); + + @Query("update SysRole r set r.status = ?1 where r.roleId = ?2") + @Modifying + void updateStatus(String status, Long roleId); + + @EntityGraph(attributePaths = {"depts", "menus"}) + SysRole findByRoleId(Long roleId); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java index 2a10e307b..259c758ee 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -2,6 +2,7 @@ package com.ruoyi.system.repository; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysPost; +import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.EntityGraph; @@ -36,4 +37,6 @@ public interface SysUserRepository extends BaseRepository { @Modifying @Query("update SysUser u set u.status = ?1 where u.userId = ?2") void changeStatus(String status, Long userId); + + int countByRolesContaining(SysRole sysRole); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java index bedf5298e..f7b3a3b47 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java @@ -1,10 +1,12 @@ package com.ruoyi.system.service; -import java.util.List; -import java.util.Set; - import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUserRole; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; +import java.util.Set; /** * 角色业务层 @@ -18,7 +20,7 @@ public interface ISysRoleService { * @param role 角色信息 * @return 角色数据集合信息 */ - public List selectRoleList(SysRole role); + public Page selectRoleList(SysRole role, Pageable pageable); /** * 根据用户ID查询角色 @@ -34,7 +36,7 @@ public interface ISysRoleService { * @param userId 用户ID * @return 角色列表 */ - public List selectRolesByUserId(Long userId); + public Set selectRolesByUserId(Long userId); /** * 查询所有角色 @@ -74,7 +76,7 @@ public interface ISysRoleService { * @param role 角色信息 * @return 结果 */ - public int insertRole(SysRole role); + public SysRole insertRole(SysRole role); /** * 修改保存角色信息 @@ -82,7 +84,7 @@ public interface ISysRoleService { * @param role 角色信息 * @return 结果 */ - public int updateRole(SysRole role); + public SysRole updateRole(SysRole role); /** * 修改数据权限信息 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index 339c74176..c56388f93 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -98,7 +98,7 @@ public class SysDeptServiceImpl implements ISysDeptService { List ztrees; List deptList = sysDeptRepository.findAll(getSpecification(new SysDept())); if (StringUtils.isNotNull(roleId)) { - SysRole sysRole = sysRoleRepository.findById(roleId).get(); + SysRole sysRole = sysRoleRepository.findByRoleId(roleId); ztrees = initZtree(deptList, sysRole.getDepts()); } else { ztrees = initZtree(deptList); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index 8bb25b489..14c8d94ad 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -1,18 +1,23 @@ package com.ruoyi.system.service.impl; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.system.domain.QSysRole; import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUserRole; -import com.ruoyi.system.mapper.SysRoleDeptMapper; -import com.ruoyi.system.mapper.SysRoleMapper; -import com.ruoyi.system.mapper.SysUserRoleMapper; import com.ruoyi.system.repository.SysRoleRepository; +import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysRoleService; +import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,18 +29,12 @@ import java.util.*; * @author ruoyi */ @Service -public class SysRoleServiceImpl implements ISysRoleService { - @Autowired - private SysRoleMapper roleMapper; - - @Autowired - private SysUserRoleMapper userRoleMapper; - - @Autowired - private SysRoleDeptMapper roleDeptMapper; +public class SysRoleServiceImpl extends BaseService implements ISysRoleService { @Autowired private SysRoleRepository sysRoleRepository; + @Autowired + private SysUserRepository sysUserRepository; /** * 根据条件分页查询角色数据 @@ -44,8 +43,33 @@ public class SysRoleServiceImpl implements ISysRoleService { * @return 角色数据集合信息 */ @Override - public List selectRoleList(SysRole role) { - return roleMapper.selectRoleList(role); + public Page selectRoleList(SysRole role, Pageable pageable) { + return sysRoleRepository.findAll(getPredicate(role), pageable); + } + + private Predicate getPredicate(SysRole role){ + QSysRole qSysRole = QSysRole.sysRole; + List predicates = new ArrayList<>(); + predicates.add(buildEqual(qSysRole.delFlag, BaseEntity.NOT_DELETED)); + if(StringUtils.isNotEmpty(role.getRoleName())){ + predicates.add(buildLike(qSysRole.roleName, role.getRoleName())); + } + if(StringUtils.isNotEmpty(role.getStatus())){ + predicates.add(buildEqual(qSysRole.status, role.getStatus())); + } + if(StringUtils.isNotEmpty(role.getRoleKey())){ + predicates.add(buildLike(qSysRole.roleKey, role.getRoleKey())); + } + if(StringUtils.isNotEmpty(role.getDataScope())){ + predicates.add(buildEqual(qSysRole.dataScope, role.getDataScope())); + } + if(role.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysRole.createTime, role.getStartTime())); + } + if(role.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysRole.createTime, role.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -56,12 +80,11 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override public Set selectRoleKeys(Long userId) { - List perms = roleMapper.selectRolesByUserId(userId); + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + Set roles = sysUser.getRoles(); Set permsSet = new HashSet<>(); - for (SysRole perm : perms) { - if (StringUtils.isNotNull(perm)) { - permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); - } + for (SysRole perm : roles) { + permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); } return permsSet; } @@ -73,18 +96,9 @@ public class SysRoleServiceImpl implements ISysRoleService { * @return 角色列表 */ @Override - public List selectRolesByUserId(Long userId) { - List userRoles = roleMapper.selectRolesByUserId(userId); - List roles = selectRoleAll(); - for (SysRole role : roles) { - for (SysRole userRole : userRoles) { - if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { - role.setFlag(true); - break; - } - } - } - return roles; + public Set selectRolesByUserId(Long userId) { + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + return sysUser.getRoles(); } /** @@ -94,7 +108,7 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override public List selectRoleAll() { - return SpringUtils.getAopProxy(this).selectRoleList(new SysRole()); + return sysRoleRepository.findAll(getPredicate(new SysRole()), Pageable.unpaged()).getContent(); } /** @@ -114,9 +128,11 @@ public class SysRoleServiceImpl implements ISysRoleService { * @param roleId 角色ID * @return 结果 */ + @Transactional @Override public boolean deleteRoleById(Long roleId) { - return roleMapper.deleteRoleById(roleId) > 0 ? true : false; + sysRoleRepository.deleteById(roleId); + return true; } /** @@ -125,6 +141,7 @@ public class SysRoleServiceImpl implements ISysRoleService { * @param ids 需要删除的数据ID * @throws Exception */ + @Transactional @Override public int deleteRoleByIds(String ids) throws BusinessException { Long[] roleIds = Convert.toLongArray(ids); @@ -134,8 +151,9 @@ public class SysRoleServiceImpl implements ISysRoleService { if (countUserRoleByRoleId(roleId) > 0) { throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName())); } + deleteRoleById(roleId); } - return roleMapper.deleteRoleByIds(roleIds); + return roleIds.length; } /** @@ -146,10 +164,8 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override @Transactional - public int insertRole(SysRole role) { - // 新增角色信息 - roleMapper.insertRole(role); - return insertRoleMenu(role); + public SysRole insertRole(SysRole role) { + return sysRoleRepository.save(role); } /** @@ -159,10 +175,8 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override @Transactional - public int updateRole(SysRole role) { - // 修改角色信息 - sysRoleRepository.save(role); - return 1; + public SysRole updateRole(SysRole role) { + return sysRoleRepository.save(role); } /** @@ -173,31 +187,10 @@ public class SysRoleServiceImpl implements ISysRoleService { @Override @Transactional public int authDataScope(SysRole role) { - // 修改角色信息 - roleMapper.updateRole(role); - // 删除角色与部门关联 - roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId()); - // 新增角色和部门信息(数据权限) - return insertRoleDept(role); - } - - /** - * 新增角色菜单信息 - * @param role 角色对象 - */ - public int insertRoleMenu(SysRole role) { - int rows = 1; - return rows; - } - - /** - * 新增角色部门信息(数据权限) - * - * @param role 角色对象 - */ - public int insertRoleDept(SysRole role) { - int rows = 1; - return rows; + SysRole db = sysRoleRepository.findById(role.getRoleId()).get(); + db.setDataScope(role.getDataScope()); + db.setDepts(role.getDepts()); + return 1; } /** @@ -209,7 +202,7 @@ public class SysRoleServiceImpl implements ISysRoleService { @Override public String checkRoleNameUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); - SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); + SysRole info = sysRoleRepository.findFirstByRoleName(role.getRoleName()); if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { return UserConstants.ROLE_NAME_NOT_UNIQUE; } @@ -225,7 +218,7 @@ public class SysRoleServiceImpl implements ISysRoleService { @Override public String checkRoleKeyUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); - SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); + SysRole info = sysRoleRepository.findFirstByRoleKey(role.getRoleKey()); if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { return UserConstants.ROLE_KEY_NOT_UNIQUE; } @@ -251,7 +244,7 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override public int countUserRoleByRoleId(Long roleId) { - return userRoleMapper.countUserRoleByRoleId(roleId); + return sysUserRepository.countByRolesContaining(new SysRole(roleId)); } /** @@ -262,7 +255,8 @@ public class SysRoleServiceImpl implements ISysRoleService { */ @Override public int changeStatus(SysRole role) { - return roleMapper.updateRole(role); + sysRoleRepository.updateStatus(role.getStatus(), role.getRoleId()); + return 1; } /** @@ -271,9 +265,13 @@ public class SysRoleServiceImpl implements ISysRoleService { * @param userRole 用户和角色关联信息 * @return 结果 */ + @Transactional @Override public int deleteAuthUser(SysUserRole userRole) { - return userRoleMapper.deleteUserRoleInfo(userRole); + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userRole.getUserId()); + Set roles = sysUser.getRoles(); + roles.remove(new SysRole(userRole.getRoleId())); + return 1; } /** @@ -284,7 +282,13 @@ public class SysRoleServiceImpl implements ISysRoleService { * @return 结果 */ public int deleteAuthUsers(Long roleId, String userIds) { - return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds)); + SysRole sysRole = sysRoleRepository.findById(roleId).get(); + Long[] users = Convert.toLongArray(userIds); + for (Long userId : users) { + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + sysUser.getRoles().remove(sysRole); + } + return 1; } /** @@ -294,16 +298,14 @@ public class SysRoleServiceImpl implements ISysRoleService { * @param userIds 需要删除的用户数据ID * @return 结果 */ + @Transactional public int insertAuthUsers(Long roleId, String userIds) { + SysRole sysRole = sysRoleRepository.findById(roleId).get(); Long[] users = Convert.toLongArray(userIds); - // 新增用户与角色管理 - List list = new ArrayList(); for (Long userId : users) { - SysUserRole ur = new SysUserRole(); - ur.setUserId(userId); - ur.setRoleId(roleId); - list.add(ur); + SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + sysUser.getRoles().add(sysRole); } - return userRoleMapper.batchUserRole(list); + return 1; } } From cf52d99b2af5254de067d8ca773b0a3f7b2e632e Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 16:07:30 +0800 Subject: [PATCH 37/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../monitor/SysOperlogController.java | 25 +- .../system/SysNoticeController.java | 4 +- .../mysql/v003__update_root_menu_id.sql | 1 + .../com/ruoyi/system/domain/SysNotice.java | 5 + .../com/ruoyi/system/domain/SysOperLog.java | 7 + .../ruoyi/system/mapper/SysMenuMapper.java | 124 ---------- .../ruoyi/system/mapper/SysNoticeMapper.java | 52 ----- .../ruoyi/system/mapper/SysOperLogMapper.java | 48 ---- .../ruoyi/system/mapper/SysPostMapper.java | 83 ------- .../system/mapper/SysRoleDeptMapper.java | 44 ---- .../ruoyi/system/mapper/SysRoleMapper.java | 84 ------- .../system/mapper/SysRoleMenuMapper.java | 44 ---- .../ruoyi/system/mapper/SysUserMapper.java | 124 ---------- .../system/mapper/SysUserOnlineMapper.java | 52 ----- .../system/mapper/SysUserPostMapper.java | 44 ---- .../system/mapper/SysUserRoleMapper.java | 62 ----- .../repository/SysNoticeRepository.java | 15 ++ .../repository/SysOperLogRepository.java | 15 ++ .../system/service/ISysNoticeService.java | 4 +- .../system/service/ISysOperLogService.java | 4 +- .../service/impl/SysNoticeServiceImpl.java | 56 +++-- .../service/impl/SysOperLogServiceImpl.java | 68 ++++-- .../resources/mapper/system/SysMenuMapper.xml | 179 -------------- .../mapper/system/SysNoticeMapper.xml | 85 ------- .../mapper/system/SysOperLogMapper.xml | 82 ------- .../resources/mapper/system/SysPostMapper.xml | 110 --------- .../mapper/system/SysRoleDeptMapper.xml | 34 --- .../resources/mapper/system/SysRoleMapper.xml | 131 ----------- .../mapper/system/SysRoleMenuMapper.xml | 34 --- .../resources/mapper/system/SysUserMapper.xml | 219 ------------------ .../mapper/system/SysUserOnlineMapper.xml | 57 ----- .../mapper/system/SysUserPostMapper.xml | 34 --- .../mapper/system/SysUserRoleMapper.xml | 44 ---- 33 files changed, 158 insertions(+), 1816 deletions(-) create mode 100644 ruoyi-admin/src/main/resources/db/migration/mysql/v003__update_root_menu_id.sql delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysMenuMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysNoticeMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysOperLogMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysPostMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysRoleMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysUserOnlineMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysUserPostMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysUserRoleMapper.xml diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java index 2c51d7891..d7001d272 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java @@ -1,16 +1,5 @@ package com.ruoyi.web.controller.monitor; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -19,6 +8,14 @@ import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.system.domain.SysOperLog; import com.ruoyi.system.service.ISysOperLogService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 操作日志记录 @@ -43,9 +40,7 @@ public class SysOperlogController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysOperLog operLog) { - startPage(); - List list = operLogService.selectOperLogList(operLog); - return getDataTable(list); + return getDataTable(operLogService.selectOperLogList(operLog, getPageRequest())); } @Log(title = "操作日志", businessType = BusinessType.EXPORT) @@ -53,7 +48,7 @@ public class SysOperlogController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysOperLog operLog) { - List list = operLogService.selectOperLogList(operLog); + List list = operLogService.selectOperLogList(operLog, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysOperLog.class); return util.exportExcel(list, "操作日志"); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java index c9a1aceb2..c28ceeacc 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysNoticeController.java @@ -46,9 +46,7 @@ public class SysNoticeController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysNotice notice) { - startPage(); - List list = noticeService.selectNoticeList(notice); - return getDataTable(list); + return getDataTable(noticeService.selectNoticeList(notice, getPageRequest())); } /** diff --git a/ruoyi-admin/src/main/resources/db/migration/mysql/v003__update_root_menu_id.sql b/ruoyi-admin/src/main/resources/db/migration/mysql/v003__update_root_menu_id.sql new file mode 100644 index 000000000..b157b1204 --- /dev/null +++ b/ruoyi-admin/src/main/resources/db/migration/mysql/v003__update_root_menu_id.sql @@ -0,0 +1 @@ +UPDATE sys_menu SET parent_id = NULL WHERE parent_id = 0; \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java index fc6798458..6188167d4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java @@ -1,5 +1,6 @@ package com.ruoyi.system.domain; +import javax.persistence.*; import javax.validation.constraints.*; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -11,12 +12,16 @@ import com.ruoyi.common.core.domain.BaseEntity; * * @author ruoyi */ +@Entity +@Table(name = "sys_notice") public class SysNotice extends BaseEntity { private static final long serialVersionUID = 1L; /** * 公告ID */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long noticeId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java index 68d486336..620183120 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java @@ -9,11 +9,15 @@ import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import javax.persistence.*; + /** * 操作日志记录表 oper_log * * @author ruoyi */ +@Entity +@Table(name = "sys_oper_log") public class SysOperLog extends BaseEntity { private static final long serialVersionUID = 1L; @@ -21,6 +25,8 @@ public class SysOperLog extends BaseEntity { * 日志主键 */ @Excel(name = "操作序号", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long operId; /** @@ -38,6 +44,7 @@ public class SysOperLog extends BaseEntity { /** * 业务类型数组 */ + @Transient private Integer[] businessTypes; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java deleted file mode 100644 index 526059e83..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysMenu; - -/** - * 菜单表 数据层 - * - * @author ruoyi - */ -public interface SysMenuMapper { - /** - * 查询系统所有菜单(含按钮) - * - * @return 菜单列表 - */ - public List selectMenuAll(); - - /** - * 根据用户ID查询菜单 - * - * @param userId 用户ID - * @return 菜单列表 - */ - public List selectMenuAllByUserId(Long userId); - - /** - * 查询系统正常显示菜单(不含按钮) - * - * @return 菜单列表 - */ - public List selectMenuNormalAll(); - - /** - * 根据用户ID查询菜单 - * - * @param userId 用户ID - * @return 菜单列表 - */ - public List selectMenusByUserId(Long userId); - - /** - * 根据用户ID查询权限 - * - * @param userId 用户ID - * @return 权限列表 - */ - public List selectPermsByUserId(Long userId); - - /** - * 根据角色ID查询菜单 - * - * @param roleId 角色ID - * @return 菜单列表 - */ - public List selectMenuTree(Long roleId); - - /** - * 查询系统菜单列表 - * - * @param menu 菜单信息 - * @return 菜单列表 - */ - public List selectMenuList(SysMenu menu); - - /** - * 查询系统菜单列表 - * - * @param menu 菜单信息 - * @return 菜单列表 - */ - public List selectMenuListByUserId(SysMenu menu); - - /** - * 删除菜单管理信息 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int deleteMenuById(Long menuId); - - /** - * 根据菜单ID查询信息 - * - * @param menuId 菜单ID - * @return 菜单信息 - */ - public SysMenu selectMenuById(Long menuId); - - /** - * 查询菜单数量 - * - * @param parentId 菜单父ID - * @return 结果 - */ - public int selectCountMenuByParentId(Long parentId); - - /** - * 新增菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int insertMenu(SysMenu menu); - - /** - * 修改菜单信息 - * - * @param menu 菜单信息 - * @return 结果 - */ - public int updateMenu(SysMenu menu); - - /** - * 校验菜单名称是否唯一 - * - * @param menuName 菜单名称 - * @param parentId 父菜单ID - * @return 结果 - */ - public SysMenu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") Long parentId); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java deleted file mode 100644 index dec9ba486..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysNoticeMapper.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysNotice; - -/** - * 公告 数据层 - * - * @author ruoyi - */ -public interface SysNoticeMapper { - /** - * 查询公告信息 - * - * @param noticeId 公告ID - * @return 公告信息 - */ - public SysNotice selectNoticeById(Long noticeId); - - /** - * 查询公告列表 - * - * @param notice 公告信息 - * @return 公告集合 - */ - public List selectNoticeList(SysNotice notice); - - /** - * 新增公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int insertNotice(SysNotice notice); - - /** - * 修改公告 - * - * @param notice 公告信息 - * @return 结果 - */ - public int updateNotice(SysNotice notice); - - /** - * 批量删除公告 - * - * @param noticeIds 需要删除的数据ID - * @return 结果 - */ - public int deleteNoticeByIds(String[] noticeIds); -} \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java deleted file mode 100644 index 3f92aebe5..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysOperLogMapper.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysOperLog; - -/** - * 操作日志 数据层 - * - * @author ruoyi - */ -public interface SysOperLogMapper { - /** - * 新增操作日志 - * - * @param operLog 操作日志对象 - */ - public void insertOperlog(SysOperLog operLog); - - /** - * 查询系统操作日志集合 - * - * @param operLog 操作日志对象 - * @return 操作日志集合 - */ - public List selectOperLogList(SysOperLog operLog); - - /** - * 批量删除系统操作日志 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteOperLogByIds(String[] ids); - - /** - * 查询操作日志详细 - * - * @param operId 操作ID - * @return 操作日志对象 - */ - public SysOperLog selectOperLogById(Long operId); - - /** - * 清空操作日志 - */ - public void cleanOperLog(); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java deleted file mode 100644 index 1649802d7..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysPostMapper.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysPost; - -/** - * 岗位信息 数据层 - * - * @author ruoyi - */ -public interface SysPostMapper { - /** - * 查询岗位数据集合 - * - * @param post 岗位信息 - * @return 岗位数据集合 - */ - public List selectPostList(SysPost post); - - /** - * 查询所有岗位 - * - * @return 岗位列表 - */ - public List selectPostAll(); - - /** - * 根据用户ID查询岗位 - * - * @param userId 用户ID - * @return 岗位列表 - */ - public List selectPostsByUserId(Long userId); - - /** - * 通过岗位ID查询岗位信息 - * - * @param postId 岗位ID - * @return 角色对象信息 - */ - public SysPost selectPostById(Long postId); - - /** - * 批量删除岗位信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deletePostByIds(Long[] ids); - - /** - * 修改岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int updatePost(SysPost post); - - /** - * 新增岗位信息 - * - * @param post 岗位信息 - * @return 结果 - */ - public int insertPost(SysPost post); - - /** - * 校验岗位名称 - * - * @param postName 岗位名称 - * @return 结果 - */ - public SysPost checkPostNameUnique(String postName); - - /** - * 校验岗位编码 - * - * @param postCode 岗位编码 - * @return 结果 - */ - public SysPost checkPostCodeUnique(String postCode); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java deleted file mode 100644 index e2615c035..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleDeptMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysRoleDept; - -/** - * 角色与部门关联表 数据层 - * - * @author ruoyi - */ -public interface SysRoleDeptMapper { - /** - * 通过角色ID删除角色和部门关联 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleDeptByRoleId(Long roleId); - - /** - * 批量删除角色部门关联信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleDept(Long[] ids); - - /** - * 查询部门使用数量 - * - * @param deptId 部门ID - * @return 结果 - */ - public int selectCountRoleDeptByDeptId(Long deptId); - - /** - * 批量新增角色部门信息 - * - * @param roleDeptList 角色部门列表 - * @return 结果 - */ - public int batchRoleDept(List roleDeptList); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java deleted file mode 100644 index 9a2b1dff3..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMapper.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysRole; - -/** - * 角色表 数据层 - * - * @author ruoyi - */ -public interface SysRoleMapper { - /** - * 根据条件分页查询角色数据 - * - * @param role 角色信息 - * @return 角色数据集合信息 - */ - public List selectRoleList(SysRole role); - - /** - * 根据用户ID查询角色 - * - * @param userId 用户ID - * @return 角色列表 - */ - public List selectRolesByUserId(Long userId); - - /** - * 通过角色ID查询角色 - * - * @param roleId 角色ID - * @return 角色对象信息 - */ - public SysRole selectRoleById(Long roleId); - - /** - * 通过角色ID删除角色 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleById(Long roleId); - - /** - * 批量角色用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleByIds(Long[] ids); - - /** - * 修改角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int updateRole(SysRole role); - - /** - * 新增角色信息 - * - * @param role 角色信息 - * @return 结果 - */ - public int insertRole(SysRole role); - - /** - * 校验角色名称是否唯一 - * - * @param roleName 角色名称 - * @return 角色信息 - */ - public SysRole checkRoleNameUnique(String roleName); - - /** - * 校验角色权限是否唯一 - * - * @param roleKey 角色权限 - * @return 角色信息 - */ - public SysRole checkRoleKeyUnique(String roleKey); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java deleted file mode 100644 index c69f9fbf9..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysRoleMenuMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysRoleMenu; - -/** - * 角色与菜单关联表 数据层 - * - * @author ruoyi - */ -public interface SysRoleMenuMapper { - /** - * 通过角色ID删除角色和菜单关联 - * - * @param roleId 角色ID - * @return 结果 - */ - public int deleteRoleMenuByRoleId(Long roleId); - - /** - * 批量删除角色菜单关联信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteRoleMenu(Long[] ids); - - /** - * 查询菜单使用数量 - * - * @param menuId 菜单ID - * @return 结果 - */ - public int selectCountRoleMenuByMenuId(Long menuId); - - /** - * 批量新增角色菜单信息 - * - * @param roleMenuList 角色菜单列表 - * @return 结果 - */ - public int batchRoleMenu(List roleMenuList); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java deleted file mode 100644 index 51dbdb7bc..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysUser; - -/** - * 用户表 数据层 - * - * @author ruoyi - */ -public interface SysUserMapper { - /** - * 根据条件分页查询用户列表 - * - * @param sysUser 用户信息 - * @return 用户信息集合信息 - */ - public List selectUserList(SysUser sysUser); - - /** - * 根据条件分页查询未已配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectAllocatedList(SysUser user); - - /** - * 根据条件分页查询未分配用户角色列表 - * - * @param user 用户信息 - * @return 用户信息集合信息 - */ - public List selectUnallocatedList(SysUser user); - - /** - * 通过用户名查询用户 - * - * @param userName 用户名 - * @return 用户对象信息 - */ - public SysUser selectUserByLoginName(String userName); - - /** - * 通过手机号码查询用户 - * - * @param phoneNumber 手机号码 - * @return 用户对象信息 - */ - public SysUser selectUserByPhoneNumber(String phoneNumber); - - /** - * 通过邮箱查询用户 - * - * @param email 邮箱 - * @return 用户对象信息 - */ - public SysUser selectUserByEmail(String email); - - /** - * 通过用户ID查询用户 - * - * @param userId 用户ID - * @return 用户对象信息 - */ - public SysUser selectUserById(Long userId); - - /** - * 通过用户ID删除用户 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserById(Long userId); - - /** - * 批量删除用户信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserByIds(Long[] ids); - - /** - * 修改用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int updateUser(SysUser user); - - /** - * 新增用户信息 - * - * @param user 用户信息 - * @return 结果 - */ - public int insertUser(SysUser user); - - /** - * 校验用户名称是否唯一 - * - * @param loginName 登录名称 - * @return 结果 - */ - public int checkLoginNameUnique(String loginName); - - /** - * 校验手机号码是否唯一 - * - * @param phonenumber 手机号码 - * @return 结果 - */ - public SysUser checkPhoneUnique(String phonenumber); - - /** - * 校验email是否唯一 - * - * @param email 用户邮箱 - * @return 结果 - */ - public SysUser checkEmailUnique(String email); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java deleted file mode 100644 index 807f9b838..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserOnlineMapper.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysUserOnline; - -/** - * 在线用户 数据层 - * - * @author ruoyi - */ -public interface SysUserOnlineMapper { - /** - * 通过会话序号查询信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public SysUserOnline selectOnlineById(String sessionId); - - /** - * 通过会话序号删除信息 - * - * @param sessionId 会话ID - * @return 在线用户信息 - */ - public int deleteOnlineById(String sessionId); - - /** - * 保存会话信息 - * - * @param online 会话信息 - * @return 结果 - */ - public int saveOnline(SysUserOnline online); - - /** - * 查询会话集合 - * - * @param userOnline 会话参数 - * @return 会话集合 - */ - public List selectUserOnlineList(SysUserOnline userOnline); - - /** - * 查询过期会话集合 - * - * @param lastAccessTime 过期时间 - * @return 会话集合 - */ - public List selectOnlineByExpired(String lastAccessTime); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java deleted file mode 100644 index 468efb990..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserPostMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysUserPost; - -/** - * 用户与岗位关联表 数据层 - * - * @author ruoyi - */ -public interface SysUserPostMapper { - /** - * 通过用户ID删除用户和岗位关联 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserPostByUserId(Long userId); - - /** - * 通过岗位ID查询岗位使用数量 - * - * @param postId 岗位ID - * @return 结果 - */ - public int countUserPostById(Long postId); - - /** - * 批量删除用户和岗位关联 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserPost(Long[] ids); - - /** - * 批量新增用户岗位信息 - * - * @param userPostList 用户角色列表 - * @return 结果 - */ - public int batchUserPost(List userPostList); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java deleted file mode 100644 index 020be070f..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserRoleMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysUserRole; - -/** - * 用户与角色关联表 数据层 - * - * @author ruoyi - */ -public interface SysUserRoleMapper { - /** - * 通过用户ID删除用户和角色关联 - * - * @param userId 用户ID - * @return 结果 - */ - public int deleteUserRoleByUserId(Long userId); - - /** - * 批量删除用户和角色关联 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteUserRole(Long[] ids); - - /** - * 通过角色ID查询角色使用数量 - * - * @param roleId 角色ID - * @return 结果 - */ - public int countUserRoleByRoleId(Long roleId); - - /** - * 批量新增用户角色信息 - * - * @param userRoleList 用户角色列表 - * @return 结果 - */ - public int batchUserRole(List userRoleList); - - /** - * 删除用户和角色关联信息 - * - * @param userRole 用户和角色关联信息 - * @return 结果 - */ - public int deleteUserRoleInfo(SysUserRole userRole); - - /** - * 批量取消授权用户角色 - * - * @param roleId 角色ID - * @param userIds 需要删除的用户数据ID - * @return 结果 - */ - public int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java new file mode 100644 index 000000000..fc7c74699 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysNotice; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Repository; + +import java.util.Collection; + +@Repository +public interface SysNoticeRepository extends BaseRepository { + + @Modifying + void deleteByNoticeIdIn(Collection ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java new file mode 100644 index 000000000..f37f90ab8 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysOperLog; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Repository; + +import java.util.Collection; + +@Repository +public interface SysOperLogRepository extends BaseRepository { + + @Modifying + void deleteByOperIdIn(Collection ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java index 7dc902da6..85ea7774b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysNoticeService.java @@ -3,6 +3,8 @@ package com.ruoyi.system.service; import java.util.List; import com.ruoyi.system.domain.SysNotice; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 公告 服务层 @@ -24,7 +26,7 @@ public interface ISysNoticeService { * @param notice 公告信息 * @return 公告集合 */ - public List selectNoticeList(SysNotice notice); + public Page selectNoticeList(SysNotice notice, Pageable pageable); /** * 新增公告 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java index 66b45382f..270c4edff 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysOperLogService.java @@ -3,6 +3,8 @@ package com.ruoyi.system.service; import java.util.List; import com.ruoyi.system.domain.SysOperLog; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 操作日志 服务层 @@ -23,7 +25,7 @@ public interface ISysOperLogService { * @param operLog 操作日志对象 * @return 操作日志集合 */ - public List selectOperLogList(SysOperLog operLog); + public Page selectOperLogList(SysOperLog operLog, Pageable pageable); /** * 批量删除系统操作日志 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java index 6d76b75fd..ff485c602 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java @@ -1,13 +1,23 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysNotice; import com.ruoyi.system.domain.SysNotice; -import com.ruoyi.system.mapper.SysNoticeMapper; +import com.ruoyi.system.repository.SysNoticeRepository; import com.ruoyi.system.service.ISysNoticeService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * 公告 服务层实现 @@ -16,9 +26,9 @@ import com.ruoyi.system.service.ISysNoticeService; * @date 2018-06-25 */ @Service -public class SysNoticeServiceImpl implements ISysNoticeService { +public class SysNoticeServiceImpl extends BaseService implements ISysNoticeService { @Autowired - private SysNoticeMapper noticeMapper; + private SysNoticeRepository sysNoticeRepository; /** * 查询公告信息 @@ -28,7 +38,7 @@ public class SysNoticeServiceImpl implements ISysNoticeService { */ @Override public SysNotice selectNoticeById(Long noticeId) { - return noticeMapper.selectNoticeById(noticeId); + return sysNoticeRepository.findById(noticeId).get(); } /** @@ -38,8 +48,23 @@ public class SysNoticeServiceImpl implements ISysNoticeService { * @return 公告集合 */ @Override - public List selectNoticeList(SysNotice notice) { - return noticeMapper.selectNoticeList(notice); + public Page selectNoticeList(SysNotice notice, Pageable pageable) { + return sysNoticeRepository.findAll(getPredicate(notice), pageable); + } + + private Predicate getPredicate(SysNotice sysNotice){ + QSysNotice qSysNotice = QSysNotice.sysNotice; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysNotice.getNoticeTitle())){ + predicates.add(buildLike(qSysNotice.noticeTitle, sysNotice.getNoticeTitle())); + } + if(StringUtils.isNotEmpty(sysNotice.getNoticeType())){ + predicates.add(buildEqual(qSysNotice.noticeType, sysNotice.getNoticeType())); + } + if(StringUtils.isNotEmpty(sysNotice.getCreateBy())){ + predicates.add(buildLike(qSysNotice.createBy, sysNotice.getCreateBy())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -48,9 +73,11 @@ public class SysNoticeServiceImpl implements ISysNoticeService { * @param notice 公告信息 * @return 结果 */ + @Transactional @Override public int insertNotice(SysNotice notice) { - return noticeMapper.insertNotice(notice); + sysNoticeRepository.save(notice); + return 1; } /** @@ -59,9 +86,11 @@ public class SysNoticeServiceImpl implements ISysNoticeService { * @param notice 公告信息 * @return 结果 */ + @Transactional @Override public int updateNotice(SysNotice notice) { - return noticeMapper.updateNotice(notice); + sysNoticeRepository.save(notice); + return 1; } /** @@ -72,6 +101,7 @@ public class SysNoticeServiceImpl implements ISysNoticeService { */ @Override public int deleteNoticeByIds(String ids) { - return noticeMapper.deleteNoticeByIds(Convert.toStrArray(ids)); + sysNoticeRepository.deleteByNoticeIdIn(Arrays.asList(Convert.toLongArray(ids))); + return 1; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java index 69ff4450e..89822dd7a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java @@ -1,13 +1,24 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysOperLog; import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.mapper.SysOperLogMapper; +import com.ruoyi.system.repository.SysOperLogRepository; import com.ruoyi.system.service.ISysOperLogService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * 操作日志 服务层处理 @@ -15,9 +26,11 @@ import com.ruoyi.system.service.ISysOperLogService; * @author ruoyi */ @Service -public class SysOperLogServiceImpl implements ISysOperLogService { +public class SysOperLogServiceImpl extends BaseService implements ISysOperLogService { @Autowired - private SysOperLogMapper operLogMapper; + private SysOperLogRepository sysOperLogRepository; + @Autowired + private JdbcTemplate jdbcTemplate; /** * 新增操作日志 @@ -26,7 +39,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService { */ @Override public void insertOperlog(SysOperLog operLog) { - operLogMapper.insertOperlog(operLog); + sysOperLogRepository.save(operLog); } /** @@ -36,8 +49,35 @@ public class SysOperLogServiceImpl implements ISysOperLogService { * @return 操作日志集合 */ @Override - public List selectOperLogList(SysOperLog operLog) { - return operLogMapper.selectOperLogList(operLog); + public Page selectOperLogList(SysOperLog operLog, Pageable pageable) { + return sysOperLogRepository.findAll(getPredicate(operLog), pageable); + } + + private Predicate getPredicate(SysOperLog operLog){ + QSysOperLog qSysOperLog = QSysOperLog.sysOperLog; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(operLog.getTitle())){ + predicates.add(buildLike(qSysOperLog.title, operLog.getTitle())); + } + if(operLog.getBusinessType() != null){ + predicates.add(buildEqual(qSysOperLog.businessType, operLog.getBusinessType())); + } + if(operLog.getBusinessTypes() != null && operLog.getBusinessTypes().length > 0){ + predicates.add(qSysOperLog.businessType.in(operLog.getBusinessTypes())); + } + if(operLog.getStatus() != null){ + predicates.add(buildEqual(qSysOperLog.status, operLog.getStatus())); + } + if(StringUtils.isNotEmpty(operLog.getOperName())){ + predicates.add(buildLike(qSysOperLog.operName, operLog.getOperName())); + } + if(operLog.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysOperLog.operTime, operLog.getStartTime())); + } + if(operLog.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysOperLog.operTime, operLog.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -48,7 +88,8 @@ public class SysOperLogServiceImpl implements ISysOperLogService { */ @Override public int deleteOperLogByIds(String ids) { - return operLogMapper.deleteOperLogByIds(Convert.toStrArray(ids)); + sysOperLogRepository.deleteByOperIdIn(Arrays.asList(Convert.toLongArray(ids))); + return 1; } /** @@ -59,14 +100,15 @@ public class SysOperLogServiceImpl implements ISysOperLogService { */ @Override public SysOperLog selectOperLogById(Long operId) { - return operLogMapper.selectOperLogById(operId); + return sysOperLogRepository.findById(operId).get(); } /** * 清空操作日志 */ + @Transactional @Override public void cleanOperLog() { - operLogMapper.cleanOperLog(); + jdbcTemplate.update("truncate table sys_oper_log"); } } diff --git a/ruoyi-system/src/main/resources/mapper/system/SysMenuMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysMenuMapper.xml deleted file mode 100644 index 47f9b8376..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysMenuMapper.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - select menu_id, menu_name, parent_id, order_num, url, target, menu_type, visible, ifnull(perms,'') as perms, icon, create_by, create_time - from sys_menu - - - - - - - - - - - - - - - - - - - - delete from sys_menu where menu_id = #{menuId} or parent_id = #{menuId} - - - - - - - - - - update sys_menu - - menu_name = #{menuName}, - parent_id = #{parentId}, - order_num = #{orderNum}, - url = #{url}, - target = #{target}, - menu_type = #{menuType}, - visible = #{visible}, - perms = #{perms}, - icon = #{icon}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where menu_id = #{menuId} - - - - insert into sys_menu( - menu_id, - parent_id, - menu_name, - order_num, - url, - target, - menu_type, - visible, - perms, - icon, - remark, - create_by, - create_time - )values( - #{menuId}, - #{parentId}, - #{menuName}, - #{orderNum}, - #{url}, - #{target}, - #{menuType}, - #{visible}, - #{perms}, - #{icon}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysNoticeMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysNoticeMapper.xml deleted file mode 100644 index dfca13c04..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysNoticeMapper.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - select notice_id, notice_title, notice_type, notice_content, status, create_by, create_time, update_by, update_time, remark - from sys_notice - - - - - - - - insert into sys_notice ( - notice_title, - notice_type, - notice_content, - status, - remark, - create_by, - create_time - )values( - #{noticeTitle}, - #{noticeType}, - #{noticeContent}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - - update sys_notice - - notice_title = #{noticeTitle}, - notice_type = #{noticeType}, - notice_content = #{noticeContent}, - status = #{status}, - update_by = #{updateBy}, - update_time = sysdate() - - where notice_id = #{noticeId} - - - - delete from sys_notice where notice_id in - - #{noticeId} - - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysOperLogMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysOperLogMapper.xml deleted file mode 100644 index 9658e873a..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysOperLogMapper.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time - from sys_oper_log - - - - insert into sys_oper_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time) - values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, sysdate()) - - - - - - delete from sys_oper_log where oper_id in - - #{operId} - - - - - - - truncate table sys_oper_log - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysPostMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysPostMapper.xml deleted file mode 100644 index 8b0c0292c..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysPostMapper.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - - - - - - - - - select post_id, post_code, post_name, post_sort, status, create_by, create_time, remark - from sys_post - - - - - - - - - - - - - - - - delete from sys_post where post_id in - - #{postId} - - - - - update sys_post - - post_code = #{postCode}, - post_name = #{postName}, - post_sort = #{postSort}, - status = #{status}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where post_id = #{postId} - - - - insert into sys_post( - post_id, - post_code, - post_name, - post_sort, - status, - remark, - create_by, - create_time - )values( - #{postId}, - #{postCode}, - #{postName}, - #{postSort}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml deleted file mode 100644 index 700671e15..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - delete from sys_role_dept where role_id=#{roleId} - - - - - - delete from sys_role_dept where role_id in - - #{roleId} - - - - - insert into sys_role_dept(role_id, dept_id) values - - (#{item.roleId},#{item.deptId}) - - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysRoleMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysRoleMapper.xml deleted file mode 100644 index 8d810c395..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysRoleMapper.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - select distinct r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, - r.status, r.del_flag, r.create_time, r.remark - from sys_role r - left join sys_user_role ur on ur.role_id = r.role_id - left join sys_user u on u.user_id = ur.user_id - left join sys_dept d on u.dept_id = d.dept_id - - - - select r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status, r.del_flag, r.create_time, r.remark - from sys_role r - - - - - - - - - - - - - - delete from sys_role where role_id = #{roleId} - - - - update sys_role set del_flag = '2' where role_id in - - #{roleId} - - - - - update sys_role - - role_name = #{roleName}, - role_key = #{roleKey}, - role_sort = #{roleSort}, - data_scope = #{dataScope}, - status = #{status}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where role_id = #{roleId} - - - - insert into sys_role( - role_id, - role_name, - role_key, - role_sort, - data_scope, - status, - remark, - create_by, - create_time - )values( - #{roleId}, - #{roleName}, - #{roleKey}, - #{roleSort}, - #{dataScope}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml deleted file mode 100644 index f509d207e..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - delete from sys_role_menu where role_id=#{roleId} - - - - - - delete from sys_role_menu where role_id in - - #{roleId} - - - - - insert into sys_role_menu(role_id, menu_id) values - - (#{item.roleId},#{item.menuId}) - - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml deleted file mode 100644 index d32e2f6bf..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - select u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phonenumber, u.sex, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_time, u.remark, - d.dept_id, d.parent_id, d.dept_name, d.order_num, d.leader, d.status as dept_status, - r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status - from sys_user u - left join sys_dept d on u.dept_id = d.dept_id - left join sys_user_role ur on u.user_id = ur.user_id - left join sys_role r on r.role_id = ur.role_id - - - - - - - - - - - - - - - - - - - - - - - - delete from sys_user where user_id = #{userId} - - - - update sys_user set del_flag = '2' where user_id in - - #{userId} - - - - - update sys_user - - dept_id = #{deptId}, - login_name = #{loginName}, - user_name = #{userName}, - email = #{email}, - phonenumber = #{phonenumber}, - sex = #{sex}, - avatar = #{avatar}, - password = #{password}, - salt = #{salt}, - status = #{status}, - login_ip = #{loginIp}, - login_date = #{loginDate}, - update_by = #{updateBy}, - remark = #{remark}, - update_time = sysdate() - - where user_id = #{userId} - - - - insert into sys_user( - user_id, - dept_id, - login_name, - user_name, - email, - avatar, - phonenumber, - sex, - password, - salt, - status, - create_by, - remark, - create_time - )values( - #{userId}, - #{deptId}, - #{loginName}, - #{userName}, - #{email}, - #{avatar}, - #{phonenumber}, - #{sex}, - #{password}, - #{salt}, - #{status}, - #{createBy}, - #{remark}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysUserOnlineMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysUserOnlineMapper.xml deleted file mode 100644 index 56adfd320..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysUserOnlineMapper.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - select sessionId, login_name, dept_name, ipaddr, login_location, browser, os, status, start_timestamp, last_access_time, expire_time - from sys_user_online - - - - - - replace into sys_user_online(sessionId, login_name, dept_name, ipaddr, login_location, browser, os, status, start_timestamp, last_access_time, expire_time) - values (#{sessionId}, #{loginName}, #{deptName}, #{ipaddr}, #{loginLocation}, #{browser}, #{os}, #{status}, #{startTimestamp}, #{lastAccessTime}, #{expireTime}) - - - - delete from sys_user_online where sessionId = #{sessionId} - - - - - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysUserPostMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysUserPostMapper.xml deleted file mode 100644 index 21c40981b..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysUserPostMapper.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - delete from sys_user_post where user_id=#{userId} - - - - - - delete from sys_user_post where user_id in - - #{userId} - - - - - insert into sys_user_post(user_id, post_id) values - - (#{item.userId},#{item.postId}) - - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysUserRoleMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysUserRoleMapper.xml deleted file mode 100644 index 95e07adb1..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysUserRoleMapper.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - delete from sys_user_role where user_id=#{userId} - - - - - - delete from sys_user_role where user_id in - - #{userId} - - - - - insert into sys_user_role(user_id, role_id) values - - (#{item.userId},#{item.roleId}) - - - - - delete from sys_user_role where user_id=#{userId} and role_id=#{roleId} - - - - delete from sys_user_role where role_id=#{roleId} and user_id in - - #{userId} - - - \ No newline at end of file From bb7d4657e18eb5594c8fa194a6d501f6b8666572 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 16:22:00 +0800 Subject: [PATCH 38/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../monitor/SysLogininforController.java | 27 ++++---- .../ruoyi/system/domain/SysLogininfor.java | 15 +++-- .../com/ruoyi/system/domain/SysOperLog.java | 11 ++-- .../system/mapper/SysLogininforMapper.java | 42 ------------- .../repository/SysLogininfoRepository.java | 15 +++++ .../system/service/ISysLogininforService.java | 4 +- .../impl/SysLogininforServiceImpl.java | 63 +++++++++++++++---- .../service/impl/SysOperLogServiceImpl.java | 2 +- .../mapper/system/SysLogininforMapper.xml | 56 ----------------- 9 files changed, 98 insertions(+), 137 deletions(-) delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysLogininforMapper.xml diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java index 7fa7ec19a..cd1a54a95 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java @@ -1,23 +1,24 @@ package com.ruoyi.web.controller.monitor; -import java.util.List; - -import com.ruoyi.framework.shiro.service.SysPasswordService; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.framework.shiro.service.SysPasswordService; import com.ruoyi.system.domain.SysLogininfor; import com.ruoyi.system.service.ISysLogininforService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.List; /** * 系统访问记录 @@ -45,9 +46,7 @@ public class SysLogininforController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysLogininfor logininfor) { - startPage(); - List list = logininforService.selectLogininforList(logininfor); - return getDataTable(list); + return getDataTable(logininforService.selectLogininforList(logininfor, getPageRequest())); } @Log(title = "登陆日志", businessType = BusinessType.EXPORT) @@ -55,7 +54,7 @@ public class SysLogininforController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysLogininfor logininfor) { - List list = logininforService.selectLogininforList(logininfor); + List list = logininforService.selectLogininforList(logininfor, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysLogininfor.class); return util.exportExcel(list, "登陆日志"); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java index e823cdfda..073946a2c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java @@ -1,26 +1,31 @@ package com.ruoyi.system.domain; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import java.util.Date; - import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.*; +import java.util.Date; /** * 系统访问记录表 sys_logininfor * * @author ruoyi */ +@Entity +@Table(name = SysLogininfor.TABLE_NAME) public class SysLogininfor extends BaseEntity { private static final long serialVersionUID = 1L; + public static final String TABLE_NAME = "sys_logininfor"; /** * ID */ @Excel(name = "序号", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long infoId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java index 620183120..e635bdc99 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java @@ -1,15 +1,13 @@ package com.ruoyi.system.domain; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import java.util.Date; - import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; import javax.persistence.*; +import java.util.Date; /** * 操作日志记录表 oper_log @@ -17,9 +15,10 @@ import javax.persistence.*; * @author ruoyi */ @Entity -@Table(name = "sys_oper_log") +@Table(name = SysOperLog.TABLE_NAME) public class SysOperLog extends BaseEntity { private static final long serialVersionUID = 1L; + public static final String TABLE_NAME = "sys_oper_log"; /** * 日志主键 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java deleted file mode 100644 index f750701bd..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysLogininforMapper.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysLogininfor; - -/** - * 系统访问日志情况信息 数据层 - * - * @author ruoyi - */ -public interface SysLogininforMapper { - /** - * 新增系统登录日志 - * - * @param logininfor 访问日志对象 - */ - public void insertLogininfor(SysLogininfor logininfor); - - /** - * 查询系统登录日志集合 - * - * @param logininfor 访问日志对象 - * @return 登录记录集合 - */ - public List selectLogininforList(SysLogininfor logininfor); - - /** - * 批量删除系统登录日志 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteLogininforByIds(String[] ids); - - /** - * 清空系统登录日志 - * - * @return 结果 - */ - public int cleanLogininfor(); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java new file mode 100644 index 000000000..6685a0fb0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysLogininfor; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Repository; + +import java.util.Collection; + +@Repository +public interface SysLogininfoRepository extends BaseRepository { + + @Modifying + void deleteByInfoIdIn(Collection ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java index ed013e4f6..1ad0949dc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysLogininforService.java @@ -3,6 +3,8 @@ package com.ruoyi.system.service; import java.util.List; import com.ruoyi.system.domain.SysLogininfor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 系统访问日志情况信息 服务层 @@ -23,7 +25,7 @@ public interface ISysLogininforService { * @param logininfor 访问日志对象 * @return 登录记录集合 */ - public List selectLogininforList(SysLogininfor logininfor); + public Page selectLogininforList(SysLogininfor logininfor, Pageable pageable); /** * 批量删除系统登录日志 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java index 09d2bc1da..5965c05d4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java @@ -1,13 +1,25 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysLogininfor; import com.ruoyi.system.domain.SysLogininfor; -import com.ruoyi.system.mapper.SysLogininforMapper; +import com.ruoyi.system.repository.SysLogininfoRepository; import com.ruoyi.system.service.ISysLogininforService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * 系统访问日志情况信息 服务层处理 @@ -15,10 +27,14 @@ import com.ruoyi.system.service.ISysLogininforService; * @author ruoyi */ @Service -public class SysLogininforServiceImpl implements ISysLogininforService { +public class SysLogininforServiceImpl extends BaseService implements ISysLogininforService { @Autowired - private SysLogininforMapper logininforMapper; + private SysLogininfoRepository sysLogininfoRepository; + @Autowired + private JdbcTemplate jdbcTemplate; + @Autowired + private EntityManager entityManager; /** * 新增系统登录日志 @@ -27,7 +43,7 @@ public class SysLogininforServiceImpl implements ISysLogininforService { */ @Override public void insertLogininfor(SysLogininfor logininfor) { - logininforMapper.insertLogininfor(logininfor); + sysLogininfoRepository.save(logininfor); } /** @@ -37,8 +53,29 @@ public class SysLogininforServiceImpl implements ISysLogininforService { * @return 登录记录集合 */ @Override - public List selectLogininforList(SysLogininfor logininfor) { - return logininforMapper.selectLogininforList(logininfor); + public Page selectLogininforList(SysLogininfor logininfor, Pageable pageable) { + return sysLogininfoRepository.findAll(getPredicate(logininfor), pageable); + } + + private Predicate getPredicate(SysLogininfor logininfor){ + QSysLogininfor qSysLogininfor = QSysLogininfor.sysLogininfor; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(logininfor.getIpaddr())){ + predicates.add(buildLike(qSysLogininfor.ipaddr, logininfor.getIpaddr())); + } + if(StringUtils.isNotEmpty(logininfor.getStatus())){ + predicates.add(buildEqual(qSysLogininfor.status, logininfor.getStatus())); + } + if(StringUtils.isNotEmpty(logininfor.getLoginName())){ + predicates.add(buildLike(qSysLogininfor.loginName, logininfor.getLoginName())); + } + if(logininfor.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysLogininfor.loginTime, logininfor.getStartTime())); + } + if(logininfor.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysLogininfor.loginTime, logininfor.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -49,14 +86,16 @@ public class SysLogininforServiceImpl implements ISysLogininforService { */ @Override public int deleteLogininforByIds(String ids) { - return logininforMapper.deleteLogininforByIds(Convert.toStrArray(ids)); + sysLogininfoRepository.deleteByInfoIdIn(Arrays.asList(Convert.toLongArray(ids))); + return 1; } /** * 清空系统登录日志 */ + @Transactional @Override public void cleanLogininfor() { - logininforMapper.cleanLogininfor(); + jdbcTemplate.update("truncate table " + SysLogininfor.TABLE_NAME); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java index 89822dd7a..422ae08e6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java @@ -109,6 +109,6 @@ public class SysOperLogServiceImpl extends BaseService implements ISysOperLogSer @Transactional @Override public void cleanOperLog() { - jdbcTemplate.update("truncate table sys_oper_log"); + jdbcTemplate.update("truncate table " + SysOperLog.TABLE_NAME); } } diff --git a/ruoyi-system/src/main/resources/mapper/system/SysLogininforMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysLogininforMapper.xml deleted file mode 100644 index a2ac5b4e5..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysLogininforMapper.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - insert into sys_logininfor (login_name, status, ipaddr, login_location, browser, os, msg, login_time) - values (#{loginName}, #{status}, #{ipaddr}, #{loginLocation}, #{browser}, #{os}, #{msg}, sysdate()) - - - - - - delete from sys_logininfor where info_id in - - #{infoId} - - - - - truncate table sys_logininfor - - - \ No newline at end of file From f1378989849c4d6ac25407b20a9949d25d8e1ed3 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 16:23:20 +0800 Subject: [PATCH 39/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ruoyi/system/mapper/SysDeptMapper.java | 109 ------------- .../service/impl/SysOperLogServiceImpl.java | 1 + .../resources/mapper/system/SysDeptMapper.xml | 154 ------------------ 3 files changed, 1 insertion(+), 263 deletions(-) delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysDeptMapper.xml diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java deleted file mode 100644 index ef2bf6ae4..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDeptMapper.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysDept; - -/** - * 部门管理 数据层 - * - * @author ruoyi - */ -public interface SysDeptMapper { - /** - * 查询部门人数 - * - * @param dept 部门信息 - * @return 结果 - */ - public int selectDeptCount(SysDept dept); - - /** - * 查询部门是否存在用户 - * - * @param deptId 部门ID - * @return 结果 - */ - public int checkDeptExistUser(Long deptId); - - /** - * 查询部门管理数据 - * - * @param dept 部门信息 - * @return 部门信息集合 - */ - public List selectDeptList(SysDept dept); - - /** - * 删除部门管理信息 - * - * @param deptId 部门ID - * @return 结果 - */ - public int deleteDeptById(Long deptId); - - /** - * 新增部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int insertDept(SysDept dept); - - /** - * 修改部门信息 - * - * @param dept 部门信息 - * @return 结果 - */ - public int updateDept(SysDept dept); - - /** - * 修改子元素关系 - * - * @param depts 子元素 - * @return 结果 - */ - public int updateDeptChildren(@Param("depts") List depts); - - /** - * 根据部门ID查询信息 - * - * @param deptId 部门ID - * @return 部门信息 - */ - public SysDept selectDeptById(Long deptId); - - /** - * 校验部门名称是否唯一 - * - * @param deptName 部门名称 - * @param parentId 父部门ID - * @return 结果 - */ - public SysDept checkDeptNameUnique(@Param("deptName") String deptName, @Param("parentId") Long parentId); - - /** - * 根据角色ID查询部门 - * - * @param roleId 角色ID - * @return 部门列表 - */ - public List selectRoleDeptTree(Long roleId); - - /** - * 修改所在部门的父级部门状态 - * - * @param dept 部门 - */ - public void updateDeptStatus(SysDept dept); - - /** - * 根据ID查询所有子部门 - * - * @param deptId 部门ID - * @return 部门列表 - */ - public List selectChildrenDeptById(Long deptId); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java index 422ae08e6..67a350565 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java @@ -86,6 +86,7 @@ public class SysOperLogServiceImpl extends BaseService implements ISysOperLogSer * @param ids 需要删除的数据 * @return */ + @Transactional @Override public int deleteOperLogByIds(String ids) { sysOperLogRepository.deleteByOperIdIn(Arrays.asList(Convert.toLongArray(ids))); diff --git a/ruoyi-system/src/main/resources/mapper/system/SysDeptMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysDeptMapper.xml deleted file mode 100644 index 02a1017c5..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysDeptMapper.xml +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - select d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag, d.create_by, d.create_time - from sys_dept d - - - - - - - - - - - - - - - - - - insert into sys_dept( - dept_id, - parent_id, - dept_name, - ancestors, - order_num, - leader, - phone, - email, - status, - create_by, - create_time - )values( - #{deptId}, - #{parentId}, - #{deptName}, - #{ancestors}, - #{orderNum}, - #{leader}, - #{phone}, - #{email}, - #{status}, - #{createBy}, - sysdate() - ) - - - - update sys_dept - - parent_id = #{parentId}, - dept_name = #{deptName}, - ancestors = #{ancestors}, - order_num = #{orderNum}, - leader = #{leader}, - phone = #{phone}, - email = #{email}, - status = #{status}, - update_by = #{updateBy}, - update_time = sysdate() - - where dept_id = #{deptId} - - - - update sys_dept set ancestors = - - when #{item.deptId} then #{item.ancestors} - - where dept_id in - - #{item.deptId} - - - - - update sys_dept set del_flag = '2' where dept_id = #{deptId} - - - - update sys_dept - - status = #{status}, - update_by = #{updateBy}, - update_time = sysdate() - - where dept_id in (${ancestors}) - - - \ No newline at end of file From 2839ee8c18008dfb6024d925589523819a144169 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 16:36:49 +0800 Subject: [PATCH 40/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/SysConfigController.java | 27 ++--- .../com/ruoyi/system/domain/SysConfig.java | 5 + .../ruoyi/system/mapper/SysConfigMapper.java | 60 ---------- .../repository/SysConfigRepository.java | 17 +++ .../system/service/ISysConfigService.java | 4 +- .../service/impl/SysConfigServiceImpl.java | 68 ++++++++--- .../mapper/system/SysConfigMapper.xml | 108 ------------------ 7 files changed, 85 insertions(+), 204 deletions(-) delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysConfigMapper.xml diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java index 9af0ed815..e3069f838 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java @@ -1,17 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; @@ -22,6 +10,15 @@ import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.service.ISysConfigService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 参数配置 信息操作处理 @@ -49,9 +46,7 @@ public class SysConfigController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysConfig config) { - startPage(); - List list = configService.selectConfigList(config); - return getDataTable(list); + return getDataTable(configService.selectConfigList(config, getPageRequest())); } @Log(title = "参数管理", businessType = BusinessType.EXPORT) @@ -59,7 +54,7 @@ public class SysConfigController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysConfig config) { - List list = configService.selectConfigList(config); + List list = configService.selectConfigList(config, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysConfig.class); return util.exportExcel(list, "参数数据"); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java index db533cd74..a068e4ba3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java @@ -1,5 +1,6 @@ package com.ruoyi.system.domain; +import javax.persistence.*; import javax.validation.constraints.*; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -13,6 +14,8 @@ import com.ruoyi.common.core.domain.BaseEntity; * * @author ruoyi */ +@Entity +@Table(name = "sys_config") public class SysConfig extends BaseEntity { private static final long serialVersionUID = 1L; @@ -20,6 +23,8 @@ public class SysConfig extends BaseEntity { * 参数主键 */ @Excel(name = "参数主键", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long configId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java deleted file mode 100644 index db89e9a8b..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysConfig; - -/** - * 参数配置 数据层 - * - * @author ruoyi - */ -public interface SysConfigMapper { - /** - * 查询参数配置信息 - * - * @param config 参数配置信息 - * @return 参数配置信息 - */ - public SysConfig selectConfig(SysConfig config); - - /** - * 查询参数配置列表 - * - * @param config 参数配置信息 - * @return 参数配置集合 - */ - public List selectConfigList(SysConfig config); - - /** - * 根据键名查询参数配置信息 - * - * @param configKey 参数键名 - * @return 参数配置信息 - */ - public SysConfig checkConfigKeyUnique(String configKey); - - /** - * 新增参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int insertConfig(SysConfig config); - - /** - * 修改参数配置 - * - * @param config 参数配置信息 - * @return 结果 - */ - public int updateConfig(SysConfig config); - - /** - * 批量删除参数配置 - * - * @param configIds 需要删除的数据ID - * @return 结果 - */ - public int deleteConfigByIds(String[] configIds); -} \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java new file mode 100644 index 000000000..63318962b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java @@ -0,0 +1,17 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysConfig; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Repository; + +import java.util.Collection; + +@Repository +public interface SysConfigRepository extends BaseRepository { + + SysConfig findFirstByConfigKey(String configKey); + + @Modifying + void deleteByConfigIdIn(Collection ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java index 54ee4d20e..5d3e36345 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java @@ -3,6 +3,8 @@ package com.ruoyi.system.service; import java.util.List; import com.ruoyi.system.domain.SysConfig; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 参数配置 服务层 @@ -32,7 +34,7 @@ public interface ISysConfigService { * @param config 参数配置信息 * @return 参数配置集合 */ - public List selectConfigList(SysConfig config); + public Page selectConfigList(SysConfig config, Pageable pageable); /** * 新增参数配置 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java index 7e95d33d7..b17863800 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java @@ -1,15 +1,24 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysConfig; import com.ruoyi.system.domain.SysConfig; -import com.ruoyi.system.mapper.SysConfigMapper; +import com.ruoyi.system.repository.SysConfigRepository; import com.ruoyi.system.service.ISysConfigService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * 参数配置 服务层实现 @@ -17,9 +26,9 @@ import com.ruoyi.system.service.ISysConfigService; * @author ruoyi */ @Service -public class SysConfigServiceImpl implements ISysConfigService { +public class SysConfigServiceImpl extends BaseService implements ISysConfigService { @Autowired - private SysConfigMapper configMapper; + private SysConfigRepository sysConfigRepository; /** * 查询参数配置信息 @@ -29,9 +38,7 @@ public class SysConfigServiceImpl implements ISysConfigService { */ @Override public SysConfig selectConfigById(Long configId) { - SysConfig config = new SysConfig(); - config.setConfigId(configId); - return configMapper.selectConfig(config); + return sysConfigRepository.findById(configId).get(); } /** @@ -42,9 +49,7 @@ public class SysConfigServiceImpl implements ISysConfigService { */ @Override public String selectConfigByKey(String configKey) { - SysConfig config = new SysConfig(); - config.setConfigKey(configKey); - SysConfig retConfig = configMapper.selectConfig(config); + SysConfig retConfig = sysConfigRepository.findFirstByConfigKey(configKey); return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : ""; } @@ -55,8 +60,29 @@ public class SysConfigServiceImpl implements ISysConfigService { * @return 参数配置集合 */ @Override - public List selectConfigList(SysConfig config) { - return configMapper.selectConfigList(config); + public Page selectConfigList(SysConfig config, Pageable pageable) { + return sysConfigRepository.findAll(getPredicate(config), pageable); + } + + private Predicate getPredicate(SysConfig config){ + QSysConfig qSysConfig = QSysConfig.sysConfig; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(config.getConfigName())){ + predicates.add(buildLike(qSysConfig.configName, config.getConfigName())); + } + if(StringUtils.isNotEmpty(config.getConfigType())){ + predicates.add(buildEqual(qSysConfig.configType, config.getConfigType())); + } + if(StringUtils.isNotEmpty(config.getConfigKey())){ + predicates.add(buildLike(qSysConfig.configKey, config.getConfigKey())); + } + if(config.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysConfig.createTime, config.getStartTime())); + } + if(config.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysConfig.createTime, config.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -67,7 +93,8 @@ public class SysConfigServiceImpl implements ISysConfigService { */ @Override public int insertConfig(SysConfig config) { - return configMapper.insertConfig(config); + sysConfigRepository.save(config); + return 1; } /** @@ -78,7 +105,8 @@ public class SysConfigServiceImpl implements ISysConfigService { */ @Override public int updateConfig(SysConfig config) { - return configMapper.updateConfig(config); + sysConfigRepository.save(config); + return 1; } /** @@ -87,9 +115,11 @@ public class SysConfigServiceImpl implements ISysConfigService { * @param ids 需要删除的数据ID * @return 结果 */ + @Transactional @Override public int deleteConfigByIds(String ids) { - return configMapper.deleteConfigByIds(Convert.toStrArray(ids)); + sysConfigRepository.deleteByConfigIdIn(Arrays.asList(Convert.toLongArray(ids))); + return 1; } /** @@ -101,7 +131,7 @@ public class SysConfigServiceImpl implements ISysConfigService { @Override public String checkConfigKeyUnique(SysConfig config) { Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); - SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); + SysConfig info = sysConfigRepository.findFirstByConfigKey(config.getConfigKey()); if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) { return UserConstants.CONFIG_KEY_NOT_UNIQUE; } diff --git a/ruoyi-system/src/main/resources/mapper/system/SysConfigMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysConfigMapper.xml deleted file mode 100644 index 4756c1f18..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysConfigMapper.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark - from sys_config - - - - - - - and config_id = #{configId} - - - and config_key = #{configKey} - - - - - - - - - - - - insert into sys_config ( - config_name, - config_key, - config_value, - config_type, - create_by, - remark, - create_time - )values( - #{configName}, - #{configKey}, - #{configValue}, - #{configType}, - #{createBy}, - #{remark}, - sysdate() - ) - - - - update sys_config - - config_name = #{configName}, - config_key = #{configKey}, - config_value = #{configValue}, - config_type = #{configType}, - update_by = #{updateBy}, - remark = #{remark}, - update_time = sysdate() - - where config_id = #{configId} - - - - delete from sys_config where config_id in - - #{configId} - - - - \ No newline at end of file From 70e652e6340cae8788e964304a926c3fc6237409 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 17:20:46 +0800 Subject: [PATCH 41/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/SysDictDataController.java | 27 ++-- .../system/SysDictTypeController.java | 28 ++-- .../com/ruoyi/system/domain/SysDictData.java | 14 +- .../com/ruoyi/system/domain/SysDictType.java | 14 +- .../system/mapper/SysDictDataMapper.java | 95 -------------- .../system/mapper/SysDictTypeMapper.java | 83 ------------ .../repository/SysDictDataRepository.java | 24 ++++ .../repository/SysDictTypeRepository.java | 11 ++ .../system/service/ISysDictDataService.java | 8 +- .../system/service/ISysDictTypeService.java | 8 +- .../service/impl/SysDictDataServiceImpl.java | 65 ++++++--- .../service/impl/SysDictTypeServiceImpl.java | 85 ++++++++---- .../mapper/system/SysDictDataMapper.xml | 123 ------------------ .../mapper/system/SysDictTypeMapper.xml | 105 --------------- 14 files changed, 194 insertions(+), 496 deletions(-) delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java delete mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml delete mode 100644 ruoyi-system/src/main/resources/mapper/system/SysDictTypeMapper.xml diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java index 167c2f459..5bad2e873 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java @@ -1,17 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -21,6 +9,15 @@ import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysDictData; import com.ruoyi.system.service.ISysDictDataService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 数据字典信息 @@ -45,9 +42,7 @@ public class SysDictDataController extends BaseController { @RequiresPermissions("system:dict:list") @ResponseBody public TableDataInfo list(SysDictData dictData) { - startPage(); - List list = dictDataService.selectDictDataList(dictData); - return getDataTable(list); + return getDataTable(dictDataService.selectDictDataList(dictData, getPageRequest())); } @Log(title = "字典数据", businessType = BusinessType.EXPORT) @@ -55,7 +50,7 @@ public class SysDictDataController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysDictData dictData) { - List list = dictDataService.selectDictDataList(dictData); + List list = dictDataService.selectDictDataList(dictData, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysDictData.class); return util.exportExcel(list, "字典数据"); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java index 37f67fcdc..f853418e1 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java @@ -1,17 +1,5 @@ package com.ruoyi.web.controller.system; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; @@ -23,6 +11,15 @@ import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysDictType; import com.ruoyi.system.service.ISysDictTypeService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 数据字典信息 @@ -47,9 +44,7 @@ public class SysDictTypeController extends BaseController { @RequiresPermissions("system:dict:list") @ResponseBody public TableDataInfo list(SysDictType dictType) { - startPage(); - List list = dictTypeService.selectDictTypeList(dictType); - return getDataTable(list); + return getDataTable(dictTypeService.selectDictTypeList(dictType, getPageRequest())); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @@ -57,8 +52,7 @@ public class SysDictTypeController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysDictType dictType) { - - List list = dictTypeService.selectDictTypeList(dictType); + List list = dictTypeService.selectDictTypeList(dictType, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysDictType.class); return util.exportExcel(list, "字典类型"); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java index 445094f99..5bd7f6b4b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictData.java @@ -1,19 +1,23 @@ package com.ruoyi.system.domain; -import javax.validation.constraints.*; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; /** * 字典数据表 sys_dict_data * * @author ruoyi */ +@Entity +@Table(name = "sys_dict_data") public class SysDictData extends BaseEntity { private static final long serialVersionUID = 1L; @@ -21,6 +25,8 @@ public class SysDictData extends BaseEntity { * 字典编码 */ @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long dictCode; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java index 2a0c851ab..271f13344 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDictType.java @@ -1,18 +1,22 @@ package com.ruoyi.system.domain; -import javax.validation.constraints.*; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; /** * 字典类型表 sys_dict_type * * @author ruoyi */ +@Entity +@Table(name = "sys_dict_type") public class SysDictType extends BaseEntity { private static final long serialVersionUID = 1L; @@ -20,6 +24,8 @@ public class SysDictType extends BaseEntity { * 字典主键 */ @Excel(name = "字典主键", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long dictId; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java deleted file mode 100644 index 4d327eff8..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictDataMapper.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import com.ruoyi.system.domain.SysDictData; - -/** - * 字典表 数据层 - * - * @author ruoyi - */ -public interface SysDictDataMapper { - /** - * 根据条件分页查询字典数据 - * - * @param dictData 字典数据信息 - * @return 字典数据集合信息 - */ - public List selectDictDataList(SysDictData dictData); - - /** - * 根据字典类型查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据集合信息 - */ - public List selectDictDataByType(String dictType); - - /** - * 根据字典类型和字典键值查询字典数据信息 - * - * @param dictType 字典类型 - * @param dictValue 字典键值 - * @return 字典标签 - */ - public String selectDictLabel(@Param("dictType") String dictType, @Param("dictValue") String dictValue); - - /** - * 根据字典数据ID查询信息 - * - * @param dictCode 字典数据ID - * @return 字典数据 - */ - public SysDictData selectDictDataById(Long dictCode); - - /** - * 查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据 - */ - public int countDictDataByType(String dictType); - - /** - * 通过字典ID删除字典数据信息 - * - * @param dictCode 字典数据ID - * @return 结果 - */ - public int deleteDictDataById(Long dictCode); - - /** - * 批量删除字典数据 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteDictDataByIds(String[] ids); - - /** - * 新增字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int insertDictData(SysDictData dictData); - - /** - * 修改字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - public int updateDictData(SysDictData dictData); - - /** - * 同步修改字典类型 - * - * @param oldDictType 旧字典类型 - * @param newDictType 新旧字典类型 - * @return 结果 - */ - public int updateDictDataType(@Param("oldDictType") String oldDictType, @Param("newDictType") String newDictType); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java deleted file mode 100644 index b260072a1..000000000 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysDictTypeMapper.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ruoyi.system.mapper; - -import java.util.List; - -import com.ruoyi.system.domain.SysDictType; - -/** - * 字典表 数据层 - * - * @author ruoyi - */ -public interface SysDictTypeMapper { - /** - * 根据条件分页查询字典类型 - * - * @param dictType 字典类型信息 - * @return 字典类型集合信息 - */ - public List selectDictTypeList(SysDictType dictType); - - /** - * 根据所有字典类型 - * - * @return 字典类型集合信息 - */ - public List selectDictTypeAll(); - - /** - * 根据字典类型ID查询信息 - * - * @param dictId 字典类型ID - * @return 字典类型 - */ - public SysDictType selectDictTypeById(Long dictId); - - /** - * 根据字典类型查询信息 - * - * @param dictType 字典类型 - * @return 字典类型 - */ - public SysDictType selectDictTypeByType(String dictType); - - /** - * 通过字典ID删除字典信息 - * - * @param dictId 字典ID - * @return 结果 - */ - public int deleteDictTypeById(Long dictId); - - /** - * 批量删除字典类型 - * - * @param ids 需要删除的数据 - * @return 结果 - */ - public int deleteDictTypeByIds(Long[] ids); - - /** - * 新增字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int insertDictType(SysDictType dictType); - - /** - * 修改字典类型信息 - * - * @param dictType 字典类型信息 - * @return 结果 - */ - public int updateDictType(SysDictType dictType); - - /** - * 校验字典类型称是否唯一 - * - * @param dictType 字典类型 - * @return 结果 - */ - public SysDictType checkDictTypeUnique(String dictType); -} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java new file mode 100644 index 000000000..88056625e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java @@ -0,0 +1,24 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysDictData; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SysDictDataRepository extends BaseRepository { + + @Modifying + @Query("update SysDictData d set d.dictType = ?1 where d.dictType = ?2") + void updateDictType(String newType, String oldType); + + int countByDictType(String dictType); + + List findByDictType(String dictType); + + SysDictData findFirstByDictTypeAndDictLabel(String type, String label); + +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java new file mode 100644 index 000000000..2b9937313 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java @@ -0,0 +1,11 @@ +package com.ruoyi.system.repository; + +import com.ruoyi.system.domain.SysDictType; +import com.ruoyi.system.repository.base.BaseRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysDictTypeRepository extends BaseRepository { + + SysDictType findFirstByDictType(String dictType); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java index 7cb1567c8..e0f19ed3d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictDataService.java @@ -1,8 +1,10 @@ package com.ruoyi.system.service; -import java.util.List; - import com.ruoyi.system.domain.SysDictData; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; /** * 字典 业务层 @@ -16,7 +18,7 @@ public interface ISysDictDataService { * @param dictData 字典数据信息 * @return 字典数据集合信息 */ - public List selectDictDataList(SysDictData dictData); + public Page selectDictDataList(SysDictData dictData, Pageable pageable); /** * 根据字典类型查询字典数据 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java index f8d3e3322..5bf810291 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDictTypeService.java @@ -1,9 +1,11 @@ package com.ruoyi.system.service; -import java.util.List; - import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.system.domain.SysDictType; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; /** * 字典 业务层 @@ -17,7 +19,7 @@ public interface ISysDictTypeService { * @param dictType 字典类型信息 * @return 字典类型集合信息 */ - public List selectDictTypeList(SysDictType dictType); + public Page selectDictTypeList(SysDictType dictType, Pageable pageable); /** * 根据所有字典类型 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java index 28c9ddca7..d564f5bfd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java @@ -1,13 +1,22 @@ package com.ruoyi.system.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysDictData; import com.ruoyi.system.domain.SysDictData; -import com.ruoyi.system.mapper.SysDictDataMapper; +import com.ruoyi.system.repository.SysDictDataRepository; import com.ruoyi.system.service.ISysDictDataService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; /** * 字典 业务层处理 @@ -15,9 +24,9 @@ import com.ruoyi.system.service.ISysDictDataService; * @author ruoyi */ @Service -public class SysDictDataServiceImpl implements ISysDictDataService { +public class SysDictDataServiceImpl extends BaseService implements ISysDictDataService { @Autowired - private SysDictDataMapper dictDataMapper; + private SysDictDataRepository sysDictDataRepository; /** * 根据条件分页查询字典数据 @@ -26,8 +35,23 @@ public class SysDictDataServiceImpl implements ISysDictDataService { * @return 字典数据集合信息 */ @Override - public List selectDictDataList(SysDictData dictData) { - return dictDataMapper.selectDictDataList(dictData); + public Page selectDictDataList(SysDictData dictData, Pageable pageable) { + return sysDictDataRepository.findAll(getPredicate(dictData), pageable); + } + + private Predicate getPredicate(SysDictData dictData){ + QSysDictData qSysDictData = QSysDictData.sysDictData; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(dictData.getDictType())){ + predicates.add(buildEqual(qSysDictData.dictType, dictData.getDictType())); + } + if(StringUtils.isNotEmpty(dictData.getDictLabel())){ + predicates.add(buildLike(qSysDictData.status, dictData.getDictLabel())); + } + if(StringUtils.isNotEmpty(dictData.getStatus())){ + predicates.add(buildEqual(qSysDictData.status, dictData.getStatus())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -38,7 +62,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService { */ @Override public List selectDictDataByType(String dictType) { - return dictDataMapper.selectDictDataByType(dictType); + return sysDictDataRepository.findByDictType(dictType); } /** @@ -50,7 +74,8 @@ public class SysDictDataServiceImpl implements ISysDictDataService { */ @Override public String selectDictLabel(String dictType, String dictValue) { - return dictDataMapper.selectDictLabel(dictType, dictValue); + SysDictData dictData = sysDictDataRepository.findFirstByDictTypeAndDictLabel(dictType, dictType); + return dictData == null ? dictData.getDictValue() : ""; } /** @@ -61,7 +86,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService { */ @Override public SysDictData selectDictDataById(Long dictCode) { - return dictDataMapper.selectDictDataById(dictCode); + return sysDictDataRepository.findById(dictCode).get(); } /** @@ -70,9 +95,11 @@ public class SysDictDataServiceImpl implements ISysDictDataService { * @param dictCode 字典数据ID * @return 结果 */ + @Transactional @Override public int deleteDictDataById(Long dictCode) { - return dictDataMapper.deleteDictDataById(dictCode); + sysDictDataRepository.deleteById(dictCode); + return 1; } /** @@ -81,9 +108,13 @@ public class SysDictDataServiceImpl implements ISysDictDataService { * @param ids 需要删除的数据 * @return 结果 */ + @Transactional @Override public int deleteDictDataByIds(String ids) { - return dictDataMapper.deleteDictDataByIds(Convert.toStrArray(ids)); + for(Long id : Convert.toLongArray(ids)){ + deleteDictDataById(id); + } + return 1; } /** @@ -94,7 +125,8 @@ public class SysDictDataServiceImpl implements ISysDictDataService { */ @Override public int insertDictData(SysDictData dictData) { - return dictDataMapper.insertDictData(dictData); + sysDictDataRepository.save(dictData); + return 1; } /** @@ -105,6 +137,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService { */ @Override public int updateDictData(SysDictData dictData) { - return dictDataMapper.updateDictData(dictData); + sysDictDataRepository.save(dictData); + return 1; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java index 322d04b88..a849b229d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java @@ -1,20 +1,26 @@ package com.ruoyi.system.service.impl; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.QSysDictType; import com.ruoyi.system.domain.SysDictType; -import com.ruoyi.system.mapper.SysDictDataMapper; -import com.ruoyi.system.mapper.SysDictTypeMapper; +import com.ruoyi.system.repository.SysDictDataRepository; +import com.ruoyi.system.repository.SysDictTypeRepository; import com.ruoyi.system.service.ISysDictTypeService; +import com.ruoyi.system.service.base.BaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; /** * 字典 业务层处理 @@ -22,12 +28,11 @@ import com.ruoyi.system.service.ISysDictTypeService; * @author ruoyi */ @Service -public class SysDictTypeServiceImpl implements ISysDictTypeService { +public class SysDictTypeServiceImpl extends BaseService implements ISysDictTypeService { @Autowired - private SysDictTypeMapper dictTypeMapper; - + private SysDictTypeRepository sysDictTypeRepository; @Autowired - private SysDictDataMapper dictDataMapper; + private SysDictDataRepository sysDictDataRepository; /** * 根据条件分页查询字典类型 @@ -36,8 +41,29 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { * @return 字典类型集合信息 */ @Override - public List selectDictTypeList(SysDictType dictType) { - return dictTypeMapper.selectDictTypeList(dictType); + public Page selectDictTypeList(SysDictType dictType, Pageable pageable) { + return sysDictTypeRepository.findAll(getPredicate(dictType), pageable); + } + + private Predicate getPredicate(SysDictType sysDictType){ + QSysDictType qSysDictType = QSysDictType.sysDictType; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(sysDictType.getDictName())){ + predicates.add(buildLike(qSysDictType.dictName, sysDictType.getDictName())); + } + if(StringUtils.isNotEmpty(sysDictType.getStatus())){ + predicates.add(buildEqual(qSysDictType.status, sysDictType.getStatus())); + } + if(StringUtils.isNotEmpty(sysDictType.getDictType())){ + predicates.add(buildLike(qSysDictType.dictType, sysDictType.getDictType())); + } + if(sysDictType.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysDictType.createTime, sysDictType.getStartTime())); + } + if(sysDictType.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysDictType.createTime, sysDictType.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -47,7 +73,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { */ @Override public List selectDictTypeAll() { - return dictTypeMapper.selectDictTypeAll(); + return sysDictTypeRepository.findAll(); } /** @@ -58,7 +84,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { */ @Override public SysDictType selectDictTypeById(Long dictId) { - return dictTypeMapper.selectDictTypeById(dictId); + return sysDictTypeRepository.findById(dictId).get(); } /** @@ -68,7 +94,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { * @return 字典类型 */ public SysDictType selectDictTypeByType(String dictType) { - return dictTypeMapper.selectDictTypeByType(dictType); + return sysDictTypeRepository.findFirstByDictType(dictType); } /** @@ -77,9 +103,11 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { * @param dictId 字典ID * @return 结果 */ + @Transactional @Override public int deleteDictTypeById(Long dictId) { - return dictTypeMapper.deleteDictTypeById(dictId); + sysDictTypeRepository.deleteById(dictId); + return 1; } /** @@ -88,17 +116,18 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { * @param ids 需要删除的数据 * @return 结果 */ + @Transactional @Override public int deleteDictTypeByIds(String ids) throws BusinessException { Long[] dictIds = Convert.toLongArray(ids); for (Long dictId : dictIds) { SysDictType dictType = selectDictTypeById(dictId); - if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) { + if (sysDictDataRepository.countByDictType(dictType.getDictType()) > 0) { throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName())); } + deleteDictTypeById(dictId); } - - return dictTypeMapper.deleteDictTypeByIds(dictIds); + return dictIds.length; } /** @@ -109,7 +138,8 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { */ @Override public int insertDictType(SysDictType dictType) { - return dictTypeMapper.insertDictType(dictType); + sysDictTypeRepository.save(dictType); + return 1; } /** @@ -121,9 +151,10 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { @Override @Transactional public int updateDictType(SysDictType dictType) { - SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId()); - dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType()); - return dictTypeMapper.updateDictType(dictType); + SysDictType oldDict = sysDictTypeRepository.findById(dictType.getDictId()).get(); + sysDictDataRepository.updateDictType(dictType.getDictType(), oldDict.getDictType()); + sysDictTypeRepository.save(dictType); + return 1; } /** @@ -135,7 +166,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { @Override public String checkDictTypeUnique(SysDictType dict) { Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); - SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); + SysDictType dictType = sysDictTypeRepository.findFirstByDictType(dict.getDictType()); if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) { return UserConstants.DICT_TYPE_NOT_UNIQUE; } @@ -150,7 +181,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService { */ public List selectDictTree(SysDictType dictType) { List ztrees = new ArrayList(); - List dictList = dictTypeMapper.selectDictTypeList(dictType); + List dictList = sysDictTypeRepository.findAll(); for (SysDictType dict : dictList) { if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) { Ztree ztree = new Ztree(); diff --git a/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml deleted file mode 100644 index ccfea4d74..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - select dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark - from sys_dict_data - - - - - - - - - - - - - - delete from sys_dict_data where dict_code = #{dictCode} - - - - delete from sys_dict_data where dict_code in - - #{dictCode} - - - - - update sys_dict_data - - dict_sort = #{dictSort}, - dict_label = #{dictLabel}, - dict_value = #{dictValue}, - dict_type = #{dictType}, - css_class = #{cssClass}, - list_class = #{listClass}, - is_default = #{isDefault}, - status = #{status}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where dict_code = #{dictCode} - - - - update sys_dict_data set dict_type = #{newDictType} where dict_type = #{oldDictType} - - - - insert into sys_dict_data( - dict_sort, - dict_label, - dict_value, - dict_type, - css_class, - list_class, - is_default, - status, - remark, - create_by, - create_time - )values( - #{dictSort}, - #{dictLabel}, - #{dictValue}, - #{dictType}, - #{cssClass}, - #{listClass}, - #{isDefault}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/SysDictTypeMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysDictTypeMapper.xml deleted file mode 100644 index 1ddabe6ef..000000000 --- a/ruoyi-system/src/main/resources/mapper/system/SysDictTypeMapper.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - select dict_id, dict_name, dict_type, status, create_by, create_time, remark - from sys_dict_type - - - - - - - - - - - - - - delete from sys_dict_type where dict_id = #{dictId} - - - - delete from sys_dict_type where dict_id in - - #{dictId} - - - - - update sys_dict_type - - dict_name = #{dictName}, - dict_type = #{dictType}, - status = #{status}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where dict_id = #{dictId} - - - - insert into sys_dict_type( - dict_name, - dict_type, - status, - remark, - create_by, - create_time - )values( - #{dictName}, - #{dictType}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file From f842c8947f4771e209bfacd2194124429460793e Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 17:25:25 +0800 Subject: [PATCH 42/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ruoyi/system/domain/SysLogininfor.java | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java index 073946a2c..e9fa6cd0f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysLogininfor.java @@ -2,11 +2,11 @@ package com.ruoyi.system.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import javax.persistence.*; +import java.io.Serializable; import java.util.Date; /** @@ -16,7 +16,7 @@ import java.util.Date; */ @Entity @Table(name = SysLogininfor.TABLE_NAME) -public class SysLogininfor extends BaseEntity { +public class SysLogininfor implements Serializable { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "sys_logininfor"; @@ -76,6 +76,12 @@ public class SysLogininfor extends BaseEntity { @Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") private Date loginTime; + @Transient + private Date startTime; + + @Transient + private Date endTime; + public Long getInfoId() { return infoId; } @@ -162,4 +168,20 @@ public class SysLogininfor extends BaseEntity { .append("loginTime", getLoginTime()) .toString(); } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } } \ No newline at end of file From 5dfdd0db1ae4bb03779b5f6d66b0e577d4d025da Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 17:35:10 +0800 Subject: [PATCH 43/52] =?UTF-8?q?hibernate=E4=BA=8C=E7=BA=A7=E7=BC=93?= =?UTF-8?q?=E5=AD=98=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/application.yml | 4 + .../src/main/resources/hibernate.properties | 5 ++ .../resources/hibernate_2level_ehcache.xml | 23 ++++++ ruoyi-framework/pom.xml | 16 ++++ .../ehcache/MyJCacheRegionFactory.java | 74 +++++++++++++++++++ .../java/com/ruoyi/system/domain/SysDept.java | 2 + 6 files changed, 124 insertions(+) create mode 100644 ruoyi-admin/src/main/resources/hibernate.properties create mode 100644 ruoyi-admin/src/main/resources/hibernate_2level_ehcache.xml create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/ehcache/MyJCacheRegionFactory.java diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 4c3b3f5ee..deb1852ed 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -81,6 +81,10 @@ spring: properties: hibernate: format_sql: false + cache: + type: jcache + jcache: + provider: org.ehcache.jsr107.EhcacheCachingProvider # MyBatis mybatis: diff --git a/ruoyi-admin/src/main/resources/hibernate.properties b/ruoyi-admin/src/main/resources/hibernate.properties new file mode 100644 index 000000000..ae462b4b8 --- /dev/null +++ b/ruoyi-admin/src/main/resources/hibernate.properties @@ -0,0 +1,5 @@ +hibernate.cache.use_second_level_cache=true +hibernate.cache.region.factory_class=com.ruoyi.framework.ehcache.MyJCacheRegionFactory +hibernate.cache.use_query_cache=true +hibernate.generate_statistics=true +hibernate.javax.cache.uri=hibernate_2level_ehcache.xml \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/hibernate_2level_ehcache.xml b/ruoyi-admin/src/main/resources/hibernate_2level_ehcache.xml new file mode 100644 index 000000000..2b20dd27c --- /dev/null +++ b/ruoyi-admin/src/main/resources/hibernate_2level_ehcache.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + 600 + + + 500 + + + + + + \ No newline at end of file diff --git a/ruoyi-framework/pom.xml b/ruoyi-framework/pom.xml index 540ecb592..64e719736 100644 --- a/ruoyi-framework/pom.xml +++ b/ruoyi-framework/pom.xml @@ -100,6 +100,22 @@ jna-platform + + org.hibernate + hibernate-jcache + + + + javax.cache + cache-api + 1.1.0 + + + + org.ehcache + ehcache + 3.8.0 + \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/ehcache/MyJCacheRegionFactory.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/ehcache/MyJCacheRegionFactory.java new file mode 100644 index 000000000..c363b55f5 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/ehcache/MyJCacheRegionFactory.java @@ -0,0 +1,74 @@ +package com.ruoyi.framework.ehcache; + +import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; +import org.hibernate.boot.spi.SessionFactoryOptions; +import org.hibernate.cache.CacheException; +import org.hibernate.cache.jcache.ConfigSettings; +import org.hibernate.cache.jcache.internal.JCacheRegionFactory; + +import javax.cache.CacheManager; +import javax.cache.spi.CachingProvider; +import java.net.URI; +import java.net.URL; +import java.util.Map; + +/** + * 解决hibernate.properties中不能配置ehcache.xml所在路径为相对路径的问题 + */ +public class MyJCacheRegionFactory extends JCacheRegionFactory { + + @Override + protected CacheManager resolveCacheManager(SessionFactoryOptions settings, Map properties) { + final Object explicitCacheManager = properties.get( ConfigSettings.CACHE_MANAGER ); + if ( explicitCacheManager != null ) { + return useExplicitCacheManager( settings, explicitCacheManager ); + } + + final CachingProvider cachingProvider = getCachingProvider( properties ); + final CacheManager cacheManager; + final URI cacheManagerUri = getUri( properties ); + // ***** begin patch ****** + URI uri = cacheManagerUri; + URL url = null; + try { + uri.toURL(); + } catch (Exception e) { + try { + url = getClassLoader(cachingProvider).getResource(cacheManagerUri.toString()); + uri = url.toURI(); + } catch (Exception e1) { + throw new IllegalArgumentException("Resource not found: " + uri, e1); + } + } + // ****** end patch ****** + if ( cacheManagerUri != null ) { + cacheManager = cachingProvider.getCacheManager( uri, getClassLoader( cachingProvider )); + } + else { + cacheManager = cachingProvider.getCacheManager(); + } + return cacheManager; + } + + private CacheManager useExplicitCacheManager(SessionFactoryOptions settings, Object setting) { + if ( setting instanceof CacheManager ) { + return (CacheManager) setting; + } + + final Class cacheManagerClass; + if ( setting instanceof Class ) { + cacheManagerClass = (Class) setting; + } + else { + cacheManagerClass = settings.getServiceRegistry().getService( ClassLoaderService.class ) + .classForName( setting.toString() ); + } + + try { + return cacheManagerClass.newInstance(); + } + catch (InstantiationException | IllegalAccessException e) { + throw new CacheException( "Could not use explicit CacheManager : " + setting ); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java index b06c23569..a1f623783 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysDept.java @@ -3,6 +3,7 @@ package com.ruoyi.system.domain; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.ForeignKey; import javax.persistence.*; @@ -18,6 +19,7 @@ import java.util.Objects; */ @Entity @Table(name = "sys_dept") +@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "com.ruoyi.system.domain.SysDept") public class SysDept extends BaseEntity { public static final Long ROOT_ID = 1L; From 7da76e84799df1a69ca03154f6d6186a3adb4961 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 18:13:50 +0800 Subject: [PATCH 44/52] refactor --- .../controller/system/SysPostController.java | 4 +- ruoyi-common/pom.xml | 8 +- .../ruoyi/common}/base/BaseRepository.java | 2 +- .../com/ruoyi/common}/base/BaseService.java | 2 +- .../core/controller/BaseController.java | 27 -- .../generator/controller/GenController.java | 36 +- .../com/ruoyi/generator/domain/GenTable.java | 5 + .../generator/domain/GenTableColumn.java | 9 +- .../repository/GenTableColumnRepository.java | 9 + .../repository/GenTableRepository.java | 9 + .../generator/service/IGenTableService.java | 10 +- .../service/impl/GenTableServiceImpl.java | 51 ++- .../main/resources/vm/java/controller.java.vm | 401 +++++++++--------- .../java/com/ruoyi/quartz/domain/SysJob.java | 5 + .../repository/SysJobLogRepository.java | 9 + .../quartz/repository/SysJobRepository.java | 9 + .../repository/SysConfigRepository.java | 2 +- .../system/repository/SysDeptRepository.java | 2 +- .../repository/SysDictDataRepository.java | 2 +- .../repository/SysDictTypeRepository.java | 2 +- .../repository/SysLogininfoRepository.java | 2 +- .../system/repository/SysMenuRepository.java | 2 +- .../repository/SysNoticeRepository.java | 2 +- .../repository/SysOperLogRepository.java | 2 +- .../system/repository/SysPostRepository.java | 2 +- .../system/repository/SysRoleRepository.java | 2 +- .../repository/SysUserOnlineRepository.java | 2 +- .../system/repository/SysUserRepository.java | 2 +- .../service/impl/SysConfigServiceImpl.java | 2 +- .../service/impl/SysDeptServiceImpl.java | 4 +- .../service/impl/SysDictDataServiceImpl.java | 2 +- .../service/impl/SysDictTypeServiceImpl.java | 2 +- .../impl/SysLogininforServiceImpl.java | 2 +- .../service/impl/SysMenuServiceImpl.java | 3 +- .../service/impl/SysNoticeServiceImpl.java | 2 +- .../service/impl/SysOperLogServiceImpl.java | 2 +- .../service/impl/SysPostServiceImpl.java | 3 +- .../service/impl/SysRoleServiceImpl.java | 2 +- .../impl/SysUserOnlineServiceImpl.java | 3 +- .../service/impl/SysUserServiceImpl.java | 2 +- 40 files changed, 333 insertions(+), 316 deletions(-) rename {ruoyi-system/src/main/java/com/ruoyi/system/repository => ruoyi-common/src/main/java/com/ruoyi/common}/base/BaseRepository.java (91%) rename {ruoyi-system/src/main/java/com/ruoyi/system/service => ruoyi-common/src/main/java/com/ruoyi/common}/base/BaseService.java (96%) create mode 100644 ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java create mode 100644 ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java create mode 100644 ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobLogRepository.java create mode 100644 ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java index c0587fbaf..9f98d9dcb 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java @@ -42,9 +42,7 @@ public class SysPostController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysPost post) { - startPage(); - Page page = postService.selectPostList(post, getPageRequest()); - return getDataTable(page); + return getDataTable(postService.selectPostList(post, getPageRequest())); } @Log(title = "岗位管理", businessType = BusinessType.EXPORT) diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index bcf10818a..89d170ae1 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -34,13 +34,7 @@ org.apache.shiro shiro-core - - - - com.github.pagehelper - pagehelper-spring-boot-starter - - + javax.validation diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java similarity index 91% rename from ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java rename to ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java index 9ea8c41d3..4e8b0d457 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/base/BaseRepository.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java @@ -1,4 +1,4 @@ -package com.ruoyi.system.repository.base; +package com.ruoyi.common.base; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java similarity index 96% rename from ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java rename to ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java index 08db4ee12..c5dbdf642 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BaseService.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java @@ -1,4 +1,4 @@ -package com.ruoyi.system.service.base; +package com.ruoyi.common.base; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.ComparableExpression; diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java index 66fcbbacf..25f13cdc1 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java @@ -1,7 +1,5 @@ package com.ruoyi.common.core.controller; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult.Type; import com.ruoyi.common.core.page.PageDomain; @@ -48,19 +46,6 @@ public class BaseController { }); } - /** - * 设置请求分页数据 - */ - protected void startPage() { - PageDomain pageDomain = TableSupport.buildPageRequest(); - Integer pageNum = pageDomain.getPageNum(); - Integer pageSize = pageDomain.getPageSize(); - if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { - String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); - PageHelper.startPage(pageNum, pageSize, orderBy); - } - } - /** * 获取request */ @@ -82,18 +67,6 @@ public class BaseController { return getRequest().getSession(); } - /** - * 响应请求分页数据 - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - protected TableDataInfo getDataTable(List list) { - TableDataInfo rspData = new TableDataInfo(); - rspData.setCode(0); - rspData.setRows(list); - rspData.setTotal(new PageInfo(list).getTotal()); - return rspData; - } - /** * 设置请求分页数据 */ diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java index efdbb31bc..d93b942b2 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java @@ -1,21 +1,5 @@ package com.ruoyi.generator.controller; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -27,6 +11,18 @@ import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.service.IGenTableColumnService; import com.ruoyi.generator.service.IGenTableService; +import org.apache.commons.io.IOUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Map; /** * 代码生成 操作处理 @@ -57,9 +53,7 @@ public class GenController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo genList(GenTable genTable) { - startPage(); - List list = genTableService.selectGenTableList(genTable); - return getDataTable(list); + return getDataTable(genTableService.selectGenTableList(genTable, getPageRequest())); } /** @@ -69,9 +63,7 @@ public class GenController extends BaseController { @PostMapping("/db/list") @ResponseBody public TableDataInfo dataList(GenTable genTable) { - startPage(); - List list = genTableService.selectDbTableList(genTable); - return getDataTable(list); + return getDataTable(genTableService.selectDbTableList(genTable, getPageRequest())); } /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java index e08d5017d..8587e53ae 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java @@ -1,6 +1,7 @@ package com.ruoyi.generator.domain; import java.util.List; +import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotBlank; @@ -13,12 +14,16 @@ import com.ruoyi.common.utils.StringUtils; * * @author ruoyi */ +@Entity +@Table(name = "gen_table") public class GenTable extends BaseEntity { private static final long serialVersionUID = 1L; /** * 编号 */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long tableId; /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java index 0777ccf3a..058edbe97 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java @@ -1,21 +1,26 @@ package com.ruoyi.generator.domain; -import javax.validation.constraints.NotBlank; - import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.utils.StringUtils; +import javax.persistence.*; +import javax.validation.constraints.NotBlank; + /** * 代码生成业务字段表 gen_table_column * * @author ruoyi */ +@Entity +@Table(name = "gen_table_column") public class GenTableColumn extends BaseEntity { private static final long serialVersionUID = 1L; /** * 编号 */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long columnId; /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java new file mode 100644 index 000000000..5e55976b9 --- /dev/null +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java @@ -0,0 +1,9 @@ +package com.ruoyi.generator.repository; + +import com.ruoyi.common.base.BaseRepository; +import com.ruoyi.generator.domain.GenTableColumn; +import org.springframework.stereotype.Repository; + +@Repository +public interface GenTableColumnRepository extends BaseRepository { +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java new file mode 100644 index 000000000..c0ce83fb5 --- /dev/null +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java @@ -0,0 +1,9 @@ +package com.ruoyi.generator.repository; + +import com.ruoyi.common.base.BaseRepository; +import com.ruoyi.generator.domain.GenTable; +import org.springframework.stereotype.Repository; + +@Repository +public interface GenTableRepository extends BaseRepository { +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java index 3950948ac..57ed5bce5 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableService.java @@ -1,10 +1,12 @@ package com.ruoyi.generator.service; +import com.ruoyi.generator.domain.GenTable; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + import java.util.List; import java.util.Map; -import com.ruoyi.generator.domain.GenTable; - /** * 业务 服务层 * @@ -17,7 +19,7 @@ public interface IGenTableService { * @param genTable 业务信息 * @return 业务集合 */ - public List selectGenTableList(GenTable genTable); + public Page selectGenTableList(GenTable genTable, Pageable pageable); /** * 查询据库列表 @@ -25,7 +27,7 @@ public interface IGenTableService { * @param genTable 业务信息 * @return 数据库表集合 */ - public List selectDbTableList(GenTable genTable); + public Page selectDbTableList(GenTable genTable, Pageable pageable); /** * 查询据库列表 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java index 944f33a27..3d90c9f7e 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java @@ -1,23 +1,5 @@ package com.ruoyi.generator.service.impl; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.commons.io.IOUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ruoyi.common.constant.Constants; @@ -29,10 +11,31 @@ import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.mapper.GenTableColumnMapper; import com.ruoyi.generator.mapper.GenTableMapper; +import com.ruoyi.generator.repository.GenTableRepository; import com.ruoyi.generator.service.IGenTableService; import com.ruoyi.generator.util.GenUtils; import com.ruoyi.generator.util.VelocityInitializer; import com.ruoyi.generator.util.VelocityUtils; +import org.apache.commons.io.IOUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; /** * 业务 服务层实现 @@ -48,6 +51,8 @@ public class GenTableServiceImpl implements IGenTableService { @Autowired private GenTableColumnMapper genTableColumnMapper; + @Autowired + private GenTableRepository genTableRepository; /** * 查询业务信息 @@ -69,8 +74,8 @@ public class GenTableServiceImpl implements IGenTableService { * @return 业务集合 */ @Override - public List selectGenTableList(GenTable genTable) { - return genTableMapper.selectGenTableList(genTable); + public Page selectGenTableList(GenTable genTable, Pageable pageable) { + return genTableRepository.findAll(pageable); } /** @@ -79,8 +84,8 @@ public class GenTableServiceImpl implements IGenTableService { * @param genTable 业务信息 * @return 数据库表集合 */ - public List selectDbTableList(GenTable genTable) { - return genTableMapper.selectDbTableList(genTable); + public Page selectDbTableList(GenTable genTable, Pageable pageable) { + return genTableRepository.findAll(pageable); } /** @@ -269,7 +274,7 @@ public class GenTableServiceImpl implements IGenTableService { /** * 设置主键列信息 * - * @param genTable 业务表信息 + * @param table 业务表信息 * @param columns 业务字段列表 */ public void setPkColumn(GenTable table, List columns) { diff --git a/ruoyi-generator/src/main/resources/vm/java/controller.java.vm b/ruoyi-generator/src/main/resources/vm/java/controller.java.vm index 7b4bf470b..97eb459c0 100644 --- a/ruoyi-generator/src/main/resources/vm/java/controller.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/controller.java.vm @@ -1,201 +1,200 @@ -package ${basePackage}.web.controller.${moduleName}; - -import java.util.List; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.enums.BusinessType; -import ${packageName}.domain.${ClassName}; -import ${packageName}.service.I${ClassName}Service; -import com.ruoyi.common.core.controller.BaseController; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.utils.poi.ExcelUtil; -#if($table.crud) -import com.ruoyi.common.core.page.TableDataInfo; -#elseif($table.tree) -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.core.domain.Ztree; -#end - -/** - * ${functionName}Controller - * - * @author ${author} - * @date ${datetime} - */ -@Controller -@RequestMapping("/${moduleName}/${businessName}") -public class ${ClassName}Controller extends BaseController -{ - private String prefix = "${moduleName}/${businessName}"; - - @Autowired - private I${ClassName}Service ${className}Service; - - @RequiresPermissions("${permissionPrefix}:view") - @GetMapping() - public String ${businessName}() - { - return prefix + "/${businessName}"; - } - -#if($table.crud) - /** - * 查询${functionName}列表 - */ - @RequiresPermissions("${permissionPrefix}:list") - @PostMapping("/list") - @ResponseBody - public TableDataInfo list(${ClassName} ${className}) - { - startPage(); - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); - return getDataTable(list); - } -#elseif($table.tree) - /** - * 查询${functionName}树列表 - */ - @RequiresPermissions("${permissionPrefix}:list") - @PostMapping("/list") - @ResponseBody - public List<${ClassName}> list(${ClassName} ${className}) - { - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); - return list; - } -#end - - /** - * 导出${functionName}列表 - */ - @RequiresPermissions("${permissionPrefix}:export") - @Log(title = "${functionName}", businessType = BusinessType.EXPORT) - @PostMapping("/export") - @ResponseBody - public AjaxResult export(${ClassName} ${className}) - { - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); - ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}.class); - return util.exportExcel(list, "${businessName}"); - } - -#if($table.crud) - /** - * 新增${functionName} - */ - @GetMapping("/add") - public String add() - { - return prefix + "/add"; - } -#elseif($table.tree) - /** - * 新增${functionName} - */ - @GetMapping(value = { "/add/{${pkColumn.javaField}}", "/add/" }) - public String add(@PathVariable(value = "${pkColumn.javaField}", required = false) Long ${pkColumn.javaField}, ModelMap mmap) - { - if (StringUtils.isNotNull(${pkColumn.javaField})) - { - mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); - } - return prefix + "/add"; - } -#end - - /** - * 新增保存${functionName} - */ - @RequiresPermissions("${permissionPrefix}:add") - @Log(title = "${functionName}", businessType = BusinessType.INSERT) - @PostMapping("/add") - @ResponseBody - public AjaxResult addSave(${ClassName} ${className}) - { - return toAjax(${className}Service.insert${ClassName}(${className})); - } - - /** - * 修改${functionName} - */ - @GetMapping("/edit/{${pkColumn.javaField}}") - public String edit(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}, ModelMap mmap) - { - ${ClassName} ${className} = ${className}Service.select${ClassName}ById(${pkColumn.javaField}); - mmap.put("${className}", ${className}); - return prefix + "/edit"; - } - - /** - * 修改保存${functionName} - */ - @RequiresPermissions("${permissionPrefix}:edit") - @Log(title = "${functionName}", businessType = BusinessType.UPDATE) - @PostMapping("/edit") - @ResponseBody - public AjaxResult editSave(${ClassName} ${className}) - { - return toAjax(${className}Service.update${ClassName}(${className})); - } - -#if($table.crud) - /** - * 删除${functionName} - */ - @RequiresPermissions("${permissionPrefix}:remove") - @Log(title = "${functionName}", businessType = BusinessType.DELETE) - @PostMapping( "/remove") - @ResponseBody - public AjaxResult remove(String ids) - { - return toAjax(${className}Service.delete${ClassName}ByIds(ids)); - } -#elseif($table.tree) - /** - * 删除 - */ - @RequiresPermissions("${permissionPrefix}:remove") - @Log(title = "${functionName}", businessType = BusinessType.DELETE) - @GetMapping("/remove/{${pkColumn.javaField}}") - @ResponseBody - public AjaxResult remove(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) - { - return toAjax(${className}Service.delete${ClassName}ById(${pkColumn.javaField})); - } -#end -#if($table.tree) - - /** - * 选择${functionName}树 - */ -#set($BusinessName=$businessName.substring(0,1).toUpperCase() + ${businessName.substring(1)}) - @GetMapping(value = { "/select${BusinessName}Tree/{${pkColumn.javaField}}", "/select${BusinessName}Tree/" }) - public String select${BusinessName}Tree(@PathVariable(value = "${pkColumn.javaField}", required = false) Long ${pkColumn.javaField}, ModelMap mmap) - { - if (StringUtils.isNotNull(${pkColumn.javaField})) - { - mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); - } - return prefix + "/tree"; - } - - /** - * 加载${functionName}树列表 - */ - @GetMapping("/treeData") - @ResponseBody - public List treeData() - { - List ztrees = ${className}Service.select${ClassName}Tree(); - return ztrees; - } -#end -} +package ${basePackage}.web.controller.${moduleName}; + +import java.util.List; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.enums.BusinessType; +import ${packageName}.domain.${ClassName}; +import ${packageName}.service.I${ClassName}Service; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.utils.poi.ExcelUtil; +#if($table.crud) +import com.ruoyi.common.core.page.TableDataInfo; +#elseif($table.tree) +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.core.domain.Ztree; +#end + +/** + * ${functionName}Controller + * + * @author ${author} + * @date ${datetime} + */ +@Controller +@RequestMapping("/${moduleName}/${businessName}") +public class ${ClassName}Controller extends BaseController +{ + private String prefix = "${moduleName}/${businessName}"; + + @Autowired + private I${ClassName}Service ${className}Service; + + @RequiresPermissions("${permissionPrefix}:view") + @GetMapping() + public String ${businessName}() + { + return prefix + "/${businessName}"; + } + +#if($table.crud) + /** + * 查询${functionName}列表 + */ + @RequiresPermissions("${permissionPrefix}:list") + @PostMapping("/list") + @ResponseBody + public TableDataInfo list(${ClassName} ${className}) { + startPage(); + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + return getDataTable(list); + } +#elseif($table.tree) + /** + * 查询${functionName}树列表 + */ + @RequiresPermissions("${permissionPrefix}:list") + @PostMapping("/list") + @ResponseBody + public List<${ClassName}> list(${ClassName} ${className}) + { + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + return list; + } +#end + + /** + * 导出${functionName}列表 + */ + @RequiresPermissions("${permissionPrefix}:export") + @Log(title = "${functionName}", businessType = BusinessType.EXPORT) + @PostMapping("/export") + @ResponseBody + public AjaxResult export(${ClassName} ${className}) + { + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}.class); + return util.exportExcel(list, "${businessName}"); + } + +#if($table.crud) + /** + * 新增${functionName} + */ + @GetMapping("/add") + public String add() + { + return prefix + "/add"; + } +#elseif($table.tree) + /** + * 新增${functionName} + */ + @GetMapping(value = { "/add/{${pkColumn.javaField}}", "/add/" }) + public String add(@PathVariable(value = "${pkColumn.javaField}", required = false) Long ${pkColumn.javaField}, ModelMap mmap) + { + if (StringUtils.isNotNull(${pkColumn.javaField})) + { + mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); + } + return prefix + "/add"; + } +#end + + /** + * 新增保存${functionName} + */ + @RequiresPermissions("${permissionPrefix}:add") + @Log(title = "${functionName}", businessType = BusinessType.INSERT) + @PostMapping("/add") + @ResponseBody + public AjaxResult addSave(${ClassName} ${className}) + { + return toAjax(${className}Service.insert${ClassName}(${className})); + } + + /** + * 修改${functionName} + */ + @GetMapping("/edit/{${pkColumn.javaField}}") + public String edit(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}, ModelMap mmap) + { + ${ClassName} ${className} = ${className}Service.select${ClassName}ById(${pkColumn.javaField}); + mmap.put("${className}", ${className}); + return prefix + "/edit"; + } + + /** + * 修改保存${functionName} + */ + @RequiresPermissions("${permissionPrefix}:edit") + @Log(title = "${functionName}", businessType = BusinessType.UPDATE) + @PostMapping("/edit") + @ResponseBody + public AjaxResult editSave(${ClassName} ${className}) + { + return toAjax(${className}Service.update${ClassName}(${className})); + } + +#if($table.crud) + /** + * 删除${functionName} + */ + @RequiresPermissions("${permissionPrefix}:remove") + @Log(title = "${functionName}", businessType = BusinessType.DELETE) + @PostMapping( "/remove") + @ResponseBody + public AjaxResult remove(String ids) + { + return toAjax(${className}Service.delete${ClassName}ByIds(ids)); + } +#elseif($table.tree) + /** + * 删除 + */ + @RequiresPermissions("${permissionPrefix}:remove") + @Log(title = "${functionName}", businessType = BusinessType.DELETE) + @GetMapping("/remove/{${pkColumn.javaField}}") + @ResponseBody + public AjaxResult remove(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) + { + return toAjax(${className}Service.delete${ClassName}ById(${pkColumn.javaField})); + } +#end +#if($table.tree) + + /** + * 选择${functionName}树 + */ +#set($BusinessName=$businessName.substring(0,1).toUpperCase() + ${businessName.substring(1)}) + @GetMapping(value = { "/select${BusinessName}Tree/{${pkColumn.javaField}}", "/select${BusinessName}Tree/" }) + public String select${BusinessName}Tree(@PathVariable(value = "${pkColumn.javaField}", required = false) Long ${pkColumn.javaField}, ModelMap mmap) + { + if (StringUtils.isNotNull(${pkColumn.javaField})) + { + mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); + } + return prefix + "/tree"; + } + + /** + * 加载${functionName}树列表 + */ + @GetMapping("/treeData") + @ResponseBody + public List treeData() + { + List ztrees = ${className}Service.select${ClassName}Tree(); + return ztrees; + } +#end +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java index b2d36c2f4..25556c985 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java @@ -2,6 +2,7 @@ package com.ruoyi.quartz.domain; import java.io.Serializable; import java.util.Date; +import javax.persistence.*; import javax.validation.constraints.*; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -18,6 +19,8 @@ import com.ruoyi.quartz.util.CronUtils; * * @author ruoyi */ +@Entity +@Table(name = "sys_job") public class SysJob extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @@ -25,6 +28,8 @@ public class SysJob extends BaseEntity implements Serializable { * 任务ID */ @Excel(name = "任务序号", cellType = ColumnType.NUMERIC) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long jobId; /** diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobLogRepository.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobLogRepository.java new file mode 100644 index 000000000..e40452a7c --- /dev/null +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobLogRepository.java @@ -0,0 +1,9 @@ +package com.ruoyi.quartz.repository; + +import com.ruoyi.common.base.BaseRepository; +import com.ruoyi.quartz.domain.SysJobLog; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysJobLogRepository extends BaseRepository { +} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java new file mode 100644 index 000000000..281b20360 --- /dev/null +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java @@ -0,0 +1,9 @@ +package com.ruoyi.quartz.repository; + +import com.ruoyi.common.base.BaseRepository; +import com.ruoyi.quartz.domain.SysJob; +import org.springframework.stereotype.Repository; + +@Repository +public interface SysJobRepository extends BaseRepository { +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java index 63318962b..6ee8b5980 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysConfigRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysConfig; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java index 511a5fba6..05109716d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDeptRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysDept; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java index 88056625e..e4d278ffc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictDataRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysDictData; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java index 2b9937313..626251541 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysDictTypeRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysDictType; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java index 6685a0fb0..8d7706b0a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysLogininfoRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysLogininfor; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java index cc08f3047..bb8b1d7d8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysMenuRepository.java @@ -1,8 +1,8 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; import java.util.Collection; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java index fc7c74699..95173734c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysNoticeRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysNotice; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java index f37f90ab8..727497dda 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysOperLogRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysOperLog; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java index abcb506d1..556958753 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysPostRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysPost; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java index 554487390..06352826d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysRoleRepository.java @@ -1,8 +1,8 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysRole; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java index fa15604e8..5707aecb1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserOnlineRepository.java @@ -1,7 +1,7 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.stereotype.Repository; import java.util.Date; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java index 259c758ee..1c166cefd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/repository/SysUserRepository.java @@ -1,10 +1,10 @@ package com.ruoyi.system.repository; +import com.ruoyi.common.base.BaseRepository; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; -import com.ruoyi.system.repository.base.BaseRepository; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java index b17863800..e6e2f0d6a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java @@ -2,6 +2,7 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; @@ -9,7 +10,6 @@ import com.ruoyi.system.domain.QSysConfig; import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.repository.SysConfigRepository; import com.ruoyi.system.service.ISysConfigService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java index c56388f93..9bce70d19 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java @@ -1,6 +1,6 @@ package com.ruoyi.system.service.impl; -import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.Ztree; @@ -32,7 +32,7 @@ import java.util.List; * @author ruoyi */ @Service -public class SysDeptServiceImpl implements ISysDeptService { +public class SysDeptServiceImpl extends BaseService implements ISysDeptService { @Autowired private SysDeptRepository sysDeptRepository; @Autowired diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java index d564f5bfd..aac788a21 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java @@ -2,13 +2,13 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.QSysDictData; import com.ruoyi.system.domain.SysDictData; import com.ruoyi.system.repository.SysDictDataRepository; import com.ruoyi.system.service.ISysDictDataService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java index a849b229d..af6a98dde 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java @@ -2,6 +2,7 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.text.Convert; @@ -12,7 +13,6 @@ import com.ruoyi.system.domain.SysDictType; import com.ruoyi.system.repository.SysDictDataRepository; import com.ruoyi.system.repository.SysDictTypeRepository; import com.ruoyi.system.service.ISysDictTypeService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java index 5965c05d4..61d92a560 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java @@ -2,13 +2,13 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.QSysLogininfor; import com.ruoyi.system.domain.SysLogininfor; import com.ruoyi.system.repository.SysLogininfoRepository; import com.ruoyi.system.service.ISysLogininforService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java index 5bc139905..67ac1a679 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java @@ -1,6 +1,7 @@ package com.ruoyi.system.service.impl; import com.google.common.collect.Lists; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.Ztree; @@ -27,7 +28,7 @@ import java.util.*; * @author ruoyi */ @Service -public class SysMenuServiceImpl implements ISysMenuService { +public class SysMenuServiceImpl extends BaseService implements ISysMenuService { public static final String PREMISSION_STRING = "perms[\"{0}\"]"; @Autowired diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java index ff485c602..9b29c78a0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysNoticeServiceImpl.java @@ -2,13 +2,13 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.QSysNotice; import com.ruoyi.system.domain.SysNotice; import com.ruoyi.system.repository.SysNoticeRepository; import com.ruoyi.system.service.ISysNoticeService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java index 67a350565..369695c85 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysOperLogServiceImpl.java @@ -2,13 +2,13 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.QSysOperLog; import com.ruoyi.system.domain.SysOperLog; import com.ruoyi.system.repository.SysOperLogRepository; import com.ruoyi.system.service.ISysOperLogService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java index cca258cd6..fcb1c5bbe 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java @@ -1,5 +1,6 @@ package com.ruoyi.system.service.impl; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; @@ -29,7 +30,7 @@ import java.util.List; * @author ruoyi */ @Service -public class SysPostServiceImpl implements ISysPostService { +public class SysPostServiceImpl extends BaseService implements ISysPostService { @Autowired private SysPostRepository sysPostRepository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index 14c8d94ad..ec1cb2bcb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -2,6 +2,7 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; @@ -14,7 +15,6 @@ import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.repository.SysRoleRepository; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysRoleService; -import com.ruoyi.system.service.base.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java index e4e06e24d..aa08650d8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java @@ -1,5 +1,6 @@ package com.ruoyi.system.service.impl; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysUserOnline; import com.ruoyi.system.repository.SysUserOnlineRepository; @@ -25,7 +26,7 @@ import java.util.List; * @author ruoyi */ @Service -public class SysUserOnlineServiceImpl implements ISysUserOnlineService { +public class SysUserOnlineServiceImpl extends BaseService implements ISysUserOnlineService { @Autowired private SysUserOnlineRepository sysUserOnlineRepository; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index c290729c2..2955b73e7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -1,6 +1,7 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; @@ -13,7 +14,6 @@ import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; -import com.ruoyi.system.service.base.BaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; From aaab18742dbacf045d98dcbd3b5a08a549f7cc18 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Wed, 25 Dec 2019 18:27:38 +0800 Subject: [PATCH 45/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../framework/config/ApplicationConfig.java | 4 +-- .../ruoyi/framework/config/MyBatisConfig.java | 33 +++---------------- .../com/ruoyi/generator/domain/GenTable.java | 1 + .../generator/domain/GenTableColumn.java | 26 +++++++-------- .../impl/GenTableColumnServiceImpl.java | 1 - .../service/impl/GenTableServiceImpl.java | 2 -- .../com/ruoyi/generator/util/GenUtils.java | 4 +-- .../quartz/controller/SysJobController.java | 29 +++++++--------- .../controller/SysJobLogController.java | 25 ++++++-------- .../com/ruoyi/quartz/domain/SysJobLog.java | 13 +++++--- .../quartz/service/ISysJobLogService.java | 4 ++- .../ruoyi/quartz/service/ISysJobService.java | 8 ++--- .../service/impl/SysJobLogServiceImpl.java | 16 +++++---- .../service/impl/SysJobServiceImpl.java | 32 ++++++++++-------- 14 files changed, 87 insertions(+), 111 deletions(-) diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java index 8cfcae95f..b1013ab38 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ApplicationConfig.java @@ -1,6 +1,5 @@ package com.ruoyi.framework.config; -import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -13,7 +12,6 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; // 表示通过aop框架暴露该代理对象,AopContext能够访问 @EnableAspectJAutoProxy(exposeProxy = true) // 指定要扫描的Mapper类的包的路径 -@MapperScan("com.ruoyi.**.mapper") public class ApplicationConfig { -} +} \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java index 09d3db033..7a9d0ba2d 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java @@ -1,20 +1,8 @@ package com.ruoyi.framework.config; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import javax.sql.DataSource; - -import org.apache.ibatis.io.VFS; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; -import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; @@ -23,6 +11,11 @@ import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.ClassUtils; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + /** * Mybatis支持*匹配扫描包 * @@ -73,20 +66,4 @@ public class MyBatisConfig { } return typeAliasesPackage; } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); - String mapperLocations = env.getProperty("mybatis.mapperLocations"); - String configLocation = env.getProperty("mybatis.configLocation"); - typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage); - VFS.addImplClass(SpringBootVFS.class); - - final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); - sessionFactory.setDataSource(dataSource); - sessionFactory.setTypeAliasesPackage(typeAliasesPackage); - sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations)); - sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); - return sessionFactory.getObject(); - } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java index 8587e53ae..5c6d90ab0 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java @@ -88,6 +88,7 @@ public class GenTable extends BaseEntity { * 表列信息 */ @Valid + @OneToMany(fetch = FetchType.EAGER, mappedBy = "") private List columns; /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java index 058edbe97..a20078e21 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java @@ -23,11 +23,6 @@ public class GenTableColumn extends BaseEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long columnId; - /** - * 归属表编号 - */ - private Long tableId; - /** * 列名称 */ @@ -109,6 +104,11 @@ public class GenTableColumn extends BaseEntity { */ private Integer sort; + @ManyToOne + @JoinColumn(name = "tableId", referencedColumnName = "tableId") + @org.hibernate.annotations.ForeignKey(name = "none") + private GenTable table; + public void setColumnId(Long columnId) { this.columnId = columnId; } @@ -117,14 +117,6 @@ public class GenTableColumn extends BaseEntity { return columnId; } - public void setTableId(Long tableId) { - this.tableId = tableId; - } - - public Long getTableId() { - return tableId; - } - public void setColumnName(String columnName) { this.columnName = columnName; } @@ -346,4 +338,12 @@ public class GenTableColumn extends BaseEntity { return this.columnComment; } } + + public GenTable getTable() { + return table; + } + + public void setTable(GenTable table) { + this.table = table; + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java index 650166efa..a0b716032 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java @@ -16,7 +16,6 @@ import com.ruoyi.generator.service.IGenTableColumnService; */ @Service public class GenTableColumnServiceImpl implements IGenTableColumnService { - @Autowired private GenTableColumnMapper genTableColumnMapper; /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java index 3d90c9f7e..8d1cf247e 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java @@ -46,10 +46,8 @@ import java.util.zip.ZipOutputStream; public class GenTableServiceImpl implements IGenTableService { private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); - @Autowired private GenTableMapper genTableMapper; - @Autowired private GenTableColumnMapper genTableColumnMapper; @Autowired private GenTableRepository genTableRepository; diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java index 2f881af25..3a30afb00 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java @@ -34,7 +34,7 @@ public class GenUtils { public static void initColumnField(GenTableColumn column, GenTable table) { String dataType = getDbType(column.getColumnType()); String columnName = column.getColumnName(); - column.setTableId(table.getTableId()); + column.setTable(table); column.setCreateBy(table.getCreateBy()); // 设置java字段名 column.setJavaField(StringUtils.toCamelCase(columnName)); @@ -154,7 +154,7 @@ public class GenUtils { /** * 关键字替换 * - * @param name 需要被替换的名字 + * @param text 需要被替换的名字 * @return 替换后的名字 */ public static String replaceText(String text) { diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java index e827117d0..ba2ee7a45 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java @@ -1,18 +1,5 @@ package com.ruoyi.quartz.controller; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -22,6 +9,16 @@ import com.ruoyi.common.exception.job.TaskException; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.quartz.domain.SysJob; import com.ruoyi.quartz.service.ISysJobService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 调度任务信息操作处理 @@ -46,9 +43,7 @@ public class SysJobController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysJob job) { - startPage(); - List list = jobService.selectJobList(job); - return getDataTable(list); + return getDataTable(jobService.selectJobList(job, getPageRequest())); } @Log(title = "定时任务", businessType = BusinessType.EXPORT) @@ -56,7 +51,7 @@ public class SysJobController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysJob job) { - List list = jobService.selectJobList(job); + List list = jobService.selectJobList(job, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysJob.class); return util.exportExcel(list, "定时任务"); } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java index 20ba7403f..2e5f40374 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java @@ -1,16 +1,5 @@ package com.ruoyi.quartz.controller; -import java.util.List; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -19,6 +8,14 @@ import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.quartz.domain.SysJobLog; import com.ruoyi.quartz.service.ISysJobLogService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.*; + +import java.util.List; /** * 调度日志操作处理 @@ -43,9 +40,7 @@ public class SysJobLogController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysJobLog jobLog) { - startPage(); - List list = jobLogService.selectJobLogList(jobLog); - return getDataTable(list); + return getDataTable(jobLogService.selectJobLogList(jobLog, getPageRequest())); } @Log(title = "调度日志", businessType = BusinessType.EXPORT) @@ -53,7 +48,7 @@ public class SysJobLogController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysJobLog jobLog) { - List list = jobLogService.selectJobLogList(jobLog); + List list = jobLogService.selectJobLogList(jobLog, Pageable.unpaged()).getContent(); ExcelUtil util = new ExcelUtil(SysJobLog.class); return util.exportExcel(list, "调度日志"); } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java index af82675dd..df9e212ad 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java @@ -1,17 +1,20 @@ package com.ruoyi.quartz.domain; -import java.util.Date; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.persistence.*; +import java.util.Date; /** * 定时任务调度日志表 sys_job_log * * @author ruoyi */ +@Entity +@Table(name = "sys_job_log") public class SysJobLog extends BaseEntity { private static final long serialVersionUID = 1L; @@ -19,6 +22,8 @@ public class SysJobLog extends BaseEntity { * ID */ @Excel(name = "日志序号") + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long jobLogId; /** diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java index 9366bc35e..a1d0ddc13 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobLogService.java @@ -3,6 +3,8 @@ package com.ruoyi.quartz.service; import java.util.List; import com.ruoyi.quartz.domain.SysJobLog; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 定时任务调度日志信息信息 服务层 @@ -16,7 +18,7 @@ public interface ISysJobLogService { * @param jobLog 调度日志信息 * @return 调度任务日志集合 */ - public List selectJobLogList(SysJobLog jobLog); + public Page selectJobLogList(SysJobLog jobLog, Pageable pageable); /** * 通过调度任务日志ID查询调度信息 diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java index 84f11e054..3ed2f983e 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/ISysJobService.java @@ -1,10 +1,10 @@ package com.ruoyi.quartz.service; -import java.util.List; - -import org.quartz.SchedulerException; import com.ruoyi.common.exception.job.TaskException; import com.ruoyi.quartz.domain.SysJob; +import org.quartz.SchedulerException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 定时任务调度信息信息 服务层 @@ -18,7 +18,7 @@ public interface ISysJobService { * @param job 调度信息 * @return 调度任务集合 */ - public List selectJobList(SysJob job); + public Page selectJobList(SysJob job, Pageable pageable); /** * 通过调度任务ID查询调度信息 diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java index 2e4ebe325..0433852fc 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java @@ -1,13 +1,14 @@ package com.ruoyi.quartz.service.impl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.ruoyi.common.core.text.Convert; import com.ruoyi.quartz.domain.SysJobLog; import com.ruoyi.quartz.mapper.SysJobLogMapper; +import com.ruoyi.quartz.repository.SysJobLogRepository; import com.ruoyi.quartz.service.ISysJobLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; /** * 定时任务调度日志信息 服务层 @@ -16,8 +17,9 @@ import com.ruoyi.quartz.service.ISysJobLogService; */ @Service public class SysJobLogServiceImpl implements ISysJobLogService { - @Autowired private SysJobLogMapper jobLogMapper; + @Autowired + private SysJobLogRepository sysJobLogRepository; /** * 获取quartz调度器日志的计划任务 @@ -26,8 +28,8 @@ public class SysJobLogServiceImpl implements ISysJobLogService { * @return 调度任务日志集合 */ @Override - public List selectJobLogList(SysJobLog jobLog) { - return jobLogMapper.selectJobLogList(jobLog); + public Page selectJobLogList(SysJobLog jobLog, Pageable pageable) { + return sysJobLogRepository.findAll(pageable); } /** diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java index 3e3eeba4c..53f9883da 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java @@ -1,23 +1,26 @@ package com.ruoyi.quartz.service.impl; -import java.util.List; -import javax.annotation.PostConstruct; - -import org.quartz.JobDataMap; -import org.quartz.JobKey; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.ruoyi.common.constant.ScheduleConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.job.TaskException; import com.ruoyi.quartz.domain.SysJob; import com.ruoyi.quartz.mapper.SysJobMapper; +import com.ruoyi.quartz.repository.SysJobRepository; import com.ruoyi.quartz.service.ISysJobService; import com.ruoyi.quartz.util.CronUtils; import com.ruoyi.quartz.util.ScheduleUtils; +import org.quartz.JobDataMap; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import java.util.List; /** * 定时任务调度信息 服务层 @@ -29,8 +32,9 @@ public class SysJobServiceImpl implements ISysJobService { @Autowired private Scheduler scheduler; - @Autowired private SysJobMapper jobMapper; + @Autowired + private SysJobRepository sysJobRepository; /** * 项目启动时,初始化定时器 @@ -38,7 +42,7 @@ public class SysJobServiceImpl implements ISysJobService { */ @PostConstruct public void init() throws SchedulerException, TaskException { - List jobList = jobMapper.selectJobAll(); + List jobList = sysJobRepository.findAll(); for (SysJob job : jobList) { updateSchedulerJob(job, job.getJobGroup()); } @@ -51,8 +55,8 @@ public class SysJobServiceImpl implements ISysJobService { * @return */ @Override - public List selectJobList(SysJob job) { - return jobMapper.selectJobList(job); + public Page selectJobList(SysJob job, Pageable pageable) { + return sysJobRepository.findAll(pageable); } /** From 9622b8f5945ea34e0d659042a28202aa19072036 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Thu, 26 Dec 2019 18:23:40 +0800 Subject: [PATCH 46/52] =?UTF-8?q?=E5=8E=BB=E6=8E=89mybatis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ruoyi/quartz/domain/SysJobLog.java | 7 +- .../ruoyi/quartz/mapper/SysJobLogMapper.java | 64 ---------- .../com/ruoyi/quartz/mapper/SysJobMapper.java | 67 ----------- .../quartz/repository/SysJobRepository.java | 6 + .../service/impl/SysJobLogServiceImpl.java | 60 ++++++++-- .../service/impl/SysJobServiceImpl.java | 76 +++++++----- .../ruoyi/quartz/util/AbstractQuartzJob.java | 2 +- .../mapper/quartz/SysJobLogMapper.xml | 93 --------------- .../resources/mapper/quartz/SysJobMapper.xml | 111 ------------------ .../com/ruoyi/system/domain/SysOperLog.java | 26 +++- 10 files changed, 130 insertions(+), 382 deletions(-) delete mode 100644 ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java delete mode 100644 ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java delete mode 100644 ruoyi-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml delete mode 100644 ruoyi-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java index df9e212ad..d341ea62e 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java @@ -1,11 +1,11 @@ package com.ruoyi.quartz.domain; import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import javax.persistence.*; +import java.io.Serializable; import java.util.Date; /** @@ -14,9 +14,10 @@ import java.util.Date; * @author ruoyi */ @Entity -@Table(name = "sys_job_log") -public class SysJobLog extends BaseEntity { +@Table(name = SysJobLog.TABLE_NAME) +public class SysJobLog implements Serializable { private static final long serialVersionUID = 1L; + public static final String TABLE_NAME = "sys_job_log"; /** * ID diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java deleted file mode 100644 index d2ec1a700..000000000 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobLogMapper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.ruoyi.quartz.mapper; - -import com.ruoyi.quartz.domain.SysJobLog; - -import java.util.List; - -/** - * 调度任务日志信息 数据层 - * - * @author ruoyi - */ -public interface SysJobLogMapper { - /** - * 获取quartz调度器日志的计划任务 - * - * @param jobLog 调度日志信息 - * @return 调度任务日志集合 - */ - public List selectJobLogList(SysJobLog jobLog); - - /** - * 查询所有调度任务日志 - * - * @return 调度任务日志列表 - */ - public List selectJobLogAll(); - - /** - * 通过调度任务日志ID查询调度信息 - * - * @param jobLogId 调度任务日志ID - * @return 调度任务日志对象信息 - */ - public SysJobLog selectJobLogById(Long jobLogId); - - /** - * 新增任务日志 - * - * @param jobLog 调度日志信息 - * @return 结果 - */ - public int insertJobLog(SysJobLog jobLog); - - /** - * 批量删除调度日志信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteJobLogByIds(String[] ids); - - /** - * 删除任务日志 - * - * @param jobId 调度日志ID - * @return 结果 - */ - public int deleteJobLogById(Long jobId); - - /** - * 清空任务日志 - */ - public void cleanJobLog(); -} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java deleted file mode 100644 index 3614b3481..000000000 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/mapper/SysJobMapper.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ruoyi.quartz.mapper; - -import com.ruoyi.quartz.domain.SysJob; - -import java.util.List; - -/** - * 调度任务信息 数据层 - * - * @author ruoyi - */ -public interface SysJobMapper { - /** - * 查询调度任务日志集合 - * - * @param job 调度信息 - * @return 操作日志集合 - */ - public List selectJobList(SysJob job); - - /** - * 查询所有调度任务 - * - * @return 调度任务列表 - */ - public List selectJobAll(); - - /** - * 通过调度ID查询调度任务信息 - * - * @param jobId 调度ID - * @return 角色对象信息 - */ - public SysJob selectJobById(Long jobId); - - /** - * 通过调度ID删除调度任务信息 - * - * @param jobId 调度ID - * @return 结果 - */ - public int deleteJobById(Long jobId); - - /** - * 批量删除调度任务信息 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteJobByIds(Long[] ids); - - /** - * 修改调度任务信息 - * - * @param job 调度任务信息 - * @return 结果 - */ - public int updateJob(SysJob job); - - /** - * 新增调度任务信息 - * - * @param job 调度任务信息 - * @return 结果 - */ - public int insertJob(SysJob job); -} diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java index 281b20360..89bc38637 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/repository/SysJobRepository.java @@ -2,8 +2,14 @@ package com.ruoyi.quartz.repository; import com.ruoyi.common.base.BaseRepository; import com.ruoyi.quartz.domain.SysJob; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface SysJobRepository extends BaseRepository { + + @Modifying + @Query("update SysJob j set j.status = ?1 where j.jobId = ?2") + void updateStatus(String status, Long id); } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java index 0433852fc..6e1814b31 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobLogServiceImpl.java @@ -1,14 +1,23 @@ package com.ruoyi.quartz.service.impl; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.quartz.domain.QSysJobLog; import com.ruoyi.quartz.domain.SysJobLog; -import com.ruoyi.quartz.mapper.SysJobLogMapper; import com.ruoyi.quartz.repository.SysJobLogRepository; import com.ruoyi.quartz.service.ISysJobLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; /** * 定时任务调度日志信息 服务层 @@ -16,10 +25,11 @@ import org.springframework.stereotype.Service; * @author ruoyi */ @Service -public class SysJobLogServiceImpl implements ISysJobLogService { - private SysJobLogMapper jobLogMapper; +public class SysJobLogServiceImpl extends BaseService implements ISysJobLogService { @Autowired private SysJobLogRepository sysJobLogRepository; + @Autowired + private JdbcTemplate jdbcTemplate; /** * 获取quartz调度器日志的计划任务 @@ -29,7 +39,31 @@ public class SysJobLogServiceImpl implements ISysJobLogService { */ @Override public Page selectJobLogList(SysJobLog jobLog, Pageable pageable) { - return sysJobLogRepository.findAll(pageable); + return sysJobLogRepository.findAll(getPredicate(jobLog), pageable); + } + + private Predicate getPredicate(SysJobLog jobLog){ + QSysJobLog qSysJobLog = QSysJobLog.sysJobLog; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(jobLog.getJobName())){ + predicates.add(buildLike(qSysJobLog.jobName, jobLog.getJobName())); + } + if(StringUtils.isNotEmpty(jobLog.getJobGroup())){ + predicates.add(buildEqual(qSysJobLog.jobGroup, jobLog.getJobGroup())); + } + if(StringUtils.isNotEmpty(jobLog.getStatus())){ + predicates.add(buildEqual(qSysJobLog.status, jobLog.getStatus())); + } + if(StringUtils.isNotEmpty(jobLog.getInvokeTarget())){ + predicates.add(buildLike(qSysJobLog.invokeTarget, jobLog.getInvokeTarget())); + } + if(jobLog.getStartTime() != null){ + predicates.add(buildGreaterThanOrEqualTo(qSysJobLog.startTime, jobLog.getStartTime())); + } + if(jobLog.getEndTime() != null){ + predicates.add(buildLessThanOrEqualTo(qSysJobLog.endTime, jobLog.getEndTime())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -40,7 +74,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService { */ @Override public SysJobLog selectJobLogById(Long jobLogId) { - return jobLogMapper.selectJobLogById(jobLogId); + return sysJobLogRepository.findById(jobLogId).get(); } /** @@ -48,9 +82,10 @@ public class SysJobLogServiceImpl implements ISysJobLogService { * * @param jobLog 调度日志信息 */ + @Transactional @Override public void addJobLog(SysJobLog jobLog) { - jobLogMapper.insertJobLog(jobLog); + sysJobLogRepository.save(jobLog); } /** @@ -59,9 +94,13 @@ public class SysJobLogServiceImpl implements ISysJobLogService { * @param ids 需要删除的数据ID * @return 结果 */ + @Transactional @Override public int deleteJobLogByIds(String ids) { - return jobLogMapper.deleteJobLogByIds(Convert.toStrArray(ids)); + for(Long id : Convert.toLongArray(ids)){ + deleteJobLogById(id); + } + return 1; } /** @@ -69,16 +108,19 @@ public class SysJobLogServiceImpl implements ISysJobLogService { * * @param jobId 调度日志ID */ + @Transactional @Override public int deleteJobLogById(Long jobId) { - return jobLogMapper.deleteJobLogById(jobId); + sysJobLogRepository.deleteById(jobId); + return 1; } /** * 清空任务日志 */ + @Transactional @Override public void cleanJobLog() { - jobLogMapper.cleanJobLog(); + jdbcTemplate.update("truncate table " + SysJobLog.TABLE_NAME); } } diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java index 53f9883da..4d4e0547b 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/impl/SysJobServiceImpl.java @@ -1,10 +1,14 @@ package com.ruoyi.quartz.service.impl; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.ScheduleConstants; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.job.TaskException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.quartz.domain.QSysJob; import com.ruoyi.quartz.domain.SysJob; -import com.ruoyi.quartz.mapper.SysJobMapper; import com.ruoyi.quartz.repository.SysJobRepository; import com.ruoyi.quartz.service.ISysJobService; import com.ruoyi.quartz.util.CronUtils; @@ -13,6 +17,7 @@ import org.quartz.JobDataMap; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -20,6 +25,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; +import java.util.ArrayList; import java.util.List; /** @@ -28,11 +34,9 @@ import java.util.List; * @author ruoyi */ @Service -public class SysJobServiceImpl implements ISysJobService { +public class SysJobServiceImpl extends BaseService implements ISysJobService { @Autowired private Scheduler scheduler; - - private SysJobMapper jobMapper; @Autowired private SysJobRepository sysJobRepository; @@ -56,7 +60,25 @@ public class SysJobServiceImpl implements ISysJobService { */ @Override public Page selectJobList(SysJob job, Pageable pageable) { - return sysJobRepository.findAll(pageable); + return sysJobRepository.findAll(getPredicate(job), pageable); + } + + private Predicate getPredicate(SysJob job){ + QSysJob qSysJob = QSysJob.sysJob; + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(job.getJobName())){ + predicates.add(buildLike(qSysJob.jobName, job.getJobName())); + } + if(StringUtils.isNotEmpty(job.getJobGroup())){ + predicates.add(buildEqual(qSysJob.jobGroup, job.getJobGroup())); + } + if(StringUtils.isNotEmpty(job.getStatus())){ + predicates.add(buildEqual(qSysJob.status, job.getStatus())); + } + if(StringUtils.isNotEmpty(job.getInvokeTarget())){ + predicates.add(buildLike(qSysJob.invokeTarget, job.getInvokeTarget())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -67,7 +89,7 @@ public class SysJobServiceImpl implements ISysJobService { */ @Override public SysJob selectJobById(Long jobId) { - return jobMapper.selectJobById(jobId); + return sysJobRepository.findById(jobId).get(); } /** @@ -81,11 +103,9 @@ public class SysJobServiceImpl implements ISysJobService { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); - int rows = jobMapper.updateJob(job); - if (rows > 0) { - scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; + sysJobRepository.updateStatus(job.getStatus(), jobId); + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + return 1; } /** @@ -99,11 +119,9 @@ public class SysJobServiceImpl implements ISysJobService { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); - int rows = jobMapper.updateJob(job); - if (rows > 0) { - scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; + sysJobRepository.updateStatus(job.getStatus(), jobId); + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + return 1; } /** @@ -116,11 +134,9 @@ public class SysJobServiceImpl implements ISysJobService { public int deleteJob(SysJob job) throws SchedulerException { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); - int rows = jobMapper.deleteJobById(jobId); - if (rows > 0) { - scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); - } - return rows; + sysJobRepository.deleteById(jobId); + scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + return 1; } /** @@ -134,7 +150,7 @@ public class SysJobServiceImpl implements ISysJobService { public void deleteJobByIds(String ids) throws SchedulerException { Long[] jobIds = Convert.toLongArray(ids); for (Long jobId : jobIds) { - SysJob job = jobMapper.selectJobById(jobId); + SysJob job = selectJobById(jobId); deleteJob(job); } } @@ -183,11 +199,9 @@ public class SysJobServiceImpl implements ISysJobService { @Transactional public int insertJob(SysJob job) throws SchedulerException, TaskException { job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); - int rows = jobMapper.insertJob(job); - if (rows > 0) { - ScheduleUtils.createScheduleJob(scheduler, job); - } - return rows; + sysJobRepository.save(job); + ScheduleUtils.createScheduleJob(scheduler, job); + return 1; } /** @@ -199,11 +213,9 @@ public class SysJobServiceImpl implements ISysJobService { @Transactional public int updateJob(SysJob job) throws SchedulerException, TaskException { SysJob properties = selectJobById(job.getJobId()); - int rows = jobMapper.updateJob(job); - if (rows > 0) { - updateSchedulerJob(job, properties.getJobGroup()); - } - return rows; + BeanUtils.copyProperties(job, properties); + updateSchedulerJob(job, properties.getJobGroup()); + return 1; } /** diff --git a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java index ad2bd12f3..96d8cf055 100644 --- a/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java +++ b/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java @@ -60,7 +60,7 @@ public abstract class AbstractQuartzJob implements Job { * 执行后 * * @param context 工作执行上下文对象 - * @param sysScheduleJob 系统计划任务 + * @param sysJob 系统计划任务 */ protected void after(JobExecutionContext context, SysJob sysJob, Exception e) { Date startTime = threadLocal.get(); diff --git a/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml b/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml deleted file mode 100644 index 745bed364..000000000 --- a/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - - select job_log_id, job_name, job_group, invoke_target, job_message, status, exception_info, create_time - from sys_job_log - - - - - - - - - - delete from sys_job_log where job_log_id = #{jobLogId} - - - - delete from sys_job_log where job_log_id in - - #{jobLogId} - - - - - truncate table sys_job_log - - - - insert into sys_job_log( - job_log_id, - job_name, - job_group, - invoke_target, - job_message, - status, - exception_info, - create_time - )values( - #{jobLogId}, - #{jobName}, - #{jobGroup}, - #{invokeTarget}, - #{jobMessage}, - #{status}, - #{exceptionInfo}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml b/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml deleted file mode 100644 index 69233bdf7..000000000 --- a/ruoyi-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - select job_id, job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, status, create_by, create_time, remark - from sys_job - - - - - - - - - - delete from sys_job where job_id = #{jobId} - - - - delete from sys_job where job_id in - - #{jobId} - - - - - update sys_job - - job_name = #{jobName}, - job_group = #{jobGroup}, - invoke_target = #{invokeTarget}, - cron_expression = #{cronExpression}, - misfire_policy = #{misfirePolicy}, - concurrent = #{concurrent}, - status = #{status}, - remark = #{remark}, - update_by = #{updateBy}, - update_time = sysdate() - - where job_id = #{jobId} - - - - insert into sys_job( - job_id, - job_name, - job_group, - invoke_target, - cron_expression, - misfire_policy, - concurrent, - status, - remark, - create_by, - create_time - )values( - #{jobId}, - #{jobName}, - #{jobGroup}, - #{invokeTarget}, - #{cronExpression}, - #{misfirePolicy}, - #{concurrent}, - #{status}, - #{remark}, - #{createBy}, - sysdate() - ) - - - \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java index e635bdc99..0888cf0e8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java @@ -2,11 +2,11 @@ package com.ruoyi.system.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import javax.persistence.*; +import java.io.Serializable; import java.util.Date; /** @@ -16,7 +16,7 @@ import java.util.Date; */ @Entity @Table(name = SysOperLog.TABLE_NAME) -public class SysOperLog extends BaseEntity { +public class SysOperLog implements Serializable { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "sys_oper_log"; @@ -124,6 +124,12 @@ public class SysOperLog extends BaseEntity { @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") private Date operTime; + @Transient + private Date startTime; + + @Transient + private Date endTime; + public Long getOperId() { return operId; } @@ -281,4 +287,20 @@ public class SysOperLog extends BaseEntity { .append("operTime", getOperTime()) .toString(); } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } } From 9e34fc572dbcdc0c4a7eaefbcfcf57927f5781a7 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 27 Dec 2019 12:08:18 +0800 Subject: [PATCH 47/52] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ruoyi/common/base/BaseService.java | 8 ++ .../utils/querydsl/ExpressionUtils.java | 8 ++ .../generator/controller/GenController.java | 4 +- .../com/ruoyi/generator/domain/GenTable.java | 20 ++- .../generator/domain/GenTableColumn.java | 4 +- .../repository/GenTableColumnRepository.java | 11 ++ .../repository/GenTableRepository.java | 9 ++ .../service/IGenTableColumnService.java | 5 +- .../impl/GenTableColumnServiceImpl.java | 37 ++++-- .../service/impl/GenTableServiceImpl.java | 114 +++++++++++++----- 10 files changed, 168 insertions(+), 52 deletions(-) diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java index c5dbdf642..0a5c78288 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java @@ -27,4 +27,12 @@ public class BaseService { protected > BooleanExpression buildLessThanOrEqualTo(ComparableExpression path, T value){ return ExpressionUtils.buildLessThanOrEqualTo(path, value); } + + protected BooleanExpression notLike(StringPath path, String value){ + return ExpressionUtils.notLike(path, value); + } + + protected BooleanExpression notStartWith(StringPath path, String value){ + return ExpressionUtils.notStartWith(path, value); + } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java index 2ab49348b..d6cdd56a3 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java @@ -20,6 +20,14 @@ public class ExpressionUtils { return path.like("%" + value + "%"); } + public static BooleanExpression notLike(StringPath path, String value){ + return path.notLike("%" + value + "%"); + } + + public static BooleanExpression notStartWith(StringPath path, String value){ + return path.notLike(value + "%"); + } + /** * 构建 等于 查询 * @param path diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java index d93b942b2..f1b0b89fc 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java @@ -72,9 +72,9 @@ public class GenController extends BaseController { @RequiresPermissions("tool:gen:list") @PostMapping("/column/list") @ResponseBody - public TableDataInfo columnList(GenTableColumn genTableColumn) { + public TableDataInfo columnList(GenTable genTable) { TableDataInfo dataInfo = new TableDataInfo(); - List list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn); + List list = genTableColumnService.selectGenTableColumnListByTableId(genTable); dataInfo.setRows(list); dataInfo.setTotal(list.size()); return dataInfo; diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java index 5c6d90ab0..456f9ea40 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java @@ -1,14 +1,14 @@ package com.ruoyi.generator.domain; -import java.util.List; -import javax.persistence.*; -import javax.validation.Valid; -import javax.validation.constraints.NotBlank; - import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.utils.StringUtils; +import javax.persistence.*; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import java.util.List; + /** * 业务表 gen_table * @@ -82,13 +82,14 @@ public class GenTable extends BaseEntity { /** * 主键信息 */ + @Transient private GenTableColumn pkColumn; /** * 表列信息 */ @Valid - @OneToMany(fetch = FetchType.EAGER, mappedBy = "") + @OneToMany(mappedBy = "table") private List columns; /** @@ -265,4 +266,11 @@ public class GenTable extends BaseEntity { } return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); } + + public GenTable() { + } + + public GenTable(Long tableId) { + this.tableId = tableId; + } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java index a20078e21..d6bcd489b 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java @@ -105,7 +105,9 @@ public class GenTableColumn extends BaseEntity { private Integer sort; @ManyToOne - @JoinColumn(name = "tableId", referencedColumnName = "tableId") + @JoinTable(name = "gen_table_columns", + inverseJoinColumns = @JoinColumn(name = "genTableTableId", referencedColumnName = "tableId"), + joinColumns = @JoinColumn(name = "columnsColumnId", referencedColumnName = "columnId")) @org.hibernate.annotations.ForeignKey(name = "none") private GenTable table; diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java index 5e55976b9..f77b2a2b0 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java @@ -1,9 +1,20 @@ package com.ruoyi.generator.repository; import com.ruoyi.common.base.BaseRepository; +import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; +import java.util.Collection; +import java.util.List; + @Repository public interface GenTableColumnRepository extends BaseRepository { + + List findByTable(GenTable genTable); + + @Modifying + void deleteByTableIn(Collection tables); + } diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java index c0ce83fb5..32c1bc8e7 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java @@ -2,8 +2,17 @@ package com.ruoyi.generator.repository; import com.ruoyi.common.base.BaseRepository; import com.ruoyi.generator.domain.GenTable; +import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.stereotype.Repository; +import java.util.Optional; + @Repository public interface GenTableRepository extends BaseRepository { + + GenTable findFirstByTableName(String tableName); + + @EntityGraph(attributePaths = {"columns"}) + @Override + Optional findById(Long id); } diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java index 15d7cefb9..eab765355 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java @@ -2,6 +2,7 @@ package com.ruoyi.generator.service; import java.util.List; +import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; /** @@ -13,10 +14,10 @@ public interface IGenTableColumnService { /** * 查询业务字段列表 * - * @param genTableColumn 业务字段信息 + * @param genTable 业务字段信息 * @return 业务字段集合 */ - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); + public List selectGenTableColumnListByTableId(GenTable genTable); /** * 新增业务字段 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java index a0b716032..21c94b4f7 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java @@ -1,13 +1,15 @@ package com.ruoyi.generator.service.impl; -import java.util.List; - +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.generator.domain.GenTable; +import com.ruoyi.generator.domain.GenTableColumn; +import com.ruoyi.generator.repository.GenTableColumnRepository; +import com.ruoyi.generator.service.IGenTableColumnService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.ruoyi.common.core.text.Convert; -import com.ruoyi.generator.domain.GenTableColumn; -import com.ruoyi.generator.mapper.GenTableColumnMapper; -import com.ruoyi.generator.service.IGenTableColumnService; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; /** * 业务字段 服务层实现 @@ -16,17 +18,18 @@ import com.ruoyi.generator.service.IGenTableColumnService; */ @Service public class GenTableColumnServiceImpl implements IGenTableColumnService { - private GenTableColumnMapper genTableColumnMapper; + @Autowired + private GenTableColumnRepository genTableColumnRepository; /** * 查询业务字段列表 * - * @param genTableColumn 业务字段信息 + * @param genTable 业务字段信息 * @return 业务字段集合 */ @Override - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn) { - return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn); + public List selectGenTableColumnListByTableId(GenTable genTable) { + return genTableColumnRepository.findByTable(genTable); } /** @@ -35,9 +38,11 @@ public class GenTableColumnServiceImpl implements IGenTableColumnService { * @param genTableColumn 业务字段信息 * @return 结果 */ + @Transactional @Override public int insertGenTableColumn(GenTableColumn genTableColumn) { - return genTableColumnMapper.insertGenTableColumn(genTableColumn); + genTableColumnRepository.save(genTableColumn); + return 1; } /** @@ -46,9 +51,11 @@ public class GenTableColumnServiceImpl implements IGenTableColumnService { * @param genTableColumn 业务字段信息 * @return 结果 */ + @Transactional @Override public int updateGenTableColumn(GenTableColumn genTableColumn) { - return genTableColumnMapper.updateGenTableColumn(genTableColumn); + genTableColumnRepository.save(genTableColumn); + return 1; } /** @@ -57,8 +64,12 @@ public class GenTableColumnServiceImpl implements IGenTableColumnService { * @param ids 需要删除的数据ID * @return 结果 */ + @Transactional @Override public int deleteGenTableColumnByIds(String ids) { - return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); + for(Long id : Convert.toLongArray(ids)){ + genTableColumnRepository.deleteById(id); + } + return 1; } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java index 8d1cf247e..849aa004e 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java @@ -2,6 +2,9 @@ package com.ruoyi.generator.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; +import com.ruoyi.common.base.BaseService; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.core.text.Convert; @@ -9,8 +12,8 @@ import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; -import com.ruoyi.generator.mapper.GenTableColumnMapper; -import com.ruoyi.generator.mapper.GenTableMapper; +import com.ruoyi.generator.domain.QGenTable; +import com.ruoyi.generator.repository.GenTableColumnRepository; import com.ruoyi.generator.repository.GenTableRepository; import com.ruoyi.generator.service.IGenTableService; import com.ruoyi.generator.util.GenUtils; @@ -24,13 +27,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -43,14 +50,18 @@ import java.util.zip.ZipOutputStream; * @author ruoyi */ @Service -public class GenTableServiceImpl implements IGenTableService { +public class GenTableServiceImpl extends BaseService implements IGenTableService { + + private static final String QUARTZ_TABLE_PREFIX = "qrtz_"; + private static final String GEN_TABLE_PREFIX = "gen_"; private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); - private GenTableMapper genTableMapper; - - private GenTableColumnMapper genTableColumnMapper; @Autowired private GenTableRepository genTableRepository; + @Autowired + private JdbcTemplate jdbcTemplate; + @Autowired + private GenTableColumnRepository genTableColumnRepository; /** * 查询业务信息 @@ -60,7 +71,7 @@ public class GenTableServiceImpl implements IGenTableService { */ @Override public GenTable selectGenTableById(Long id) { - GenTable genTable = genTableMapper.selectGenTableById(id); + GenTable genTable = genTableRepository.findById(id).get(); setTableFromOptions(genTable); return genTable; } @@ -73,7 +84,7 @@ public class GenTableServiceImpl implements IGenTableService { */ @Override public Page selectGenTableList(GenTable genTable, Pageable pageable) { - return genTableRepository.findAll(pageable); + return genTableRepository.findAll(getPredicate(genTable), pageable); } /** @@ -83,7 +94,43 @@ public class GenTableServiceImpl implements IGenTableService { * @return 数据库表集合 */ public Page selectDbTableList(GenTable genTable, Pageable pageable) { - return genTableRepository.findAll(pageable); + String sql = " select table_name, table_comment, create_time, update_time from information_schema.tables " + + " where table_schema = (select database()) " + + " AND table_name NOT LIKE '"+QUARTZ_TABLE_PREFIX+"%' AND table_name NOT LIKE '"+GEN_TABLE_PREFIX+"%' " + + " AND table_name NOT IN (select table_name from gen_table) "; + if(StringUtils.isNotEmpty(genTable.getTableName())){ + sql += " AND lower(table_name) like lower(concat('%', " + genTable.getTableName()+ ", '%')) "; + } + if(StringUtils.isNotEmpty(genTable.getTableName())){ + sql += " AND lower(table_comment) like lower(concat('%', " + genTable.getTableComment() + ", '%'))"; + } + String countSql = "select count(0) from ( " + sql + " ) t"; + if(pageable.isPaged()){ + int page = pageable.getPageNumber(); + int size = pageable.getPageSize(); + int start = 0; + if(page > 0){ + start = page * size ; + } + sql += " limit " + start + "," + size; + } + List tables = jdbcTemplate.query(sql, new BeanPropertyRowMapper(GenTable.class)); + int count = jdbcTemplate.queryForObject(countSql, Integer.class); + return new PageImpl(tables, pageable, count); + } + + private Predicate getPredicate(GenTable genTable){ + QGenTable qGenTable = QGenTable.genTable; + List predicates = new ArrayList<>(); + predicates.add(notStartWith(qGenTable.tableName, QUARTZ_TABLE_PREFIX)); + predicates.add(notStartWith(qGenTable.tableName, GEN_TABLE_PREFIX)); + if(StringUtils.isNotEmpty(genTable.getTableName())){ + predicates.add(buildLike(qGenTable.tableName, genTable.getTableName())); + } + if(StringUtils.isNotEmpty(genTable.getTableComment())){ + predicates.add(buildLike(qGenTable.tableComment, genTable.getTableComment())); + } + return ExpressionUtils.allOf(predicates); } /** @@ -93,7 +140,17 @@ public class GenTableServiceImpl implements IGenTableService { * @return 数据库表集合 */ public List selectDbTableListByNames(String[] tableNames) { - return genTableMapper.selectDbTableListByNames(tableNames); + String sql = "select table_name, table_comment, create_time, update_time from information_schema.tables " + + " where table_name NOT LIKE '"+QUARTZ_TABLE_PREFIX+"%' and table_name NOT LIKE '"+GEN_TABLE_PREFIX+"%' and table_schema = (select database()) " + + " and table_name in ("; + for(int i=0;i(GenTable.class)); } /** @@ -107,11 +164,9 @@ public class GenTableServiceImpl implements IGenTableService { public void updateGenTable(GenTable genTable) { String options = JSON.toJSONString(genTable.getParams()); genTable.setOptions(options); - int row = genTableMapper.updateGenTable(genTable); - if (row > 0) { - for (GenTableColumn cenTableColumn : genTable.getColumns()) { - genTableColumnMapper.updateGenTableColumn(cenTableColumn); - } + genTableRepository.save(genTable); + for (GenTableColumn cenTableColumn : genTable.getColumns()) { + genTableColumnRepository.save(cenTableColumn); } } @@ -124,8 +179,12 @@ public class GenTableServiceImpl implements IGenTableService { @Override @Transactional public void deleteGenTableByIds(String ids) { - genTableMapper.deleteGenTableByIds(Convert.toLongArray(ids)); - genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); + List tables = new ArrayList<>(); + for(Long id : Convert.toLongArray(ids)){ + genTableRepository.deleteById(id); + tables.add(new GenTable(id)); + } + genTableColumnRepository.deleteByTableIn(tables); } /** @@ -139,16 +198,15 @@ public class GenTableServiceImpl implements IGenTableService { public void importGenTable(List tableList, String operName) { for (GenTable table : tableList) { try { - String tableName = table.getTableName(); GenUtils.initTable(table, operName); - int row = genTableMapper.insertGenTable(table); - if (row > 0) { - // 保存列信息 - List genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); - for (GenTableColumn column : genTableColumns) { - GenUtils.initColumnField(column, table); - genTableColumnMapper.insertGenTableColumn(column); - } + genTableRepository.save(table); + String sql = "select column_name, (case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type " + + " from information_schema.columns where table_schema = (select database()) and table_name = '" + table.getTableName() + "'" + + " order by ordinal_position"; + List genTableColumns = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GenTableColumn.class)); + for (GenTableColumn column : genTableColumns) { + GenUtils.initColumnField(column, table); + genTableColumnRepository.save(column); } } catch (Exception e) { log.error("表名 " + table.getTableName() + " 导入失败:", e); @@ -165,7 +223,7 @@ public class GenTableServiceImpl implements IGenTableService { public Map previewCode(Long tableId) { Map dataMap = new LinkedHashMap<>(); // 查询表信息 - GenTable table = genTableMapper.selectGenTableById(tableId); + GenTable table = genTableRepository.findById(tableId).get(); // 查询列信息 List columns = table.getColumns(); setPkColumn(table, columns); @@ -222,7 +280,7 @@ public class GenTableServiceImpl implements IGenTableService { */ private void generatorCode(String tableName, ZipOutputStream zip) { // 查询表信息 - GenTable table = genTableMapper.selectGenTableByName(tableName); + GenTable table = genTableRepository.findFirstByTableName(tableName); // 查询列信息 List columns = table.getColumns(); setPkColumn(table, columns); From 69aaf0d922cda1178094e893ca1c329edcfbac77 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Fri, 27 Dec 2019 12:09:12 +0800 Subject: [PATCH 48/52] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mapper/GenTableColumnMapper.java | 52 ------ .../generator/mapper/GenTableMapper.java | 76 -------- .../mapper/generator/GenTableColumnMapper.xml | 120 ------------- .../mapper/generator/GenTableMapper.xml | 169 ------------------ 4 files changed, 417 deletions(-) delete mode 100644 ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java delete mode 100644 ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java delete mode 100644 ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml delete mode 100644 ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java deleted file mode 100644 index 616a922d7..000000000 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableColumnMapper.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ruoyi.generator.mapper; - -import java.util.List; - -import com.ruoyi.generator.domain.GenTableColumn; - -/** - * 业务字段 数据层 - * - * @author ruoyi - */ -public interface GenTableColumnMapper { - /** - * 根据表名称查询列信息 - * - * @param tableName 表名称 - * @return 列信息 - */ - public List selectDbTableColumnsByName(String tableName); - - /** - * 查询业务字段列表 - * - * @param genTableColumn 业务字段信息 - * @return 业务字段集合 - */ - public List selectGenTableColumnListByTableId(GenTableColumn genTableColumn); - - /** - * 新增业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int insertGenTableColumn(GenTableColumn genTableColumn); - - /** - * 修改业务字段 - * - * @param genTableColumn 业务字段信息 - * @return 结果 - */ - public int updateGenTableColumn(GenTableColumn genTableColumn); - - /** - * 批量删除业务字段 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteGenTableColumnByIds(Long[] ids); -} \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java deleted file mode 100644 index 086ee8f43..000000000 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/mapper/GenTableMapper.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ruoyi.generator.mapper; - -import java.util.List; - -import com.ruoyi.generator.domain.GenTable; - -/** - * 业务 数据层 - * - * @author ruoyi - */ -public interface GenTableMapper { - /** - * 查询业务列表 - * - * @param genTable 业务信息 - * @return 业务集合 - */ - public List selectGenTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param genTable 业务信息 - * @return 数据库表集合 - */ - public List selectDbTableList(GenTable genTable); - - /** - * 查询据库列表 - * - * @param tableNames 表名称组 - * @return 数据库表集合 - */ - public List selectDbTableListByNames(String[] tableNames); - - /** - * 查询表ID业务信息 - * - * @param id 业务ID - * @return 业务信息 - */ - public GenTable selectGenTableById(Long id); - - /** - * 查询表名称业务信息 - * - * @param tableName 表名称 - * @return 业务信息 - */ - public GenTable selectGenTableByName(String tableName); - - /** - * 新增业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - public int insertGenTable(GenTable genTable); - - /** - * 修改业务 - * - * @param genTable 业务信息 - * @return 结果 - */ - public int updateGenTable(GenTable genTable); - - /** - * 批量删除业务 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int deleteGenTableByIds(Long[] ids); -} \ No newline at end of file diff --git a/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml b/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml deleted file mode 100644 index acfaebcfb..000000000 --- a/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - select column_id, table_id, column_name, column_comment, column_type, java_type, java_field, is_pk, is_increment, is_required, is_insert, is_edit, is_list, is_query, query_type, html_type, dict_type, sort, create_by, create_time, update_by, update_time from gen_table_column - - - - - - - - insert into gen_table_column ( - table_id, - column_name, - column_comment, - column_type, - java_type, - java_field, - is_pk, - is_increment, - is_required, - is_insert, - is_edit, - is_list, - is_query, - query_type, - html_type, - dict_type, - sort, - create_by, - create_time - )values( - #{tableId}, - #{columnName}, - #{columnComment}, - #{columnType}, - #{javaType}, - #{javaField}, - #{isPk}, - #{isIncrement}, - #{isRequired}, - #{isInsert}, - #{isEdit}, - #{isList}, - #{isQuery}, - #{queryType}, - #{htmlType}, - #{dictType}, - #{sort}, - #{createBy}, - sysdate() - ) - - - - update gen_table_column - - column_comment = #{columnComment}, - java_type = #{javaType}, - java_field = #{javaField}, - is_insert = #{isInsert}, - is_edit = #{isEdit}, - is_list = #{isList}, - is_query = #{isQuery}, - is_required = #{isRequired}, - query_type = #{queryType}, - html_type = #{htmlType}, - dict_type = #{dictType}, - sort = #{sort}, - update_by = #{updateBy}, - update_time = sysdate() - - where column_id = #{columnId} - - - - delete from gen_table_column where table_id in - - #{tableId} - - - - \ No newline at end of file diff --git a/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml b/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml deleted file mode 100644 index 1682f6217..000000000 --- a/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml +++ /dev/null @@ -1,169 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - select table_id, table_name, table_comment, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, options, create_by, create_time, update_by, update_time, remark from gen_table - - - - - - - - - - - - - - - - insert into gen_table ( - table_name, - table_comment, - class_name, - tpl_category, - package_name, - module_name, - business_name, - function_name, - function_author, - remark, - create_by, - create_time - )values( - #{tableName}, - #{tableComment}, - #{className}, - #{tplCategory}, - #{packageName}, - #{moduleName}, - #{businessName}, - #{functionName}, - #{functionAuthor}, - #{remark}, - #{createBy}, - sysdate() - ) - - - - update gen_table - - table_name = #{tableName}, - table_comment = #{tableComment}, - class_name = #{className}, - function_author = #{functionAuthor}, - tpl_category = #{tplCategory}, - package_name = #{packageName}, - module_name = #{moduleName}, - business_name = #{businessName}, - function_name = #{functionName}, - options = #{options}, - update_by = #{updateBy}, - remark = #{remark}, - update_time = sysdate() - - where table_id = #{tableId} - - - - delete from gen_table where table_id in - - #{tableId} - - - - \ No newline at end of file From 883a68b7b297fb8dc565a6250c8b8c428c58f630 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Thu, 13 Aug 2020 16:03:20 +0800 Subject: [PATCH 49/52] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=9D=83=E9=99=90?= =?UTF-8?q?=EF=BC=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysRoleController.java | 8 +- .../controller/system/base/WebController.java | 12 + .../src/main/resources/application-druid.yml | 2 +- .../src/main/resources/static/ruoyi/index.js | 1194 +++++++++-------- .../src/main/resources/templates/index.html | 636 ++++----- .../ruoyi/common/annotation/DataScope.java | 12 +- .../ruoyi/common/annotation/DataScopes.java | 25 + .../com/ruoyi/common/base/BaseRepository.java | 4 +- .../com/ruoyi/common/base/BaseService.java | 7 +- .../core/controller/BaseController.java | 1 + .../repository/DataScopeRepository.java | 230 ++++ .../utils/querydsl/ExpressionUtils.java | 7 +- .../framework/aspectj/DataScopeAspect.java | 122 +- .../aspectj/DataScopeContextHolder.java | 20 + .../framework/aspectj/MySpecification.java | 60 + .../java/com/ruoyi/system/domain/SysRole.java | 7 +- .../domain/converter/DataScopesConverter.java | 23 + .../ruoyi/system/service/ISysRoleService.java | 4 +- .../ruoyi/system/service/ISysUserService.java | 4 + .../system/service/base/BusinessService.java | 46 + .../service/impl/SysRoleServiceImpl.java | 20 +- .../service/impl/SysUserServiceImpl.java | 21 +- 22 files changed, 1445 insertions(+), 1020 deletions(-) create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/base/WebController.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScopes.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/repository/DataScopeRepository.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeContextHolder.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/MySpecification.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/domain/converter/DataScopesConverter.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/base/BusinessService.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 64e219830..6c8d22019 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -2,7 +2,6 @@ package com.ruoyi.web.controller.system; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; @@ -13,6 +12,7 @@ import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; +import com.ruoyi.web.controller.system.base.WebController; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; @@ -30,7 +30,7 @@ import java.util.List; */ @Controller @RequestMapping("/system/role") -public class SysRoleController extends BaseController { +public class SysRoleController extends WebController { private String prefix = "system/role"; @Autowired @@ -49,7 +49,7 @@ public class SysRoleController extends BaseController { @PostMapping("/list") @ResponseBody public TableDataInfo list(SysRole role) { - return getDataTable(roleService.selectRoleList(role, getPageRequest())); + return getDataTable(roleService.selectRoleList(role, getPageRequest(), getUser())); } @Log(title = "角色管理", businessType = BusinessType.EXPORT) @@ -57,7 +57,7 @@ public class SysRoleController extends BaseController { @PostMapping("/export") @ResponseBody public AjaxResult export(SysRole role) { - List list = roleService.selectRoleList(role, Pageable.unpaged()).getContent(); + List list = roleService.selectRoleList(role, Pageable.unpaged(), getUser()).getContent(); ExcelUtil util = new ExcelUtil(SysRole.class); return util.exportExcel(list, "角色数据"); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/base/WebController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/base/WebController.java new file mode 100644 index 000000000..24e5119fa --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/base/WebController.java @@ -0,0 +1,12 @@ +package com.ruoyi.web.controller.system.base; + +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysUser; + +public class WebController extends BaseController { + + protected SysUser getUser(){ + return ShiroUtils.getSysUser(); + } +} diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index b848b4f9e..e865580dd 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -68,7 +68,7 @@ spring: url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 user: ${db.username} password: ${db.password} - #需要目标数据库已经存在,不自动升级 + #目标数据库已经存在,不自动升级 baseline-on-migrate: false encoding: utf-8 clean-on-validation-error: false diff --git a/ruoyi-admin/src/main/resources/static/ruoyi/index.js b/ruoyi-admin/src/main/resources/static/ruoyi/index.js index 2e130d377..f346c6c38 100644 --- a/ruoyi-admin/src/main/resources/static/ruoyi/index.js +++ b/ruoyi-admin/src/main/resources/static/ruoyi/index.js @@ -1,594 +1,602 @@ -/** - * 首页方法封装处理 - * Copyright (c) 2019 ruoyi - */ -layer.config({ - extend: 'moon/style.css', - skin: 'layer-ext-moon' -}); - -$(function() { - // MetsiMenu - $('#side-menu').metisMenu(); - - //固定菜单栏 - $(function() { - $('.sidebar-collapse').slimScroll({ - height: '100%', - railOpacity: 0.9, - alwaysVisible: false - }); - }); - - // 菜单切换 - $('.navbar-minimalize').click(function() { - $("body").toggleClass("mini-navbar"); - SmoothlyMenu(); - }); - - $('#side-menu>li').click(function() { - if ($('body').hasClass('mini-navbar')) { - NavToggle(); - } - }); - $('#side-menu>li li a').click(function() { - if ($(window).width() < 769) { - NavToggle(); - } - }); - - $('.nav-close').click(NavToggle); - - //ios浏览器兼容性处理 - if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { - $('#content-main').css('overflow-y', 'auto'); - } - -}); - -$(window).bind("load resize", -function() { - if ($(this).width() < 769) { - $('body').addClass('mini-navbar'); - $('.navbar-static-side').fadeIn(); - $(".sidebar-collapse .logo").addClass("hide"); - $(".slimScrollDiv").css({ "overflow":"hidden" }) - } -}); - -function NavToggle() { - $('.navbar-minimalize').trigger('click'); -} - -function SmoothlyMenu() { - if (!$('body').hasClass('mini-navbar')) { - $('#side-menu').hide(); - $(".sidebar-collapse .logo").removeClass("hide"); - setTimeout(function() { - $('#side-menu').fadeIn(500); - }, - 100); - } else if ($('body').hasClass('fixed-sidebar')) { - $('#side-menu').hide(); - $(".sidebar-collapse .logo").addClass("hide"); - setTimeout(function() { - $('#side-menu').fadeIn(500); - }, - 300); - } else { - $('#side-menu').removeAttr('style'); - } -} - -/** - * iframe处理 - */ -$(function() { - //计算元素集合的总宽度 - function calSumWidth(elements) { - var width = 0; - $(elements).each(function() { - width += $(this).outerWidth(true); - }); - return width; - } - - // 激活指定选项卡 - function setActiveTab(element) { - if (!$(element).hasClass('active')) { - var currentId = $(element).data('id'); - // 显示tab对应的内容区 - $('.RuoYi_iframe').each(function() { - if ($(this).data('id') == currentId) { - $(this).show().siblings('.RuoYi_iframe').hide(); - } - }); - $(element).addClass('active').siblings('.menuTab').removeClass('active'); - scrollToTab(element); - } - } - - //滚动到指定选项卡 - function scrollToTab(element) { - var marginLeftVal = calSumWidth($(element).prevAll()), - marginRightVal = calSumWidth($(element).nextAll()); - // 可视区域非tab宽度 - var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); - //可视区域tab宽度 - var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; - //实际滚动宽度 - var scrollVal = 0; - if ($(".page-tabs-content").outerWidth() < visibleWidth) { - scrollVal = 0; - } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) { - if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) { - scrollVal = marginLeftVal; - var tabElement = element; - while ((scrollVal - $(tabElement).outerWidth()) > ($(".page-tabs-content").outerWidth() - visibleWidth)) { - scrollVal -= $(tabElement).prev().outerWidth(); - tabElement = $(tabElement).prev(); - } - } - } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) { - scrollVal = marginLeftVal - $(element).prev().outerWidth(true); - } - $('.page-tabs-content').animate({ - marginLeft: 0 - scrollVal + 'px' - }, - "fast"); - } - - //查看左侧隐藏的选项卡 - function scrollTabLeft() { - var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left'))); - // 可视区域非tab宽度 - var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); - //可视区域tab宽度 - var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; - //实际滚动宽度 - var scrollVal = 0; - if (($(".page-tabs-content").width()) < visibleWidth) { - return false; - } else { - var tabElement = $(".menuTab:first"); - var offsetVal = 0; - while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素 - offsetVal += $(tabElement).outerWidth(true); - tabElement = $(tabElement).next(); - } - offsetVal = 0; - if (calSumWidth($(tabElement).prevAll()) > visibleWidth) { - while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) { - offsetVal += $(tabElement).outerWidth(true); - tabElement = $(tabElement).prev(); - } - scrollVal = calSumWidth($(tabElement).prevAll()); - } - } - $('.page-tabs-content').animate({ - marginLeft: 0 - scrollVal + 'px' - }, - "fast"); - } - - //查看右侧隐藏的选项卡 - function scrollTabRight() { - var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left'))); - // 可视区域非tab宽度 - var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); - //可视区域tab宽度 - var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; - //实际滚动宽度 - var scrollVal = 0; - if ($(".page-tabs-content").width() < visibleWidth) { - return false; - } else { - var tabElement = $(".menuTab:first"); - var offsetVal = 0; - while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素 - offsetVal += $(tabElement).outerWidth(true); - tabElement = $(tabElement).next(); - } - offsetVal = 0; - while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) { - offsetVal += $(tabElement).outerWidth(true); - tabElement = $(tabElement).next(); - } - scrollVal = calSumWidth($(tabElement).prevAll()); - if (scrollVal > 0) { - $('.page-tabs-content').animate({ - marginLeft: 0 - scrollVal + 'px' - }, - "fast"); - } - } - } - - //通过遍历给菜单项加上data-index属性 - $(".menuItem").each(function(index) { - if (!$(this).attr('data-index')) { - $(this).attr('data-index', index); - } - }); - - function menuItem() { - // 获取标识数据 - var dataUrl = $(this).attr('href'), - dataIndex = $(this).data('index'), - menuName = $.trim($(this).text()), - flag = true; - $(".nav ul li, .nav li").removeClass("selected"); - $(this).parent("li").addClass("selected"); - setIframeUrl($(this).attr("href")); - if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false; - - // 选项卡菜单已存在 - $('.menuTab').each(function() { - if ($(this).data('id') == dataUrl) { - if (!$(this).hasClass('active')) { - $(this).addClass('active').siblings('.menuTab').removeClass('active'); - scrollToTab(this); - // 显示tab对应的内容区 - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == dataUrl) { - $(this).show().siblings('.RuoYi_iframe').hide(); - return false; - } - }); - } - flag = false; - return false; - } - }); - // 选项卡菜单不存在 - if (flag) { - var str = '' + menuName + ' '; - $('.menuTab').removeClass('active'); - - // 添加选项卡对应的iframe - var str1 = ''; - $('.mainContent').find('iframe.RuoYi_iframe').hide().parents('.mainContent').append(str1); - - $.modal.loading("数据加载中,请稍后..."); - - $('.mainContent iframe:visible').load(function () { - $.modal.closeLoading(); - }); - - // 添加选项卡 - $('.menuTabs .page-tabs-content').append(str); - scrollToTab($('.menuTab.active')); - } - return false; - } - - function menuBlank() { - // 新窗口打开外网以http://开头,如http://ruoyi.vip - var dataUrl = $(this).attr('href'); - window.open(dataUrl); - return false; - } - - $('.menuItem').on('click', menuItem); - - $('.menuBlank').on('click', menuBlank); - - // 关闭选项卡菜单 - function closeTab() { - var closeTabId = $(this).parents('.menuTab').data('id'); - var currentWidth = $(this).parents('.menuTab').width(); - var panelUrl = $(this).parents('.menuTab').data('panel'); - // 当前元素处于活动状态 - if ($(this).parents('.menuTab').hasClass('active')) { - - // 当前元素后面有同辈元素,使后面的一个元素处于活动状态 - if ($(this).parents('.menuTab').next('.menuTab').size()) { - - var activeId = $(this).parents('.menuTab').next('.menuTab:eq(0)').data('id'); - $(this).parents('.menuTab').next('.menuTab:eq(0)').addClass('active'); - - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == activeId) { - $(this).show().siblings('.RuoYi_iframe').hide(); - return false; - } - }); - - var marginLeftVal = parseInt($('.page-tabs-content').css('margin-left')); - if (marginLeftVal < 0) { - $('.page-tabs-content').animate({ - marginLeft: (marginLeftVal + currentWidth) + 'px' - }, - "fast"); - } - - // 移除当前选项卡 - $(this).parents('.menuTab').remove(); - - // 移除tab对应的内容区 - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == closeTabId) { - $(this).remove(); - return false; - } - }); - } - - // 当前元素后面没有同辈元素,使当前元素的上一个元素处于活动状态 - if ($(this).parents('.menuTab').prev('.menuTab').size()) { - var activeId = $(this).parents('.menuTab').prev('.menuTab:last').data('id'); - $(this).parents('.menuTab').prev('.menuTab:last').addClass('active'); - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == activeId) { - $(this).show().siblings('.RuoYi_iframe').hide(); - return false; - } - }); - - // 移除当前选项卡 - $(this).parents('.menuTab').remove(); - - // 移除tab对应的内容区 - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == closeTabId) { - $(this).remove(); - return false; - } - }); - - if($.common.isNotEmpty(panelUrl)){ - $('.menuTab[data-id="' + panelUrl + '"]').addClass('active').siblings('.menuTab').removeClass('active'); - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == panelUrl) { - $(this).show().siblings('.RuoYi_iframe').hide(); - return false; - } - }); - } - } - } - // 当前元素不处于活动状态 - else { - // 移除当前选项卡 - $(this).parents('.menuTab').remove(); - - // 移除相应tab对应的内容区 - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == closeTabId) { - $(this).remove(); - return false; - } - }); - } - scrollToTab($('.menuTab.active')); - return false; - } - - $('.menuTabs').on('click', '.menuTab i', closeTab); - - //滚动到已激活的选项卡 - function showActiveTab() { - scrollToTab($('.menuTab.active')); - } - $('.tabShowActive').on('click', showActiveTab); - - // 点击选项卡菜单 - function activeTab() { - if (!$(this).hasClass('active')) { - var currentId = $(this).data('id'); - // 显示tab对应的内容区 - $('.mainContent .RuoYi_iframe').each(function() { - if ($(this).data('id') == currentId) { - $(this).show().siblings('.RuoYi_iframe').hide(); - return false; - } - }); - $(this).addClass('active').siblings('.menuTab').removeClass('active'); - scrollToTab(this); - } - } - - // 点击选项卡菜单 - $('.menuTabs').on('click', '.menuTab', activeTab); - - // 刷新iframe - function refreshTab() { - var currentId = $('.page-tabs-content').find('.active').attr('data-id'); - var target = $('.RuoYi_iframe[data-id="' + currentId + '"]'); - var url = target.attr('src'); - target.attr('src', url).ready(); - } - - // 页签全屏 - function fullScreenTab() { - var currentId = $('.page-tabs-content').find('.active').attr('data-id'); - var target = $('.RuoYi_iframe[data-id="' + currentId + '"]'); - target.fullScreen(true); - } - - // 关闭当前选项卡 - function tabCloseCurrent() { - $('.page-tabs-content').find('.active i').trigger("click"); - } - - //关闭其他选项卡 - function tabCloseOther() { - $('.page-tabs-content').children("[data-id]").not(":first").not(".active").each(function() { - $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); - $(this).remove(); - }); - $('.page-tabs-content').css("margin-left", "0"); - } - - // 关闭全部选项卡 - function tabCloseAll() { - $('.page-tabs-content').children("[data-id]").not(":first").each(function() { - $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); - $(this).remove(); - }); - $('.page-tabs-content').children("[data-id]:first").each(function() { - $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').show(); - $(this).addClass("active"); - }); - $('.page-tabs-content').css("margin-left", "0"); - } - - - // 全屏显示 - $('#fullScreen').on('click', function () { - $(document).toggleFullScreen(); - }); - - // 页签刷新按钮 - $('.tabReload').on('click', refreshTab); - - // 页签全屏按钮 - $('.tabFullScreen').on('click', fullScreenTab); - - // 双击选项卡全屏显示 - $('.menuTabs').on('dblclick', '.menuTab', activeTabMax); - - // 左移按扭 - $('.tabLeft').on('click', scrollTabLeft); - - // 右移按扭 - $('.tabRight').on('click', scrollTabRight); - - // 关闭当前 - $('.tabCloseCurrent').on('click', tabCloseCurrent); - - // 关闭其他 - $('.tabCloseOther').on('click', tabCloseOther); - - // 关闭全部 - $('.tabCloseAll').on('click', tabCloseAll); - - // tab全屏显示 - $('.tabMaxCurrent').on('click', function () { - $('.page-tabs-content').find('.active').trigger("dblclick"); - }); - - // 关闭全屏 - $('#ax_close_max').click(function(){ - $('#content-main').toggleClass('max'); - $('#ax_close_max').hide(); - }) - - // 双击选项卡全屏显示 - function activeTabMax() { - $('#content-main').toggleClass('max'); - $('#ax_close_max').show(); - } - - // 设置锚点 - function setIframeUrl(href) { - if($.common.equals("history", mode)) { - storage.set('publicPath', href); - } else { - var nowUrl = window.location.href; - var newUrl = nowUrl.substring(0, nowUrl.indexOf("#")); - window.location.href = newUrl + "#" + href; - } - } - - $(window).keydown(function(event) { - if (event.keyCode == 27) { - $('#content-main').removeClass('max'); - $('#ax_close_max').hide(); - } - }); - - window.onhashchange = function() { - var hash = location.hash; - var url = hash.substring(1, hash.length); - $('a[href$="' + url + '"]').click(); - }; - - // 右键菜单实现 - $.contextMenu({ - selector: ".menuTab", - trigger: 'right', - autoHide: true, - items: { - "close_current": { - name: "关闭当前", - icon: "fa-close", - callback: function(key, opt) { - opt.$trigger.find('i').trigger("click"); - } - }, - "close_other": { - name: "关闭其他", - icon: "fa-window-close-o", - callback: function(key, opt) { - setActiveTab(this); - tabCloseOther(); - } - }, - "close_left": { - name: "关闭左侧", - icon: "fa-reply", - callback: function(key, opt) { - setActiveTab(this); - this.prevAll('.menuTab').not(":last").each(function() { - if ($(this).hasClass('active')) { - setActiveTab(this); - } - $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); - $(this).remove(); - }); - $('.page-tabs-content').css("margin-left", "0"); - } - }, - "close_right": { - name: "关闭右侧", - icon: "fa-share", - callback: function(key, opt) { - setActiveTab(this); - this.nextAll('.menuTab').each(function() { - $('.menuTab[data-id="' + $(this).data('id') + '"]').remove(); - $(this).remove(); - }); - } - }, - "close_all": { - name: "全部关闭", - icon: "fa-window-close", - callback: function(key, opt) { - tabCloseAll(); - } - }, - "step": "---------", - "full": { - name: "全屏显示", - icon: "fa-arrows-alt", - callback: function(key, opt) { - setActiveTab(this); - var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); - target.fullScreen(true); - } - }, - "refresh": { - name: "刷新页面", - icon: "fa-refresh", - callback: function(key, opt) { - setActiveTab(this); - var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); - var url = target.attr('src'); - $.modal.loading("数据加载中,请稍后..."); - target.attr('src', url).load(function () { - $.modal.closeLoading(); - }); - } - }, - "open": { - name: "新窗口打开", - icon: "fa-link", - callback: function(key, opt) { - var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); - window.open(target.attr('src')); - } - }, - } - }) +/** + * 首页方法封装处理 + * Copyright (c) 2019 ruoyi + */ +layer.config({ + extend: 'moon/style.css', + skin: 'layer-ext-moon' +}); + +var currentMenuId = null; + +$(function() { + // MetsiMenu + $('#side-menu').metisMenu(); + + //固定菜单栏 + $(function() { + $('.sidebar-collapse').slimScroll({ + height: '100%', + railOpacity: 0.9, + alwaysVisible: false + }); + }); + + // 菜单切换 + $('.navbar-minimalize').click(function() { + $("body").toggleClass("mini-navbar"); + SmoothlyMenu(); + }); + + $('#side-menu>li').click(function() { + if ($('body').hasClass('mini-navbar')) { + NavToggle(); + } + }); + $('#side-menu>li li a').click(function() { + if ($(window).width() < 769) { + NavToggle(); + } + }); + + $('.nav-close').click(NavToggle); + + //ios浏览器兼容性处理 + if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { + $('#content-main').css('overflow-y', 'auto'); + } + +}); + +$(window).bind("load resize", +function() { + if ($(this).width() < 769) { + $('body').addClass('mini-navbar'); + $('.navbar-static-side').fadeIn(); + $(".sidebar-collapse .logo").addClass("hide"); + $(".slimScrollDiv").css({ "overflow":"hidden" }) + } +}); + +function NavToggle() { + $('.navbar-minimalize').trigger('click'); +} + +function SmoothlyMenu() { + if (!$('body').hasClass('mini-navbar')) { + $('#side-menu').hide(); + $(".sidebar-collapse .logo").removeClass("hide"); + setTimeout(function() { + $('#side-menu').fadeIn(500); + }, + 100); + } else if ($('body').hasClass('fixed-sidebar')) { + $('#side-menu').hide(); + $(".sidebar-collapse .logo").addClass("hide"); + setTimeout(function() { + $('#side-menu').fadeIn(500); + }, + 300); + } else { + $('#side-menu').removeAttr('style'); + } +} + +/** + * iframe处理 + */ +$(function() { + //计算元素集合的总宽度 + function calSumWidth(elements) { + var width = 0; + $(elements).each(function() { + width += $(this).outerWidth(true); + }); + return width; + } + + // 激活指定选项卡 + function setActiveTab(element) { + if (!$(element).hasClass('active')) { + var currentId = $(element).data('id'); + // 显示tab对应的内容区 + $('.RuoYi_iframe').each(function() { + if ($(this).data('id') == currentId) { + $(this).show().siblings('.RuoYi_iframe').hide(); + } + }); + $(element).addClass('active').siblings('.menuTab').removeClass('active'); + scrollToTab(element); + } + } + + //滚动到指定选项卡 + function scrollToTab(element) { + var marginLeftVal = calSumWidth($(element).prevAll()), + marginRightVal = calSumWidth($(element).nextAll()); + // 可视区域非tab宽度 + var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); + //可视区域tab宽度 + var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; + //实际滚动宽度 + var scrollVal = 0; + if ($(".page-tabs-content").outerWidth() < visibleWidth) { + scrollVal = 0; + } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) { + if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) { + scrollVal = marginLeftVal; + var tabElement = element; + while ((scrollVal - $(tabElement).outerWidth()) > ($(".page-tabs-content").outerWidth() - visibleWidth)) { + scrollVal -= $(tabElement).prev().outerWidth(); + tabElement = $(tabElement).prev(); + } + } + } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) { + scrollVal = marginLeftVal - $(element).prev().outerWidth(true); + } + $('.page-tabs-content').animate({ + marginLeft: 0 - scrollVal + 'px' + }, + "fast"); + } + + //查看左侧隐藏的选项卡 + function scrollTabLeft() { + var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left'))); + // 可视区域非tab宽度 + var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); + //可视区域tab宽度 + var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; + //实际滚动宽度 + var scrollVal = 0; + if (($(".page-tabs-content").width()) < visibleWidth) { + return false; + } else { + var tabElement = $(".menuTab:first"); + var offsetVal = 0; + while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素 + offsetVal += $(tabElement).outerWidth(true); + tabElement = $(tabElement).next(); + } + offsetVal = 0; + if (calSumWidth($(tabElement).prevAll()) > visibleWidth) { + while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) { + offsetVal += $(tabElement).outerWidth(true); + tabElement = $(tabElement).prev(); + } + scrollVal = calSumWidth($(tabElement).prevAll()); + } + } + $('.page-tabs-content').animate({ + marginLeft: 0 - scrollVal + 'px' + }, + "fast"); + } + + //查看右侧隐藏的选项卡 + function scrollTabRight() { + var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left'))); + // 可视区域非tab宽度 + var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".menuTabs")); + //可视区域tab宽度 + var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth; + //实际滚动宽度 + var scrollVal = 0; + if ($(".page-tabs-content").width() < visibleWidth) { + return false; + } else { + var tabElement = $(".menuTab:first"); + var offsetVal = 0; + while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素 + offsetVal += $(tabElement).outerWidth(true); + tabElement = $(tabElement).next(); + } + offsetVal = 0; + while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) { + offsetVal += $(tabElement).outerWidth(true); + tabElement = $(tabElement).next(); + } + scrollVal = calSumWidth($(tabElement).prevAll()); + if (scrollVal > 0) { + $('.page-tabs-content').animate({ + marginLeft: 0 - scrollVal + 'px' + }, + "fast"); + } + } + } + + //通过遍历给菜单项加上data-index属性 + $(".menuItem").each(function(index) { + if (!$(this).attr('data-index')) { + $(this).attr('data-index', index); + } + }); + + function menuItem() { + // 获取标识数据 + var dataUrl = $(this).attr('href'); + dataIndex = $(this).data('index'); + menuName = $.trim($(this).text()); + currentMenuId = $(this).attr('id'); + flag = true; + $(".nav ul li, .nav li").removeClass("selected"); + $(this).parent("li").addClass("selected"); + setIframeUrl($(this).attr("href")); + if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false; + + // 选项卡菜单已存在 + $('.menuTab').each(function() { + if ($(this).data('id') == dataUrl) { + if (!$(this).hasClass('active')) { + $(this).addClass('active').siblings('.menuTab').removeClass('active'); + scrollToTab(this); + // 显示tab对应的内容区 + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == dataUrl) { + $(this).show().siblings('.RuoYi_iframe').hide(); + return false; + } + }); + } + flag = false; + return false; + } + }); + // 选项卡菜单不存在 + if (flag) { + var str = '' + menuName + ' '; + $('.menuTab').removeClass('active'); + + // 添加选项卡对应的iframe + var str1 = ''; + $('.mainContent').find('iframe.RuoYi_iframe').hide().parents('.mainContent').append(str1); + + $.modal.loading("数据加载中,请稍后..."); + + $('.mainContent iframe:visible').load(function () { + $.modal.closeLoading(); + }); + + // 添加选项卡 + $('.menuTabs .page-tabs-content').append(str); + scrollToTab($('.menuTab.active')); + } + return false; + } + + function menuBlank() { + // 新窗口打开外网以http://开头,如http://ruoyi.vip + var dataUrl = $(this).attr('href'); + window.open(dataUrl); + return false; + } + + $('.menuItem').on('click', menuItem); + + $('.menuBlank').on('click', menuBlank); + + // 关闭选项卡菜单 + function closeTab() { + var closeTabId = $(this).parents('.menuTab').data('id'); + var currentWidth = $(this).parents('.menuTab').width(); + var panelUrl = $(this).parents('.menuTab').data('panel'); + // 当前元素处于活动状态 + if ($(this).parents('.menuTab').hasClass('active')) { + + // 当前元素后面有同辈元素,使后面的一个元素处于活动状态 + if ($(this).parents('.menuTab').next('.menuTab').size()) { + + var toShow = $(this).parents('.menuTab').next('.menuTab:eq(0)'); + var activeId = toShow.data('id'); + currentMenuId = toShow.attr('id'); + $(this).parents('.menuTab').next('.menuTab:eq(0)').addClass('active'); + + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == activeId) { + $(this).show().siblings('.RuoYi_iframe').hide(); + return false; + } + }); + + var marginLeftVal = parseInt($('.page-tabs-content').css('margin-left')); + if (marginLeftVal < 0) { + $('.page-tabs-content').animate({ + marginLeft: (marginLeftVal + currentWidth) + 'px' + }, + "fast"); + } + + // 移除当前选项卡 + $(this).parents('.menuTab').remove(); + + // 移除tab对应的内容区 + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == closeTabId) { + $(this).remove(); + return false; + } + }); + } + + // 当前元素后面没有同辈元素,使当前元素的上一个元素处于活动状态 + if ($(this).parents('.menuTab').prev('.menuTab').size()) { + var toShow = $(this).parents('.menuTab').prev('.menuTab:last'); + var activeId = toShow.data('id'); + currentMenuId = toShow.attr('id'); + $(this).parents('.menuTab').prev('.menuTab:last').addClass('active'); + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == activeId) { + $(this).show().siblings('.RuoYi_iframe').hide(); + return false; + } + }); + + // 移除当前选项卡 + $(this).parents('.menuTab').remove(); + + // 移除tab对应的内容区 + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == closeTabId) { + $(this).remove(); + return false; + } + }); + + if($.common.isNotEmpty(panelUrl)){ + $('.menuTab[data-id="' + panelUrl + '"]').addClass('active').siblings('.menuTab').removeClass('active'); + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == panelUrl) { + $(this).show().siblings('.RuoYi_iframe').hide(); + return false; + } + }); + } + } + } + // 当前元素不处于活动状态 + else { + // 移除当前选项卡 + $(this).parents('.menuTab').remove(); + + // 移除相应tab对应的内容区 + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == closeTabId) { + $(this).remove(); + return false; + } + }); + } + scrollToTab($('.menuTab.active')); + return false; + } + + $('.menuTabs').on('click', '.menuTab i', closeTab); + + //滚动到已激活的选项卡 + function showActiveTab() { + scrollToTab($('.menuTab.active')); + } + $('.tabShowActive').on('click', showActiveTab); + + // 点击选项卡菜单 + function activeTab() { + if (!$(this).hasClass('active')) { + var currentId = $(this).data('id'); + currentMenuId = $(this).attr('id'); + // 显示tab对应的内容区 + $('.mainContent .RuoYi_iframe').each(function() { + if ($(this).data('id') == currentId) { + $(this).show().siblings('.RuoYi_iframe').hide(); + return false; + } + }); + $(this).addClass('active').siblings('.menuTab').removeClass('active'); + scrollToTab(this); + } + } + + // 点击选项卡菜单 + $('.menuTabs').on('click', '.menuTab', activeTab); + + // 刷新iframe + function refreshTab() { + var currentId = $('.page-tabs-content').find('.active').attr('data-id'); + var target = $('.RuoYi_iframe[data-id="' + currentId + '"]'); + var url = target.attr('src'); + target.attr('src', url).ready(); + } + + // 页签全屏 + function fullScreenTab() { + var currentId = $('.page-tabs-content').find('.active').attr('data-id'); + var target = $('.RuoYi_iframe[data-id="' + currentId + '"]'); + target.fullScreen(true); + } + + // 关闭当前选项卡 + function tabCloseCurrent() { + $('.page-tabs-content').find('.active i').trigger("click"); + } + + //关闭其他选项卡 + function tabCloseOther() { + $('.page-tabs-content').children("[data-id]").not(":first").not(".active").each(function() { + $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); + $(this).remove(); + }); + $('.page-tabs-content').css("margin-left", "0"); + } + + // 关闭全部选项卡 + function tabCloseAll() { + $('.page-tabs-content').children("[data-id]").not(":first").each(function() { + $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); + $(this).remove(); + }); + $('.page-tabs-content').children("[data-id]:first").each(function() { + $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').show(); + $(this).addClass("active"); + }); + $('.page-tabs-content').css("margin-left", "0"); + } + + + // 全屏显示 + $('#fullScreen').on('click', function () { + $(document).toggleFullScreen(); + }); + + // 页签刷新按钮 + $('.tabReload').on('click', refreshTab); + + // 页签全屏按钮 + $('.tabFullScreen').on('click', fullScreenTab); + + // 双击选项卡全屏显示 + $('.menuTabs').on('dblclick', '.menuTab', activeTabMax); + + // 左移按扭 + $('.tabLeft').on('click', scrollTabLeft); + + // 右移按扭 + $('.tabRight').on('click', scrollTabRight); + + // 关闭当前 + $('.tabCloseCurrent').on('click', tabCloseCurrent); + + // 关闭其他 + $('.tabCloseOther').on('click', tabCloseOther); + + // 关闭全部 + $('.tabCloseAll').on('click', tabCloseAll); + + // tab全屏显示 + $('.tabMaxCurrent').on('click', function () { + $('.page-tabs-content').find('.active').trigger("dblclick"); + }); + + // 关闭全屏 + $('#ax_close_max').click(function(){ + $('#content-main').toggleClass('max'); + $('#ax_close_max').hide(); + }) + + // 双击选项卡全屏显示 + function activeTabMax() { + $('#content-main').toggleClass('max'); + $('#ax_close_max').show(); + } + + // 设置锚点 + function setIframeUrl(href) { + if($.common.equals("history", mode)) { + storage.set('publicPath', href); + } else { + var nowUrl = window.location.href; + var newUrl = nowUrl.substring(0, nowUrl.indexOf("#")); + window.location.href = newUrl + "#" + href; + } + } + + $(window).keydown(function(event) { + if (event.keyCode == 27) { + $('#content-main').removeClass('max'); + $('#ax_close_max').hide(); + } + }); + + window.onhashchange = function() { + var hash = location.hash; + var url = hash.substring(1, hash.length); + $('a[href$="' + url + '"]').click(); + }; + + // 右键菜单实现 + $.contextMenu({ + selector: ".menuTab", + trigger: 'right', + autoHide: true, + items: { + "close_current": { + name: "关闭当前", + icon: "fa-close", + callback: function(key, opt) { + opt.$trigger.find('i').trigger("click"); + } + }, + "close_other": { + name: "关闭其他", + icon: "fa-window-close-o", + callback: function(key, opt) { + setActiveTab(this); + tabCloseOther(); + } + }, + "close_left": { + name: "关闭左侧", + icon: "fa-reply", + callback: function(key, opt) { + setActiveTab(this); + this.prevAll('.menuTab').not(":last").each(function() { + if ($(this).hasClass('active')) { + setActiveTab(this); + } + $('.RuoYi_iframe[data-id="' + $(this).data('id') + '"]').remove(); + $(this).remove(); + }); + $('.page-tabs-content').css("margin-left", "0"); + } + }, + "close_right": { + name: "关闭右侧", + icon: "fa-share", + callback: function(key, opt) { + setActiveTab(this); + this.nextAll('.menuTab').each(function() { + $('.menuTab[data-id="' + $(this).data('id') + '"]').remove(); + $(this).remove(); + }); + } + }, + "close_all": { + name: "全部关闭", + icon: "fa-window-close", + callback: function(key, opt) { + tabCloseAll(); + } + }, + "step": "---------", + "full": { + name: "全屏显示", + icon: "fa-arrows-alt", + callback: function(key, opt) { + setActiveTab(this); + var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); + target.fullScreen(true); + } + }, + "refresh": { + name: "刷新页面", + icon: "fa-refresh", + callback: function(key, opt) { + setActiveTab(this); + var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); + var url = target.attr('src'); + $.modal.loading("数据加载中,请稍后..."); + target.attr('src', url).load(function () { + $.modal.closeLoading(); + }); + } + }, + "open": { + name: "新窗口打开", + icon: "fa-link", + callback: function(key, opt) { + var target = $('.RuoYi_iframe[data-id="' + this.data('id') + '"]'); + window.open(target.attr('src')); + } + }, + } + }) }); \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/templates/index.html b/ruoyi-admin/src/main/resources/templates/index.html index 15b0f6fe0..5ab14d044 100644 --- a/ruoyi-admin/src/main/resources/templates/index.html +++ b/ruoyi-admin/src/main/resources/templates/index.html @@ -1,317 +1,319 @@ - - - - - - - 若依系统首页 - - - - - - - - - - - -
- - - - - - -
- -
- - - - 刷新 -
- - - -
- -
- -
- -
- - - - - - - - - - - - - - - + + + + + + + 若依系统首页 + + + + + + + + + + + +
+ + + + + + +
+ +
+ + + + 刷新 +
+ + + +
+ +
+ +
+ +
+ + + + + + + + + + + + + + + diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java index b0d4b7ffc..248058368 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScope.java @@ -11,17 +11,13 @@ import java.lang.annotation.Target; * * @author ruoyi */ -@Target(ElementType.METHOD) +@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataScope { /** - * 部门表的别名 + * 业务表的所属用户的字段名称:过滤仅本人的数据权限, + * 该字段的类型为:{@link com.ruoyi.system.domain.SysUser} */ - public String deptAlias() default ""; - - /** - * 用户表的别名 - */ - public String userAlias() default ""; + String userFieldName() default ""; } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScopes.java b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScopes.java new file mode 100644 index 000000000..0da657142 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/annotation/DataScopes.java @@ -0,0 +1,25 @@ +package com.ruoyi.common.annotation; + +public enum DataScopes implements Comparable{ + /** + * 全部数据权限 + */ + DATA_SCOPE_ALL, + /** + * 自定数据权限 + */ + DATA_SCOPE_CUSTOM, + /** + * 部门数据权限 + */ + DATA_SCOPE_DEPT, + /** + * 部门及以下数据权限 + */ + DATA_SCOPE_DEPT_AND_CHILD, + /** + * 仅本人数据权限 + */ + DATA_SCOPE_SELF, + ; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java index 4e8b0d457..6bce9515b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseRepository.java @@ -5,9 +5,11 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.NoRepositoryBean; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Predicate; + @NoRepositoryBean public interface BaseRepository extends JpaRepository, JpaSpecificationExecutor, QuerydslPredicateExecutor { - } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java index 0a5c78288..59c0a5ed4 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/base/BaseService.java @@ -1,9 +1,6 @@ package com.ruoyi.common.base; -import com.querydsl.core.types.dsl.BooleanExpression; -import com.querydsl.core.types.dsl.ComparableExpression; -import com.querydsl.core.types.dsl.NumberPath; -import com.querydsl.core.types.dsl.StringPath; +import com.querydsl.core.types.dsl.*; import com.ruoyi.common.utils.querydsl.ExpressionUtils; public class BaseService { @@ -12,7 +9,7 @@ public class BaseService { return ExpressionUtils.buildLike(path, value); } - protected > BooleanExpression buildEqual(ComparableExpression path, T value){ + protected > BooleanExpression buildEqual(ComparableExpressionBase path, T value){ return ExpressionUtils.buildEqual(path, value); } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java index 25f13cdc1..69d4bf49c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java @@ -171,4 +171,5 @@ public class BaseController { public String redirect(String url) { return StringUtils.format("redirect:{}", url); } + } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/repository/DataScopeRepository.java b/ruoyi-common/src/main/java/com/ruoyi/common/repository/DataScopeRepository.java new file mode 100644 index 000000000..97ca1debb --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/repository/DataScopeRepository.java @@ -0,0 +1,230 @@ +package com.ruoyi.common.repository; + +import com.querydsl.core.types.OrderSpecifier; +import com.querydsl.core.types.Predicate; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.support.*; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; + +import javax.persistence.EntityManager; +import java.io.Serializable; +import java.util.List; +import java.util.Optional; + + +public class DataScopeRepository implements JpaRepositoryImplementation, + QuerydslPredicateExecutor { + + private @Nullable + CrudMethodMetadata metadata; + + private SimpleJpaRepository simpleJpaRepository; + private QuerydslPredicateExecutor querydslPredicateExecutor; + + public DataScopeRepository(JpaEntityInformation entityInformation, EntityManager entityManager) { + Assert.notNull(entityInformation, "JpaEntityInformation must not be null!"); + Assert.notNull(entityManager, "EntityManager must not be null!"); + this.simpleJpaRepository = new SimpleJpaRepository(entityInformation, entityManager); + } + + public DataScopeRepository(Class domainClass, EntityManager em) { + this.simpleJpaRepository = new SimpleJpaRepository(JpaEntityInformationSupport.getEntityInformation(domainClass, em), em); + } + + @Override + public void setRepositoryMethodMetadata(CrudMethodMetadata crudMethodMetadata) { + this.metadata = crudMethodMetadata; + simpleJpaRepository.setRepositoryMethodMetadata(crudMethodMetadata); + } + + @Override + public List findAll() { + return simpleJpaRepository.findAll(); + } + + @Override + public List findAll(Sort sort) { + return null; + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } + + @Override + public List findAllById(Iterable ids) { + return null; + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(ID id) { + + } + + @Override + public void delete(T entity) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return null; + } + + @Override + public Optional findById(ID id) { + return Optional.empty(); + } + + @Override + public boolean existsById(ID id) { + return false; + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public void deleteInBatch(Iterable entities) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public T getOne(ID id) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return null; + } + + @Override + public List findAll(Example example, Sort sort) { + return null; + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public Optional findOne(Specification spec) { + return Optional.empty(); + } + + @Override + public List findAll(Specification spec) { + return null; + } + + @Override + public Page findAll(Specification spec, Pageable pageable) { + return null; + } + + @Override + public List findAll(Specification spec, Sort sort) { + return null; + } + + @Override + public long count(Specification spec) { + return 0; + } + + @Override + public Optional findOne(Predicate predicate) { + return querydslPredicateExecutor.findOne(predicate); + } + + @Override + public Iterable findAll(Predicate predicate) { + return querydslPredicateExecutor.findAll(predicate); + } + + @Override + public Iterable findAll(Predicate predicate, Sort sort) { + return querydslPredicateExecutor.findAll(predicate, sort); + } + + @Override + public Iterable findAll(Predicate predicate, OrderSpecifier... orders) { + return querydslPredicateExecutor.findAll(predicate, orders); + } + + @Override + public Iterable findAll(OrderSpecifier... orders) { + return querydslPredicateExecutor.findAll(orders); + } + + @Override + public Page findAll(Predicate predicate, Pageable pageable) { + return querydslPredicateExecutor.findAll(predicate, pageable); + } + + @Override + public long count(Predicate predicate) { + return querydslPredicateExecutor.count(predicate); + } + + @Override + public boolean exists(Predicate predicate) { + return querydslPredicateExecutor.exists(predicate); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java index d6cdd56a3..d6019804f 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/querydsl/ExpressionUtils.java @@ -1,9 +1,6 @@ package com.ruoyi.common.utils.querydsl; -import com.querydsl.core.types.dsl.BooleanExpression; -import com.querydsl.core.types.dsl.ComparableExpression; -import com.querydsl.core.types.dsl.NumberPath; -import com.querydsl.core.types.dsl.StringPath; +import com.querydsl.core.types.dsl.*; /** * QueryDsl 构建查询条件的工具类 @@ -35,7 +32,7 @@ public class ExpressionUtils { * @param * @return */ - public static > BooleanExpression buildEqual(ComparableExpression path, T value){ + public static > BooleanExpression buildEqual(ComparableExpressionBase path, T value){ return path.eq(value); } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java index 88c1b52fe..7412b9047 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java @@ -1,20 +1,32 @@ package com.ruoyi.framework.aspectj; -import java.lang.reflect.Method; - -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.Signature; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.stereotype.Component; +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysUserService; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Root; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; /** * 数据过滤处理 @@ -24,35 +36,11 @@ import com.ruoyi.system.domain.SysUser; @Aspect @Component public class DataScopeAspect { - /** - * 全部数据权限 - */ - public static final String DATA_SCOPE_ALL = "1"; - /** - * 自定数据权限 - */ - public static final String DATA_SCOPE_CUSTOM = "2"; - - /** - * 部门数据权限 - */ - public static final String DATA_SCOPE_DEPT = "3"; - - /** - * 部门及以下数据权限 - */ - public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; - - /** - * 仅本人数据权限 - */ - public static final String DATA_SCOPE_SELF = "5"; - - /** - * 数据权限过滤关键字 - */ - public static final String DATA_SCOPE = "dataScope"; + @Autowired + private ISysUserService userService; + @PersistenceContext + private EntityManager entityManager; // 配置织入点 @Pointcut("@annotation(com.ruoyi.common.annotation.DataScope)") @@ -64,19 +52,25 @@ public class DataScopeAspect { handleDataScope(point); } + @After("dataScopePointCut()") + public void doAfter(JoinPoint point) throws Throwable{ + DataScopeContextHolder.clear(); + } + protected void handleDataScope(final JoinPoint joinPoint) { // 获得注解 + SysUser currentUser = ShiroUtils.getSysUser(); DataScope controllerDataScope = getAnnotationLog(joinPoint); + if (controllerDataScope == null) { return; } // 获取当前的用户 - SysUser currentUser = ShiroUtils.getSysUser(); + if (currentUser != null) { // 如果是超级管理员,则不过滤数据 if (!currentUser.isAdmin()) { - dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), - controllerDataScope.userAlias()); + dataScopeFilter(joinPoint, currentUser, controllerDataScope); } } } @@ -86,40 +80,30 @@ public class DataScopeAspect { * * @param joinPoint 切点 * @param user 用户 - * @param deptAlias 别名 */ - public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { - StringBuilder sqlString = new StringBuilder(); + private void dataScopeFilter(JoinPoint joinPoint, SysUser user, DataScope controllerDataScope) { + user = userService.selectUserWithRolesAndPostsById(user.getUserId()); - for (SysRole role : user.getRoles()) { - String dataScope = role.getDataScope(); - if (DATA_SCOPE_ALL.equals(dataScope)) { - sqlString = new StringBuilder(); - break; - } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, - role.getRoleId())); - } else if (DATA_SCOPE_DEPT.equals(dataScope)) { - sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDept().getDeptId())); - } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", - deptAlias, user.getDept().getDeptId(), user.getDept().getDeptId())); - } else if (DATA_SCOPE_SELF.equals(dataScope)) { - if (StringUtils.isNotBlank(userAlias)) { - sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); - } else { - // 数据权限为仅本人且没有userAlias别名不查询任何数据 - sqlString.append(" OR 1=0 "); - } + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + List predicates = new ArrayList<>(); + Set roles = user.getRoles(); + for(SysRole sysRole : roles){ + switch (sysRole.getDataScope()){ + case DATA_SCOPE_DEPT: //当前部门 + break; + case DATA_SCOPE_SELF: //自己 + break; + case DATA_SCOPE_CUSTOM: //自定义 + break; + case DATA_SCOPE_DEPT_AND_CHILD: //子部门 + break; + default: + //无需过滤 + break; } } - if (StringUtils.isNotBlank(sqlString.toString())) { - BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0]; - baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); - } + DataScopeContextHolder.set(ExpressionUtils.anyOf(predicates)); } /** diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeContextHolder.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeContextHolder.java new file mode 100644 index 000000000..4a6ad0e6b --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeContextHolder.java @@ -0,0 +1,20 @@ +package com.ruoyi.framework.aspectj; + +import com.querydsl.core.types.Predicate; + +public class DataScopeContextHolder { + + private static ThreadLocal threadLocal = new ThreadLocal<>(); + + public static void set(Predicate predicate){ + threadLocal.set(predicate); + } + + public static void clear(){ + threadLocal.remove(); + } + + public static Predicate get(){ + return threadLocal.get(); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/MySpecification.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/MySpecification.java new file mode 100644 index 000000000..5a94592cf --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/MySpecification.java @@ -0,0 +1,60 @@ +package com.ruoyi.framework.aspectj; + +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.framework.util.ShiroUtils; +import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.service.ISysUserService; +import org.springframework.data.jpa.domain.Specification; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.List; + +public abstract class MySpecification implements Specification { + + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + + //custom filter + addPredicate(root, query, criteriaBuilder, predicates); + + //datascope filter + Predicate predicate = addDataScopeFilter(root, query, criteriaBuilder); + predicates.add(predicate); + + //条件之间是 and 关系 + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + + public abstract void addPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder, List predicates); + + protected Predicate addDataScopeFilter(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder){ + List predicates = new ArrayList<>(); + + ISysUserService userService = SpringUtils.getBean(ISysUserService.class); + SysUser sysUser = userService.selectUserWithRolesAndPostsById(ShiroUtils.getUserId()); + + if(!sysUser.isAdmin()){ + for(SysRole sysRole : sysUser.getRoles()){ + switch (sysRole.getDataScope()){ + case DATA_SCOPE_DEPT_AND_CHILD: + break; + case DATA_SCOPE_CUSTOM: + break; + case DATA_SCOPE_SELF: + break; + case DATA_SCOPE_DEPT: + break; + } + } + } + + //条件之间是 or 关系 + return criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()])); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java index 0dd028a41..b792e4cce 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysRole.java @@ -1,5 +1,6 @@ package com.ruoyi.system.domain; +import com.ruoyi.common.annotation.DataScopes; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.core.domain.BaseEntity; @@ -54,7 +55,7 @@ public class SysRole extends BaseEntity { * 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) */ @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限") - private String dataScope; + private DataScopes dataScope; /** * 角色状态(0正常 1停用) @@ -111,11 +112,11 @@ public class SysRole extends BaseEntity { return roleId != null && 1L == roleId; } - public String getDataScope() { + public DataScopes getDataScope() { return dataScope; } - public void setDataScope(String dataScope) { + public void setDataScope(DataScopes dataScope) { this.dataScope = dataScope; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/converter/DataScopesConverter.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/converter/DataScopesConverter.java new file mode 100644 index 000000000..f4244f2a2 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/converter/DataScopesConverter.java @@ -0,0 +1,23 @@ +package com.ruoyi.system.domain.converter; + +import com.ruoyi.common.annotation.DataScopes; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.util.Arrays; + +@Converter(autoApply = true) +public class DataScopesConverter implements AttributeConverter { + @Override + public String convertToDatabaseColumn(DataScopes attribute) { + return attribute != null ? attribute.name() : null; + } + + @Override + public DataScopes convertToEntityAttribute(String dbData) { + return Arrays.stream(DataScopes.values()) + .filter(dataScopes -> dataScopes.name().equals(dbData)) + .findFirst() + .orElse(DataScopes.DATA_SCOPE_ALL); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java index f7b3a3b47..8c7fc25cb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysRoleService.java @@ -1,6 +1,7 @@ package com.ruoyi.system.service; import com.ruoyi.system.domain.SysRole; +import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUserRole; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -18,9 +19,10 @@ public interface ISysRoleService { * 根据条件分页查询角色数据 * * @param role 角色信息 + * @param user * @return 角色数据集合信息 */ - public Page selectRoleList(SysRole role, Pageable pageable); + public Page selectRoleList(SysRole role, Pageable pageable, SysUser user); /** * 根据用户ID查询角色 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java index 9af23ec75..69239aebe 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java @@ -1,10 +1,12 @@ package com.ruoyi.system.service; +import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysUser; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; +import java.util.Set; /** * 用户 业务层 @@ -169,4 +171,6 @@ public interface ISysUserService { * @return 结果 */ public void changeStatus(SysUser user); + + Set getUserRoleDepts(Long userId); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BusinessService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BusinessService.java new file mode 100644 index 000000000..50899506c --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/base/BusinessService.java @@ -0,0 +1,46 @@ +package com.ruoyi.system.service.base; + +import com.querydsl.core.types.ExpressionUtils; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.types.dsl.ListPath; +import com.ruoyi.common.base.BaseService; +import com.ruoyi.system.domain.QSysDept; +import com.ruoyi.system.domain.SysDept; +import com.ruoyi.system.service.ISysUserService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class BusinessService extends BaseService { + + @Autowired + private ISysUserService userService; + + /** + * 过滤数据权限 + * @param path dept属性 + * @param userId 当前用户id + * @return + */ + protected Predicate buildDataPermission(QSysDept path, Long userId){ + Set depts = userService.getUserRoleDepts(userId); + List predicates = new ArrayList<>(); + predicates.add(ExpressionUtils.in(path, depts)); + return ExpressionUtils.allOf(predicates); + } + + /** + * 过滤数据权限 + * @param path dept属性 + * @param userId 当前用户id + * @return + */ + protected Predicate buildDataPermission(ListPath path, Long userId){ + Set depts = userService.getUserRoleDepts(userId); + List predicates = new ArrayList<>(); + predicates.add(ExpressionUtils.in(path.any(), depts)); + return ExpressionUtils.allOf(predicates); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java index ec1cb2bcb..9ee9347e3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java @@ -2,7 +2,7 @@ package com.ruoyi.system.service.impl; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; -import com.ruoyi.common.base.BaseService; +import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.text.Convert; @@ -15,6 +15,7 @@ import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.repository.SysRoleRepository; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysRoleService; +import com.ruoyi.system.service.base.BusinessService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -28,8 +29,9 @@ import java.util.*; * * @author ruoyi */ +@DataScope(userFieldName = "user") @Service -public class SysRoleServiceImpl extends BaseService implements ISysRoleService { +public class SysRoleServiceImpl extends BusinessService implements ISysRoleService { @Autowired private SysRoleRepository sysRoleRepository; @@ -40,14 +42,15 @@ public class SysRoleServiceImpl extends BaseService implements ISysRoleService { * 根据条件分页查询角色数据 * * @param role 角色信息 + * @param user * @return 角色数据集合信息 */ @Override - public Page selectRoleList(SysRole role, Pageable pageable) { - return sysRoleRepository.findAll(getPredicate(role), pageable); + public Page selectRoleList(SysRole role, Pageable pageable, SysUser user) { + return sysRoleRepository.findAll(getPredicate(role, user), pageable); } - private Predicate getPredicate(SysRole role){ + public Predicate getPredicate(SysRole role, SysUser user){ QSysRole qSysRole = QSysRole.sysRole; List predicates = new ArrayList<>(); predicates.add(buildEqual(qSysRole.delFlag, BaseEntity.NOT_DELETED)); @@ -60,8 +63,8 @@ public class SysRoleServiceImpl extends BaseService implements ISysRoleService { if(StringUtils.isNotEmpty(role.getRoleKey())){ predicates.add(buildLike(qSysRole.roleKey, role.getRoleKey())); } - if(StringUtils.isNotEmpty(role.getDataScope())){ - predicates.add(buildEqual(qSysRole.dataScope, role.getDataScope())); + if(role.getDataScope() != null){ + predicates.add(buildEqual(qSysRole.dataScope, role.getDataScope().name())); } if(role.getStartTime() != null){ predicates.add(buildGreaterThanOrEqualTo(qSysRole.createTime, role.getStartTime())); @@ -69,6 +72,7 @@ public class SysRoleServiceImpl extends BaseService implements ISysRoleService { if(role.getEndTime() != null){ predicates.add(buildLessThanOrEqualTo(qSysRole.createTime, role.getEndTime())); } +// predicates.add(buildDataPermission(qSysRole.depts, user.getUserId())); return ExpressionUtils.allOf(predicates); } @@ -108,7 +112,7 @@ public class SysRoleServiceImpl extends BaseService implements ISysRoleService { */ @Override public List selectRoleAll() { - return sysRoleRepository.findAll(getPredicate(new SysRole()), Pageable.unpaged()).getContent(); + return sysRoleRepository.findAll(getPredicate(new SysRole(), new SysUser()), Pageable.unpaged()).getContent(); } /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java index 2955b73e7..a4d967a4d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java @@ -9,8 +9,10 @@ import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.Md5Utils; import com.ruoyi.system.domain.QSysUser; +import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysUser; +import com.ruoyi.system.repository.SysRoleRepository; import com.ruoyi.system.repository.SysUserRepository; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; @@ -28,10 +30,7 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Set; +import java.util.*; /** * 用户 业务层处理 @@ -44,9 +43,10 @@ public class SysUserServiceImpl extends BaseService implements ISysUserService { @Autowired private SysUserRepository sysUserRepository; - @Autowired private ISysConfigService configService; + @Autowired + private SysRoleRepository sysRoleRepository; /** * 根据条件分页查询用户列表 @@ -414,4 +414,15 @@ public class SysUserServiceImpl extends BaseService implements ISysUserService { public void changeStatus(SysUser user) { sysUserRepository.changeStatus(user.getStatus(), user.getUserId()); } + + public Set getUserRoleDepts(Long userId){ + SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId); + Set depts = new HashSet<>(); + Set roles = user.getRoles(); + for(SysRole sysRole : roles){ + sysRole = sysRoleRepository.findByRoleId(sysRole.getRoleId()); + depts.addAll(sysRole.getDepts()); + } + return depts; + } } From 692cb45255410e921dffeeb98d39636ba8ad5038 Mon Sep 17 00:00:00 2001 From: administrator <2316696377@qq.com> Date: Thu, 13 Aug 2020 16:05:45 +0800 Subject: [PATCH 50/52] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../generator/controller/GenController.java | 2 +- .../com/ruoyi/generator/domain/GenTable.java | 7 +- .../generator/domain/GenTableColumn.java | 15 +- .../repository/GenTableColumnRepository.java | 10 - .../repository/GenTableRepository.java | 2 - .../service/IGenTableColumnService.java | 10 - .../impl/GenTableColumnServiceImpl.java | 13 - .../service/impl/GenTableServiceImpl.java | 9 +- .../com/ruoyi/generator/util/GenUtils.java | 7 +- .../generator/util/VelocityInitializer.java | 6 +- .../ruoyi/generator/util/VelocityUtils.java | 21 +- .../main/resources/vm/java/controller.java.vm | 40 ++- .../src/main/resources/vm/java/domain.java.vm | 170 +++++----- .../main/resources/vm/java/repository.java.vm | 16 + .../main/resources/vm/java/service.java.vm | 212 ++++++++----- .../resources/vm/java/serviceImpl.java.vm | 290 +++++++++--------- 16 files changed, 443 insertions(+), 387 deletions(-) create mode 100644 ruoyi-generator/src/main/resources/vm/java/repository.java.vm diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java index f1b0b89fc..3955a4e47 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java @@ -74,7 +74,7 @@ public class GenController extends BaseController { @ResponseBody public TableDataInfo columnList(GenTable genTable) { TableDataInfo dataInfo = new TableDataInfo(); - List list = genTableColumnService.selectGenTableColumnListByTableId(genTable); + List list = genTableService.selectGenTableById(genTable.getTableId()).getColumns(); dataInfo.setRows(list); dataInfo.setTotal(list.size()); return dataInfo; diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java index 456f9ea40..748edd962 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTable.java @@ -35,7 +35,6 @@ public class GenTable extends BaseEntity { /** * 表描述 */ - @NotBlank(message = "表描述不能为空") private String tableComment; /** @@ -70,7 +69,6 @@ public class GenTable extends BaseEntity { /** * 生成功能名 */ - @NotBlank(message = "生成功能名不能为空") private String functionName; /** @@ -89,7 +87,10 @@ public class GenTable extends BaseEntity { * 表列信息 */ @Valid - @OneToMany(mappedBy = "table") + @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @JoinTable(name = "gen_table_columns", + joinColumns = @JoinColumn(name = "genTableTableId", referencedColumnName = "tableId"), + inverseJoinColumns = @JoinColumn(name = "columnsColumnId", referencedColumnName = "columnId")) private List columns; /** diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java index d6bcd489b..6fb3f1ad0 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/domain/GenTableColumn.java @@ -104,13 +104,6 @@ public class GenTableColumn extends BaseEntity { */ private Integer sort; - @ManyToOne - @JoinTable(name = "gen_table_columns", - inverseJoinColumns = @JoinColumn(name = "genTableTableId", referencedColumnName = "tableId"), - joinColumns = @JoinColumn(name = "columnsColumnId", referencedColumnName = "columnId")) - @org.hibernate.annotations.ForeignKey(name = "none") - private GenTable table; - public void setColumnId(Long columnId) { this.columnId = columnId; } @@ -341,11 +334,7 @@ public class GenTableColumn extends BaseEntity { } } - public GenTable getTable() { - return table; - } - - public void setTable(GenTable table) { - this.table = table; + public String capital(){ + return StringUtils.capitalize(this.javaField); } } \ No newline at end of file diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java index f77b2a2b0..fee996c0d 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableColumnRepository.java @@ -1,20 +1,10 @@ package com.ruoyi.generator.repository; import com.ruoyi.common.base.BaseRepository; -import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; -import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Repository; -import java.util.Collection; -import java.util.List; - @Repository public interface GenTableColumnRepository extends BaseRepository { - List findByTable(GenTable genTable); - - @Modifying - void deleteByTableIn(Collection tables); - } diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java index 32c1bc8e7..0ca6bc17e 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/repository/GenTableRepository.java @@ -2,7 +2,6 @@ package com.ruoyi.generator.repository; import com.ruoyi.common.base.BaseRepository; import com.ruoyi.generator.domain.GenTable; -import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.stereotype.Repository; import java.util.Optional; @@ -12,7 +11,6 @@ public interface GenTableRepository extends BaseRepository { GenTable findFirstByTableName(String tableName); - @EntityGraph(attributePaths = {"columns"}) @Override Optional findById(Long id); } diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java index eab765355..1cbbdeb5b 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/IGenTableColumnService.java @@ -1,8 +1,5 @@ package com.ruoyi.generator.service; -import java.util.List; - -import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; /** @@ -11,13 +8,6 @@ import com.ruoyi.generator.domain.GenTableColumn; * @author ruoyi */ public interface IGenTableColumnService { - /** - * 查询业务字段列表 - * - * @param genTable 业务字段信息 - * @return 业务字段集合 - */ - public List selectGenTableColumnListByTableId(GenTable genTable); /** * 新增业务字段 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java index 21c94b4f7..d7c898458 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableColumnServiceImpl.java @@ -1,7 +1,6 @@ package com.ruoyi.generator.service.impl; import com.ruoyi.common.core.text.Convert; -import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.repository.GenTableColumnRepository; import com.ruoyi.generator.service.IGenTableColumnService; @@ -9,8 +8,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - /** * 业务字段 服务层实现 * @@ -21,16 +18,6 @@ public class GenTableColumnServiceImpl implements IGenTableColumnService { @Autowired private GenTableColumnRepository genTableColumnRepository; - /** - * 查询业务字段列表 - * - * @param genTable 业务字段信息 - * @return 业务字段集合 - */ - @Override - public List selectGenTableColumnListByTableId(GenTable genTable) { - return genTableColumnRepository.findByTable(genTable); - } /** * 新增业务字段 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java index 849aa004e..b59ce6643 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/impl/GenTableServiceImpl.java @@ -179,12 +179,9 @@ public class GenTableServiceImpl extends BaseService implements IGenTableService @Override @Transactional public void deleteGenTableByIds(String ids) { - List tables = new ArrayList<>(); for(Long id : Convert.toLongArray(ids)){ genTableRepository.deleteById(id); - tables.add(new GenTable(id)); } - genTableColumnRepository.deleteByTableIn(tables); } /** @@ -199,15 +196,17 @@ public class GenTableServiceImpl extends BaseService implements IGenTableService for (GenTable table : tableList) { try { GenUtils.initTable(table, operName); - genTableRepository.save(table); + List columns = new ArrayList<>(); String sql = "select column_name, (case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type " + " from information_schema.columns where table_schema = (select database()) and table_name = '" + table.getTableName() + "'" + " order by ordinal_position"; List genTableColumns = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GenTableColumn.class)); for (GenTableColumn column : genTableColumns) { GenUtils.initColumnField(column, table); - genTableColumnRepository.save(column); + columns.add(column); } + table.setColumns(columns); + genTableRepository.save(table); } catch (Exception e) { log.error("表名 " + table.getTableName() + " 导入失败:", e); } diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java index 3a30afb00..192a50415 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/GenUtils.java @@ -1,13 +1,13 @@ package com.ruoyi.generator.util; -import java.util.Arrays; - -import org.apache.commons.lang3.RegExUtils; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.generator.config.GenConfig; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; +import org.apache.commons.lang3.RegExUtils; + +import java.util.Arrays; /** * 代码生成器 工具类 @@ -34,7 +34,6 @@ public class GenUtils { public static void initColumnField(GenTableColumn column, GenTable table) { String dataType = getDbType(column.getColumnType()); String columnName = column.getColumnName(); - column.setTable(table); column.setCreateBy(table.getCreateBy()); // 设置java字段名 column.setJavaField(StringUtils.toCamelCase(columnName)); diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java index 5abe6ee52..f5ef3039c 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java @@ -1,9 +1,9 @@ package com.ruoyi.generator.util; -import java.util.Properties; - -import org.apache.velocity.app.Velocity; import com.ruoyi.common.constant.Constants; +import org.apache.velocity.app.Velocity; + +import java.util.Properties; /** * VelocityEngine工厂 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java index 543916eb9..01cbe6dde 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java @@ -1,10 +1,5 @@ package com.ruoyi.generator.util; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import org.apache.velocity.VelocityContext; import com.alibaba.fastjson.JSONObject; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.utils.DateUtils; @@ -12,6 +7,11 @@ import com.ruoyi.common.utils.StringUtils; import com.ruoyi.generator.config.GenConfig; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; +import org.apache.velocity.VelocityContext; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; public class VelocityUtils { /** @@ -47,6 +47,7 @@ public class VelocityUtils { velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("ClassName", genTable.getClassName()); velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); + velocityContext.put("classname", StringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("moduleName", genTable.getModuleName()); velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("basePackage", getPackagePrefix(packageName)); @@ -54,6 +55,7 @@ public class VelocityUtils { velocityContext.put("author", genTable.getFunctionAuthor()); velocityContext.put("datetime", DateUtils.getDate()); velocityContext.put("pkColumn", genTable.getPkColumn()); + velocityContext.put("primaryKeyType", genTable.getPkColumn().getJavaType()); velocityContext.put("importList", getImportList(genTable.getColumns())); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("columns", genTable.getColumns()); @@ -91,9 +93,8 @@ public class VelocityUtils { public static List getTemplateList(String tplCategory) { List templates = new ArrayList(); templates.add("vm/java/domain.java.vm"); - templates.add("vm/java/mapper.java.vm"); + templates.add("vm/java/repository.java.vm"); templates.add("vm/java/service.java.vm"); - templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/controller.java.vm"); templates.add("vm/xml/mapper.xml.vm"); if (GenConstants.TPL_CRUD.equals(tplCategory)) { @@ -128,11 +129,13 @@ public class VelocityUtils { String htmlPath = TEMPLATES_PATH + "/" + moduleName + "/" + businessName; if (template.contains("domain.java.vm")) { - fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); + fileName = StringUtils.format("{}/entity/{}.java", javaPath, className); } else if (template.contains("mapper.java.vm")) { fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); + } else if (template.contains("repository.java.vm")) { + fileName = StringUtils.format("{}/repository/{}Repository.java", javaPath, className); } else if (template.contains("service.java.vm")) { - fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); + fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className); } else if (template.contains("serviceImpl.java.vm")) { fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); } else if (template.contains("controller.java.vm")) { diff --git a/ruoyi-generator/src/main/resources/vm/java/controller.java.vm b/ruoyi-generator/src/main/resources/vm/java/controller.java.vm index 97eb459c0..fa0c6aceb 100644 --- a/ruoyi-generator/src/main/resources/vm/java/controller.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/controller.java.vm @@ -12,15 +12,15 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessType; -import ${packageName}.domain.${ClassName}; -import ${packageName}.service.I${ClassName}Service; +import ${packageName}.entity.${ClassName}; +import ${packageName}.service.${ClassName}Service; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.utils.StringUtils; #if($table.crud) import com.ruoyi.common.core.page.TableDataInfo; #elseif($table.tree) -import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.core.domain.Ztree; #end @@ -37,7 +37,7 @@ public class ${ClassName}Controller extends BaseController private String prefix = "${moduleName}/${businessName}"; @Autowired - private I${ClassName}Service ${className}Service; + private ${ClassName}Service ${className}Service; @RequiresPermissions("${permissionPrefix}:view") @GetMapping() @@ -54,9 +54,7 @@ public class ${ClassName}Controller extends BaseController @PostMapping("/list") @ResponseBody public TableDataInfo list(${ClassName} ${className}) { - startPage(); - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); - return getDataTable(list); + return getDataTable(${className}Service.findByPage(${className}, getPageRequest())); } #elseif($table.tree) /** @@ -67,7 +65,7 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public List<${ClassName}> list(${ClassName} ${className}) { - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + List<${ClassName}> list = ${className}Service.findAll(${className}); return list; } #end @@ -81,7 +79,7 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public AjaxResult export(${ClassName} ${className}) { - List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + List<${ClassName}> list = ${className}Service.findAll(${className}); ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}.class); return util.exportExcel(list, "${businessName}"); } @@ -104,7 +102,7 @@ public class ${ClassName}Controller extends BaseController { if (StringUtils.isNotNull(${pkColumn.javaField})) { - mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); + mmap.put("${className}", ${className}Service.findById(${pkColumn.javaField})); } return prefix + "/add"; } @@ -119,7 +117,12 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public AjaxResult addSave(${ClassName} ${className}) { - return toAjax(${className}Service.insert${ClassName}(${className})); + try{ + ${className}Service.insert(${className}); + return toAjax(true); + }catch (Exception e){ + return error(e.getMessage()); + } } /** @@ -128,7 +131,7 @@ public class ${ClassName}Controller extends BaseController @GetMapping("/edit/{${pkColumn.javaField}}") public String edit(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}, ModelMap mmap) { - ${ClassName} ${className} = ${className}Service.select${ClassName}ById(${pkColumn.javaField}); + ${ClassName} ${className} = ${className}Service.findById(${pkColumn.javaField}); mmap.put("${className}", ${className}); return prefix + "/edit"; } @@ -142,7 +145,12 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public AjaxResult editSave(${ClassName} ${className}) { - return toAjax(${className}Service.update${ClassName}(${className})); + try{ + ${className}Service.update(${className}); + return toAjax(true); + }catch (Exception e){ + return error(e.getMessage()); + } } #if($table.crud) @@ -155,7 +163,7 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public AjaxResult remove(String ids) { - return toAjax(${className}Service.delete${ClassName}ByIds(ids)); + return toAjax(${className}Service.deleteByIds(ids)); } #elseif($table.tree) /** @@ -167,7 +175,7 @@ public class ${ClassName}Controller extends BaseController @ResponseBody public AjaxResult remove(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) { - return toAjax(${className}Service.delete${ClassName}ById(${pkColumn.javaField})); + return toAjax(${className}Service.deleteById(${pkColumn.javaField})); } #end #if($table.tree) @@ -181,7 +189,7 @@ public class ${ClassName}Controller extends BaseController { if (StringUtils.isNotNull(${pkColumn.javaField})) { - mmap.put("${className}", ${className}Service.select${ClassName}ById(${pkColumn.javaField})); + mmap.put("${className}", ${className}Service.findById(${pkColumn.javaField})); } return prefix + "/tree"; } diff --git a/ruoyi-generator/src/main/resources/vm/java/domain.java.vm b/ruoyi-generator/src/main/resources/vm/java/domain.java.vm index 91180253f..4ea4f99b3 100644 --- a/ruoyi-generator/src/main/resources/vm/java/domain.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/domain.java.vm @@ -1,84 +1,86 @@ -package ${packageName}.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import com.ruoyi.common.annotation.Excel; -#if($table.crud) -import com.ruoyi.common.core.domain.BaseEntity; -#elseif($table.tree) -import com.ruoyi.common.core.domain.TreeEntity; -#end -#foreach ($import in $importList) -import ${import}; -#end - -/** - * ${functionName}对象 ${tableName} - * - * @author ${author} - * @date ${datetime} - */ -#if($table.crud) -#set($Entity="BaseEntity") -#elseif($table.tree) -#set($Entity="TreeEntity") -#end -public class ${ClassName} extends ${Entity} -{ - private static final long serialVersionUID = 1L; - -#foreach ($column in $columns) -#if(!$table.isSuperColumn($column.javaField)) - /** $column.columnComment */ -#if($column.list) -#set($parentheseIndex=$column.columnComment.indexOf("(")) -#if($parentheseIndex != -1) -#set($comment=$column.columnComment.substring(0, $parentheseIndex)) -#else -#set($comment=$column.columnComment) -#end -#if($parentheseIndex != -1) - @Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()") -#elseif($column.javaType == 'Date') - @Excel(name = "${comment}", width = 30, dateFormat = "yyyy-MM-dd") -#else - @Excel(name = "${comment}") -#end -#end - private $column.javaType $column.javaField; - -#end -#end -#foreach ($column in $columns) -#if(!$table.isSuperColumn($column.javaField)) -#if($column.javaField.substring(1,2).matches("[A-Z]")) -#set($AttrName=$column.javaField) -#else -#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) -#end - public void set${AttrName}($column.javaType $column.javaField) - { - this.$column.javaField = $column.javaField; - } - - public $column.javaType get${AttrName}() - { - return $column.javaField; - } -#end -#end - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) -#foreach ($column in $columns) -#if($column.javaField.substring(1,2).matches("[A-Z]")) -#set($AttrName=$column.javaField) -#else -#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) -#end - .append("${column.javaField}", get${AttrName}()) -#end - .toString(); - } -} +package ${packageName}.entity; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import javax.persistence.Entity; +#if($table.crud) +import com.ruoyi.common.core.domain.BaseDatabaseEntity; +#elseif($table.tree) +import com.ruoyi.common.core.domain.TreeEntity; +#end +#foreach ($import in $importList) +import ${import}; +#end + +/** + * ${functionName}对象 ${tableName} + * + * @author ${author} + * @date ${datetime} + */ +#if($table.crud) +#set($Entity="BaseDatabaseEntity") +#elseif($table.tree) +#set($Entity="TreeEntity") +#end +@Entity +public class ${ClassName} extends ${Entity} +{ + private static final long serialVersionUID = 1L; + +#foreach ($column in $columns) +#if(!$table.isSuperColumn($column.javaField)) + /** $column.columnComment */ +#if($column.list) +#set($parentheseIndex=$column.columnComment.indexOf("(")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if($parentheseIndex != -1) + @Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()") +#elseif($column.javaType == 'Date') + @Excel(name = "${comment}", width = 30, dateFormat = "yyyy-MM-dd") +#else + @Excel(name = "${comment}") +#end +#end + private $column.javaType $column.javaField; + +#end +#end +#foreach ($column in $columns) +#if(!$table.isSuperColumn($column.javaField)) +#if($column.javaField.substring(1,2).matches("[A-Z]")) +#set($AttrName=$column.javaField) +#else +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +#end + public void set${AttrName}($column.javaType $column.javaField) + { + this.$column.javaField = $column.javaField; + } + + public $column.javaType get${AttrName}() + { + return $column.javaField; + } +#end +#end + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) +#foreach ($column in $columns) +#if($column.javaField.substring(1,2).matches("[A-Z]")) +#set($AttrName=$column.javaField) +#else +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +#end + .append("${column.javaField}", get${AttrName}()) +#end + .toString(); + } +} diff --git a/ruoyi-generator/src/main/resources/vm/java/repository.java.vm b/ruoyi-generator/src/main/resources/vm/java/repository.java.vm new file mode 100644 index 000000000..ad85c028c --- /dev/null +++ b/ruoyi-generator/src/main/resources/vm/java/repository.java.vm @@ -0,0 +1,16 @@ +package ${packageName}.repository; + +import ${packageName}.entity.${ClassName}; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.stereotype.Repository; +/** + * ${functionName} dao层实现 + * + * @author ${author} + * @date ${datetime} + */ +@Repository +public interface ${ClassName}Repository extends BaseRepository<${ClassName}, ${primaryKeyType}>{ + +} \ No newline at end of file diff --git a/ruoyi-generator/src/main/resources/vm/java/service.java.vm b/ruoyi-generator/src/main/resources/vm/java/service.java.vm index 1668c2466..567b19a9e 100644 --- a/ruoyi-generator/src/main/resources/vm/java/service.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/service.java.vm @@ -1,73 +1,139 @@ -package ${packageName}.service; - -import ${packageName}.domain.${ClassName}; -import java.util.List; -#if($table.tree) -import com.ruoyi.common.core.domain.Ztree; -#end - -/** - * ${functionName}Service接口 - * - * @author ${author} - * @date ${datetime} - */ -public interface I${ClassName}Service -{ - /** - * 查询${functionName} - * - * @param ${pkColumn.javaField} ${functionName}ID - * @return ${functionName} - */ - public ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}); - - /** - * 查询${functionName}列表 - * - * @param ${className} ${functionName} - * @return ${functionName}集合 - */ - public List<${ClassName}> select${ClassName}List(${ClassName} ${className}); - - /** - * 新增${functionName} - * - * @param ${className} ${functionName} - * @return 结果 - */ - public int insert${ClassName}(${ClassName} ${className}); - - /** - * 修改${functionName} - * - * @param ${className} ${functionName} - * @return 结果 - */ - public int update${ClassName}(${ClassName} ${className}); - - /** - * 批量删除${functionName} - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - public int delete${ClassName}ByIds(String ids); - - /** - * 删除${functionName}信息 - * - * @param ${pkColumn.javaField} ${functionName}ID - * @return 结果 - */ - public int delete${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}); -#if($table.tree) - - /** - * 查询${functionName}树列表 - * - * @return 所有${functionName}信息 - */ - public List select${ClassName}Tree(); -#end -} +package ${packageName}.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Date; + +import com.ruoyi.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.transaction.annotation.Transactional; +import ${packageName}.repository.${ClassName}Repository; +import ${packageName}.entity.${ClassName}; +import com.ruoyi.common.core.text.Convert; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +/** + * ${functionName} 服务层实现 + * + * @author ${author} + * @date ${datetime} + */ +@Service +public class ${ClassName}Service { + + @Autowired + private ${ClassName}Repository ${classname}Repository; + + /** + * 查询 ${functionName} 分页信息 + * + * @param ${classname} 查询对象 + * @param pageRequest 分页信息 + * @return ${functionName} 分页后结果 + */ + public Page<${ClassName}> findByPage(${ClassName} ${classname}, Pageable pageRequest){ + return ${classname}Repository.findAll(getSpecification(${classname}), pageRequest); + } + + /** + * 查询 ${functionName} 所有信息 + * + * @param ${classname} 查询对象 + * @return ${functionName} 结果 + */ + public List<${ClassName}> findAll(${ClassName} ${classname}){ + return ${classname}Repository.findAll(getSpecification(${classname})); + } + + /** + * 新增${functionName} + * + * @param ${classname} ${functionName}信息 + * @return 保存后的对象 + */ + @Transactional + public ${ClassName} insert(${ClassName} ${classname}){ + return ${classname}Repository.save(${classname}); + } + + /** + * 修改${functionName} + * + * @param ${classname} ${functionName}信息 + * @return 保存后的对象 + */ + @Transactional + public ${ClassName} update(${ClassName} ${classname}){ + return ${classname}Repository.save(${classname}); + } + + /** + * 查询${functionName}对象 + * + * @param ${pkColumn.javaField} 需要查询的id + * @return + */ + public ${ClassName} findById(${pkColumn.javaType} ${pkColumn.javaField}){ + return ${classname}Repository.findById(${pkColumn.javaField}).orElse(null); + } + + /** + * 删除${functionName}对象 + * + * @param ${pkColumn.javaField} 需要删除的数据ID + */ + @Transactional + public void deleteById(${pkColumn.javaType} ${pkColumn.javaField}){ + ${classname}Repository.deleteById(${pkColumn.javaField}); + } + + /** + * 删除${functionName}对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Transactional + public int deleteByIds(String ids) { + for(String id : Convert.toStrArray(ids)){ + ${classname}Repository.deleteById(${pkColumn.javaType}.valueOf(id)); + } + return 1; + } + + + private Specification<${ClassName}> getSpecification(${ClassName} ${classname}){ + return new Specification<${ClassName}>() { + @Override + public Predicate toPredicate(Root<${ClassName}> root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + #foreach($column in $columns) + #if($column.javaType == "String") + if(StringUtils.isNotEmpty(${classname}.get${column.capital()}())){ + predicates.add(criteriaBuilder.like(root.get("$column.javaField").as(${column.javaType}.class), "%" + ${classname}.get${column.capital()}() + "%")); + } + #else + if(${classname}.get${column.capital()}() != null){ + predicates.add(criteriaBuilder.equal(root.get("$column.javaField").as(${column.javaType}.class), ${classname}.get${column.capital()}())); + } + #end + #end + if(${classname}.getStartTime() != null){ + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createDate").as(Date.class), ${classname}.getStartTime())); + } + if(${classname}.getEndTime() != null){ + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createDate").as(Date.class), ${classname}.getEndTime())); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; + } +} \ No newline at end of file diff --git a/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm b/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm index bbeb4de89..0394a230a 100644 --- a/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm @@ -1,141 +1,149 @@ -package ${packageName}.service.impl; - -import java.util.List; -#if($table.tree) -import java.util.ArrayList; -import com.ruoyi.common.core.domain.Ztree; -#end -#foreach ($column in $columns) -#if($column.javaField == 'createTime' || $column.javaField == 'updateTime') -import com.ruoyi.common.utils.DateUtils; -#break -#end -#end -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import ${packageName}.mapper.${ClassName}Mapper; -import ${packageName}.domain.${ClassName}; -import ${packageName}.service.I${ClassName}Service; -import com.ruoyi.common.core.text.Convert; - -/** - * ${functionName}Service业务层处理 - * - * @author ${author} - * @date ${datetime} - */ -@Service -public class ${ClassName}ServiceImpl implements I${ClassName}Service -{ - @Autowired - private ${ClassName}Mapper ${className}Mapper; - - /** - * 查询${functionName} - * - * @param ${pkColumn.javaField} ${functionName}ID - * @return ${functionName} - */ - @Override - public ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}) - { - return ${className}Mapper.select${ClassName}ById(${pkColumn.javaField}); - } - - /** - * 查询${functionName}列表 - * - * @param ${className} ${functionName} - * @return ${functionName} - */ - @Override - public List<${ClassName}> select${ClassName}List(${ClassName} ${className}) - { - return ${className}Mapper.select${ClassName}List(${className}); - } - - /** - * 新增${functionName} - * - * @param ${className} ${functionName} - * @return 结果 - */ - @Override - public int insert${ClassName}(${ClassName} ${className}) - { -#foreach ($column in $columns) -#if($column.javaField == 'createTime') - ${className}.setCreateTime(DateUtils.getNowDate()); -#end -#end - return ${className}Mapper.insert${ClassName}(${className}); - } - - /** - * 修改${functionName} - * - * @param ${className} ${functionName} - * @return 结果 - */ - @Override - public int update${ClassName}(${ClassName} ${className}) - { -#foreach ($column in $columns) -#if($column.javaField == 'updateTime') - ${className}.setUpdateTime(DateUtils.getNowDate()); -#end -#end - return ${className}Mapper.update${ClassName}(${className}); - } - - /** - * 删除${functionName}对象 - * - * @param ids 需要删除的数据ID - * @return 结果 - */ - @Override - public int delete${ClassName}ByIds(String ids) - { - return ${className}Mapper.delete${ClassName}ByIds(Convert.toStrArray(ids)); - } - - /** - * 删除${functionName}信息 - * - * @param ${pkColumn.javaField} ${functionName}ID - * @return 结果 - */ - @Override - public int delete${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}) - { - return ${className}Mapper.delete${ClassName}ById(${pkColumn.javaField}); - } -#if($table.tree) - - /** - * 查询${functionName}树列表 - * - * @return 所有${functionName}信息 - */ - @Override - public List select${ClassName}Tree() - { - List<${ClassName}> ${className}List = ${className}Mapper.select${ClassName}List(new ${ClassName}()); - List ztrees = new ArrayList(); - for (${ClassName} ${className} : ${className}List) - { - Ztree ztree = new Ztree(); -#set($TreeCode=$treeCode.substring(0,1).toUpperCase() + ${treeCode.substring(1)}) -#set($TreeParentCode=$treeParentCode.substring(0,1).toUpperCase() + ${treeParentCode.substring(1)}) -#set($TreeName=$treeName.substring(0,1).toUpperCase() + ${treeName.substring(1)}) - ztree.setId(${className}.get${TreeCode}()); - ztree.setpId(${className}.get${TreeParentCode}()); - ztree.setName(${className}.get${TreeName}()); - ztree.setTitle(${className}.get${TreeName}()); - ztrees.add(ztree); - } - return ztrees; - } -#end -} +package ${packageName}.service.impl; + +import java.util.List; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +#if($table.tree) +import java.util.ArrayList; +import com.ruoyi.common.core.domain.Ztree; +#end +#foreach ($column in $columns) +#if($column.javaField == 'createTime' || $column.javaField == 'updateTime') +import com.ruoyi.common.utils.DateUtils; +#break +#end +#end +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import ${packageName}.mapper.${ClassName}Mapper; +import ${packageName}.domain.${ClassName}; +import ${packageName}.service.I${ClassName}Service; +import com.ruoyi.common.core.text.Convert; + +/** + * ${functionName}Service业务层处理 + * + * @author ${author} + * @date ${datetime} + */ +@Service +public class ${ClassName}ServiceImpl implements I${ClassName}Service +{ + @Autowired + private ${ClassName}Mapper ${className}Mapper; + @Autowired + private ${ClassName}Repository ${className}Repository; + + public Page<${ClassName}> findByPage(${className}, Pageable pageable){ + + } + + /** + * 查询${functionName} + * + * @param ${pkColumn.javaField} ${functionName}ID + * @return ${functionName} + */ + @Override + public ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}) + { + return ${className}Mapper.select${ClassName}ById(${pkColumn.javaField}); + } + + /** + * 查询${functionName}列表 + * + * @param ${className} ${functionName} + * @return ${functionName} + */ + @Override + public List<${ClassName}> select${ClassName}List(${ClassName} ${className}) + { + return ${className}Mapper.select${ClassName}List(${className}); + } + + /** + * 新增${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + @Override + public int insert${ClassName}(${ClassName} ${className}) + { +#foreach ($column in $columns) +#if($column.javaField == 'createTime') + ${className}.setCreateTime(DateUtils.getNowDate()); +#end +#end + return ${className}Mapper.insert${ClassName}(${className}); + } + + /** + * 修改${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + @Override + public int update${ClassName}(${ClassName} ${className}) + { +#foreach ($column in $columns) +#if($column.javaField == 'updateTime') + ${className}.setUpdateTime(DateUtils.getNowDate()); +#end +#end + return ${className}Mapper.update${ClassName}(${className}); + } + + /** + * 删除${functionName}对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int delete${ClassName}ByIds(String ids) + { + return ${className}Mapper.delete${ClassName}ByIds(Convert.toStrArray(ids)); + } + + /** + * 删除${functionName}信息 + * + * @param ${pkColumn.javaField} ${functionName}ID + * @return 结果 + */ + @Override + public int delete${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}) + { + return ${className}Mapper.delete${ClassName}ById(${pkColumn.javaField}); + } +#if($table.tree) + + /** + * 查询${functionName}树列表 + * + * @return 所有${functionName}信息 + */ + @Override + public List select${ClassName}Tree() + { + List<${ClassName}> ${className}List = ${className}Mapper.select${ClassName}List(new ${ClassName}()); + List ztrees = new ArrayList(); + for (${ClassName} ${className} : ${className}List) + { + Ztree ztree = new Ztree(); +#set($TreeCode=$treeCode.substring(0,1).toUpperCase() + ${treeCode.substring(1)}) +#set($TreeParentCode=$treeParentCode.substring(0,1).toUpperCase() + ${treeParentCode.substring(1)}) +#set($TreeName=$treeName.substring(0,1).toUpperCase() + ${treeName.substring(1)}) + ztree.setId(${className}.get${TreeCode}()); + ztree.setpId(${className}.get${TreeParentCode}()); + ztree.setName(${className}.get${TreeName}()); + ztree.setTitle(${className}.get${TreeName}()); + ztrees.add(ztree); + } + return ztrees; + } +#end +} From 8aa53ca11f9720423a6c5abcb077c3f78aec01a8 Mon Sep 17 00:00:00 2001 From: Quieter <2316696377@qq.com> Date: Mon, 14 Sep 2020 20:51:09 +0800 Subject: [PATCH 51/52] dependency --- business/pom.xml | 23 ----------------------- pom.xml | 1 - ruoyi-admin/pom.xml | 6 +++--- 3 files changed, 3 insertions(+), 27 deletions(-) delete mode 100644 business/pom.xml diff --git a/business/pom.xml b/business/pom.xml deleted file mode 100644 index 814edde33..000000000 --- a/business/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - ruoyi - com.ruoyi - 4.1.0 - - 4.0.0 - - business - - - - - - com.ruoyi - ruoyi-framework - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index 66f94d2a5..2493c9fa2 100644 --- a/pom.xml +++ b/pom.xml @@ -214,7 +214,6 @@ ruoyi-quartz ruoyi-generator ruoyi-common - business pom diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index b81d1950f..ad7345a68 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -55,13 +55,13 @@ springfox-swagger-ui
- + com.ruoyi - business + ruoyi-framework ${ruoyi.version} - + com.ruoyi From 6f4f2e204993036e3a9cc3c503a15886764b298e Mon Sep 17 00:00:00 2001 From: Quieter <2316696377@qq.com> Date: Mon, 14 Sep 2020 21:41:39 +0800 Subject: [PATCH 52/52] =?UTF-8?q?=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 36 ++++- ruoyi-admin/pom.xml | 11 ++ .../monitor/SysUserOnlineController.java | 7 +- ruoyi-common/pom.xml | 17 +++ .../core/controller/BaseController.java | 28 ---- .../ruoyi/framework/config/MyBatisConfig.java | 69 --------- .../system/service/ISysUserOnlineService.java | 6 +- .../impl/SysUserOnlineServiceImpl.java | 131 +++++++++--------- 8 files changed, 131 insertions(+), 174 deletions(-) delete mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java diff --git a/pom.xml b/pom.xml index a664b5332..d9ae53d8c 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,6 @@ 1.8 1.6.0 2.0.0 - 1.3.2 1.1.22 1.19 2.3.2 @@ -30,6 +29,7 @@ 1.3.3 3.17 1.7 + 4.2.1 @@ -202,6 +202,12 @@ ${ruoyi.version} + + com.querydsl + querydsl-jpa + ${querydsl.version} + + @@ -215,13 +221,31 @@ pom - - - - - + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + + process + + + target/generated-sources/java + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + com.querydsl + querydsl-apt + ${querydsl.version} + + + org.apache.maven.plugins maven-compiler-plugin diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 06a6028ce..94e6abf6f 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -79,6 +79,17 @@ ruoyi-generator + + org.flywaydb + flyway-core + + + + + com.fasterxml.jackson.datatype + jackson-datatype-hibernate5 + 2.10.1 + diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java index d9a09f0f2..4ba0eaeab 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java @@ -49,11 +49,8 @@ public class SysUserOnlineController extends BaseController @RequiresPermissions("monitor:online:list") @PostMapping("/list") @ResponseBody - public TableDataInfo list(SysUserOnline userOnline) - { - startPage(); - List list = userOnlineService.selectUserOnlineList(userOnline); - return getDataTable(list); + public TableDataInfo list(SysUserOnline userOnline) { + return getDataTable(userOnlineService.selectUserOnlineList(userOnline, getPageRequest())); } @RequiresPermissions(value = { "monitor:online:batchForceLogout", "monitor:online:forceLogout" }, logical = Logical.OR) diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index 5adbe2a15..31f7a433c 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -101,6 +101,23 @@ javax.servlet-api + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.projectlombok + lombok + + + + com.querydsl + querydsl-jpa + + \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java index 6adeffb47..69d4bf49c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java @@ -46,34 +46,6 @@ public class BaseController { }); } - /** - * 设置请求分页数据 - */ - protected void startPage() - { - PageDomain pageDomain = TableSupport.buildPageRequest(); - Integer pageNum = pageDomain.getPageNum(); - Integer pageSize = pageDomain.getPageSize(); - if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) - { - String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); - PageHelper.startPage(pageNum, pageSize, orderBy); - } - } - - /** - * 设置请求排序数据 - */ - protected void startOrderBy() - { - PageDomain pageDomain = TableSupport.buildPageRequest(); - if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) - { - String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); - PageHelper.orderBy(orderBy); - } - } - /** * 获取request */ diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java deleted file mode 100644 index 7a9d0ba2d..000000000 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ruoyi.framework.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.util.ClassUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -/** - * Mybatis支持*匹配扫描包 - * - * @author ruoyi - */ -@Configuration -public class MyBatisConfig { - @Autowired - private Environment env; - - static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; - - public static String setTypeAliasesPackage(String typeAliasesPackage) { - ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); - MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); - List allResult = new ArrayList(); - try { - for (String aliasesPackage : typeAliasesPackage.split(",")) { - List result = new ArrayList(); - aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX - + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; - Resource[] resources = resolver.getResources(aliasesPackage); - if (resources != null && resources.length > 0) { - MetadataReader metadataReader = null; - for (Resource resource : resources) { - if (resource.isReadable()) { - metadataReader = metadataReaderFactory.getMetadataReader(resource); - try { - result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - } - } - if (result.size() > 0) { - HashSet hashResult = new HashSet(result); - allResult.addAll(hashResult); - } - } - if (allResult.size() > 0) { - typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); - } else { - throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return typeAliasesPackage; - } -} \ No newline at end of file diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java index 50c99a1cb..7b1a87cc5 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserOnlineService.java @@ -3,6 +3,8 @@ package com.ruoyi.system.service; import java.util.Date; import java.util.List; import com.ruoyi.system.domain.SysUserOnline; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * 在线用户 服务层 @@ -40,7 +42,7 @@ public interface ISysUserOnlineService * * @param online 会话信息 */ - public void saveOnline(SysUserOnline online); + public SysUserOnline saveOnline(SysUserOnline online); /** * 查询会话集合 @@ -48,7 +50,7 @@ public interface ISysUserOnlineService * @param userOnline 分页参数 * @return 会话集合 */ - public List selectUserOnlineList(SysUserOnline userOnline); + public Page selectUserOnlineList(SysUserOnline userOnline, Pageable pageable); /** * 强退用户 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java index c170d4258..dfbc043b3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java @@ -1,123 +1,128 @@ package com.ruoyi.system.service.impl; - -import java.io.Serializable; -import java.util.Date; -import java.util.Deque; -import java.util.List; +import com.ruoyi.common.base.BaseService; +import com.ruoyi.common.constant.ShiroConstants; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysUserOnline; +import com.ruoyi.system.repository.SysUserOnlineRepository; +import com.ruoyi.system.service.ISysUserOnlineService; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; -import com.ruoyi.common.constant.ShiroConstants; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.system.domain.SysUserOnline; -import com.ruoyi.system.mapper.SysUserOnlineMapper; -import com.ruoyi.system.service.ISysUserOnlineService; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.Deque; +import java.util.List; /** * 在线用户 服务层处理 - * + * * @author ruoyi */ @Service -public class SysUserOnlineServiceImpl implements ISysUserOnlineService -{ +public class SysUserOnlineServiceImpl extends BaseService implements ISysUserOnlineService { + @Autowired - private SysUserOnlineMapper userOnlineDao; - + private SysUserOnlineRepository sysUserOnlineRepository; @Autowired private EhCacheManager ehCacheManager; /** * 通过会话序号查询信息 - * + * * @param sessionId 会话ID * @return 在线用户信息 */ @Override - public SysUserOnline selectOnlineById(String sessionId) - { - return userOnlineDao.selectOnlineById(sessionId); + public SysUserOnline selectOnlineById(String sessionId) { + return sysUserOnlineRepository.findById(sessionId).orElse(null); } /** * 通过会话序号删除信息 - * + * * @param sessionId 会话ID * @return 在线用户信息 */ + @Transactional @Override - public void deleteOnlineById(String sessionId) - { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) - { - userOnlineDao.deleteOnlineById(sessionId); - } + public void deleteOnlineById(String sessionId) { + sysUserOnlineRepository.deleteById(sessionId); } /** * 通过会话序号删除信息 - * + * * @param sessions 会话ID集合 * @return 在线用户信息 */ + @Transactional @Override - public void batchDeleteOnline(List sessions) - { - for (String sessionId : sessions) - { - SysUserOnline userOnline = selectOnlineById(sessionId); - if (StringUtils.isNotNull(userOnline)) - { - userOnlineDao.deleteOnlineById(sessionId); - } + public void batchDeleteOnline(List sessions) { + for (String sessionId : sessions) { + deleteOnlineById(sessionId); } } /** * 保存会话信息 - * + * * @param online 会话信息 */ @Override - public void saveOnline(SysUserOnline online) - { - userOnlineDao.saveOnline(online); + public SysUserOnline saveOnline(SysUserOnline online) { + return sysUserOnlineRepository.save(online); } /** * 查询会话集合 - * + * * @param userOnline 在线用户 */ @Override - public List selectUserOnlineList(SysUserOnline userOnline) - { - return userOnlineDao.selectUserOnlineList(userOnline); + public Page selectUserOnlineList(SysUserOnline userOnline, Pageable pageable) { + return sysUserOnlineRepository.findAll(getSpecification(userOnline), pageable); + } + + private Specification getSpecification(SysUserOnline userOnline){ + return new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + List predicates = new ArrayList<>(); + if(StringUtils.isNotEmpty(userOnline.getIpaddr())){ + predicates.add(criteriaBuilder.like(root.get("ipaddr").as(String.class), "%" + userOnline.getIpaddr() + "%")); + } + if(StringUtils.isNotEmpty(userOnline.getLoginName())){ + predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + userOnline.getLoginName() + "%")); + } + return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); + } + }; } /** * 强退用户 - * + * * @param sessionId 会话ID */ + @Transactional @Override - public void forceLogout(String sessionId) - { - userOnlineDao.deleteOnlineById(sessionId); + public void forceLogout(String sessionId) { + deleteOnlineById(sessionId); } - /** - * 清理用户缓存 - * - * @param loginName 登录名称 - * @param sessionId 会话ID - */ @Override - public void removeUserCache(String loginName, String sessionId) - { + public void removeUserCache(String loginName, String sessionId) { Cache> cache = ehCacheManager.getCache(ShiroConstants.SYS_USERCACHE); Deque deque = cache.get(loginName); if (StringUtils.isEmpty(deque) || deque.size() == 0) @@ -129,13 +134,11 @@ public class SysUserOnlineServiceImpl implements ISysUserOnlineService /** * 查询会话集合 - * + * * @param expiredDate 失效日期 */ @Override - public List selectOnlineByExpired(Date expiredDate) - { - String lastAccessTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiredDate); - return userOnlineDao.selectOnlineByExpired(lastAccessTime); + public List selectOnlineByExpired(Date expiredDate) { + return sysUserOnlineRepository.findByLastAccessTimeLessThanEqual(expiredDate); } -} +} \ No newline at end of file