| New file |
| | |
| | | # These are supported funding model platforms |
| | | |
| | | github: # [user1, user2] |
| | | otechie: c9635b6fcfabfeed |
| | | custom: https://aurora-1255840532.cos.ap-chengdu.myqcloud.com/donation.png |
| New file |
| | |
| | | ### IDEA ### |
| | | .idea/* |
| | | *.iml |
| | | */target/* |
| | | */*.iml |
| | | /.gradle/ |
| | | /application.pid |
| New file |
| | |
| | | Apache License |
| | | Version 2.0, January 2004 |
| | | http://www.apache.org/licenses/ |
| | | |
| | | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
| | | |
| | | 1. Definitions. |
| | | |
| | | "License" shall mean the terms and conditions for use, reproduction, and |
| | | distribution as defined by Sections 1 through 9 of this document. |
| | | |
| | | "Licensor" shall mean the copyright owner or entity authorized by the copyright |
| | | owner that is granting the License. |
| | | |
| | | "Legal Entity" shall mean the union of the acting entity and all other entities |
| | | that control, are controlled by, or are under common control with that entity. |
| | | For the purposes of this definition, "control" means (i) the power, direct or |
| | | indirect, to cause the direction or management of such entity, whether by |
| | | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the |
| | | outstanding shares, or (iii) beneficial ownership of such entity. |
| | | |
| | | "You" (or "Your") shall mean an individual or Legal Entity exercising |
| | | permissions granted by this License. |
| | | |
| | | "Source" form shall mean the preferred form for making modifications, including |
| | | but not limited to software source code, documentation source, and configuration |
| | | files. |
| | | |
| | | "Object" form shall mean any form resulting from mechanical transformation or |
| | | translation of a Source form, including but not limited to compiled object code, |
| | | generated documentation, and conversions to other media types. |
| | | |
| | | "Work" shall mean the work of authorship, whether in Source or Object form, made |
| | | available under the License, as indicated by a copyright notice that is included |
| | | in or attached to the work (an example is provided in the Appendix below). |
| | | |
| | | "Derivative Works" shall mean any work, whether in Source or Object form, that |
| | | is based on (or derived from) the Work and for which the editorial revisions, |
| | | annotations, elaborations, or other modifications represent, as a whole, an |
| | | original work of authorship. For the purposes of this License, Derivative Works |
| | | shall not include works that remain separable from, or merely link (or bind by |
| | | name) to the interfaces of, the Work and Derivative Works thereof. |
| | | |
| | | "Contribution" shall mean any work of authorship, including the original version |
| | | of the Work and any modifications or additions to that Work or Derivative Works |
| | | thereof, that is intentionally submitted to Licensor for inclusion in the Work |
| | | by the copyright owner or by an individual or Legal Entity authorized to submit |
| | | on behalf of the copyright owner. For the purposes of this definition, |
| | | "submitted" means any form of electronic, verbal, or written communication sent |
| | | to the Licensor or its representatives, including but not limited to |
| | | communication on electronic mailing lists, source code control systems, and |
| | | issue tracking systems that are managed by, or on behalf of, the Licensor for |
| | | the purpose of discussing and improving the Work, but excluding communication |
| | | that is conspicuously marked or otherwise designated in writing by the copyright |
| | | owner as "Not a Contribution." |
| | | |
| | | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf |
| | | of whom a Contribution has been received by Licensor and subsequently |
| | | incorporated within the Work. |
| | | |
| | | 2. Grant of Copyright License. |
| | | |
| | | Subject to the terms and conditions of this License, each Contributor hereby |
| | | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, |
| | | irrevocable copyright license to reproduce, prepare Derivative Works of, |
| | | publicly display, publicly perform, sublicense, and distribute the Work and such |
| | | Derivative Works in Source or Object form. |
| | | |
| | | 3. Grant of Patent License. |
| | | |
| | | Subject to the terms and conditions of this License, each Contributor hereby |
| | | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, |
| | | irrevocable (except as stated in this section) patent license to make, have |
| | | made, use, offer to sell, sell, import, and otherwise transfer the Work, where |
| | | such license applies only to those patent claims licensable by such Contributor |
| | | that are necessarily infringed by their Contribution(s) alone or by combination |
| | | of their Contribution(s) with the Work to which such Contribution(s) was |
| | | submitted. If You institute patent litigation against any entity (including a |
| | | cross-claim or counterclaim in a lawsuit) alleging that the Work or a |
| | | Contribution incorporated within the Work constitutes direct or contributory |
| | | patent infringement, then any patent licenses granted to You under this License |
| | | for that Work shall terminate as of the date such litigation is filed. |
| | | |
| | | 4. Redistribution. |
| | | |
| | | You may reproduce and distribute copies of the Work or Derivative Works thereof |
| | | in any medium, with or without modifications, and in Source or Object form, |
| | | provided that You meet the following conditions: |
| | | |
| | | You must give any other recipients of the Work or Derivative Works a copy of |
| | | this License; and |
| | | You must cause any modified files to carry prominent notices stating that You |
| | | changed the files; and |
| | | You must retain, in the Source form of any Derivative Works that You distribute, |
| | | all copyright, patent, trademark, and attribution notices from the Source form |
| | | of the Work, excluding those notices that do not pertain to any part of the |
| | | Derivative Works; and |
| | | If the Work includes a "NOTICE" text file as part of its distribution, then any |
| | | Derivative Works that You distribute must include a readable copy of the |
| | | attribution notices contained within such NOTICE file, excluding those notices |
| | | that do not pertain to any part of the Derivative Works, in at least one of the |
| | | following places: within a NOTICE text file distributed as part of the |
| | | Derivative Works; within the Source form or documentation, if provided along |
| | | with the Derivative Works; or, within a display generated by the Derivative |
| | | Works, if and wherever such third-party notices normally appear. The contents of |
| | | the NOTICE file are for informational purposes only and do not modify the |
| | | License. You may add Your own attribution notices within Derivative Works that |
| | | You distribute, alongside or as an addendum to the NOTICE text from the Work, |
| | | provided that such additional attribution notices cannot be construed as |
| | | modifying the License. |
| | | You may add Your own copyright statement to Your modifications and may provide |
| | | additional or different license terms and conditions for use, reproduction, or |
| | | distribution of Your modifications, or for any such Derivative Works as a whole, |
| | | provided Your use, reproduction, and distribution of the Work otherwise complies |
| | | with the conditions stated in this License. |
| | | |
| | | 5. Submission of Contributions. |
| | | |
| | | Unless You explicitly state otherwise, any Contribution intentionally submitted |
| | | for inclusion in the Work by You to the Licensor shall be under the terms and |
| | | conditions of this License, without any additional terms or conditions. |
| | | Notwithstanding the above, nothing herein shall supersede or modify the terms of |
| | | any separate license agreement you may have executed with Licensor regarding |
| | | such Contributions. |
| | | |
| | | 6. Trademarks. |
| | | |
| | | This License does not grant permission to use the trade names, trademarks, |
| | | service marks, or product names of the Licensor, except as required for |
| | | reasonable and customary use in describing the origin of the Work and |
| | | reproducing the content of the NOTICE file. |
| | | |
| | | 7. Disclaimer of Warranty. |
| | | |
| | | Unless required by applicable law or agreed to in writing, Licensor provides the |
| | | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, |
| | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, |
| | | including, without limitation, any warranties or conditions of TITLE, |
| | | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are |
| | | solely responsible for determining the appropriateness of using or |
| | | redistributing the Work and assume any risks associated with Your exercise of |
| | | permissions under this License. |
| | | |
| | | 8. Limitation of Liability. |
| | | |
| | | In no event and under no legal theory, whether in tort (including negligence), |
| | | contract, or otherwise, unless required by applicable law (such as deliberate |
| | | and grossly negligent acts) or agreed to in writing, shall any Contributor be |
| | | liable to You for damages, including any direct, indirect, special, incidental, |
| | | or consequential damages of any character arising as a result of this License or |
| | | out of the use or inability to use the Work (including but not limited to |
| | | damages for loss of goodwill, work stoppage, computer failure or malfunction, or |
| | | any and all other commercial damages or losses), even if such Contributor has |
| | | been advised of the possibility of such damages. |
| | | |
| | | 9. Accepting Warranty or Additional Liability. |
| | | |
| | | While redistributing the Work or Derivative Works thereof, You may choose to |
| | | offer, and charge a fee for, acceptance of support, warranty, indemnity, or |
| | | other liability obligations and/or rights consistent with this License. However, |
| | | in accepting such obligations, You may act only on Your own behalf and on Your |
| | | sole responsibility, not on behalf of any other Contributor, and only if You |
| | | agree to indemnify, defend, and hold each Contributor harmless for any liability |
| | | incurred by, or claims asserted against, such Contributor by reason of your |
| | | accepting any such warranty or additional liability. |
| | | |
| | | END OF TERMS AND CONDITIONS |
| | | |
| | | APPENDIX: How to apply the Apache License to your work |
| | | |
| | | To apply the Apache License to your work, attach the following boilerplate |
| | | notice, with the fields enclosed by brackets "{}" replaced with your own |
| | | identifying information. (Don't include the brackets!) The text should be |
| | | enclosed in the appropriate comment syntax for the file format. We also |
| | | recommend that a file or class name and description of purpose be included on |
| | | the same "printed page" as the copyright notice for easier identification within |
| | | third-party archives. |
| | | |
| | | Copyright 2019-2020 Zheng Jie |
| | | |
| | | Licensed under the Apache License, Version 2.0 (the "License"); |
| | | you may not use this file except in compliance with the License. |
| | | You may obtain a copy of the License at |
| | | |
| | | http://www.apache.org/licenses/LICENSE-2.0 |
| | | |
| | | Unless required by applicable law or agreed to in writing, software |
| | | distributed under the License is distributed on an "AS IS" BASIS, |
| | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | See the License for the specific language governing permissions and |
| | | limitations under the License. |
| New file |
| | |
| | | <h1 style="text-align: center">ELADMIN 后台管理系统</h1> |
| | | <div style="text-align: center"> |
| | | |
| | | [](https://github.com/elunez/eladmin/blob/master/LICENSE) |
| | | [](https://gitee.com/elunez/eladmin) |
| | | [](https://github.com/elunez/eladmin) |
| | | [](https://github.com/elunez/eladmin) |
| | | |
| | | </div> |
| | | |
| | | #### 项目简介 |
| | | 一个基于 Spring Boot 2.1.0 、 Spring Boot Jpa、 JWT、Spring Security、Redis、Vue的前后端分离的后台管理系统 |
| | | |
| | | **开发文档:** [https://eladmin.vip](https://eladmin.vip) |
| | | |
| | | **体验地址:** [https://eladmin.vip/demo](https://eladmin.vip/demo) |
| | | |
| | | **账号密码:** `admin / 123456` |
| | | |
| | | #### 项目源码 |
| | | |
| | | | | 后端源码 | 前端源码 | |
| | | |--- |--- | --- | |
| | | | github | https://github.com/elunez/eladmin | https://github.com/elunez/eladmin-web | |
| | | | 码云 | https://gitee.com/elunez/eladmin | https://gitee.com/elunez/eladmin-web | |
| | | |
| | | #### 主要特性 |
| | | - 使用最新技术栈,社区资源丰富。 |
| | | - 高效率开发,代码生成器可一键生成前后端代码 |
| | | - 支持数据字典,可方便地对一些状态进行管理 |
| | | - 支持接口限流,避免恶意请求导致服务层压力过大 |
| | | - 支持接口级别的功能权限与数据权限,可自定义操作 |
| | | - 自定义权限注解与匿名接口注解,可快速对接口拦截与放行 |
| | | - 对一些常用地前端组件封装:表格数据请求、数据字典等 |
| | | - 前后端统一异常拦截处理,统一输出异常,避免繁琐的判断 |
| | | - 支持在线用户管理与服务器性能监控,支持限制单用户登录 |
| | | - 支持运维管理,可方便地对远程服务器的应用进行部署与管理 |
| | | |
| | | #### 系统功能 |
| | | - 用户管理:提供用户的相关配置,新增用户后,默认密码为123456 |
| | | - 角色管理:对权限与菜单进行分配,可根据部门设置角色的数据权限 |
| | | - 菜单管理:已实现菜单动态路由,后端可配置化,支持多级菜单 |
| | | - 部门管理:可配置系统组织架构,树形表格展示 |
| | | - 岗位管理:配置各个部门的职位 |
| | | - 字典管理:可维护常用一些固定的数据,如:状态,性别等 |
| | | - 系统日志:记录用户操作日志与异常日志,方便开发人员定位排错 |
| | | - SQL监控:采用druid 监控数据库访问性能,默认用户名admin,密码123456 |
| | | - 定时任务:整合Quartz做定时任务,加入任务日志,任务运行情况一目了然 |
| | | - 代码生成:高灵活度生成前后端代码,减少大量重复的工作任务 |
| | | - 邮件工具:配合富文本,发送html格式的邮件 |
| | | - 七牛云存储:可同步七牛云存储的数据到系统,无需登录七牛云直接操作云数据 |
| | | - 支付宝支付:整合了支付宝支付并且提供了测试账号,可自行测试 |
| | | - 服务监控:监控服务器的负载情况 |
| | | - 运维管理:一键部署你的应用 |
| | | |
| | | #### 项目结构 |
| | | 项目采用按功能分模块的开发方式,结构如下 |
| | | |
| | | - `eladmin-common` 为系统的公共模块,各种工具类,公共配置存在该模块 |
| | | |
| | | - `eladmin-system` 为系统核心模块也是项目入口模块,也是最终需要打包部署的模块 |
| | | |
| | | - `eladmin-logging` 为系统的日志模块,其他模块如果需要记录日志需要引入该模块 |
| | | |
| | | - `eladmin-tools` 为第三方工具模块,包含:图床、邮件、云存储、本地存储、支付宝 |
| | | |
| | | - `eladmin-generator` 为系统的代码生成模块,代码生成的模板在 system 模块中 |
| | | |
| | | #### 详细结构 |
| | | |
| | | ``` |
| | | - eladmin-common 公共模块 |
| | | - annotation 为系统自定义注解 |
| | | - aspect 自定义注解的切面 |
| | | - base 提供了Entity、DTO基类和mapstruct的通用mapper |
| | | - config 自定义权限实现、redis配置、swagger配置、Rsa配置等 |
| | | - exception 项目统一异常的处理 |
| | | - utils 系统通用工具类 |
| | | - eladmin-system 系统核心模块(系统启动入口) |
| | | - config 配置跨域与静态资源,与数据权限 |
| | | - thread 线程池相关 |
| | | - modules 系统相关模块(登录授权、系统监控、定时任务、运维管理等) |
| | | - eladmin-logging 系统日志模块 |
| | | - eladmin-tools 系统第三方工具模块 |
| | | - eladmin-generator 系统代码生成模块 |
| | | ``` |
| | | |
| | | #### 特别鸣谢 |
| | | |
| | | - 感谢 [七牛云](https://portal.qiniu.com/signup?utm_source=kaiyuan&utm_media=ELADMIN) 提供的免费云存储与CDN加速支持 |
| | | |
| | | - 感谢 [JetBrains](https://www.jetbrains.com/) 提供的非商业开源软件开发授权 |
| | | |
| | | - 感谢 [PanJiaChen](https://github.com/PanJiaChen/vue-element-admin) 大佬提供的前端模板 |
| | | |
| | | - 感谢 [Moxun](https://github.com/moxun1639) 大佬提供的前端 Curd 通用组件 |
| | | |
| | | - 感谢 [zhy6599](https://gitee.com/zhy6599) 大佬提供的后端运维管理相关功能 |
| | | |
| | | - 感谢 [j.yao.SUSE](https://github.com/everhopingandwaiting) 大佬提供的匿名接口与Redis限流等功能 |
| | | |
| | | - 感谢 [d15801543974](https://github.com/d15801543974) 大佬提供的基于注解的通用查询方式 |
| | | |
| | | #### 项目捐赠 |
| | | 项目的发展离不开你的支持,请作者喝杯咖啡吧☕ [Donate](https://eladmin.vip/donation/) |
| | | |
| | | #### 反馈交流 |
| | | - QQ交流群:一群:<strike>891137268</strike> 、二群:<strike>947578238</strike>、三群:659622532 |
| New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <project xmlns="http://maven.apache.org/POM/4.0.0" |
| | | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| | | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| | | <parent> |
| | | <artifactId>eladmin</artifactId> |
| | | <groupId>me.zhengjie</groupId> |
| | | <version>2.6</version> |
| | | </parent> |
| | | <modelVersion>4.0.0</modelVersion> |
| | | <properties> |
| | | <hutool.version>5.7.22</hutool.version> |
| | | </properties> |
| | | |
| | | <artifactId>eladmin-common</artifactId> |
| | | <name>公共模块</name> |
| | | |
| | | <dependencies> |
| | | <!--工具包--> |
| | | <dependency> |
| | | <groupId>cn.hutool</groupId> |
| | | <artifactId>hutool-all</artifactId> |
| | | <version>${hutool.version}</version> |
| | | </dependency> |
| | | </dependencies> |
| | | </project> |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.annotation; |
| | | |
| | | import java.lang.annotation.*; |
| | | |
| | | /** |
| | | * @author jacky |
| | | * 用于标记匿名访问方法 |
| | | */ |
| | | @Inherited |
| | | @Documented |
| | | @Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE}) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface AnonymousAccess { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.annotation; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * <p> |
| | | * 用于判断是否过滤数据权限 |
| | | * 1、如果没有用到 @OneToOne 这种关联关系,只需要填写 fieldName [参考:DeptQueryCriteria.class] |
| | | * 2、如果用到了 @OneToOne ,fieldName 和 joinName 都需要填写,拿UserQueryCriteria.class举例: |
| | | * 应该是 @DataPermission(joinName = "dept", fieldName = "id") |
| | | * </p> |
| | | * @author Zheng Jie |
| | | * @website https://eladmin.vip |
| | | * @date 2020-05-07 |
| | | **/ |
| | | @Target(ElementType.TYPE) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface DataPermission { |
| | | |
| | | /** |
| | | * Entity 中的字段名称 |
| | | */ |
| | | String fieldName() default ""; |
| | | |
| | | /** |
| | | * Entity 中与部门关联的字段名称 |
| | | */ |
| | | String joinName() default ""; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.annotation; |
| | | |
| | | import me.zhengjie.aspect.LimitType; |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * @author jacky |
| | | */ |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface Limit { |
| | | |
| | | // 资源名称,用于描述接口功能 |
| | | String name() default ""; |
| | | |
| | | // 资源 key |
| | | String key() default ""; |
| | | |
| | | // key prefix |
| | | String prefix() default ""; |
| | | |
| | | // 时间的,单位秒 |
| | | int period(); |
| | | |
| | | // 限制访问次数 |
| | | int count(); |
| | | |
| | | // 限制类型 |
| | | LimitType limitType() default LimitType.CUSTOMER; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.annotation; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-4 13:52:30 |
| | | */ |
| | | @Target(ElementType.FIELD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface Query { |
| | | |
| | | // Dong ZhaoYang 2017/8/7 基本对象的属性名 |
| | | String propName() default ""; |
| | | // Dong ZhaoYang 2017/8/7 查询方式 |
| | | Type type() default Type.EQUAL; |
| | | |
| | | /** |
| | | * 连接查询的属性名,如User类中的dept |
| | | */ |
| | | String joinName() default ""; |
| | | |
| | | /** |
| | | * 默认左连接 |
| | | */ |
| | | Join join() default Join.LEFT; |
| | | |
| | | /** |
| | | * 多字段模糊搜索,仅支持String类型字段,多个用逗号隔开, 如@Query(blurry = "email,username") |
| | | */ |
| | | String blurry() default ""; |
| | | |
| | | enum Type { |
| | | // jie 2019/6/4 相等 |
| | | EQUAL |
| | | // Dong ZhaoYang 2017/8/7 大于等于 |
| | | , GREATER_THAN |
| | | // Dong ZhaoYang 2017/8/7 小于等于 |
| | | , LESS_THAN |
| | | // Dong ZhaoYang 2017/8/7 中模糊查询 |
| | | , INNER_LIKE |
| | | // Dong ZhaoYang 2017/8/7 左模糊查询 |
| | | , LEFT_LIKE |
| | | // Dong ZhaoYang 2017/8/7 右模糊查询 |
| | | , RIGHT_LIKE |
| | | // Dong ZhaoYang 2017/8/7 小于 |
| | | , LESS_THAN_NQ |
| | | // jie 2019/6/4 包含 |
| | | , IN |
| | | // 不包含 |
| | | , NOT_IN |
| | | // 不等于 |
| | | ,NOT_EQUAL |
| | | // between |
| | | ,BETWEEN |
| | | // 不为空 |
| | | ,NOT_NULL |
| | | // 为空 |
| | | ,IS_NULL |
| | | } |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询 |
| | | */ |
| | | enum Join { |
| | | /** jie 2019-6-4 13:18:30 */ |
| | | LEFT, RIGHT, INNER |
| | | } |
| | | |
| | | } |
| | | |
| New file |
| | |
| | | /* |
| | | * Copyright 2002-2016 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.annotation.rest; |
| | | |
| | | 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 me.zhengjie.annotation.AnonymousAccess; |
| | | import org.springframework.core.annotation.AliasFor; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | |
| | | /** |
| | | * Annotation for mapping HTTP {@code DELETE} requests onto specific handler |
| | | * methods. |
| | | * 支持匿名访问 DeleteMapping |
| | | * |
| | | * @author liaojinlong |
| | | * @see AnonymousGetMapping |
| | | * @see AnonymousPostMapping |
| | | * @see AnonymousPutMapping |
| | | * @see AnonymousPatchMapping |
| | | * @see RequestMapping |
| | | */ |
| | | @AnonymousAccess |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | @Documented |
| | | @RequestMapping(method = RequestMethod.DELETE) |
| | | public @interface AnonymousDeleteMapping { |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#name}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String name() default ""; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#value}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] value() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#path}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] path() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#params}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] params() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#headers}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] headers() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#consumes}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] consumes() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#produces}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] produces() default {}; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2002-2016 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.annotation.rest; |
| | | |
| | | 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 me.zhengjie.annotation.AnonymousAccess; |
| | | import org.springframework.core.annotation.AliasFor; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | |
| | | /** |
| | | * Annotation for mapping HTTP {@code GET} requests onto specific handler |
| | | * methods. |
| | | * <p> |
| | | * 支持匿名访问 GetMapping |
| | | * |
| | | * @author liaojinlong |
| | | * @see RequestMapping |
| | | */ |
| | | @AnonymousAccess |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | @Documented |
| | | @RequestMapping(method = RequestMethod.GET) |
| | | public @interface AnonymousGetMapping { |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#name}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String name() default ""; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#value}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] value() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#path}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] path() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#params}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] params() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#headers}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] headers() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#consumes}. |
| | | * |
| | | * @since 4.3.5 |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] consumes() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#produces}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] produces() default {}; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2002-2016 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.annotation.rest; |
| | | |
| | | 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 me.zhengjie.annotation.AnonymousAccess; |
| | | import org.springframework.core.annotation.AliasFor; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | |
| | | /** |
| | | * Annotation for mapping HTTP {@code PATCH} requests onto specific handler |
| | | * methods. |
| | | * * 支持匿名访问 PatchMapping |
| | | * |
| | | * @author liaojinlong |
| | | * @see AnonymousGetMapping |
| | | * @see AnonymousPostMapping |
| | | * @see AnonymousPutMapping |
| | | * @see AnonymousDeleteMapping |
| | | * @see RequestMapping |
| | | */ |
| | | @AnonymousAccess |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | @Documented |
| | | @RequestMapping(method = RequestMethod.PATCH) |
| | | public @interface AnonymousPatchMapping { |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#name}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String name() default ""; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#value}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] value() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#path}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] path() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#params}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] params() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#headers}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] headers() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#consumes}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] consumes() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#produces}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] produces() default {}; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2002-2016 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.annotation.rest; |
| | | |
| | | 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 me.zhengjie.annotation.AnonymousAccess; |
| | | import org.springframework.core.annotation.AliasFor; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | |
| | | /** |
| | | * Annotation for mapping HTTP {@code POST} requests onto specific handler |
| | | * methods. |
| | | * 支持匿名访问 PostMapping |
| | | * |
| | | * @author liaojinlong |
| | | * @see AnonymousGetMapping |
| | | * @see AnonymousPostMapping |
| | | * @see AnonymousPutMapping |
| | | * @see AnonymousDeleteMapping |
| | | * @see RequestMapping |
| | | */ |
| | | @AnonymousAccess |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | @Documented |
| | | @RequestMapping(method = RequestMethod.POST) |
| | | public @interface AnonymousPostMapping { |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#name}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String name() default ""; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#value}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] value() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#path}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] path() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#params}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] params() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#headers}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] headers() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#consumes}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] consumes() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#produces}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] produces() default {}; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2002-2016 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.annotation.rest; |
| | | |
| | | 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 me.zhengjie.annotation.AnonymousAccess; |
| | | import org.springframework.core.annotation.AliasFor; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | |
| | | /** |
| | | * Annotation for mapping HTTP {@code PUT} requests onto specific handler |
| | | * methods. |
| | | * * 支持匿名访问 PutMapping |
| | | * |
| | | * @author liaojinlong |
| | | * @see AnonymousGetMapping |
| | | * @see AnonymousPostMapping |
| | | * @see AnonymousPutMapping |
| | | * @see AnonymousDeleteMapping |
| | | * @see RequestMapping |
| | | */ |
| | | @AnonymousAccess |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | @Documented |
| | | @RequestMapping(method = RequestMethod.PUT) |
| | | public @interface AnonymousPutMapping { |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#name}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String name() default ""; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#value}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] value() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#path}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] path() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#params}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] params() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#headers}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] headers() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#consumes}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] consumes() default {}; |
| | | |
| | | /** |
| | | * Alias for {@link RequestMapping#produces}. |
| | | */ |
| | | @AliasFor(annotation = RequestMapping.class) |
| | | String[] produces() default {}; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.aspect; |
| | | |
| | | import com.google.common.collect.ImmutableList; |
| | | import me.zhengjie.annotation.Limit; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.utils.RequestHolder; |
| | | import me.zhengjie.utils.StringUtils; |
| | | 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.data.redis.core.RedisTemplate; |
| | | import org.springframework.data.redis.core.script.DefaultRedisScript; |
| | | import org.springframework.data.redis.core.script.RedisScript; |
| | | import org.springframework.stereotype.Component; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.lang.reflect.Method; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @Aspect |
| | | @Component |
| | | public class LimitAspect { |
| | | |
| | | private final RedisTemplate<Object,Object> redisTemplate; |
| | | private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class); |
| | | |
| | | public LimitAspect(RedisTemplate<Object,Object> redisTemplate) { |
| | | this.redisTemplate = redisTemplate; |
| | | } |
| | | |
| | | @Pointcut("@annotation(me.zhengjie.annotation.Limit)") |
| | | public void pointcut() { |
| | | } |
| | | |
| | | @Around("pointcut()") |
| | | public Object around(ProceedingJoinPoint joinPoint) throws Throwable { |
| | | HttpServletRequest request = RequestHolder.getHttpServletRequest(); |
| | | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); |
| | | Method signatureMethod = signature.getMethod(); |
| | | Limit limit = signatureMethod.getAnnotation(Limit.class); |
| | | LimitType limitType = limit.limitType(); |
| | | String key = limit.key(); |
| | | if (StringUtils.isEmpty(key)) { |
| | | if (limitType == LimitType.IP) { |
| | | key = StringUtils.getIp(request); |
| | | } else { |
| | | key = signatureMethod.getName(); |
| | | } |
| | | } |
| | | |
| | | ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replace("/","_"))); |
| | | |
| | | String luaScript = buildLuaScript(); |
| | | RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); |
| | | Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period()); |
| | | if (null != count && count.intValue() <= limit.count()) { |
| | | logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name()); |
| | | return joinPoint.proceed(); |
| | | } else { |
| | | throw new BadRequestException("访问次数受限制"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 限流脚本 |
| | | */ |
| | | private String buildLuaScript() { |
| | | return "local c" + |
| | | "\nc = redis.call('get',KEYS[1])" + |
| | | "\nif c and tonumber(c) > tonumber(ARGV[1]) then" + |
| | | "\nreturn c;" + |
| | | "\nend" + |
| | | "\nc = redis.call('incr',KEYS[1])" + |
| | | "\nif tonumber(c) == 1 then" + |
| | | "\nredis.call('expire',KEYS[1],ARGV[2])" + |
| | | "\nend" + |
| | | "\nreturn c;"; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.aspect; |
| | | |
| | | /** |
| | | * 限流枚举 |
| | | * @author / |
| | | */ |
| | | public enum LimitType { |
| | | // 默认 |
| | | CUSTOMER, |
| | | // by ip addr |
| | | IP |
| | | } |
| New file |
| | |
| | | package me.zhengjie.base; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import org.apache.commons.lang3.builder.ToStringBuilder; |
| | | import java.io.Serializable; |
| | | import java.lang.reflect.Field; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019年10月24日20:48:53 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class BaseDTO implements Serializable { |
| | | |
| | | private String createBy; |
| | | |
| | | private String updateBy; |
| | | |
| | | private Timestamp createTime; |
| | | |
| | | private Timestamp updateTime; |
| | | |
| | | @Override |
| | | public String toString() { |
| | | ToStringBuilder builder = new ToStringBuilder(this); |
| | | Field[] fields = this.getClass().getDeclaredFields(); |
| | | try { |
| | | for (Field f : fields) { |
| | | f.setAccessible(true); |
| | | builder.append(f.getName(), f.get(this)).append("\n"); |
| | | } |
| | | } catch (Exception e) { |
| | | builder.append("toString builder encounter an error"); |
| | | } |
| | | return builder.toString(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.base; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import org.apache.commons.lang3.builder.ToStringBuilder; |
| | | import org.hibernate.annotations.CreationTimestamp; |
| | | import org.hibernate.annotations.UpdateTimestamp; |
| | | import org.springframework.data.annotation.CreatedBy; |
| | | import org.springframework.data.annotation.LastModifiedBy; |
| | | import org.springframework.data.jpa.domain.support.AuditingEntityListener; |
| | | import javax.persistence.Column; |
| | | import javax.persistence.EntityListeners; |
| | | import javax.persistence.MappedSuperclass; |
| | | import java.io.Serializable; |
| | | import java.lang.reflect.Field; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * 通用字段, is_del 根据需求自行添加 |
| | | * @author Zheng Jie |
| | | * @Date 2019年10月24日20:46:32 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @MappedSuperclass |
| | | @EntityListeners(AuditingEntityListener.class) |
| | | public class BaseEntity implements Serializable { |
| | | |
| | | @CreatedBy |
| | | @Column(name = "create_by", updatable = false) |
| | | @ApiModelProperty(value = "创建人", hidden = true) |
| | | private String createBy; |
| | | |
| | | @LastModifiedBy |
| | | @Column(name = "update_by") |
| | | @ApiModelProperty(value = "更新人", hidden = true) |
| | | private String updateBy; |
| | | |
| | | @CreationTimestamp |
| | | @Column(name = "create_time", updatable = false) |
| | | @ApiModelProperty(value = "创建时间", hidden = true) |
| | | private Timestamp createTime; |
| | | |
| | | @UpdateTimestamp |
| | | @Column(name = "update_time") |
| | | @ApiModelProperty(value = "更新时间", hidden = true) |
| | | private Timestamp updateTime; |
| | | |
| | | /* 分组校验 */ |
| | | public @interface Create {} |
| | | |
| | | /* 分组校验 */ |
| | | public @interface Update {} |
| | | |
| | | @Override |
| | | public String toString() { |
| | | ToStringBuilder builder = new ToStringBuilder(this); |
| | | Field[] fields = this.getClass().getDeclaredFields(); |
| | | try { |
| | | for (Field f : fields) { |
| | | f.setAccessible(true); |
| | | builder.append(f.getName(), f.get(this)).append("\n"); |
| | | } |
| | | } catch (Exception e) { |
| | | builder.append("toString builder encounter an error"); |
| | | } |
| | | return builder.toString(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.base; |
| | | |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | public interface BaseMapper<D, E> { |
| | | |
| | | /** |
| | | * DTO转Entity |
| | | * @param dto / |
| | | * @return / |
| | | */ |
| | | E toEntity(D dto); |
| | | |
| | | /** |
| | | * Entity转DTO |
| | | * @param entity / |
| | | * @return / |
| | | */ |
| | | D toDto(E entity); |
| | | |
| | | /** |
| | | * DTO集合转Entity集合 |
| | | * @param dtoList / |
| | | * @return / |
| | | */ |
| | | List <E> toEntity(List<D> dtoList); |
| | | |
| | | /** |
| | | * Entity集合转DTO集合 |
| | | * @param entityList / |
| | | * @return / |
| | | */ |
| | | List <D> toDto(List<E> entityList); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import org.springframework.data.domain.AuditorAware; |
| | | import org.springframework.stereotype.Component; |
| | | import java.util.Optional; |
| | | |
| | | /** |
| | | * @description : 设置审计 |
| | | * @author : Dong ZhaoYang |
| | | * @date : 2019/10/28 |
| | | */ |
| | | @Component("auditorAware") |
| | | public class AuditorConfig implements AuditorAware<String> { |
| | | |
| | | /** |
| | | * 返回操作员标志信息 |
| | | * |
| | | * @return / |
| | | */ |
| | | @Override |
| | | public Optional<String> getCurrentAuditor() { |
| | | try { |
| | | // 这里应根据实际业务情况获取具体信息 |
| | | return Optional.of(SecurityUtils.getCurrentUsername()); |
| | | }catch (Exception ignored){} |
| | | // 用户定时任务,或者无Token调用的情况 |
| | | return Optional.of("System"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @description |
| | | * @date 2021-11-22 |
| | | **/ |
| | | @Data |
| | | @Component |
| | | public class ElAdminProperties { |
| | | |
| | | public static Boolean ipLocal; |
| | | |
| | | @Value("${ip.local-parsing}") |
| | | public void setIpLocal(Boolean ipLocal) { |
| | | ElAdminProperties.ipLocal = ipLocal; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import org.springframework.security.core.GrantedAuthority; |
| | | import org.springframework.stereotype.Service; |
| | | import java.util.Arrays; |
| | | import java.util.List; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Service(value = "el") |
| | | public class ElPermissionConfig { |
| | | |
| | | public Boolean check(String ...permissions){ |
| | | // 获取当前用户的所有权限 |
| | | List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); |
| | | // 判断当前用户的所有权限是否包含接口上定义的权限 |
| | | return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.utils.ElAdminConstant; |
| | | import org.springframework.boot.context.properties.ConfigurationProperties; |
| | | import org.springframework.context.annotation.Configuration; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Data |
| | | @Configuration |
| | | @ConfigurationProperties(prefix = "file") |
| | | public class FileProperties { |
| | | |
| | | /** 文件大小限制 */ |
| | | private Long maxSize; |
| | | |
| | | /** 头像大小限制 */ |
| | | private Long avatarMaxSize; |
| | | |
| | | private ElPath mac; |
| | | |
| | | private ElPath linux; |
| | | |
| | | private ElPath windows; |
| | | |
| | | public ElPath getPath(){ |
| | | String os = System.getProperty("os.name"); |
| | | if(os.toLowerCase().startsWith(ElAdminConstant.WIN)) { |
| | | return windows; |
| | | } else if(os.toLowerCase().startsWith(ElAdminConstant.MAC)){ |
| | | return mac; |
| | | } |
| | | return linux; |
| | | } |
| | | |
| | | @Data |
| | | public static class ElPath{ |
| | | |
| | | private String path; |
| | | |
| | | private String avatar; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import cn.hutool.core.lang.Assert; |
| | | import com.alibaba.fastjson.JSON; |
| | | import com.alibaba.fastjson.parser.ParserConfig; |
| | | import com.alibaba.fastjson.serializer.SerializerFeature; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.apache.commons.codec.digest.DigestUtils; |
| | | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; |
| | | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
| | | import org.springframework.boot.autoconfigure.data.redis.RedisProperties; |
| | | import org.springframework.boot.context.properties.EnableConfigurationProperties; |
| | | import org.springframework.cache.Cache; |
| | | import org.springframework.cache.annotation.CachingConfigurerSupport; |
| | | import org.springframework.cache.annotation.EnableCaching; |
| | | import org.springframework.cache.interceptor.CacheErrorHandler; |
| | | import org.springframework.cache.interceptor.KeyGenerator; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.data.redis.cache.RedisCacheConfiguration; |
| | | import org.springframework.data.redis.connection.RedisConnectionFactory; |
| | | import org.springframework.data.redis.core.RedisOperations; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.data.redis.serializer.RedisSerializationContext; |
| | | import org.springframework.data.redis.serializer.RedisSerializer; |
| | | import reactor.util.annotation.Nullable; |
| | | import java.nio.charset.Charset; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.time.Duration; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Slf4j |
| | | @Configuration |
| | | @EnableCaching |
| | | @ConditionalOnClass(RedisOperations.class) |
| | | @EnableConfigurationProperties(RedisProperties.class) |
| | | public class RedisConfig extends CachingConfigurerSupport { |
| | | |
| | | /** |
| | | * 设置 redis 数据默认过期时间,默认2小时 |
| | | * 设置@cacheable 序列化方式 |
| | | */ |
| | | @Bean |
| | | public RedisCacheConfiguration redisCacheConfiguration(){ |
| | | FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); |
| | | RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); |
| | | configuration = configuration.serializeValuesWith(RedisSerializationContext. |
| | | SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2)); |
| | | return configuration; |
| | | } |
| | | |
| | | @SuppressWarnings("all") |
| | | @Bean(name = "redisTemplate") |
| | | @ConditionalOnMissingBean(name = "redisTemplate") |
| | | public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { |
| | | RedisTemplate<Object, Object> template = new RedisTemplate<>(); |
| | | //序列化 |
| | | FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); |
| | | // value值的序列化采用fastJsonRedisSerializer |
| | | template.setValueSerializer(fastJsonRedisSerializer); |
| | | template.setHashValueSerializer(fastJsonRedisSerializer); |
| | | // fastjson 升级到 1.2.83 后需要指定序列化白名单 |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto"); |
| | | // 模块内的实体类 |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.mnt.domain"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain"); |
| | | // 模块内的 Dto |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.mnt.service.dto"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.service.dto"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.service.dto"); |
| | | ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto"); |
| | | // key的序列化采用StringRedisSerializer |
| | | template.setKeySerializer(new StringRedisSerializer()); |
| | | template.setHashKeySerializer(new StringRedisSerializer()); |
| | | template.setConnectionFactory(redisConnectionFactory); |
| | | return template; |
| | | } |
| | | |
| | | /** |
| | | * 自定义缓存key生成策略,默认将使用该策略 |
| | | */ |
| | | @Bean |
| | | @Override |
| | | public KeyGenerator keyGenerator() { |
| | | return (target, method, params) -> { |
| | | Map<String,Object> container = new HashMap<>(8); |
| | | Class<?> targetClassClass = target.getClass(); |
| | | // 类地址 |
| | | container.put("class",targetClassClass.toGenericString()); |
| | | // 方法名称 |
| | | container.put("methodName",method.getName()); |
| | | // 包名称 |
| | | container.put("package",targetClassClass.getPackage()); |
| | | // 参数列表 |
| | | for (int i = 0; i < params.length; i++) { |
| | | container.put(String.valueOf(i),params[i]); |
| | | } |
| | | // 转为JSON字符串 |
| | | String jsonString = JSON.toJSONString(container); |
| | | // 做SHA256 Hash计算,得到一个SHA256摘要作为Key |
| | | return DigestUtils.sha256Hex(jsonString); |
| | | }; |
| | | } |
| | | |
| | | @Bean |
| | | @Override |
| | | public CacheErrorHandler errorHandler() { |
| | | // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 |
| | | log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); |
| | | return new CacheErrorHandler() { |
| | | @Override |
| | | public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { |
| | | log.error("Redis occur handleCacheGetError:key -> [{}]", key, e); |
| | | } |
| | | |
| | | @Override |
| | | public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { |
| | | log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e); |
| | | } |
| | | |
| | | @Override |
| | | public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { |
| | | log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e); |
| | | } |
| | | |
| | | @Override |
| | | public void handleCacheClearError(RuntimeException e, Cache cache) { |
| | | log.error("Redis occur handleCacheClearError:", e); |
| | | } |
| | | }; |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * Value 序列化 |
| | | * |
| | | * @author / |
| | | * @param <T> |
| | | */ |
| | | class FastJsonRedisSerializer<T> implements RedisSerializer<T> { |
| | | |
| | | private final Class<T> clazz; |
| | | |
| | | FastJsonRedisSerializer(Class<T> clazz) { |
| | | super(); |
| | | this.clazz = clazz; |
| | | } |
| | | |
| | | @Override |
| | | public byte[] serialize(T t) { |
| | | if (t == null) { |
| | | return new byte[0]; |
| | | } |
| | | return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8); |
| | | } |
| | | |
| | | @Override |
| | | public T deserialize(byte[] bytes) { |
| | | if (bytes == null || bytes.length <= 0) { |
| | | return null; |
| | | } |
| | | String str = new String(bytes, StandardCharsets.UTF_8); |
| | | return JSON.parseObject(str, clazz); |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * 重写序列化器 |
| | | * |
| | | * @author / |
| | | */ |
| | | class StringRedisSerializer implements RedisSerializer<Object> { |
| | | |
| | | private final Charset charset; |
| | | |
| | | StringRedisSerializer() { |
| | | this(StandardCharsets.UTF_8); |
| | | } |
| | | |
| | | private StringRedisSerializer(Charset charset) { |
| | | Assert.notNull(charset, "Charset must not be null!"); |
| | | this.charset = charset; |
| | | } |
| | | |
| | | @Override |
| | | public String deserialize(byte[] bytes) { |
| | | return (bytes == null ? null : new String(bytes, charset)); |
| | | } |
| | | |
| | | @Override |
| | | public @Nullable byte[] serialize(Object object) { |
| | | String string = JSON.toJSONString(object); |
| | | |
| | | if (org.apache.commons.lang3.StringUtils.isBlank(string)) { |
| | | return null; |
| | | } |
| | | string = string.replace("\"", ""); |
| | | return string.getBytes(charset); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import lombok.Data; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @website https://eladmin.vip |
| | | * @description |
| | | * @date 2020-05-18 |
| | | **/ |
| | | @Data |
| | | @Component |
| | | public class RsaProperties { |
| | | |
| | | public static String privateKey; |
| | | |
| | | @Value("${rsa.private_key}") |
| | | public void setPrivateKey(String privateKey) { |
| | | RsaProperties.privateKey = privateKey; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import com.fasterxml.classmate.TypeResolver; |
| | | import io.swagger.annotations.ApiModel; |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Data; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.core.Ordered; |
| | | import org.springframework.data.domain.Pageable; |
| | | import springfox.documentation.builders.ApiInfoBuilder; |
| | | import springfox.documentation.builders.PathSelectors; |
| | | import springfox.documentation.schema.AlternateTypeRule; |
| | | import springfox.documentation.schema.AlternateTypeRuleConvention; |
| | | import springfox.documentation.service.ApiInfo; |
| | | import springfox.documentation.service.ApiKey; |
| | | import springfox.documentation.service.AuthorizationScope; |
| | | import springfox.documentation.service.SecurityReference; |
| | | import springfox.documentation.service.SecurityScheme; |
| | | import springfox.documentation.spi.DocumentationType; |
| | | import springfox.documentation.spi.service.contexts.SecurityContext; |
| | | import springfox.documentation.spring.web.plugins.Docket; |
| | | import springfox.documentation.swagger2.annotations.EnableSwagger2; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import static springfox.documentation.schema.AlternateTypeRules.newRule; |
| | | |
| | | /** |
| | | * api页面 /doc.html |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Configuration |
| | | @EnableSwagger2 |
| | | public class SwaggerConfig { |
| | | |
| | | @Value("${jwt.header}") |
| | | private String tokenHeader; |
| | | |
| | | @Value("${swagger.enabled}") |
| | | private Boolean enabled; |
| | | |
| | | @Bean |
| | | @SuppressWarnings("all") |
| | | public Docket createRestApi() { |
| | | return new Docket(DocumentationType.SWAGGER_2) |
| | | .enable(enabled) |
| | | .pathMapping("/") |
| | | .apiInfo(apiInfo()) |
| | | .select() |
| | | .paths(PathSelectors.regex("^(?!/error).*")) |
| | | .paths(PathSelectors.any()) |
| | | .build() |
| | | //添加登陆认证 |
| | | .securitySchemes(securitySchemes()) |
| | | .securityContexts(securityContexts()); |
| | | } |
| | | |
| | | private ApiInfo apiInfo() { |
| | | return new ApiInfoBuilder() |
| | | .description("一个简单且易上手的 Spring boot 后台管理框架") |
| | | .title("ELADMIN 接口文档") |
| | | .version("2.6") |
| | | .build(); |
| | | } |
| | | |
| | | private List<SecurityScheme> securitySchemes() { |
| | | //设置请求头信息 |
| | | List<SecurityScheme> securitySchemes = new ArrayList<>(); |
| | | ApiKey apiKey = new ApiKey(tokenHeader, tokenHeader, "header"); |
| | | securitySchemes.add(apiKey); |
| | | return securitySchemes; |
| | | } |
| | | |
| | | private List<SecurityContext> securityContexts() { |
| | | //设置需要登录认证的路径 |
| | | List<SecurityContext> securityContexts = new ArrayList<>(); |
| | | // ^(?!auth).*$ 表示所有包含auth的接口不需要使用securitySchemes即不需要带token |
| | | // ^标识开始 ()里是一子表达式 ?!/auth表示匹配不是/auth的位置,匹配上则添加请求头,注意路径已/开头 .表示任意字符 *表示前面的字符匹配多次 $标识结束 |
| | | securityContexts.add(getContextByPath()); |
| | | return securityContexts; |
| | | } |
| | | |
| | | private SecurityContext getContextByPath() { |
| | | return SecurityContext.builder() |
| | | .securityReferences(defaultAuth()) |
| | | .operationSelector(o->o.requestMappingPattern().matches("^(?!/auth).*$")) |
| | | .build(); |
| | | } |
| | | |
| | | private List<SecurityReference> defaultAuth() { |
| | | List<SecurityReference> securityReferences = new ArrayList<>(); |
| | | AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); |
| | | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; |
| | | authorizationScopes[0] = authorizationScope; |
| | | securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes)); |
| | | return securityReferences; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将Pageable转换展示在swagger中 |
| | | */ |
| | | @Configuration |
| | | class SwaggerDataConfig { |
| | | |
| | | @Bean |
| | | public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) { |
| | | return new AlternateTypeRuleConvention() { |
| | | @Override |
| | | public int getOrder() { |
| | | return Ordered.HIGHEST_PRECEDENCE; |
| | | } |
| | | |
| | | @Override |
| | | public List<AlternateTypeRule> rules() { |
| | | return CollUtil.newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class))); |
| | | } |
| | | }; |
| | | } |
| | | |
| | | @ApiModel |
| | | @Data |
| | | private static class Page { |
| | | @ApiModelProperty("页码 (0..N)") |
| | | private Integer page; |
| | | |
| | | @ApiModelProperty("每页显示的数目") |
| | | private Integer size; |
| | | |
| | | @ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc") |
| | | private List<String> sort; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception; |
| | | |
| | | /** |
| | | * 统一关于错误配置信息 异常 |
| | | * |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/10 18:06 |
| | | */ |
| | | public class BadConfigurationException extends RuntimeException { |
| | | /** |
| | | * Constructs a new runtime exception with {@code null} as its |
| | | * detail message. The cause is not initialized, and may subsequently be |
| | | * initialized by a call to {@link #initCause}. |
| | | */ |
| | | public BadConfigurationException() { |
| | | super(); |
| | | } |
| | | |
| | | /** |
| | | * Constructs a new runtime exception with the specified detail message. |
| | | * The cause is not initialized, and may subsequently be initialized by a |
| | | * call to {@link #initCause}. |
| | | * |
| | | * @param message the detail message. The detail message is saved for |
| | | * later retrieval by the {@link #getMessage()} method. |
| | | */ |
| | | public BadConfigurationException(String message) { |
| | | super(message); |
| | | } |
| | | |
| | | /** |
| | | * Constructs a new runtime exception with the specified detail message and |
| | | * cause. <p>Note that the detail message associated with |
| | | * {@code cause} is <i>not</i> automatically incorporated in |
| | | * this runtime exception's detail message. |
| | | * |
| | | * @param message the detail message (which is saved for later retrieval |
| | | * by the {@link #getMessage()} method). |
| | | * @param cause the cause (which is saved for later retrieval by the |
| | | * {@link #getCause()} method). (A {@code null} value is |
| | | * permitted, and indicates that the cause is nonexistent or |
| | | * unknown.) |
| | | * @since 1.4 |
| | | */ |
| | | public BadConfigurationException(String message, Throwable cause) { |
| | | super(message, cause); |
| | | } |
| | | |
| | | /** |
| | | * Constructs a new runtime exception with the specified cause and a |
| | | * detail message of {@code (cause==null ? null : cause.toString())} |
| | | * (which typically contains the class and detail message of |
| | | * {@code cause}). This constructor is useful for runtime exceptions |
| | | * that are little more than wrappers for other throwables. |
| | | * |
| | | * @param cause the cause (which is saved for later retrieval by the |
| | | * {@link #getCause()} method). (A {@code null} value is |
| | | * permitted, and indicates that the cause is nonexistent or |
| | | * unknown.) |
| | | * @since 1.4 |
| | | */ |
| | | public BadConfigurationException(Throwable cause) { |
| | | super(cause); |
| | | } |
| | | |
| | | /** |
| | | * Constructs a new runtime exception with the specified detail |
| | | * message, cause, suppression enabled or disabled, and writable |
| | | * stack trace enabled or disabled. |
| | | * |
| | | * @param message the detail message. |
| | | * @param cause the cause. (A {@code null} value is permitted, |
| | | * and indicates that the cause is nonexistent or unknown.) |
| | | * @param enableSuppression whether or not suppression is enabled |
| | | * or disabled |
| | | * @param writableStackTrace whether or not the stack trace should |
| | | * be writable |
| | | * @since 1.7 |
| | | */ |
| | | protected BadConfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { |
| | | super(message, cause, enableSuppression, writableStackTrace); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception; |
| | | |
| | | import lombok.Getter; |
| | | import org.springframework.http.HttpStatus; |
| | | import static org.springframework.http.HttpStatus.BAD_REQUEST; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | * 统一异常处理 |
| | | */ |
| | | @Getter |
| | | public class BadRequestException extends RuntimeException{ |
| | | |
| | | private Integer status = BAD_REQUEST.value(); |
| | | |
| | | public BadRequestException(String msg){ |
| | | super(msg); |
| | | } |
| | | |
| | | public BadRequestException(HttpStatus status,String msg){ |
| | | super(msg); |
| | | this.status = status.value(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception; |
| | | |
| | | import org.springframework.util.StringUtils; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | public class EntityExistException extends RuntimeException { |
| | | |
| | | public EntityExistException(Class clazz, String field, String val) { |
| | | super(EntityExistException.generateMessage(clazz.getSimpleName(), field, val)); |
| | | } |
| | | |
| | | private static String generateMessage(String entity, String field, String val) { |
| | | return StringUtils.capitalize(entity) |
| | | + " with " + field + " "+ val + " existed"; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception; |
| | | |
| | | import org.springframework.util.StringUtils; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | public class EntityNotFoundException extends RuntimeException { |
| | | |
| | | public EntityNotFoundException(Class clazz, String field, String val) { |
| | | super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), field, val)); |
| | | } |
| | | |
| | | private static String generateMessage(String entity, String field, String val) { |
| | | return StringUtils.capitalize(entity) |
| | | + " with " + field + " "+ val + " does not exist"; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception.handler; |
| | | |
| | | import com.fasterxml.jackson.annotation.JsonFormat; |
| | | import lombok.Data; |
| | | import java.time.LocalDateTime; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Data |
| | | class ApiError { |
| | | |
| | | private Integer status = 400; |
| | | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") |
| | | private LocalDateTime timestamp; |
| | | private String message; |
| | | |
| | | private ApiError() { |
| | | timestamp = LocalDateTime.now(); |
| | | } |
| | | |
| | | public static ApiError error(String message){ |
| | | ApiError apiError = new ApiError(); |
| | | apiError.setMessage(message); |
| | | return apiError; |
| | | } |
| | | |
| | | public static ApiError error(Integer status, String message){ |
| | | ApiError apiError = new ApiError(); |
| | | apiError.setStatus(status); |
| | | apiError.setMessage(message); |
| | | return apiError; |
| | | } |
| | | } |
| | | |
| | | |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.exception.handler; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.exception.EntityExistException; |
| | | import me.zhengjie.exception.EntityNotFoundException; |
| | | import me.zhengjie.utils.ThrowableUtil; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.authentication.BadCredentialsException; |
| | | import org.springframework.validation.FieldError; |
| | | import org.springframework.validation.ObjectError; |
| | | import org.springframework.web.bind.MethodArgumentNotValidException; |
| | | import org.springframework.web.bind.annotation.ExceptionHandler; |
| | | import org.springframework.web.bind.annotation.RestControllerAdvice; |
| | | import static org.springframework.http.HttpStatus.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Slf4j |
| | | @RestControllerAdvice |
| | | public class GlobalExceptionHandler { |
| | | |
| | | /** |
| | | * 处理所有不可知的异常 |
| | | */ |
| | | @ExceptionHandler(Throwable.class) |
| | | public ResponseEntity<ApiError> handleException(Throwable e){ |
| | | // 打印堆栈信息 |
| | | log.error(ThrowableUtil.getStackTrace(e)); |
| | | return buildResponseEntity(ApiError.error(e.getMessage())); |
| | | } |
| | | |
| | | /** |
| | | * BadCredentialsException |
| | | */ |
| | | @ExceptionHandler(BadCredentialsException.class) |
| | | public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){ |
| | | // 打印堆栈信息 |
| | | String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage(); |
| | | log.error(message); |
| | | return buildResponseEntity(ApiError.error(message)); |
| | | } |
| | | |
| | | /** |
| | | * 处理自定义异常 |
| | | */ |
| | | @ExceptionHandler(value = BadRequestException.class) |
| | | public ResponseEntity<ApiError> badRequestException(BadRequestException e) { |
| | | // 打印堆栈信息 |
| | | log.error(ThrowableUtil.getStackTrace(e)); |
| | | return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage())); |
| | | } |
| | | |
| | | /** |
| | | * 处理 EntityExist |
| | | */ |
| | | @ExceptionHandler(value = EntityExistException.class) |
| | | public ResponseEntity<ApiError> entityExistException(EntityExistException e) { |
| | | // 打印堆栈信息 |
| | | log.error(ThrowableUtil.getStackTrace(e)); |
| | | return buildResponseEntity(ApiError.error(e.getMessage())); |
| | | } |
| | | |
| | | /** |
| | | * 处理 EntityNotFound |
| | | */ |
| | | @ExceptionHandler(value = EntityNotFoundException.class) |
| | | public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) { |
| | | // 打印堆栈信息 |
| | | log.error(ThrowableUtil.getStackTrace(e)); |
| | | return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage())); |
| | | } |
| | | |
| | | /** |
| | | * 处理所有接口数据验证异常 |
| | | */ |
| | | @ExceptionHandler(MethodArgumentNotValidException.class) |
| | | public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ |
| | | // 打印堆栈信息 |
| | | log.error(ThrowableUtil.getStackTrace(e)); |
| | | ObjectError objectError = e.getBindingResult().getAllErrors().get(0); |
| | | String message = objectError.getDefaultMessage(); |
| | | if (objectError instanceof FieldError) { |
| | | message = ((FieldError) objectError).getField() + ": " + message; |
| | | } |
| | | return buildResponseEntity(ApiError.error(message)); |
| | | } |
| | | |
| | | /** |
| | | * 统一返回 |
| | | */ |
| | | private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) { |
| | | return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | /** |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/11 15:49 |
| | | * @apiNote: 关于缓存的Key集合 |
| | | */ |
| | | public interface CacheKey { |
| | | |
| | | /** |
| | | * 用户 |
| | | */ |
| | | String USER_ID = "user::id:"; |
| | | /** |
| | | * 数据 |
| | | */ |
| | | String DATA_USER = "data::user:"; |
| | | /** |
| | | * 菜单 |
| | | */ |
| | | String MENU_ID = "menu::id:"; |
| | | String MENU_USER = "menu::user:"; |
| | | /** |
| | | * 角色授权 |
| | | */ |
| | | String ROLE_AUTH = "role::auth:"; |
| | | /** |
| | | * 角色信息 |
| | | */ |
| | | String ROLE_ID = "role::id:"; |
| | | /** |
| | | * 部门 |
| | | */ |
| | | String DEPT_ID = "dept::id:"; |
| | | /** |
| | | * 岗位 |
| | | */ |
| | | String JOB_ID = "job::id:"; |
| | | /** |
| | | * 数据字典 |
| | | */ |
| | | String DICT_NAME = "dict::name:"; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.utils; |
| | | |
| | | /** |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/9 17:02 |
| | | * @since: 1.0 |
| | | * @see {@link SpringContextHolder} |
| | | * 针对某些初始化方法,在SpringContextHolder 初始化前时,<br> |
| | | * 可提交一个 提交回调任务。<br> |
| | | * 在SpringContextHolder 初始化后,进行回调使用 |
| | | */ |
| | | |
| | | public interface CallBack { |
| | | /** |
| | | * 回调执行方法 |
| | | */ |
| | | void executor(); |
| | | |
| | | /** |
| | | * 本回调任务名称 |
| | | * @return / |
| | | */ |
| | | default String getCallBackName() { |
| | | return Thread.currentThread().getId() + ":" + this.getClass().getName(); |
| | | } |
| | | } |
| | | |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import java.io.Closeable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @website https://eladmin.vip |
| | | * @description 用于关闭各种连接,缺啥补啥 |
| | | * @date 2021-03-05 |
| | | **/ |
| | | public class CloseUtil { |
| | | |
| | | public static void close(Closeable closeable) { |
| | | if (null != closeable) { |
| | | try { |
| | | closeable.close(); |
| | | } catch (Exception e) { |
| | | // 静默关闭 |
| | | } |
| | | } |
| | | } |
| | | |
| | | public static void close(AutoCloseable closeable) { |
| | | if (null != closeable) { |
| | | try { |
| | | closeable.close(); |
| | | } catch (Exception e) { |
| | | // 静默关闭 |
| | | } |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | |
| | | package me.zhengjie.utils; |
| | | |
| | | import java.time.*; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.Date; |
| | | |
| | | /** |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/11 16:28 |
| | | * @apiNote: JDK 8 新日期类 格式化与字符串转换 工具类 |
| | | */ |
| | | public class DateUtil { |
| | | |
| | | public static final DateTimeFormatter DFY_MD_HMS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| | | public static final DateTimeFormatter DFY_MD = DateTimeFormatter.ofPattern("yyyy-MM-dd"); |
| | | |
| | | /** |
| | | * LocalDateTime 转时间戳 |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static Long getTimeStamp(LocalDateTime localDateTime) { |
| | | return localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond(); |
| | | } |
| | | |
| | | /** |
| | | * 时间戳转LocalDateTime |
| | | * |
| | | * @param timeStamp / |
| | | * @return / |
| | | */ |
| | | public static LocalDateTime fromTimeStamp(Long timeStamp) { |
| | | return LocalDateTime.ofEpochSecond(timeStamp, 0, OffsetDateTime.now().getOffset()); |
| | | } |
| | | |
| | | /** |
| | | * LocalDateTime 转 Date |
| | | * Jdk8 后 不推荐使用 {@link Date} Date |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static Date toDate(LocalDateTime localDateTime) { |
| | | return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); |
| | | } |
| | | |
| | | /** |
| | | * LocalDate 转 Date |
| | | * Jdk8 后 不推荐使用 {@link Date} Date |
| | | * |
| | | * @param localDate / |
| | | * @return / |
| | | */ |
| | | public static Date toDate(LocalDate localDate) { |
| | | return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault()))); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * Date转 LocalDateTime |
| | | * Jdk8 后 不推荐使用 {@link Date} Date |
| | | * |
| | | * @param date / |
| | | * @return / |
| | | */ |
| | | public static LocalDateTime toLocalDateTime(Date date) { |
| | | return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); |
| | | } |
| | | |
| | | /** |
| | | * 日期 格式化 |
| | | * |
| | | * @param localDateTime / |
| | | * @param patten / |
| | | * @return / |
| | | */ |
| | | public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) { |
| | | DateTimeFormatter df = DateTimeFormatter.ofPattern(patten); |
| | | return df.format(localDateTime); |
| | | } |
| | | |
| | | /** |
| | | * 日期 格式化 |
| | | * |
| | | * @param localDateTime / |
| | | * @param df / |
| | | * @return / |
| | | */ |
| | | public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) { |
| | | return df.format(localDateTime); |
| | | } |
| | | |
| | | /** |
| | | * 日期格式化 yyyy-MM-dd HH:mm:ss |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) { |
| | | return DFY_MD_HMS.format(localDateTime); |
| | | } |
| | | |
| | | /** |
| | | * 日期格式化 yyyy-MM-dd |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public String localDateTimeFormatyMd(LocalDateTime localDateTime) { |
| | | return DFY_MD.format(localDateTime); |
| | | } |
| | | |
| | | /** |
| | | * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) { |
| | | DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); |
| | | return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); |
| | | } |
| | | |
| | | /** |
| | | * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) { |
| | | return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); |
| | | } |
| | | |
| | | /** |
| | | * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss |
| | | * |
| | | * @param localDateTime / |
| | | * @return / |
| | | */ |
| | | public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) { |
| | | return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | /** |
| | | * 常用静态常量 |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2018-12-26 |
| | | */ |
| | | public class ElAdminConstant { |
| | | |
| | | /** |
| | | * 用于IP定位转换 |
| | | */ |
| | | public static final String REGION = "内网IP|内网IP"; |
| | | /** |
| | | * win 系统 |
| | | */ |
| | | public static final String WIN = "win"; |
| | | |
| | | /** |
| | | * mac 系统 |
| | | */ |
| | | public static final String MAC = "mac"; |
| | | |
| | | /** |
| | | * 常用接口 |
| | | */ |
| | | public static class Url { |
| | | // IP归属地查询 |
| | | public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true"; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import javax.crypto.Cipher; |
| | | import javax.crypto.SecretKey; |
| | | import javax.crypto.SecretKeyFactory; |
| | | import javax.crypto.spec.DESKeySpec; |
| | | import javax.crypto.spec.IvParameterSpec; |
| | | import java.nio.charset.StandardCharsets; |
| | | |
| | | /** |
| | | * 加密 |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | |
| | | public class EncryptUtils { |
| | | |
| | | private static final String STR_PARAM = "Passw0rd"; |
| | | |
| | | private static Cipher cipher; |
| | | |
| | | private static final IvParameterSpec IV = new IvParameterSpec(STR_PARAM.getBytes(StandardCharsets.UTF_8)); |
| | | |
| | | private static DESKeySpec getDesKeySpec(String source) throws Exception { |
| | | if (source == null || source.length() == 0){ |
| | | return null; |
| | | } |
| | | cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); |
| | | String strKey = "Passw0rd"; |
| | | return new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8)); |
| | | } |
| | | |
| | | /** |
| | | * 对称加密 |
| | | */ |
| | | public static String desEncrypt(String source) throws Exception { |
| | | DESKeySpec desKeySpec = getDesKeySpec(source); |
| | | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); |
| | | SecretKey secretKey = keyFactory.generateSecret(desKeySpec); |
| | | cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV); |
| | | return byte2hex( |
| | | cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase(); |
| | | } |
| | | |
| | | /** |
| | | * 对称解密 |
| | | */ |
| | | public static String desDecrypt(String source) throws Exception { |
| | | byte[] src = hex2byte(source.getBytes(StandardCharsets.UTF_8)); |
| | | DESKeySpec desKeySpec = getDesKeySpec(source); |
| | | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); |
| | | SecretKey secretKey = keyFactory.generateSecret(desKeySpec); |
| | | cipher.init(Cipher.DECRYPT_MODE, secretKey, IV); |
| | | byte[] retByte = cipher.doFinal(src); |
| | | return new String(retByte); |
| | | } |
| | | |
| | | private static String byte2hex(byte[] inStr) { |
| | | String stmp; |
| | | StringBuilder out = new StringBuilder(inStr.length * 2); |
| | | for (byte b : inStr) { |
| | | stmp = Integer.toHexString(b & 0xFF); |
| | | if (stmp.length() == 1) { |
| | | // 如果是0至F的单位字符串,则添加0 |
| | | out.append("0").append(stmp); |
| | | } else { |
| | | out.append(stmp); |
| | | } |
| | | } |
| | | return out.toString(); |
| | | } |
| | | |
| | | private static byte[] hex2byte(byte[] b) { |
| | | int size = 2; |
| | | if ((b.length % size) != 0){ |
| | | throw new IllegalArgumentException("长度不是偶数"); |
| | | } |
| | | byte[] b2 = new byte[b.length / 2]; |
| | | for (int n = 0; n < b.length; n += size) { |
| | | String item = new String(b, n, 2); |
| | | b2[n / 2] = (byte) Integer.parseInt(item, 16); |
| | | } |
| | | return b2; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.core.io.IoUtil; |
| | | import cn.hutool.core.util.IdUtil; |
| | | import cn.hutool.poi.excel.BigExcelWriter; |
| | | import cn.hutool.poi.excel.ExcelUtil; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import org.apache.poi.util.IOUtils; |
| | | import org.apache.poi.xssf.streaming.SXSSFSheet; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import javax.servlet.ServletOutputStream; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.*; |
| | | import java.security.MessageDigest; |
| | | import java.text.DecimalFormat; |
| | | import java.text.SimpleDateFormat; |
| | | import java.util.Date; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * File工具类,扩展 hutool 工具包 |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2018-12-27 |
| | | */ |
| | | public class FileUtil extends cn.hutool.core.io.FileUtil { |
| | | |
| | | private static final Logger log = LoggerFactory.getLogger(FileUtil.class); |
| | | |
| | | /** |
| | | * 系统临时目录 |
| | | * <br> |
| | | * windows 包含路径分割符,但Linux 不包含, |
| | | * 在windows \\==\ 前提下, |
| | | * 为安全起见 同意拼装 路径分割符, |
| | | * <pre> |
| | | * java.io.tmpdir |
| | | * windows : C:\Users/xxx\AppData\Local\Temp\ |
| | | * linux: /temp |
| | | * </pre> |
| | | */ |
| | | public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator; |
| | | /** |
| | | * 定义GB的计算常量 |
| | | */ |
| | | private static final int GB = 1024 * 1024 * 1024; |
| | | /** |
| | | * 定义MB的计算常量 |
| | | */ |
| | | private static final int MB = 1024 * 1024; |
| | | /** |
| | | * 定义KB的计算常量 |
| | | */ |
| | | private static final int KB = 1024; |
| | | |
| | | /** |
| | | * 格式化小数 |
| | | */ |
| | | private static final DecimalFormat DF = new DecimalFormat("0.00"); |
| | | |
| | | public static final String IMAGE = "图片"; |
| | | public static final String TXT = "文档"; |
| | | public static final String MUSIC = "音乐"; |
| | | public static final String VIDEO = "视频"; |
| | | public static final String OTHER = "其他"; |
| | | |
| | | |
| | | /** |
| | | * MultipartFile转File |
| | | */ |
| | | public static File toFile(MultipartFile multipartFile) { |
| | | // 获取文件名 |
| | | String fileName = multipartFile.getOriginalFilename(); |
| | | // 获取文件后缀 |
| | | String prefix = "." + getExtensionName(fileName); |
| | | File file = null; |
| | | try { |
| | | // 用uuid作为文件名,防止生成的临时文件重复 |
| | | file = new File(SYS_TEM_DIR + IdUtil.simpleUUID() + prefix); |
| | | // MultipartFile to File |
| | | multipartFile.transferTo(file); |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return file; |
| | | } |
| | | |
| | | /** |
| | | * 获取文件扩展名,不带 . |
| | | */ |
| | | public static String getExtensionName(String filename) { |
| | | if ((filename != null) && (filename.length() > 0)) { |
| | | int dot = filename.lastIndexOf('.'); |
| | | if ((dot > -1) && (dot < (filename.length() - 1))) { |
| | | return filename.substring(dot + 1); |
| | | } |
| | | } |
| | | return filename; |
| | | } |
| | | |
| | | /** |
| | | * Java文件操作 获取不带扩展名的文件名 |
| | | */ |
| | | public static String getFileNameNoEx(String filename) { |
| | | if ((filename != null) && (filename.length() > 0)) { |
| | | int dot = filename.lastIndexOf('.'); |
| | | if ((dot > -1) && (dot < (filename.length()))) { |
| | | return filename.substring(0, dot); |
| | | } |
| | | } |
| | | return filename; |
| | | } |
| | | |
| | | /** |
| | | * 文件大小转换 |
| | | */ |
| | | public static String getSize(long size) { |
| | | String resultSize; |
| | | if (size / GB >= 1) { |
| | | //如果当前Byte的值大于等于1GB |
| | | resultSize = DF.format(size / (float) GB) + "GB "; |
| | | } else if (size / MB >= 1) { |
| | | //如果当前Byte的值大于等于1MB |
| | | resultSize = DF.format(size / (float) MB) + "MB "; |
| | | } else if (size / KB >= 1) { |
| | | //如果当前Byte的值大于等于1KB |
| | | resultSize = DF.format(size / (float) KB) + "KB "; |
| | | } else { |
| | | resultSize = size + "B "; |
| | | } |
| | | return resultSize; |
| | | } |
| | | |
| | | /** |
| | | * inputStream 转 File |
| | | */ |
| | | static File inputStreamToFile(InputStream ins, String name){ |
| | | File file = new File(SYS_TEM_DIR + name); |
| | | if (file.exists()) { |
| | | return file; |
| | | } |
| | | OutputStream os = null; |
| | | try { |
| | | os = new FileOutputStream(file); |
| | | int bytesRead; |
| | | int len = 8192; |
| | | byte[] buffer = new byte[len]; |
| | | while ((bytesRead = ins.read(buffer, 0, len)) != -1) { |
| | | os.write(buffer, 0, bytesRead); |
| | | } |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } finally { |
| | | CloseUtil.close(os); |
| | | CloseUtil.close(ins); |
| | | } |
| | | return file; |
| | | } |
| | | |
| | | /** |
| | | * 将文件名解析成文件的上传路径 |
| | | */ |
| | | public static File upload(MultipartFile file, String filePath) { |
| | | Date date = new Date(); |
| | | SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS"); |
| | | String name = getFileNameNoEx(file.getOriginalFilename()); |
| | | String suffix = getExtensionName(file.getOriginalFilename()); |
| | | String nowStr = "-" + format.format(date); |
| | | try { |
| | | String fileName = name + nowStr + "." + suffix; |
| | | String path = filePath + fileName; |
| | | // getCanonicalFile 可解析正确各种路径 |
| | | File dest = new File(path).getCanonicalFile(); |
| | | // 检测是否存在目录 |
| | | if (!dest.getParentFile().exists()) { |
| | | if (!dest.getParentFile().mkdirs()) { |
| | | System.out.println("was not successful."); |
| | | } |
| | | } |
| | | // 文件写入 |
| | | file.transferTo(dest); |
| | | return dest; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 导出excel |
| | | */ |
| | | public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException { |
| | | String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx"; |
| | | File file = new File(tempPath); |
| | | BigExcelWriter writer = ExcelUtil.getBigWriter(file); |
| | | // 一次性写出内容,使用默认样式,强制输出标题 |
| | | writer.write(list, true); |
| | | SXSSFSheet sheet = (SXSSFSheet)writer.getSheet(); |
| | | //上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法 |
| | | sheet.trackAllColumnsForAutoSizing(); |
| | | //列宽自适应 |
| | | writer.autoSizeColumnAll(); |
| | | //response为HttpServletResponse对象 |
| | | response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); |
| | | //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 |
| | | response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); |
| | | ServletOutputStream out = response.getOutputStream(); |
| | | // 终止后删除临时文件 |
| | | file.deleteOnExit(); |
| | | writer.flush(out, true); |
| | | //此处记得关闭输出Servlet流 |
| | | IoUtil.close(out); |
| | | } |
| | | |
| | | public static String getFileType(String type) { |
| | | String documents = "txt doc pdf ppt pps xlsx xls docx"; |
| | | String music = "mp3 wav wma mpa ram ra aac aif m4a"; |
| | | String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg"; |
| | | String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg"; |
| | | if (image.contains(type)) { |
| | | return IMAGE; |
| | | } else if (documents.contains(type)) { |
| | | return TXT; |
| | | } else if (music.contains(type)) { |
| | | return MUSIC; |
| | | } else if (video.contains(type)) { |
| | | return VIDEO; |
| | | } else { |
| | | return OTHER; |
| | | } |
| | | } |
| | | |
| | | public static void checkSize(long maxSize, long size) { |
| | | // 1M |
| | | int len = 1024 * 1024; |
| | | if (size > (maxSize * len)) { |
| | | throw new BadRequestException("文件超出规定大小:" + maxSize + "MB"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 判断两个文件是否相同 |
| | | */ |
| | | public static boolean check(File file1, File file2) { |
| | | String img1Md5 = getMd5(file1); |
| | | String img2Md5 = getMd5(file2); |
| | | if(img1Md5 != null){ |
| | | return img1Md5.equals(img2Md5); |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | | * 判断两个文件是否相同 |
| | | */ |
| | | public static boolean check(String file1Md5, String file2Md5) { |
| | | return file1Md5.equals(file2Md5); |
| | | } |
| | | |
| | | private static byte[] getByte(File file) { |
| | | // 得到文件长度 |
| | | byte[] b = new byte[(int) file.length()]; |
| | | InputStream in = null; |
| | | try { |
| | | in = new FileInputStream(file); |
| | | try { |
| | | System.out.println(in.read(b)); |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return null; |
| | | } finally { |
| | | CloseUtil.close(in); |
| | | } |
| | | return b; |
| | | } |
| | | |
| | | private static String getMd5(byte[] bytes) { |
| | | // 16进制字符 |
| | | char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; |
| | | try { |
| | | MessageDigest mdTemp = MessageDigest.getInstance("MD5"); |
| | | mdTemp.update(bytes); |
| | | byte[] md = mdTemp.digest(); |
| | | int j = md.length; |
| | | char[] str = new char[j * 2]; |
| | | int k = 0; |
| | | // 移位 输出字符串 |
| | | for (byte byte0 : md) { |
| | | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; |
| | | str[k++] = hexDigits[byte0 & 0xf]; |
| | | } |
| | | return new String(str); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 下载文件 |
| | | * |
| | | * @param request / |
| | | * @param response / |
| | | * @param file / |
| | | */ |
| | | public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) { |
| | | response.setCharacterEncoding(request.getCharacterEncoding()); |
| | | response.setContentType("application/octet-stream"); |
| | | FileInputStream fis = null; |
| | | try { |
| | | fis = new FileInputStream(file); |
| | | response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); |
| | | IOUtils.copy(fis, response.getOutputStream()); |
| | | response.flushBuffer(); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } finally { |
| | | if (fis != null) { |
| | | try { |
| | | fis.close(); |
| | | if (deleteOnExit) { |
| | | file.deleteOnExit(); |
| | | } |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | public static String getMd5(File file) { |
| | | return getMd5(getByte(file)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.springframework.data.domain.Page; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * 分页工具 |
| | | * @author Zheng Jie |
| | | * @date 2018-12-10 |
| | | */ |
| | | public class PageUtil extends cn.hutool.core.util.PageUtil { |
| | | |
| | | /** |
| | | * List 分页 |
| | | */ |
| | | public static List toPage(int page, int size , List list) { |
| | | int fromIndex = page * size; |
| | | int toIndex = page * size + size; |
| | | if(fromIndex > list.size()){ |
| | | return new ArrayList(); |
| | | } else if(toIndex >= list.size()) { |
| | | return list.subList(fromIndex,list.size()); |
| | | } else { |
| | | return list.subList(fromIndex,toIndex); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Page 数据处理,预防redis反序列化报错 |
| | | */ |
| | | public static Map<String,Object> toPage(Page page) { |
| | | Map<String,Object> map = new LinkedHashMap<>(2); |
| | | map.put("content",page.getContent()); |
| | | map.put("totalElements",page.getTotalElements()); |
| | | return map; |
| | | } |
| | | |
| | | /** |
| | | * 自定义分页 |
| | | */ |
| | | public static Map<String,Object> toPage(Object object, Object totalElements) { |
| | | Map<String,Object> map = new LinkedHashMap<>(2); |
| | | map.put("content",object); |
| | | map.put("totalElements",totalElements); |
| | | return map; |
| | | } |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.annotation.DataPermission; |
| | | import me.zhengjie.annotation.Query; |
| | | import javax.persistence.criteria.*; |
| | | import java.lang.reflect.Field; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-4 14:59:48 |
| | | */ |
| | | @Slf4j |
| | | @SuppressWarnings({"unchecked","all"}) |
| | | public class QueryHelp { |
| | | |
| | | public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) { |
| | | List<Predicate> list = new ArrayList<>(); |
| | | if(query == null){ |
| | | return cb.and(list.toArray(new Predicate[0])); |
| | | } |
| | | // 数据权限验证 |
| | | DataPermission permission = query.getClass().getAnnotation(DataPermission.class); |
| | | if(permission != null){ |
| | | // 获取数据权限 |
| | | List<Long> dataScopes = SecurityUtils.getCurrentUserDataScope(); |
| | | if(CollectionUtil.isNotEmpty(dataScopes)){ |
| | | if(StringUtils.isNotBlank(permission.joinName()) && StringUtils.isNotBlank(permission.fieldName())) { |
| | | Join join = root.join(permission.joinName(), JoinType.LEFT); |
| | | list.add(getExpression(permission.fieldName(),join, root).in(dataScopes)); |
| | | } else if (StringUtils.isBlank(permission.joinName()) && StringUtils.isNotBlank(permission.fieldName())) { |
| | | list.add(getExpression(permission.fieldName(),null, root).in(dataScopes)); |
| | | } |
| | | } |
| | | } |
| | | try { |
| | | List<Field> fields = getAllFields(query.getClass(), new ArrayList<>()); |
| | | for (Field field : fields) { |
| | | boolean accessible = field.isAccessible(); |
| | | // 设置对象的访问权限,保证对private的属性的访 |
| | | field.setAccessible(true); |
| | | Query q = field.getAnnotation(Query.class); |
| | | if (q != null) { |
| | | String propName = q.propName(); |
| | | String joinName = q.joinName(); |
| | | String blurry = q.blurry(); |
| | | String attributeName = isBlank(propName) ? field.getName() : propName; |
| | | Class<?> fieldType = field.getType(); |
| | | Object val = field.get(query); |
| | | if (ObjectUtil.isNull(val) || "".equals(val)) { |
| | | continue; |
| | | } |
| | | Join join = null; |
| | | // 模糊多字段 |
| | | if (ObjectUtil.isNotEmpty(blurry)) { |
| | | String[] blurrys = blurry.split(","); |
| | | List<Predicate> orPredicate = new ArrayList<>(); |
| | | for (String s : blurrys) { |
| | | orPredicate.add(cb.like(root.get(s) |
| | | .as(String.class), "%" + val.toString() + "%")); |
| | | } |
| | | Predicate[] p = new Predicate[orPredicate.size()]; |
| | | list.add(cb.or(orPredicate.toArray(p))); |
| | | continue; |
| | | } |
| | | if (ObjectUtil.isNotEmpty(joinName)) { |
| | | String[] joinNames = joinName.split(">"); |
| | | for (String name : joinNames) { |
| | | switch (q.join()) { |
| | | case LEFT: |
| | | if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){ |
| | | join = join.join(name, JoinType.LEFT); |
| | | } else { |
| | | join = root.join(name, JoinType.LEFT); |
| | | } |
| | | break; |
| | | case RIGHT: |
| | | if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){ |
| | | join = join.join(name, JoinType.RIGHT); |
| | | } else { |
| | | join = root.join(name, JoinType.RIGHT); |
| | | } |
| | | break; |
| | | case INNER: |
| | | if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){ |
| | | join = join.join(name, JoinType.INNER); |
| | | } else { |
| | | join = root.join(name, JoinType.INNER); |
| | | } |
| | | break; |
| | | default: break; |
| | | } |
| | | } |
| | | } |
| | | switch (q.type()) { |
| | | case EQUAL: |
| | | list.add(cb.equal(getExpression(attributeName,join,root) |
| | | .as((Class<? extends Comparable>) fieldType),val)); |
| | | break; |
| | | case GREATER_THAN: |
| | | list.add(cb.greaterThanOrEqualTo(getExpression(attributeName,join,root) |
| | | .as((Class<? extends Comparable>) fieldType), (Comparable) val)); |
| | | break; |
| | | case LESS_THAN: |
| | | list.add(cb.lessThanOrEqualTo(getExpression(attributeName,join,root) |
| | | .as((Class<? extends Comparable>) fieldType), (Comparable) val)); |
| | | break; |
| | | case LESS_THAN_NQ: |
| | | list.add(cb.lessThan(getExpression(attributeName,join,root) |
| | | .as((Class<? extends Comparable>) fieldType), (Comparable) val)); |
| | | break; |
| | | case INNER_LIKE: |
| | | list.add(cb.like(getExpression(attributeName,join,root) |
| | | .as(String.class), "%" + val.toString() + "%")); |
| | | break; |
| | | case LEFT_LIKE: |
| | | list.add(cb.like(getExpression(attributeName,join,root) |
| | | .as(String.class), "%" + val.toString())); |
| | | break; |
| | | case RIGHT_LIKE: |
| | | list.add(cb.like(getExpression(attributeName,join,root) |
| | | .as(String.class), val.toString() + "%")); |
| | | break; |
| | | case IN: |
| | | if (CollUtil.isNotEmpty((Collection<Object>)val)) { |
| | | list.add(getExpression(attributeName,join,root).in((Collection<Object>) val)); |
| | | } |
| | | break; |
| | | case NOT_IN: |
| | | if (CollUtil.isNotEmpty((Collection<Object>)val)) { |
| | | list.add(getExpression(attributeName,join,root).in((Collection<Object>) val).not()); |
| | | } |
| | | break; |
| | | case NOT_EQUAL: |
| | | list.add(cb.notEqual(getExpression(attributeName,join,root), val)); |
| | | break; |
| | | case NOT_NULL: |
| | | list.add(cb.isNotNull(getExpression(attributeName,join,root))); |
| | | break; |
| | | case IS_NULL: |
| | | list.add(cb.isNull(getExpression(attributeName,join,root))); |
| | | break; |
| | | case BETWEEN: |
| | | List<Object> between = new ArrayList<>((List<Object>)val); |
| | | list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()), |
| | | (Comparable) between.get(0), (Comparable) between.get(1))); |
| | | break; |
| | | default: break; |
| | | } |
| | | } |
| | | field.setAccessible(accessible); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | int size = list.size(); |
| | | return cb.and(list.toArray(new Predicate[size])); |
| | | } |
| | | |
| | | @SuppressWarnings("unchecked") |
| | | private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) { |
| | | if (ObjectUtil.isNotEmpty(join)) { |
| | | return join.get(attributeName); |
| | | } else { |
| | | return root.get(attributeName); |
| | | } |
| | | } |
| | | |
| | | private static boolean isBlank(final CharSequence cs) { |
| | | int strLen; |
| | | if (cs == null || (strLen = cs.length()) == 0) { |
| | | return true; |
| | | } |
| | | for (int i = 0; i < strLen; i++) { |
| | | if (!Character.isWhitespace(cs.charAt(i))) { |
| | | return false; |
| | | } |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | public static List<Field> getAllFields(Class clazz, List<Field> fields) { |
| | | if (clazz != null) { |
| | | fields.addAll(Arrays.asList(clazz.getDeclaredFields())); |
| | | getAllFields(clazz.getSuperclass(), fields); |
| | | } |
| | | return fields; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import com.google.common.collect.Lists; |
| | | import com.google.common.collect.Sets; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.data.redis.connection.RedisConnection; |
| | | import org.springframework.data.redis.connection.RedisConnectionFactory; |
| | | import org.springframework.data.redis.core.*; |
| | | import org.springframework.data.redis.serializer.StringRedisSerializer; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import java.util.*; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @Component |
| | | @SuppressWarnings({"unchecked", "all"}) |
| | | public class RedisUtils { |
| | | private static final Logger log = LoggerFactory.getLogger(RedisUtils.class); |
| | | private RedisTemplate<Object, Object> redisTemplate; |
| | | @Value("${jwt.online-key}") |
| | | private String onlineKey; |
| | | |
| | | public RedisUtils(RedisTemplate<Object, Object> redisTemplate) { |
| | | this.redisTemplate = redisTemplate; |
| | | this.redisTemplate.setHashKeySerializer(new StringRedisSerializer()); |
| | | this.redisTemplate.setKeySerializer(new StringRedisSerializer()); |
| | | this.redisTemplate.setStringSerializer(new StringRedisSerializer()); |
| | | } |
| | | |
| | | /** |
| | | * 指定缓存失效时间 |
| | | * |
| | | * @param key 键 |
| | | * @param time 时间(秒) |
| | | */ |
| | | public boolean expire(String key, long time) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.expire(key, time, TimeUnit.SECONDS); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | /** |
| | | * 指定缓存失效时间 |
| | | * |
| | | * @param key 键 |
| | | * @param time 时间(秒) |
| | | * @param timeUnit 单位 |
| | | */ |
| | | public boolean expire(String key, long time, TimeUnit timeUnit) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.expire(key, time, timeUnit); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | /** |
| | | * 根据 key 获取过期时间 |
| | | * |
| | | * @param key 键 不能为null |
| | | * @return 时间(秒) 返回0代表为永久有效 |
| | | */ |
| | | public long getExpire(Object key) { |
| | | return redisTemplate.getExpire(key, TimeUnit.SECONDS); |
| | | } |
| | | |
| | | /** |
| | | * 查找匹配key |
| | | * |
| | | * @param pattern key |
| | | * @return / |
| | | */ |
| | | public List<String> scan(String pattern) { |
| | | ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); |
| | | RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); |
| | | RedisConnection rc = Objects.requireNonNull(factory).getConnection(); |
| | | Cursor<byte[]> cursor = rc.scan(options); |
| | | List<String> result = new ArrayList<>(); |
| | | while (cursor.hasNext()) { |
| | | result.add(new String(cursor.next())); |
| | | } |
| | | try { |
| | | RedisConnectionUtils.releaseConnection(rc, factory); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * 分页查询 key |
| | | * |
| | | * @param patternKey key |
| | | * @param page 页码 |
| | | * @param size 每页数目 |
| | | * @return / |
| | | */ |
| | | public List<String> findKeysForPage(String patternKey, int page, int size) { |
| | | ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); |
| | | RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); |
| | | RedisConnection rc = Objects.requireNonNull(factory).getConnection(); |
| | | Cursor<byte[]> cursor = rc.scan(options); |
| | | List<String> result = new ArrayList<>(size); |
| | | int tmpIndex = 0; |
| | | int fromIndex = page * size; |
| | | int toIndex = page * size + size; |
| | | while (cursor.hasNext()) { |
| | | if (tmpIndex >= fromIndex && tmpIndex < toIndex) { |
| | | result.add(new String(cursor.next())); |
| | | tmpIndex++; |
| | | continue; |
| | | } |
| | | // 获取到满足条件的数据后,就可以退出了 |
| | | if (tmpIndex >= toIndex) { |
| | | break; |
| | | } |
| | | tmpIndex++; |
| | | cursor.next(); |
| | | } |
| | | try { |
| | | RedisConnectionUtils.releaseConnection(rc, factory); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * 判断key是否存在 |
| | | * |
| | | * @param key 键 |
| | | * @return true 存在 false不存在 |
| | | */ |
| | | public boolean hasKey(String key) { |
| | | try { |
| | | return redisTemplate.hasKey(key); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 删除缓存 |
| | | * |
| | | * @param key 可以传一个值 或多个 |
| | | */ |
| | | public void del(String... keys) { |
| | | if (keys != null && keys.length > 0) { |
| | | if (keys.length == 1) { |
| | | boolean result = redisTemplate.delete(keys[0]); |
| | | log.debug("--------------------------------------------"); |
| | | log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString()); |
| | | log.debug("--------------------------------------------"); |
| | | } else { |
| | | Set<Object> keySet = new HashSet<>(); |
| | | for (String key : keys) { |
| | | keySet.addAll(redisTemplate.keys(key)); |
| | | } |
| | | long count = redisTemplate.delete(keySet); |
| | | log.debug("--------------------------------------------"); |
| | | log.debug("成功删除缓存:" + keySet.toString()); |
| | | log.debug("缓存删除数量:" + count + "个"); |
| | | log.debug("--------------------------------------------"); |
| | | } |
| | | } |
| | | } |
| | | |
| | | // ============================String============================= |
| | | |
| | | /** |
| | | * 普通缓存获取 |
| | | * |
| | | * @param key 键 |
| | | * @return 值 |
| | | */ |
| | | public Object get(String key) { |
| | | return key == null ? null : redisTemplate.opsForValue().get(key); |
| | | } |
| | | |
| | | /** |
| | | * 批量获取 |
| | | * |
| | | * @param keys |
| | | * @return |
| | | */ |
| | | public List<Object> multiGet(List<String> keys) { |
| | | List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys)); |
| | | List resultList = Lists.newArrayList(); |
| | | Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add))); |
| | | return resultList; |
| | | } |
| | | |
| | | /** |
| | | * 普通缓存放入 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @return true成功 false失败 |
| | | */ |
| | | public boolean set(String key, Object value) { |
| | | try { |
| | | redisTemplate.opsForValue().set(key, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 普通缓存放入并设置时间 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 |
| | | * @return true成功 false 失败 |
| | | */ |
| | | public boolean set(String key, Object value, long time) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); |
| | | } else { |
| | | set(key, value); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 普通缓存放入并设置时间 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param time 时间 |
| | | * @param timeUnit 类型 |
| | | * @return true成功 false 失败 |
| | | */ |
| | | public boolean set(String key, Object value, long time, TimeUnit timeUnit) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.opsForValue().set(key, value, time, timeUnit); |
| | | } else { |
| | | set(key, value); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | // ================================Map================================= |
| | | |
| | | /** |
| | | * HashGet |
| | | * |
| | | * @param key 键 不能为null |
| | | * @param item 项 不能为null |
| | | * @return 值 |
| | | */ |
| | | public Object hget(String key, String item) { |
| | | return redisTemplate.opsForHash().get(key, item); |
| | | } |
| | | |
| | | /** |
| | | * 获取hashKey对应的所有键值 |
| | | * |
| | | * @param key 键 |
| | | * @return 对应的多个键值 |
| | | */ |
| | | public Map<Object, Object> hmget(String key) { |
| | | return redisTemplate.opsForHash().entries(key); |
| | | |
| | | } |
| | | |
| | | /** |
| | | * HashSet |
| | | * |
| | | * @param key 键 |
| | | * @param map 对应多个键值 |
| | | * @return true 成功 false 失败 |
| | | */ |
| | | public boolean hmset(String key, Map<String, Object> map) { |
| | | try { |
| | | redisTemplate.opsForHash().putAll(key, map); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * HashSet 并设置时间 |
| | | * |
| | | * @param key 键 |
| | | * @param map 对应多个键值 |
| | | * @param time 时间(秒) |
| | | * @return true成功 false失败 |
| | | */ |
| | | public boolean hmset(String key, Map<String, Object> map, long time) { |
| | | try { |
| | | redisTemplate.opsForHash().putAll(key, map); |
| | | if (time > 0) { |
| | | expire(key, time); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 向一张hash表中放入数据,如果不存在将创建 |
| | | * |
| | | * @param key 键 |
| | | * @param item 项 |
| | | * @param value 值 |
| | | * @return true 成功 false失败 |
| | | */ |
| | | public boolean hset(String key, String item, Object value) { |
| | | try { |
| | | redisTemplate.opsForHash().put(key, item, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 向一张hash表中放入数据,如果不存在将创建 |
| | | * |
| | | * @param key 键 |
| | | * @param item 项 |
| | | * @param value 值 |
| | | * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 |
| | | * @return true 成功 false失败 |
| | | */ |
| | | public boolean hset(String key, String item, Object value, long time) { |
| | | try { |
| | | redisTemplate.opsForHash().put(key, item, value); |
| | | if (time > 0) { |
| | | expire(key, time); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 删除hash表中的值 |
| | | * |
| | | * @param key 键 不能为null |
| | | * @param item 项 可以使多个 不能为null |
| | | */ |
| | | public void hdel(String key, Object... item) { |
| | | redisTemplate.opsForHash().delete(key, item); |
| | | } |
| | | |
| | | /** |
| | | * 判断hash表中是否有该项的值 |
| | | * |
| | | * @param key 键 不能为null |
| | | * @param item 项 不能为null |
| | | * @return true 存在 false不存在 |
| | | */ |
| | | public boolean hHasKey(String key, String item) { |
| | | return redisTemplate.opsForHash().hasKey(key, item); |
| | | } |
| | | |
| | | /** |
| | | * hash递增 如果不存在,就会创建一个 并把新增后的值返回 |
| | | * |
| | | * @param key 键 |
| | | * @param item 项 |
| | | * @param by 要增加几(大于0) |
| | | * @return |
| | | */ |
| | | public double hincr(String key, String item, double by) { |
| | | return redisTemplate.opsForHash().increment(key, item, by); |
| | | } |
| | | |
| | | /** |
| | | * hash递减 |
| | | * |
| | | * @param key 键 |
| | | * @param item 项 |
| | | * @param by 要减少记(小于0) |
| | | * @return |
| | | */ |
| | | public double hdecr(String key, String item, double by) { |
| | | return redisTemplate.opsForHash().increment(key, item, -by); |
| | | } |
| | | |
| | | // ============================set============================= |
| | | |
| | | /** |
| | | * 根据key获取Set中的所有值 |
| | | * |
| | | * @param key 键 |
| | | * @return |
| | | */ |
| | | public Set<Object> sGet(String key) { |
| | | try { |
| | | return redisTemplate.opsForSet().members(key); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据value从一个set中查询,是否存在 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @return true 存在 false不存在 |
| | | */ |
| | | public boolean sHasKey(String key, Object value) { |
| | | try { |
| | | return redisTemplate.opsForSet().isMember(key, value); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将数据放入set缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param values 值 可以是多个 |
| | | * @return 成功个数 |
| | | */ |
| | | public long sSet(String key, Object... values) { |
| | | try { |
| | | return redisTemplate.opsForSet().add(key, values); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将set数据放入缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param time 时间(秒) |
| | | * @param values 值 可以是多个 |
| | | * @return 成功个数 |
| | | */ |
| | | public long sSetAndTime(String key, long time, Object... values) { |
| | | try { |
| | | Long count = redisTemplate.opsForSet().add(key, values); |
| | | if (time > 0) { |
| | | expire(key, time); |
| | | } |
| | | return count; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取set缓存的长度 |
| | | * |
| | | * @param key 键 |
| | | * @return |
| | | */ |
| | | public long sGetSetSize(String key) { |
| | | try { |
| | | return redisTemplate.opsForSet().size(key); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 移除值为value的 |
| | | * |
| | | * @param key 键 |
| | | * @param values 值 可以是多个 |
| | | * @return 移除的个数 |
| | | */ |
| | | public long setRemove(String key, Object... values) { |
| | | try { |
| | | Long count = redisTemplate.opsForSet().remove(key, values); |
| | | return count; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | // ===============================list================================= |
| | | |
| | | /** |
| | | * 获取list缓存的内容 |
| | | * |
| | | * @param key 键 |
| | | * @param start 开始 |
| | | * @param end 结束 0 到 -1代表所有值 |
| | | * @return |
| | | */ |
| | | public List<Object> lGet(String key, long start, long end) { |
| | | try { |
| | | return redisTemplate.opsForList().range(key, start, end); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取list缓存的长度 |
| | | * |
| | | * @param key 键 |
| | | * @return |
| | | */ |
| | | public long lGetListSize(String key) { |
| | | try { |
| | | return redisTemplate.opsForList().size(key); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 通过索引 获取list中的值 |
| | | * |
| | | * @param key 键 |
| | | * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 |
| | | * @return |
| | | */ |
| | | public Object lGetIndex(String key, long index) { |
| | | try { |
| | | return redisTemplate.opsForList().index(key, index); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将list放入缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @return |
| | | */ |
| | | public boolean lSet(String key, Object value) { |
| | | try { |
| | | redisTemplate.opsForList().rightPush(key, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将list放入缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param time 时间(秒) |
| | | * @return |
| | | */ |
| | | public boolean lSet(String key, Object value, long time) { |
| | | try { |
| | | redisTemplate.opsForList().rightPush(key, value); |
| | | if (time > 0) { |
| | | expire(key, time); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将list放入缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @return |
| | | */ |
| | | public boolean lSet(String key, List<Object> value) { |
| | | try { |
| | | redisTemplate.opsForList().rightPushAll(key, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将list放入缓存 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param time 时间(秒) |
| | | * @return |
| | | */ |
| | | public boolean lSet(String key, List<Object> value, long time) { |
| | | try { |
| | | redisTemplate.opsForList().rightPushAll(key, value); |
| | | if (time > 0) { |
| | | expire(key, time); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据索引修改list中的某条数据 |
| | | * |
| | | * @param key 键 |
| | | * @param index 索引 |
| | | * @param value 值 |
| | | * @return / |
| | | */ |
| | | public boolean lUpdateIndex(String key, long index, Object value) { |
| | | try { |
| | | redisTemplate.opsForList().set(key, index, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 移除N个值为value |
| | | * |
| | | * @param key 键 |
| | | * @param count 移除多少个 |
| | | * @param value 值 |
| | | * @return 移除的个数 |
| | | */ |
| | | public long lRemove(String key, long count, Object value) { |
| | | try { |
| | | return redisTemplate.opsForList().remove(key, count, value); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(), e); |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * @param prefix 前缀 |
| | | * @param ids id |
| | | */ |
| | | public void delByKeys(String prefix, Set<Long> ids) { |
| | | Set<Object> keys = new HashSet<>(); |
| | | for (Long id : ids) { |
| | | keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString())); |
| | | } |
| | | long count = redisTemplate.delete(keys); |
| | | // 此处提示可自行删除 |
| | | log.debug("--------------------------------------------"); |
| | | log.debug("成功删除缓存:" + keys.toString()); |
| | | log.debug("缓存删除数量:" + count + "个"); |
| | | log.debug("--------------------------------------------"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.springframework.web.context.request.RequestContextHolder; |
| | | import org.springframework.web.context.request.ServletRequestAttributes; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * 获取 HttpServletRequest |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | public class RequestHolder { |
| | | |
| | | public static HttpServletRequest getHttpServletRequest() { |
| | | return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.apache.commons.codec.binary.Base64; |
| | | import javax.crypto.Cipher; |
| | | import java.io.ByteArrayOutputStream; |
| | | import java.security.*; |
| | | import java.security.interfaces.RSAPrivateKey; |
| | | import java.security.interfaces.RSAPublicKey; |
| | | import java.security.spec.PKCS8EncodedKeySpec; |
| | | import java.security.spec.X509EncodedKeySpec; |
| | | |
| | | /** |
| | | * @author https://www.cnblogs.com/nihaorz/p/10690643.html |
| | | * @description Rsa 工具类,公钥私钥生成,加解密 |
| | | * @date 2020-05-18 |
| | | **/ |
| | | public class RsaUtils { |
| | | |
| | | private static final String SRC = "123456"; |
| | | |
| | | public static void main(String[] args) throws Exception { |
| | | System.out.println("\n"); |
| | | RsaKeyPair keyPair = generateKeyPair(); |
| | | System.out.println("公钥:" + keyPair.getPublicKey()); |
| | | System.out.println("私钥:" + keyPair.getPrivateKey()); |
| | | System.out.println("\n"); |
| | | test1(keyPair); |
| | | System.out.println("\n"); |
| | | test2(keyPair); |
| | | System.out.println("\n"); |
| | | } |
| | | |
| | | /** |
| | | * 公钥加密私钥解密 |
| | | */ |
| | | private static void test1(RsaKeyPair keyPair) throws Exception { |
| | | System.out.println("***************** 公钥加密私钥解密开始 *****************"); |
| | | String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtils.SRC); |
| | | String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1); |
| | | System.out.println("加密前:" + RsaUtils.SRC); |
| | | System.out.println("加密后:" + text1); |
| | | System.out.println("解密后:" + text2); |
| | | if (RsaUtils.SRC.equals(text2)) { |
| | | System.out.println("解密字符串和原始字符串一致,解密成功"); |
| | | } else { |
| | | System.out.println("解密字符串和原始字符串不一致,解密失败"); |
| | | } |
| | | System.out.println("***************** 公钥加密私钥解密结束 *****************"); |
| | | } |
| | | |
| | | /** |
| | | * 私钥加密公钥解密 |
| | | * @throws Exception / |
| | | */ |
| | | private static void test2(RsaKeyPair keyPair) throws Exception { |
| | | System.out.println("***************** 私钥加密公钥解密开始 *****************"); |
| | | String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtils.SRC); |
| | | String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1); |
| | | System.out.println("加密前:" + RsaUtils.SRC); |
| | | System.out.println("加密后:" + text1); |
| | | System.out.println("解密后:" + text2); |
| | | if (RsaUtils.SRC.equals(text2)) { |
| | | System.out.println("解密字符串和原始字符串一致,解密成功"); |
| | | } else { |
| | | System.out.println("解密字符串和原始字符串不一致,解密失败"); |
| | | } |
| | | System.out.println("***************** 私钥加密公钥解密结束 *****************"); |
| | | } |
| | | |
| | | /** |
| | | * 公钥解密 |
| | | * |
| | | * @param publicKeyText 公钥 |
| | | * @param text 待解密的信息 |
| | | * @return / |
| | | * @throws Exception / |
| | | */ |
| | | public static String decryptByPublicKey(String publicKeyText, String text) throws Exception { |
| | | X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText)); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.DECRYPT_MODE, publicKey); |
| | | byte[] result = doLongerCipherFinal(Cipher.DECRYPT_MODE, cipher, Base64.decodeBase64(text)); |
| | | return new String(result); |
| | | } |
| | | |
| | | /** |
| | | * 私钥加密 |
| | | * |
| | | * @param privateKeyText 私钥 |
| | | * @param text 待加密的信息 |
| | | * @return / |
| | | * @throws Exception / |
| | | */ |
| | | public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception { |
| | | PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText)); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, privateKey); |
| | | byte[] result = doLongerCipherFinal(Cipher.ENCRYPT_MODE, cipher, text.getBytes()); |
| | | return Base64.encodeBase64String(result); |
| | | } |
| | | |
| | | /** |
| | | * 私钥解密 |
| | | * |
| | | * @param privateKeyText 私钥 |
| | | * @param text 待解密的文本 |
| | | * @return / |
| | | * @throws Exception / |
| | | */ |
| | | public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception { |
| | | PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText)); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5); |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.DECRYPT_MODE, privateKey); |
| | | byte[] result = doLongerCipherFinal(Cipher.DECRYPT_MODE, cipher, Base64.decodeBase64(text)); |
| | | return new String(result); |
| | | } |
| | | |
| | | /** |
| | | * 公钥加密 |
| | | * |
| | | * @param publicKeyText 公钥 |
| | | * @param text 待加密的文本 |
| | | * @return / |
| | | */ |
| | | public static String encryptByPublicKey(String publicKeyText, String text) throws Exception { |
| | | X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText)); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2); |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, publicKey); |
| | | byte[] result = doLongerCipherFinal(Cipher.ENCRYPT_MODE, cipher, text.getBytes()); |
| | | return Base64.encodeBase64String(result); |
| | | } |
| | | |
| | | private static byte[] doLongerCipherFinal(int opMode,Cipher cipher, byte[] source) throws Exception { |
| | | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| | | if (opMode == Cipher.DECRYPT_MODE) { |
| | | out.write(cipher.doFinal(source)); |
| | | } else { |
| | | int offset = 0; |
| | | int totalSize = source.length; |
| | | while (totalSize - offset > 0) { |
| | | int size = Math.min(cipher.getOutputSize(0) - 11, totalSize - offset); |
| | | out.write(cipher.doFinal(source, offset, size)); |
| | | offset += size; |
| | | } |
| | | } |
| | | out.close(); |
| | | return out.toByteArray(); |
| | | } |
| | | |
| | | /** |
| | | * 构建RSA密钥对 |
| | | * |
| | | * @return / |
| | | * @throws NoSuchAlgorithmException / |
| | | */ |
| | | public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException { |
| | | KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); |
| | | keyPairGenerator.initialize(1024); |
| | | KeyPair keyPair = keyPairGenerator.generateKeyPair(); |
| | | RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); |
| | | RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); |
| | | String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded()); |
| | | String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded()); |
| | | return new RsaKeyPair(publicKeyString, privateKeyString); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * RSA密钥对对象 |
| | | */ |
| | | public static class RsaKeyPair { |
| | | |
| | | private final String publicKey; |
| | | private final String privateKey; |
| | | |
| | | public RsaKeyPair(String publicKey, String privateKey) { |
| | | this.publicKey = publicKey; |
| | | this.privateKey = privateKey; |
| | | } |
| | | |
| | | public String getPublicKey() { |
| | | return publicKey; |
| | | } |
| | | |
| | | public String getPrivateKey() { |
| | | return privateKey; |
| | | } |
| | | |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.json.JSONArray; |
| | | import cn.hutool.json.JSONObject; |
| | | import cn.hutool.json.JSONUtil; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.utils.enums.DataScopeEnum; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.security.core.Authentication; |
| | | import org.springframework.security.core.context.SecurityContextHolder; |
| | | import org.springframework.security.core.userdetails.UserDetails; |
| | | import org.springframework.security.core.userdetails.UserDetailsService; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 获取当前登录的用户 |
| | | * @author Zheng Jie |
| | | * @date 2019-01-17 |
| | | */ |
| | | @Slf4j |
| | | public class SecurityUtils { |
| | | |
| | | /** |
| | | * 获取当前登录的用户 |
| | | * @return UserDetails |
| | | */ |
| | | public static UserDetails getCurrentUser() { |
| | | UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class); |
| | | return userDetailsService.loadUserByUsername(getCurrentUsername()); |
| | | } |
| | | |
| | | /** |
| | | * 获取系统用户名称 |
| | | * |
| | | * @return 系统用户名称 |
| | | */ |
| | | public static String getCurrentUsername() { |
| | | final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| | | if (authentication == null) { |
| | | throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期"); |
| | | } |
| | | if (authentication.getPrincipal() instanceof UserDetails) { |
| | | UserDetails userDetails = (UserDetails) authentication.getPrincipal(); |
| | | return userDetails.getUsername(); |
| | | } |
| | | throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息"); |
| | | } |
| | | |
| | | /** |
| | | * 获取系统用户ID |
| | | * @return 系统用户ID |
| | | */ |
| | | public static Long getCurrentUserId() { |
| | | UserDetails userDetails = getCurrentUser(); |
| | | return new JSONObject(new JSONObject(userDetails).get("user")).get("id", Long.class); |
| | | } |
| | | |
| | | /** |
| | | * 获取当前用户的数据权限 |
| | | * @return / |
| | | */ |
| | | public static List<Long> getCurrentUserDataScope(){ |
| | | UserDetails userDetails = getCurrentUser(); |
| | | JSONArray array = JSONUtil.parseArray(new JSONObject(userDetails).get("dataScopes")); |
| | | return JSONUtil.toList(array,Long.class); |
| | | } |
| | | |
| | | /** |
| | | * 获取数据权限级别 |
| | | * @return 级别 |
| | | */ |
| | | public static String getDataScopeType() { |
| | | List<Long> dataScopes = getCurrentUserDataScope(); |
| | | if(dataScopes.size() != 0){ |
| | | return ""; |
| | | } |
| | | return DataScopeEnum.ALL.getValue(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.beans.BeansException; |
| | | import org.springframework.beans.factory.DisposableBean; |
| | | import org.springframework.context.ApplicationContext; |
| | | import org.springframework.context.ApplicationContextAware; |
| | | import org.springframework.core.env.Environment; |
| | | import org.springframework.stereotype.Service; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Slf4j |
| | | public class SpringContextHolder implements ApplicationContextAware, DisposableBean { |
| | | |
| | | private static ApplicationContext applicationContext = null; |
| | | private static final List<CallBack> CALL_BACKS = new ArrayList<>(); |
| | | private static boolean addCallback = true; |
| | | |
| | | /** |
| | | * 针对 某些初始化方法,在SpringContextHolder 未初始化时 提交回调方法。 |
| | | * 在SpringContextHolder 初始化后,进行回调使用 |
| | | * |
| | | * @param callBack 回调函数 |
| | | */ |
| | | public synchronized static void addCallBacks(CallBack callBack) { |
| | | if (addCallback) { |
| | | SpringContextHolder.CALL_BACKS.add(callBack); |
| | | } else { |
| | | log.warn("CallBack:{} 已无法添加!立即执行", callBack.getCallBackName()); |
| | | callBack.executor(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. |
| | | */ |
| | | @SuppressWarnings("unchecked") |
| | | public static <T> T getBean(String name) { |
| | | assertContextInjected(); |
| | | return (T) applicationContext.getBean(name); |
| | | } |
| | | |
| | | /** |
| | | * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. |
| | | */ |
| | | public static <T> T getBean(Class<T> requiredType) { |
| | | assertContextInjected(); |
| | | return applicationContext.getBean(requiredType); |
| | | } |
| | | |
| | | /** |
| | | * 获取SpringBoot 配置信息 |
| | | * |
| | | * @param property 属性key |
| | | * @param defaultValue 默认值 |
| | | * @param requiredType 返回类型 |
| | | * @return / |
| | | */ |
| | | public static <T> T getProperties(String property, T defaultValue, Class<T> requiredType) { |
| | | T result = defaultValue; |
| | | try { |
| | | result = getBean(Environment.class).getProperty(property, requiredType); |
| | | } catch (Exception ignored) {} |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * 获取SpringBoot 配置信息 |
| | | * |
| | | * @param property 属性key |
| | | * @return / |
| | | */ |
| | | public static String getProperties(String property) { |
| | | return getProperties(property, null, String.class); |
| | | } |
| | | |
| | | /** |
| | | * 获取SpringBoot 配置信息 |
| | | * |
| | | * @param property 属性key |
| | | * @param requiredType 返回类型 |
| | | * @return / |
| | | */ |
| | | public static <T> T getProperties(String property, Class<T> requiredType) { |
| | | return getProperties(property, null, requiredType); |
| | | } |
| | | |
| | | /** |
| | | * 检查ApplicationContext不为空. |
| | | */ |
| | | private static void assertContextInjected() { |
| | | if (applicationContext == null) { |
| | | throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" + |
| | | ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder."); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 清除SpringContextHolder中的ApplicationContext为Null. |
| | | */ |
| | | private static void clearHolder() { |
| | | log.debug("清除SpringContextHolder中的ApplicationContext:" |
| | | + applicationContext); |
| | | applicationContext = null; |
| | | } |
| | | |
| | | @Override |
| | | public void destroy() { |
| | | SpringContextHolder.clearHolder(); |
| | | } |
| | | |
| | | @Override |
| | | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { |
| | | if (SpringContextHolder.applicationContext != null) { |
| | | log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); |
| | | } |
| | | SpringContextHolder.applicationContext = applicationContext; |
| | | if (addCallback) { |
| | | for (CallBack callBack : SpringContextHolder.CALL_BACKS) { |
| | | callBack.executor(); |
| | | } |
| | | CALL_BACKS.clear(); |
| | | } |
| | | SpringContextHolder.addCallback = false; |
| | | } |
| | | |
| | | /** |
| | | * 获取 @Service 的所有 bean 名称 |
| | | * @return / |
| | | */ |
| | | public static List<String> getAllServiceBeanName() { |
| | | return new ArrayList<>(Arrays.asList(applicationContext |
| | | .getBeanNamesForAnnotation(Service.class))); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.http.HttpUtil; |
| | | import cn.hutool.json.JSONObject; |
| | | import cn.hutool.json.JSONUtil; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.config.ElAdminProperties; |
| | | import net.dreamlu.mica.ip2region.core.Ip2regionSearcher; |
| | | import net.dreamlu.mica.ip2region.core.IpInfo; |
| | | import nl.basjes.parse.useragent.UserAgent; |
| | | import nl.basjes.parse.useragent.UserAgentAnalyzer; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.net.InetAddress; |
| | | import java.net.NetworkInterface; |
| | | import java.net.UnknownHostException; |
| | | import java.util.Calendar; |
| | | import java.util.Date; |
| | | import java.util.Enumeration; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 |
| | | */ |
| | | @Slf4j |
| | | public class StringUtils extends org.apache.commons.lang3.StringUtils { |
| | | |
| | | private static final char SEPARATOR = '_'; |
| | | private static final String UNKNOWN = "unknown"; |
| | | |
| | | /** |
| | | * 注入bean |
| | | */ |
| | | private final static Ip2regionSearcher IP_SEARCHER = SpringContextHolder.getBean(Ip2regionSearcher.class); |
| | | |
| | | |
| | | private static final UserAgentAnalyzer USER_AGENT_ANALYZER = UserAgentAnalyzer |
| | | .newBuilder() |
| | | .hideMatcherLoadStats() |
| | | .withCache(10000) |
| | | .withField(UserAgent.AGENT_NAME_VERSION) |
| | | .build(); |
| | | |
| | | /** |
| | | * 驼峰命名法工具 |
| | | * |
| | | * @return toCamelCase(" hello_world ") == "helloWorld" |
| | | * toCapitalizeCamelCase("hello_world") == "HelloWorld" |
| | | * toUnderScoreCase("helloWorld") = "hello_world" |
| | | */ |
| | | 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(); |
| | | } |
| | | |
| | | /** |
| | | * 驼峰命名法工具 |
| | | * |
| | | * @return toCamelCase(" hello_world ") == "helloWorld" |
| | | * toCapitalizeCamelCase("hello_world") == "HelloWorld" |
| | | * toUnderScoreCase("helloWorld") = "hello_world" |
| | | */ |
| | | public static String toCapitalizeCamelCase(String s) { |
| | | if (s == null) { |
| | | return null; |
| | | } |
| | | s = toCamelCase(s); |
| | | return s.substring(0, 1).toUpperCase() + s.substring(1); |
| | | } |
| | | |
| | | /** |
| | | * 驼峰命名法工具 |
| | | * |
| | | * @return toCamelCase(" hello_world ") == "helloWorld" |
| | | * toCapitalizeCamelCase("hello_world") == "HelloWorld" |
| | | * toUnderScoreCase("helloWorld") = "hello_world" |
| | | */ |
| | | static String toUnderScoreCase(String s) { |
| | | if (s == null) { |
| | | return null; |
| | | } |
| | | |
| | | StringBuilder sb = new StringBuilder(); |
| | | boolean upperCase = false; |
| | | for (int i = 0; i < s.length(); i++) { |
| | | char c = s.charAt(i); |
| | | |
| | | boolean nextUpperCase = true; |
| | | |
| | | if (i < (s.length() - 1)) { |
| | | nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); |
| | | } |
| | | |
| | | if ((i > 0) && Character.isUpperCase(c)) { |
| | | if (!upperCase || !nextUpperCase) { |
| | | sb.append(SEPARATOR); |
| | | } |
| | | upperCase = true; |
| | | } else { |
| | | upperCase = false; |
| | | } |
| | | |
| | | sb.append(Character.toLowerCase(c)); |
| | | } |
| | | |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /** |
| | | * 获取ip地址 |
| | | */ |
| | | public static String getIp(HttpServletRequest request) { |
| | | 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("WL-Proxy-Client-IP"); |
| | | } |
| | | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { |
| | | ip = request.getRemoteAddr(); |
| | | } |
| | | String comma = ","; |
| | | String localhost = "127.0.0.1"; |
| | | if (ip.contains(comma)) { |
| | | ip = ip.split(",")[0]; |
| | | } |
| | | if (localhost.equals(ip)) { |
| | | // 获取本机真正的ip地址 |
| | | try { |
| | | ip = InetAddress.getLocalHost().getHostAddress(); |
| | | } catch (UnknownHostException e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | } |
| | | return ip; |
| | | } |
| | | |
| | | /** |
| | | * 根据ip获取详细地址 |
| | | */ |
| | | public static String getCityInfo(String ip) { |
| | | if (ElAdminProperties.ipLocal) { |
| | | return getLocalCityInfo(ip); |
| | | } else { |
| | | return getHttpCityInfo(ip); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据ip获取详细地址 |
| | | */ |
| | | public static String getHttpCityInfo(String ip) { |
| | | String api = String.format(ElAdminConstant.Url.IP_URL, ip); |
| | | JSONObject object = JSONUtil.parseObj(HttpUtil.get(api)); |
| | | return object.get("addr", String.class); |
| | | } |
| | | |
| | | /** |
| | | * 根据ip获取详细地址 |
| | | */ |
| | | public static String getLocalCityInfo(String ip) { |
| | | IpInfo ipInfo = IP_SEARCHER.memorySearch(ip); |
| | | if(ipInfo != null){ |
| | | return ipInfo.getAddress(); |
| | | } |
| | | return null; |
| | | |
| | | } |
| | | |
| | | public static String getBrowser(HttpServletRequest request) { |
| | | UserAgent.ImmutableUserAgent userAgent = USER_AGENT_ANALYZER.parse(request.getHeader("User-Agent")); |
| | | return userAgent.get(UserAgent.AGENT_NAME_VERSION).getValue(); |
| | | } |
| | | |
| | | /** |
| | | * 获得当天是周几 |
| | | */ |
| | | public static String getWeekDay() { |
| | | String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; |
| | | Calendar cal = Calendar.getInstance(); |
| | | cal.setTime(new Date()); |
| | | |
| | | int w = cal.get(Calendar.DAY_OF_WEEK) - 1; |
| | | if (w < 0) { |
| | | w = 0; |
| | | } |
| | | return weekDays[w]; |
| | | } |
| | | |
| | | /** |
| | | * 获取当前机器的IP |
| | | * |
| | | * @return / |
| | | */ |
| | | public static String getLocalIp() { |
| | | try { |
| | | InetAddress candidateAddress = null; |
| | | // 遍历所有的网络接口 |
| | | for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { |
| | | NetworkInterface anInterface = interfaces.nextElement(); |
| | | // 在所有的接口下再遍历IP |
| | | for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) { |
| | | InetAddress inetAddr = inetAddresses.nextElement(); |
| | | // 排除loopback类型地址 |
| | | if (!inetAddr.isLoopbackAddress()) { |
| | | if (inetAddr.isSiteLocalAddress()) { |
| | | // 如果是site-local地址,就是它了 |
| | | return inetAddr.getHostAddress(); |
| | | } else if (candidateAddress == null) { |
| | | // site-local类型的地址未被发现,先记录候选地址 |
| | | candidateAddress = inetAddr; |
| | | } |
| | | } |
| | | } |
| | | } |
| | | if (candidateAddress != null) { |
| | | return candidateAddress.getHostAddress(); |
| | | } |
| | | // 如果没有发现 non-loopback地址.只能用最次选的方案 |
| | | InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); |
| | | if (jdkSuppliedAddress == null) { |
| | | return ""; |
| | | } |
| | | return jdkSuppliedAddress.getHostAddress(); |
| | | } catch (Exception e) { |
| | | return ""; |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import java.io.PrintWriter; |
| | | import java.io.StringWriter; |
| | | |
| | | /** |
| | | * 异常工具 2019-01-06 |
| | | * @author Zheng Jie |
| | | */ |
| | | public class ThrowableUtil { |
| | | |
| | | /** |
| | | * 获取堆栈信息 |
| | | */ |
| | | public static String getStackTrace(Throwable throwable){ |
| | | StringWriter sw = new StringWriter(); |
| | | try (PrintWriter pw = new PrintWriter(sw)) { |
| | | throwable.printStackTrace(pw); |
| | | return sw.toString(); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.json.JSONArray; |
| | | import java.io.BufferedReader; |
| | | import java.io.InputStreamReader; |
| | | import java.net.HttpURLConnection; |
| | | import java.net.URL; |
| | | import java.net.URLEncoder; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 翻译工具类 |
| | | */ |
| | | public class TranslatorUtil { |
| | | |
| | | public static String translate(String word){ |
| | | try { |
| | | String url = "https://translate.googleapis.com/translate_a/single?" + |
| | | "client=gtx&" + |
| | | "sl=en" + |
| | | "&tl=zh-CN" + |
| | | "&dt=t&q=" + URLEncoder.encode(word, "UTF-8"); |
| | | |
| | | URL obj = new URL(url); |
| | | HttpURLConnection con = (HttpURLConnection) obj.openConnection(); |
| | | con.setRequestProperty("User-Agent", "Mozilla/5.0"); |
| | | |
| | | BufferedReader in = new BufferedReader( |
| | | new InputStreamReader(con.getInputStream())); |
| | | String inputLine; |
| | | StringBuilder response = new StringBuilder(); |
| | | |
| | | while ((inputLine = in.readLine()) != null) { |
| | | response.append(inputLine); |
| | | } |
| | | in.close(); |
| | | return parseResult(response.toString()); |
| | | }catch (Exception e){ |
| | | return word; |
| | | } |
| | | } |
| | | |
| | | private static String parseResult(String inputJson){ |
| | | JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0); |
| | | StringBuilder result = new StringBuilder(); |
| | | for (Object o : jsonArray2) { |
| | | result.append(((JSONArray) o).get(0).toString()); |
| | | } |
| | | return result.toString(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.core.lang.Validator; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | |
| | | /** |
| | | * 验证工具 |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | public class ValidationUtil { |
| | | |
| | | /** |
| | | * 验证空 |
| | | */ |
| | | public static void isNull(Object obj, String entity, String parameter , Object value){ |
| | | if(ObjectUtil.isNull(obj)){ |
| | | String msg = entity + " 不存在: "+ parameter +" is "+ value; |
| | | throw new BadRequestException(msg); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 验证是否为邮箱 |
| | | */ |
| | | public static boolean isEmail(String email) { |
| | | return Validator.isEmail(email); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils.enums; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Getter; |
| | | |
| | | /** |
| | | * <p> |
| | | * 验证码业务场景 |
| | | * </p> |
| | | * @author Zheng Jie |
| | | * @date 2020-05-02 |
| | | */ |
| | | @Getter |
| | | @AllArgsConstructor |
| | | public enum CodeBiEnum { |
| | | |
| | | /* 旧邮箱修改邮箱 */ |
| | | ONE(1, "旧邮箱修改邮箱"), |
| | | |
| | | /* 通过邮箱修改密码 */ |
| | | TWO(2, "通过邮箱修改密码"); |
| | | |
| | | private final Integer code; |
| | | private final String description; |
| | | |
| | | public static CodeBiEnum find(Integer code) { |
| | | for (CodeBiEnum value : CodeBiEnum.values()) { |
| | | if (value.getCode().equals(code)) { |
| | | return value; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils.enums; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Getter; |
| | | |
| | | /** |
| | | * <p> |
| | | * 验证码业务场景对应的 Redis 中的 key |
| | | * </p> |
| | | * @author Zheng Jie |
| | | * @date 2020-05-02 |
| | | */ |
| | | @Getter |
| | | @AllArgsConstructor |
| | | public enum CodeEnum { |
| | | |
| | | /* 通过手机号码重置邮箱 */ |
| | | PHONE_RESET_EMAIL_CODE("phone_reset_email_code_", "通过手机号码重置邮箱"), |
| | | |
| | | /* 通过旧邮箱重置邮箱 */ |
| | | EMAIL_RESET_EMAIL_CODE("email_reset_email_code_", "通过旧邮箱重置邮箱"), |
| | | |
| | | /* 通过手机号码重置密码 */ |
| | | PHONE_RESET_PWD_CODE("phone_reset_pwd_code_", "通过手机号码重置密码"), |
| | | |
| | | /* 通过邮箱重置密码 */ |
| | | EMAIL_RESET_PWD_CODE("email_reset_pwd_code_", "通过邮箱重置密码"); |
| | | |
| | | private final String key; |
| | | private final String description; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils.enums; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Getter; |
| | | |
| | | /** |
| | | * <p> |
| | | * 数据权限枚举 |
| | | * </p> |
| | | * @author Zheng Jie |
| | | * @date 2020-05-07 |
| | | */ |
| | | @Getter |
| | | @AllArgsConstructor |
| | | public enum DataScopeEnum { |
| | | |
| | | /* 全部的数据权限 */ |
| | | ALL("全部", "全部的数据权限"), |
| | | |
| | | /* 自己部门的数据权限 */ |
| | | THIS_LEVEL("本级", "自己部门的数据权限"), |
| | | |
| | | /* 自定义的数据权限 */ |
| | | CUSTOMIZE("自定义", "自定义的数据权限"); |
| | | |
| | | private final String value; |
| | | private final String description; |
| | | |
| | | public static DataScopeEnum find(String val) { |
| | | for (DataScopeEnum dataScopeEnum : DataScopeEnum.values()) { |
| | | if (dataScopeEnum.getValue().equals(val)) { |
| | | return dataScopeEnum; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils.enums; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Getter; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @website https://eladmin.vip |
| | | * @description |
| | | * @date 2020-06-10 |
| | | **/ |
| | | @Getter |
| | | @AllArgsConstructor |
| | | public enum RequestMethodEnum { |
| | | |
| | | /** |
| | | * 搜寻 @AnonymousGetMapping |
| | | */ |
| | | GET("GET"), |
| | | |
| | | /** |
| | | * 搜寻 @AnonymousPostMapping |
| | | */ |
| | | POST("POST"), |
| | | |
| | | /** |
| | | * 搜寻 @AnonymousPutMapping |
| | | */ |
| | | PUT("PUT"), |
| | | |
| | | /** |
| | | * 搜寻 @AnonymousPatchMapping |
| | | */ |
| | | PATCH("PATCH"), |
| | | |
| | | /** |
| | | * 搜寻 @AnonymousDeleteMapping |
| | | */ |
| | | DELETE("DELETE"), |
| | | |
| | | /** |
| | | * 否则就是所有 Request 接口都放行 |
| | | */ |
| | | ALL("All"); |
| | | |
| | | /** |
| | | * Request 类型 |
| | | */ |
| | | private final String type; |
| | | |
| | | public static RequestMethodEnum find(String type) { |
| | | for (RequestMethodEnum value : RequestMethodEnum.values()) { |
| | | if (value.getType().equals(type)) { |
| | | return value; |
| | | } |
| | | } |
| | | return ALL; |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.junit.jupiter.api.Test; |
| | | |
| | | import java.time.LocalDateTime; |
| | | import java.util.Date; |
| | | |
| | | public class DateUtilsTest { |
| | | @Test |
| | | public void test1() { |
| | | long l = System.currentTimeMillis() / 1000; |
| | | LocalDateTime localDateTime = DateUtil.fromTimeStamp(l); |
| | | System.out.print(DateUtil.localDateTimeFormatyMdHms(localDateTime)); |
| | | } |
| | | |
| | | @Test |
| | | public void test2() { |
| | | LocalDateTime now = LocalDateTime.now(); |
| | | System.out.println(DateUtil.localDateTimeFormatyMdHms(now)); |
| | | Date date = DateUtil.toDate(now); |
| | | LocalDateTime localDateTime = DateUtil.toLocalDateTime(date); |
| | | System.out.println(DateUtil.localDateTimeFormatyMdHms(localDateTime)); |
| | | LocalDateTime localDateTime1 = DateUtil.fromTimeStamp(date.getTime() / 1000); |
| | | System.out.println(DateUtil.localDateTimeFormatyMdHms(localDateTime1)); |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.junit.jupiter.api.Test; |
| | | |
| | | import static me.zhengjie.utils.EncryptUtils.*; |
| | | import static org.junit.jupiter.api.Assertions.assertEquals; |
| | | |
| | | public class EncryptUtilsTest { |
| | | |
| | | /** |
| | | * 对称加密 |
| | | */ |
| | | @Test |
| | | public void testDesEncrypt() { |
| | | try { |
| | | assertEquals("7772841DC6099402", desEncrypt("123456")); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 对称解密 |
| | | */ |
| | | @Test |
| | | public void testDesDecrypt() { |
| | | try { |
| | | assertEquals("123456", desDecrypt("7772841DC6099402")); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.junit.jupiter.api.Test; |
| | | import org.springframework.mock.web.MockMultipartFile; |
| | | |
| | | import static me.zhengjie.utils.FileUtil.*; |
| | | import static org.junit.jupiter.api.Assertions.assertEquals; |
| | | |
| | | public class FileUtilTest { |
| | | |
| | | @Test |
| | | public void testToFile() { |
| | | long retval = toFile(new MockMultipartFile("foo", (byte[]) null)).getTotalSpace(); |
| | | assertEquals(500695072768L, retval); |
| | | } |
| | | |
| | | @Test |
| | | public void testGetExtensionName() { |
| | | assertEquals("foo", getExtensionName("foo")); |
| | | assertEquals("exe", getExtensionName("bar.exe")); |
| | | } |
| | | |
| | | @Test |
| | | public void testGetFileNameNoEx() { |
| | | assertEquals("foo", getFileNameNoEx("foo")); |
| | | assertEquals("bar", getFileNameNoEx("bar.txt")); |
| | | } |
| | | |
| | | @Test |
| | | public void testGetSize() { |
| | | assertEquals("1000B ", getSize(1000)); |
| | | assertEquals("1.00KB ", getSize(1024)); |
| | | assertEquals("1.00MB ", getSize(1048576)); |
| | | assertEquals("1.00GB ", getSize(1073741824)); |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.junit.jupiter.api.Test; |
| | | import org.springframework.mock.web.MockHttpServletRequest; |
| | | |
| | | import java.text.SimpleDateFormat; |
| | | import java.util.Date; |
| | | |
| | | import static me.zhengjie.utils.StringUtils.getIp; |
| | | import static me.zhengjie.utils.StringUtils.getWeekDay; |
| | | import static me.zhengjie.utils.StringUtils.toCamelCase; |
| | | import static me.zhengjie.utils.StringUtils.toCapitalizeCamelCase; |
| | | import static me.zhengjie.utils.StringUtils.toUnderScoreCase; |
| | | import static org.junit.jupiter.api.Assertions.assertEquals; |
| | | import static org.junit.jupiter.api.Assertions.assertNull; |
| | | |
| | | public class StringUtilsTest { |
| | | |
| | | @Test |
| | | public void testToCamelCase() { |
| | | assertNull(toCamelCase(null)); |
| | | } |
| | | |
| | | @Test |
| | | public void testToCapitalizeCamelCase() { |
| | | assertNull(StringUtils.toCapitalizeCamelCase(null)); |
| | | assertEquals("HelloWorld", toCapitalizeCamelCase("hello_world")); |
| | | } |
| | | |
| | | @Test |
| | | public void testToUnderScoreCase() { |
| | | assertNull(StringUtils.toUnderScoreCase(null)); |
| | | assertEquals("hello_world", toUnderScoreCase("helloWorld")); |
| | | assertEquals("\u0000\u0000", toUnderScoreCase("\u0000\u0000")); |
| | | assertEquals("\u0000_a", toUnderScoreCase("\u0000A")); |
| | | } |
| | | |
| | | @Test |
| | | public void testGetWeekDay() { |
| | | SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); |
| | | assertEquals(simpleDateformat.format(new Date()), getWeekDay()); |
| | | } |
| | | |
| | | @Test |
| | | public void testGetIP() { |
| | | assertEquals("127.0.0.1", getIp(new MockHttpServletRequest())); |
| | | } |
| | | } |
| New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <project xmlns="http://maven.apache.org/POM/4.0.0" |
| | | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| | | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| | | <parent> |
| | | <artifactId>eladmin</artifactId> |
| | | <groupId>me.zhengjie</groupId> |
| | | <version>2.6</version> |
| | | </parent> |
| | | <modelVersion>4.0.0</modelVersion> |
| | | |
| | | <artifactId>eladmin-generator</artifactId> |
| | | <name>代码生成模块</name> |
| | | |
| | | <properties> |
| | | <configuration.version>1.10</configuration.version> |
| | | </properties> |
| | | |
| | | <dependencies> |
| | | <dependency> |
| | | <groupId>me.zhengjie</groupId> |
| | | <artifactId>eladmin-common</artifactId> |
| | | <version>2.6</version> |
| | | </dependency> |
| | | |
| | | <!--模板引擎--> |
| | | <dependency> |
| | | <groupId>org.springframework.boot</groupId> |
| | | <artifactId>spring-boot-starter-freemarker</artifactId> |
| | | </dependency> |
| | | |
| | | <!-- https://mvnrepository.com/artifact/commons-configuration/commons-configuration --> |
| | | <dependency> |
| | | <groupId>commons-configuration</groupId> |
| | | <artifactId>commons-configuration</artifactId> |
| | | <version>${configuration.version}</version> |
| | | </dependency> |
| | | </dependencies> |
| | | </project> |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.NoArgsConstructor; |
| | | import lombok.Setter; |
| | | import me.zhengjie.utils.GenUtil; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * 列的数据信息 |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @Entity |
| | | @NoArgsConstructor |
| | | @Table(name = "code_column_config") |
| | | public class ColumnInfo implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "column_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @ApiModelProperty(value = "表名") |
| | | private String tableName; |
| | | |
| | | @ApiModelProperty(value = "数据库字段名称") |
| | | private String columnName; |
| | | |
| | | @ApiModelProperty(value = "数据库字段类型") |
| | | private String columnType; |
| | | |
| | | @ApiModelProperty(value = "数据库字段键类型") |
| | | private String keyType; |
| | | |
| | | @ApiModelProperty(value = "字段额外的参数") |
| | | private String extra; |
| | | |
| | | @ApiModelProperty(value = "数据库字段描述") |
| | | private String remark; |
| | | |
| | | @ApiModelProperty(value = "是否必填") |
| | | private Boolean notNull; |
| | | |
| | | @ApiModelProperty(value = "是否在列表显示") |
| | | private Boolean listShow; |
| | | |
| | | @ApiModelProperty(value = "是否表单显示") |
| | | private Boolean formShow; |
| | | |
| | | @ApiModelProperty(value = "表单类型") |
| | | private String formType; |
| | | |
| | | @ApiModelProperty(value = "查询 1:模糊 2:精确") |
| | | private String queryType; |
| | | |
| | | @ApiModelProperty(value = "字典名称") |
| | | private String dictName; |
| | | |
| | | @ApiModelProperty(value = "日期注解") |
| | | private String dateAnnotation; |
| | | |
| | | public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { |
| | | this.tableName = tableName; |
| | | this.columnName = columnName; |
| | | this.columnType = columnType; |
| | | this.keyType = keyType; |
| | | this.extra = extra; |
| | | this.notNull = notNull; |
| | | if(GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)){ |
| | | this.notNull = false; |
| | | } |
| | | this.remark = remark; |
| | | this.listShow = true; |
| | | this.formShow = true; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.NoArgsConstructor; |
| | | import lombok.Setter; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * 代码生成配置 |
| | | * @author Zheng Jie |
| | | * @date 2019-01-03 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @Entity |
| | | @NoArgsConstructor |
| | | @Table(name = "code_gen_config") |
| | | public class GenConfig implements Serializable { |
| | | |
| | | public GenConfig(String tableName) { |
| | | this.tableName = tableName; |
| | | } |
| | | |
| | | @Id |
| | | @Column(name = "config_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "表名") |
| | | private String tableName; |
| | | |
| | | @ApiModelProperty(value = "接口名称") |
| | | private String apiAlias; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "包路径") |
| | | private String pack; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "模块名") |
| | | private String moduleName; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "前端文件路径") |
| | | private String path; |
| | | |
| | | @ApiModelProperty(value = "前端文件路径") |
| | | private String apiPath; |
| | | |
| | | @ApiModelProperty(value = "作者") |
| | | private String author; |
| | | |
| | | @ApiModelProperty(value = "表前缀") |
| | | private String prefix; |
| | | |
| | | @ApiModelProperty(value = "是否覆盖") |
| | | private Boolean cover = false; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.domain.vo; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | |
| | | /** |
| | | * 表的数据信息 |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @NoArgsConstructor |
| | | public class TableInfo { |
| | | |
| | | /** 表名称 */ |
| | | private Object tableName; |
| | | |
| | | /** 创建日期 */ |
| | | private Object createTime; |
| | | |
| | | /** 数据库引擎 */ |
| | | private Object engine; |
| | | |
| | | /** 编码集 */ |
| | | private Object coding; |
| | | |
| | | /** 备注 */ |
| | | private Object remark; |
| | | |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.repository; |
| | | |
| | | import me.zhengjie.domain.ColumnInfo; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-14 |
| | | */ |
| | | public interface ColumnInfoRepository extends JpaRepository<ColumnInfo,Long> { |
| | | |
| | | /** |
| | | * 查询表信息 |
| | | * @param tableName 表格名 |
| | | * @return 表信息 |
| | | */ |
| | | List<ColumnInfo> findByTableNameOrderByIdAsc(String tableName); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.repository; |
| | | |
| | | import me.zhengjie.domain.GenConfig; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-14 |
| | | */ |
| | | public interface GenConfigRepository extends JpaRepository<GenConfig,Long> { |
| | | |
| | | /** |
| | | * 查询表配置 |
| | | * @param tableName 表名 |
| | | * @return / |
| | | */ |
| | | GenConfig findByTableName(String tableName); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.GenConfig; |
| | | import me.zhengjie.service.GenConfigService; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-14 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/genConfig") |
| | | @Api(tags = "系统:代码生成器配置管理") |
| | | public class GenConfigController { |
| | | |
| | | private final GenConfigService genConfigService; |
| | | |
| | | @ApiOperation("查询") |
| | | @GetMapping(value = "/{tableName}") |
| | | public ResponseEntity<Object> queryGenConfig(@PathVariable String tableName){ |
| | | return new ResponseEntity<>(genConfigService.find(tableName), HttpStatus.OK); |
| | | } |
| | | |
| | | @PutMapping |
| | | @ApiOperation("修改") |
| | | public ResponseEntity<Object> updateGenConfig(@Validated @RequestBody GenConfig genConfig){ |
| | | return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig),HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.ColumnInfo; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.service.GenConfigService; |
| | | import me.zhengjie.service.GeneratorService; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/generator") |
| | | @Api(tags = "系统:代码生成管理") |
| | | public class GeneratorController { |
| | | |
| | | private final GeneratorService generatorService; |
| | | private final GenConfigService genConfigService; |
| | | |
| | | @Value("${generator.enabled}") |
| | | private Boolean generatorEnabled; |
| | | |
| | | @ApiOperation("查询数据库数据") |
| | | @GetMapping(value = "/tables/all") |
| | | public ResponseEntity<Object> queryAllTables(){ |
| | | return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询数据库数据") |
| | | @GetMapping(value = "/tables") |
| | | public ResponseEntity<Object> queryTables(@RequestParam(defaultValue = "") String name, |
| | | @RequestParam(defaultValue = "0")Integer page, |
| | | @RequestParam(defaultValue = "10")Integer size){ |
| | | int[] startEnd = PageUtil.transToStartEnd(page, size); |
| | | return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询字段数据") |
| | | @GetMapping(value = "/columns") |
| | | public ResponseEntity<Object> queryColumns(@RequestParam String tableName){ |
| | | List<ColumnInfo> columnInfos = generatorService.getColumns(tableName); |
| | | return new ResponseEntity<>(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("保存字段数据") |
| | | @PutMapping |
| | | public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos){ |
| | | generatorService.save(columnInfos); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("同步字段数据") |
| | | @PostMapping(value = "sync") |
| | | public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables){ |
| | | for (String table : tables) { |
| | | generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); |
| | | } |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("生成代码") |
| | | @PostMapping(value = "/{tableName}/{type}") |
| | | public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){ |
| | | if(!generatorEnabled && type == 0){ |
| | | throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); |
| | | } |
| | | switch (type){ |
| | | // 生成代码 |
| | | case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); |
| | | break; |
| | | // 预览 |
| | | case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); |
| | | // 打包 |
| | | case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); |
| | | break; |
| | | default: throw new BadRequestException("没有这个选项"); |
| | | } |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service; |
| | | |
| | | import me.zhengjie.domain.GenConfig; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-14 |
| | | */ |
| | | public interface GenConfigService { |
| | | |
| | | /** |
| | | * 查询表配置 |
| | | * @param tableName 表名 |
| | | * @return 表配置 |
| | | */ |
| | | GenConfig find(String tableName); |
| | | |
| | | /** |
| | | * 更新表配置 |
| | | * @param tableName 表名 |
| | | * @param genConfig 表配置 |
| | | * @return 表配置 |
| | | */ |
| | | GenConfig update(String tableName, GenConfig genConfig); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service; |
| | | |
| | | import me.zhengjie.domain.GenConfig; |
| | | import me.zhengjie.domain.ColumnInfo; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | public interface GeneratorService { |
| | | |
| | | /** |
| | | * 查询数据库元数据 |
| | | * @param name 表名 |
| | | * @param startEnd 分页参数 |
| | | * @return / |
| | | */ |
| | | Object getTables(String name, int[] startEnd); |
| | | |
| | | /** |
| | | * 得到数据表的元数据 |
| | | * @param name 表名 |
| | | * @return / |
| | | */ |
| | | List<ColumnInfo> getColumns(String name); |
| | | |
| | | /** |
| | | * 同步表数据 |
| | | * @param columnInfos / |
| | | * @param columnInfoList / |
| | | */ |
| | | void sync(List<ColumnInfo> columnInfos, List<ColumnInfo> columnInfoList); |
| | | |
| | | /** |
| | | * 保持数据 |
| | | * @param columnInfos / |
| | | */ |
| | | void save(List<ColumnInfo> columnInfos); |
| | | |
| | | /** |
| | | * 获取所有table |
| | | * @return / |
| | | */ |
| | | Object getTables(); |
| | | |
| | | /** |
| | | * 代码生成 |
| | | * @param genConfig 配置信息 |
| | | * @param columns 字段信息 |
| | | */ |
| | | void generator(GenConfig genConfig, List<ColumnInfo> columns); |
| | | |
| | | /** |
| | | * 预览 |
| | | * @param genConfig 配置信息 |
| | | * @param columns 字段信息 |
| | | * @return / |
| | | */ |
| | | ResponseEntity<Object> preview(GenConfig genConfig, List<ColumnInfo> columns); |
| | | |
| | | /** |
| | | * 打包下载 |
| | | * @param genConfig 配置信息 |
| | | * @param columns 字段信息 |
| | | * @param request / |
| | | * @param response / |
| | | */ |
| | | void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response); |
| | | |
| | | /** |
| | | * 查询数据库的表字段数据数据 |
| | | * @param table / |
| | | * @return / |
| | | */ |
| | | List<ColumnInfo> query(String table); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.GenConfig; |
| | | import me.zhengjie.repository.GenConfigRepository; |
| | | import me.zhengjie.service.GenConfigService; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.springframework.stereotype.Service; |
| | | import java.io.File; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-14 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class GenConfigServiceImpl implements GenConfigService { |
| | | |
| | | private final GenConfigRepository genConfigRepository; |
| | | |
| | | @Override |
| | | public GenConfig find(String tableName) { |
| | | GenConfig genConfig = genConfigRepository.findByTableName(tableName); |
| | | if(genConfig == null){ |
| | | return new GenConfig(tableName); |
| | | } |
| | | return genConfig; |
| | | } |
| | | |
| | | @Override |
| | | public GenConfig update(String tableName, GenConfig genConfig) { |
| | | String separator = File.separator; |
| | | String[] paths; |
| | | String symbol = "\\"; |
| | | if (symbol.equals(separator)) { |
| | | paths = genConfig.getPath().split("\\\\"); |
| | | } else { |
| | | paths = genConfig.getPath().split(File.separator); |
| | | } |
| | | StringBuilder api = new StringBuilder(); |
| | | for (String path : paths) { |
| | | api.append(path); |
| | | api.append(separator); |
| | | if ("src".equals(path)) { |
| | | api.append("api"); |
| | | break; |
| | | } |
| | | } |
| | | genConfig.setApiPath(api.toString()); |
| | | return genConfigRepository.save(genConfig); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.impl; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import cn.hutool.core.util.ZipUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.GenConfig; |
| | | import me.zhengjie.domain.ColumnInfo; |
| | | import me.zhengjie.domain.vo.TableInfo; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.repository.ColumnInfoRepository; |
| | | import me.zhengjie.service.GeneratorService; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import me.zhengjie.utils.GenUtil; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.stereotype.Service; |
| | | import javax.persistence.EntityManager; |
| | | import javax.persistence.PersistenceContext; |
| | | import javax.persistence.Query; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.File; |
| | | import java.io.IOException; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class GeneratorServiceImpl implements GeneratorService { |
| | | private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class); |
| | | @PersistenceContext |
| | | private EntityManager em; |
| | | |
| | | private final ColumnInfoRepository columnInfoRepository; |
| | | |
| | | private final String CONFIG_MESSAGE = "请先配置生成器"; |
| | | @Override |
| | | public Object getTables() { |
| | | // 使用预编译防止sql注入 |
| | | String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + |
| | | "where table_schema = (select database()) " + |
| | | "order by create_time desc"; |
| | | Query query = em.createNativeQuery(sql); |
| | | return query.getResultList(); |
| | | } |
| | | |
| | | @Override |
| | | public Object getTables(String name, int[] startEnd) { |
| | | // 使用预编译防止sql注入 |
| | | String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + |
| | | "where table_schema = (select database()) " + |
| | | "and table_name like :table order by create_time desc"; |
| | | Query query = em.createNativeQuery(sql); |
| | | query.setFirstResult(startEnd[0]); |
| | | query.setMaxResults(startEnd[1] - startEnd[0]); |
| | | query.setParameter("table", StringUtils.isNotBlank(name) ? ("%" + name + "%") : "%%"); |
| | | List result = query.getResultList(); |
| | | List<TableInfo> tableInfos = new ArrayList<>(); |
| | | for (Object obj : result) { |
| | | Object[] arr = (Object[]) obj; |
| | | tableInfos.add(new TableInfo(arr[0], arr[1], arr[2], arr[3], ObjectUtil.isNotEmpty(arr[4]) ? arr[4] : "-")); |
| | | } |
| | | String countSql = "select count(1) from information_schema.tables " + |
| | | "where table_schema = (select database()) and table_name like :table"; |
| | | Query queryCount = em.createNativeQuery(countSql); |
| | | queryCount.setParameter("table", StringUtils.isNotBlank(name) ? ("%" + name + "%") : "%%"); |
| | | Object totalElements = queryCount.getSingleResult(); |
| | | return PageUtil.toPage(tableInfos, totalElements); |
| | | } |
| | | |
| | | @Override |
| | | public List<ColumnInfo> getColumns(String tableName) { |
| | | List<ColumnInfo> columnInfos = columnInfoRepository.findByTableNameOrderByIdAsc(tableName); |
| | | if (CollectionUtil.isNotEmpty(columnInfos)) { |
| | | return columnInfos; |
| | | } else { |
| | | columnInfos = query(tableName); |
| | | return columnInfoRepository.saveAll(columnInfos); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public List<ColumnInfo> query(String tableName) { |
| | | // 使用预编译防止sql注入 |
| | | String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " + |
| | | "where table_name = ? and table_schema = (select database()) order by ordinal_position"; |
| | | Query query = em.createNativeQuery(sql); |
| | | query.setParameter(1, tableName); |
| | | List result = query.getResultList(); |
| | | List<ColumnInfo> columnInfos = new ArrayList<>(); |
| | | for (Object obj : result) { |
| | | Object[] arr = (Object[]) obj; |
| | | columnInfos.add( |
| | | new ColumnInfo( |
| | | tableName, |
| | | arr[0].toString(), |
| | | "NO".equals(arr[1]), |
| | | arr[2].toString(), |
| | | ObjectUtil.isNotNull(arr[3]) ? arr[3].toString() : null, |
| | | ObjectUtil.isNotNull(arr[4]) ? arr[4].toString() : null, |
| | | ObjectUtil.isNotNull(arr[5]) ? arr[5].toString() : null) |
| | | ); |
| | | } |
| | | return columnInfos; |
| | | } |
| | | |
| | | @Override |
| | | public void sync(List<ColumnInfo> columnInfos, List<ColumnInfo> columnInfoList) { |
| | | // 第一种情况,数据库类字段改变或者新增字段 |
| | | for (ColumnInfo columnInfo : columnInfoList) { |
| | | // 根据字段名称查找 |
| | | List<ColumnInfo> columns = columnInfos.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); |
| | | // 如果能找到,就修改部分可能被字段 |
| | | if (CollectionUtil.isNotEmpty(columns)) { |
| | | ColumnInfo column = columns.get(0); |
| | | column.setColumnType(columnInfo.getColumnType()); |
| | | column.setExtra(columnInfo.getExtra()); |
| | | column.setKeyType(columnInfo.getKeyType()); |
| | | if (StringUtils.isBlank(column.getRemark())) { |
| | | column.setRemark(columnInfo.getRemark()); |
| | | } |
| | | columnInfoRepository.save(column); |
| | | } else { |
| | | // 如果找不到,则保存新字段信息 |
| | | columnInfoRepository.save(columnInfo); |
| | | } |
| | | } |
| | | // 第二种情况,数据库字段删除了 |
| | | for (ColumnInfo columnInfo : columnInfos) { |
| | | // 根据字段名称查找 |
| | | List<ColumnInfo> columns = columnInfoList.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); |
| | | // 如果找不到,就代表字段被删除了,则需要删除该字段 |
| | | if (CollectionUtil.isEmpty(columns)) { |
| | | columnInfoRepository.delete(columnInfo); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void save(List<ColumnInfo> columnInfos) { |
| | | columnInfoRepository.saveAll(columnInfos); |
| | | } |
| | | |
| | | @Override |
| | | public void generator(GenConfig genConfig, List<ColumnInfo> columns) { |
| | | if (genConfig.getId() == null) { |
| | | throw new BadRequestException(CONFIG_MESSAGE); |
| | | } |
| | | try { |
| | | GenUtil.generatorCode(columns, genConfig); |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(), e); |
| | | throw new BadRequestException("生成失败,请手动处理已生成的文件"); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public ResponseEntity<Object> preview(GenConfig genConfig, List<ColumnInfo> columns) { |
| | | if (genConfig.getId() == null) { |
| | | throw new BadRequestException(CONFIG_MESSAGE); |
| | | } |
| | | List<Map<String, Object>> genList = GenUtil.preview(columns, genConfig); |
| | | return new ResponseEntity<>(genList, HttpStatus.OK); |
| | | } |
| | | |
| | | @Override |
| | | public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) { |
| | | if (genConfig.getId() == null) { |
| | | throw new BadRequestException(CONFIG_MESSAGE); |
| | | } |
| | | try { |
| | | File file = new File(GenUtil.download(columns, genConfig)); |
| | | String zipPath = file.getPath() + ".zip"; |
| | | ZipUtil.zip(file.getPath(), zipPath); |
| | | FileUtil.downloadFile(request, response, new File(zipPath), true); |
| | | } catch (IOException e) { |
| | | throw new BadRequestException("打包失败"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import org.apache.commons.configuration.*; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | |
| | | /** |
| | | * sql字段转java |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2019-01-03 |
| | | */ |
| | | public class ColUtil { |
| | | private static final Logger log = LoggerFactory.getLogger(ColUtil.class); |
| | | |
| | | /** |
| | | * 转换mysql数据类型为java数据类型 |
| | | * |
| | | * @param type 数据库字段类型 |
| | | * @return String |
| | | */ |
| | | static String cloToJava(String type) { |
| | | Configuration config = getConfig(); |
| | | assert config != null; |
| | | return config.getString(type, "unknowType"); |
| | | } |
| | | |
| | | /** |
| | | * 获取配置信息 |
| | | */ |
| | | public static PropertiesConfiguration getConfig() { |
| | | try { |
| | | return new PropertiesConfiguration("generator.properties"); |
| | | } catch (ConfigurationException e) { |
| | | log.error(e.getMessage(), e); |
| | | } |
| | | return null; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.utils; |
| | | |
| | | import cn.hutool.core.util.StrUtil; |
| | | import cn.hutool.extra.template.*; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.domain.GenConfig; |
| | | import me.zhengjie.domain.ColumnInfo; |
| | | import org.springframework.util.ObjectUtils; |
| | | |
| | | import java.io.File; |
| | | import java.io.FileWriter; |
| | | import java.io.IOException; |
| | | import java.io.Writer; |
| | | import java.time.LocalDate; |
| | | import java.util.*; |
| | | |
| | | import static me.zhengjie.utils.FileUtil.SYS_TEM_DIR; |
| | | |
| | | /** |
| | | * 代码生成 |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2019-01-02 |
| | | */ |
| | | @Slf4j |
| | | @SuppressWarnings({"unchecked", "all"}) |
| | | public class GenUtil { |
| | | |
| | | private static final String TIMESTAMP = "Timestamp"; |
| | | |
| | | private static final String BIGDECIMAL = "BigDecimal"; |
| | | |
| | | public static final String PK = "PRI"; |
| | | |
| | | public static final String EXTRA = "auto_increment"; |
| | | |
| | | /** |
| | | * 获取后端代码模板名称 |
| | | * |
| | | * @return List |
| | | */ |
| | | private static List<String> getAdminTemplateNames() { |
| | | List<String> templateNames = new ArrayList<>(); |
| | | templateNames.add("Entity"); |
| | | templateNames.add("Dto"); |
| | | templateNames.add("Mapper"); |
| | | templateNames.add("Controller"); |
| | | templateNames.add("QueryCriteria"); |
| | | templateNames.add("Service"); |
| | | templateNames.add("ServiceImpl"); |
| | | templateNames.add("Repository"); |
| | | return templateNames; |
| | | } |
| | | |
| | | /** |
| | | * 获取前端代码模板名称 |
| | | * |
| | | * @return List |
| | | */ |
| | | private static List<String> getFrontTemplateNames() { |
| | | List<String> templateNames = new ArrayList<>(); |
| | | templateNames.add("index"); |
| | | templateNames.add("api"); |
| | | return templateNames; |
| | | } |
| | | |
| | | public static List<Map<String, Object>> preview(List<ColumnInfo> columns, GenConfig genConfig) { |
| | | Map<String, Object> genMap = getGenMap(columns, genConfig); |
| | | List<Map<String, Object>> genList = new ArrayList<>(); |
| | | // 获取后端模版 |
| | | List<String> templates = getAdminTemplateNames(); |
| | | TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); |
| | | for (String templateName : templates) { |
| | | Map<String, Object> map = new HashMap<>(1); |
| | | Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); |
| | | map.put("content", template.render(genMap)); |
| | | map.put("name", templateName); |
| | | genList.add(map); |
| | | } |
| | | // 获取前端模版 |
| | | templates = getFrontTemplateNames(); |
| | | for (String templateName : templates) { |
| | | Map<String, Object> map = new HashMap<>(1); |
| | | Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); |
| | | map.put(templateName, template.render(genMap)); |
| | | map.put("content", template.render(genMap)); |
| | | map.put("name", templateName); |
| | | genList.add(map); |
| | | } |
| | | return genList; |
| | | } |
| | | |
| | | public static String download(List<ColumnInfo> columns, GenConfig genConfig) throws IOException { |
| | | // 拼接的路径:/tmpeladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/eladmin-gen-temp/ |
| | | // String tempPath =SYS_TEM_DIR + "eladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; |
| | | String tempPath = SYS_TEM_DIR + "eladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; |
| | | Map<String, Object> genMap = getGenMap(columns, genConfig); |
| | | TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); |
| | | // 生成后端代码 |
| | | List<String> templates = getAdminTemplateNames(); |
| | | for (String templateName : templates) { |
| | | Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); |
| | | String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); |
| | | assert filePath != null; |
| | | File file = new File(filePath); |
| | | // 如果非覆盖生成 |
| | | if (!genConfig.getCover() && FileUtil.exist(file)) { |
| | | continue; |
| | | } |
| | | // 生成代码 |
| | | genFile(file, template, genMap); |
| | | } |
| | | // 生成前端代码 |
| | | templates = getFrontTemplateNames(); |
| | | for (String templateName : templates) { |
| | | Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); |
| | | String path = tempPath + "eladmin-web" + File.separator; |
| | | String apiPath = path + "src" + File.separator + "api" + File.separator; |
| | | String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; |
| | | String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); |
| | | assert filePath != null; |
| | | File file = new File(filePath); |
| | | // 如果非覆盖生成 |
| | | if (!genConfig.getCover() && FileUtil.exist(file)) { |
| | | continue; |
| | | } |
| | | // 生成代码 |
| | | genFile(file, template, genMap); |
| | | } |
| | | return tempPath; |
| | | } |
| | | |
| | | public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig) throws IOException { |
| | | Map<String, Object> genMap = getGenMap(columnInfos, genConfig); |
| | | TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); |
| | | // 生成后端代码 |
| | | List<String> templates = getAdminTemplateNames(); |
| | | for (String templateName : templates) { |
| | | Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); |
| | | String rootPath = System.getProperty("user.dir"); |
| | | String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), rootPath); |
| | | |
| | | assert filePath != null; |
| | | File file = new File(filePath); |
| | | |
| | | // 如果非覆盖生成 |
| | | if (!genConfig.getCover() && FileUtil.exist(file)) { |
| | | continue; |
| | | } |
| | | // 生成代码 |
| | | genFile(file, template, genMap); |
| | | } |
| | | |
| | | // 生成前端代码 |
| | | templates = getFrontTemplateNames(); |
| | | for (String templateName : templates) { |
| | | Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); |
| | | String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); |
| | | |
| | | assert filePath != null; |
| | | File file = new File(filePath); |
| | | |
| | | // 如果非覆盖生成 |
| | | if (!genConfig.getCover() && FileUtil.exist(file)) { |
| | | continue; |
| | | } |
| | | // 生成代码 |
| | | genFile(file, template, genMap); |
| | | } |
| | | } |
| | | |
| | | // 获取模版数据 |
| | | private static Map<String, Object> getGenMap(List<ColumnInfo> columnInfos, GenConfig genConfig) { |
| | | // 存储模版字段数据 |
| | | Map<String, Object> genMap = new HashMap<>(16); |
| | | // 接口别名 |
| | | genMap.put("apiAlias", genConfig.getApiAlias()); |
| | | // 包名称 |
| | | genMap.put("package", genConfig.getPack()); |
| | | // 模块名称 |
| | | genMap.put("moduleName", genConfig.getModuleName()); |
| | | // 作者 |
| | | genMap.put("author", genConfig.getAuthor()); |
| | | // 创建日期 |
| | | genMap.put("date", LocalDate.now().toString()); |
| | | // 表名 |
| | | genMap.put("tableName", genConfig.getTableName()); |
| | | // 大写开头的类名 |
| | | String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); |
| | | // 小写开头的类名 |
| | | String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); |
| | | // 判断是否去除表前缀 |
| | | if (StringUtils.isNotEmpty(genConfig.getPrefix())) { |
| | | className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); |
| | | changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); |
| | | changeClassName = StringUtils.uncapitalize(changeClassName); |
| | | } |
| | | // 保存类名 |
| | | genMap.put("className", className); |
| | | // 保存小写开头的类名 |
| | | genMap.put("changeClassName", changeClassName); |
| | | // 存在 Timestamp 字段 |
| | | genMap.put("hasTimestamp", false); |
| | | // 查询类中存在 Timestamp 字段 |
| | | genMap.put("queryHasTimestamp", false); |
| | | // 存在 BigDecimal 字段 |
| | | genMap.put("hasBigDecimal", false); |
| | | // 查询类中存在 BigDecimal 字段 |
| | | genMap.put("queryHasBigDecimal", false); |
| | | // 是否需要创建查询 |
| | | genMap.put("hasQuery", false); |
| | | // 自增主键 |
| | | genMap.put("auto", false); |
| | | // 存在字典 |
| | | genMap.put("hasDict", false); |
| | | // 存在日期注解 |
| | | genMap.put("hasDateAnnotation", false); |
| | | // 保存字段信息 |
| | | List<Map<String, Object>> columns = new ArrayList<>(); |
| | | // 保存查询字段的信息 |
| | | List<Map<String, Object>> queryColumns = new ArrayList<>(); |
| | | // 存储字典信息 |
| | | List<String> dicts = new ArrayList<>(); |
| | | // 存储 between 信息 |
| | | List<Map<String, Object>> betweens = new ArrayList<>(); |
| | | // 存储不为空的字段信息 |
| | | List<Map<String, Object>> isNotNullColumns = new ArrayList<>(); |
| | | |
| | | for (ColumnInfo column : columnInfos) { |
| | | Map<String, Object> listMap = new HashMap<>(16); |
| | | // 字段描述 |
| | | listMap.put("remark", column.getRemark()); |
| | | // 字段类型 |
| | | listMap.put("columnKey", column.getKeyType()); |
| | | // 主键类型 |
| | | String colType = ColUtil.cloToJava(column.getColumnType()); |
| | | // 小写开头的字段名 |
| | | String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); |
| | | // 大写开头的字段名 |
| | | String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); |
| | | if (PK.equals(column.getKeyType())) { |
| | | // 存储主键类型 |
| | | genMap.put("pkColumnType", colType); |
| | | // 存储小写开头的字段名 |
| | | genMap.put("pkChangeColName", changeColumnName); |
| | | // 存储大写开头的字段名 |
| | | genMap.put("pkCapitalColName", capitalColumnName); |
| | | } |
| | | // 是否存在 Timestamp 类型的字段 |
| | | if (TIMESTAMP.equals(colType)) { |
| | | genMap.put("hasTimestamp", true); |
| | | } |
| | | // 是否存在 BigDecimal 类型的字段 |
| | | if (BIGDECIMAL.equals(colType)) { |
| | | genMap.put("hasBigDecimal", true); |
| | | } |
| | | // 主键是否自增 |
| | | if (EXTRA.equals(column.getExtra())) { |
| | | genMap.put("auto", true); |
| | | } |
| | | // 主键存在字典 |
| | | if (StringUtils.isNotBlank(column.getDictName())) { |
| | | genMap.put("hasDict", true); |
| | | if(!dicts.contains(column.getDictName())) |
| | | dicts.add(column.getDictName()); |
| | | } |
| | | |
| | | // 存储字段类型 |
| | | listMap.put("columnType", colType); |
| | | // 存储字原始段名称 |
| | | listMap.put("columnName", column.getColumnName()); |
| | | // 不为空 |
| | | listMap.put("istNotNull", column.getNotNull()); |
| | | // 字段列表显示 |
| | | listMap.put("columnShow", column.getListShow()); |
| | | // 表单显示 |
| | | listMap.put("formShow", column.getFormShow()); |
| | | // 表单组件类型 |
| | | listMap.put("formType", StringUtils.isNotBlank(column.getFormType()) ? column.getFormType() : "Input"); |
| | | // 小写开头的字段名称 |
| | | listMap.put("changeColumnName", changeColumnName); |
| | | //大写开头的字段名称 |
| | | listMap.put("capitalColumnName", capitalColumnName); |
| | | // 字典名称 |
| | | listMap.put("dictName", column.getDictName()); |
| | | // 日期注解 |
| | | listMap.put("dateAnnotation", column.getDateAnnotation()); |
| | | if (StringUtils.isNotBlank(column.getDateAnnotation())) { |
| | | genMap.put("hasDateAnnotation", true); |
| | | } |
| | | // 添加非空字段信息 |
| | | if (column.getNotNull()) { |
| | | isNotNullColumns.add(listMap); |
| | | } |
| | | // 判断是否有查询,如有则把查询的字段set进columnQuery |
| | | if (!StringUtils.isBlank(column.getQueryType())) { |
| | | // 查询类型 |
| | | listMap.put("queryType", column.getQueryType()); |
| | | // 是否存在查询 |
| | | genMap.put("hasQuery", true); |
| | | if (TIMESTAMP.equals(colType)) { |
| | | // 查询中存储 Timestamp 类型 |
| | | genMap.put("queryHasTimestamp", true); |
| | | } |
| | | if (BIGDECIMAL.equals(colType)) { |
| | | // 查询中存储 BigDecimal 类型 |
| | | genMap.put("queryHasBigDecimal", true); |
| | | } |
| | | if ("between".equalsIgnoreCase(column.getQueryType())) { |
| | | betweens.add(listMap); |
| | | } else { |
| | | // 添加到查询列表中 |
| | | queryColumns.add(listMap); |
| | | } |
| | | } |
| | | // 添加到字段列表中 |
| | | columns.add(listMap); |
| | | } |
| | | // 保存字段列表 |
| | | genMap.put("columns", columns); |
| | | // 保存查询列表 |
| | | genMap.put("queryColumns", queryColumns); |
| | | // 保存字段列表 |
| | | genMap.put("dicts", dicts); |
| | | // 保存查询列表 |
| | | genMap.put("betweens", betweens); |
| | | // 保存非空字段信息 |
| | | genMap.put("isNotNullColumns", isNotNullColumns); |
| | | return genMap; |
| | | } |
| | | |
| | | /** |
| | | * 定义后端文件路径以及名称 |
| | | */ |
| | | private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) { |
| | | String projectPath = rootPath + File.separator + genConfig.getModuleName(); |
| | | String packagePath = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; |
| | | if (!ObjectUtils.isEmpty(genConfig.getPack())) { |
| | | packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; |
| | | } |
| | | |
| | | if ("Entity".equals(templateName)) { |
| | | return packagePath + "domain" + File.separator + className + ".java"; |
| | | } |
| | | |
| | | if ("Controller".equals(templateName)) { |
| | | return packagePath + "rest" + File.separator + className + "Controller.java"; |
| | | } |
| | | |
| | | if ("Service".equals(templateName)) { |
| | | return packagePath + "service" + File.separator + className + "Service.java"; |
| | | } |
| | | |
| | | if ("ServiceImpl".equals(templateName)) { |
| | | return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; |
| | | } |
| | | |
| | | if ("Dto".equals(templateName)) { |
| | | return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; |
| | | } |
| | | |
| | | if ("QueryCriteria".equals(templateName)) { |
| | | return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java"; |
| | | } |
| | | |
| | | if ("Mapper".equals(templateName)) { |
| | | return packagePath + "service" + File.separator + "mapstruct" + File.separator + className + "Mapper.java"; |
| | | } |
| | | |
| | | if ("Repository".equals(templateName)) { |
| | | return packagePath + "repository" + File.separator + className + "Repository.java"; |
| | | } |
| | | |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 定义前端文件路径以及名称 |
| | | */ |
| | | private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { |
| | | |
| | | if ("api".equals(templateName)) { |
| | | return apiPath + File.separator + apiName + ".js"; |
| | | } |
| | | |
| | | if ("index".equals(templateName)) { |
| | | return path + File.separator + "index.vue"; |
| | | } |
| | | |
| | | return null; |
| | | } |
| | | |
| | | private static void genFile(File file, Template template, Map<String, Object> map) throws IOException { |
| | | // 生成目标文件 |
| | | Writer writer = null; |
| | | try { |
| | | FileUtil.touch(file); |
| | | writer = new FileWriter(file); |
| | | template.render(map, writer); |
| | | } catch (TemplateException | IOException e) { |
| | | throw new RuntimeException(e); |
| | | } finally { |
| | | assert writer != null; |
| | | writer.close(); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <project xmlns="http://maven.apache.org/POM/4.0.0" |
| | | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| | | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| | | <parent> |
| | | <artifactId>eladmin</artifactId> |
| | | <groupId>me.zhengjie</groupId> |
| | | <version>2.6</version> |
| | | </parent> |
| | | <modelVersion>4.0.0</modelVersion> |
| | | |
| | | <artifactId>eladmin-logging</artifactId> |
| | | <name>日志模块</name> |
| | | |
| | | <dependencies> |
| | | <dependency> |
| | | <groupId>me.zhengjie</groupId> |
| | | <artifactId>eladmin-common</artifactId> |
| | | <version>2.6</version> |
| | | </dependency> |
| | | </dependencies> |
| | | </project> |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.annotation; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Target(ElementType.METHOD) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface Log { |
| | | String value() default ""; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.aspect; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.domain.Log; |
| | | import me.zhengjie.service.LogService; |
| | | import me.zhengjie.utils.RequestHolder; |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import me.zhengjie.utils.ThrowableUtil; |
| | | import org.aspectj.lang.JoinPoint; |
| | | import org.aspectj.lang.ProceedingJoinPoint; |
| | | import org.aspectj.lang.annotation.AfterThrowing; |
| | | import org.aspectj.lang.annotation.Around; |
| | | import org.aspectj.lang.annotation.Aspect; |
| | | import org.aspectj.lang.annotation.Pointcut; |
| | | import org.springframework.stereotype.Component; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Component |
| | | @Aspect |
| | | @Slf4j |
| | | public class LogAspect { |
| | | |
| | | private final LogService logService; |
| | | |
| | | ThreadLocal<Long> currentTime = new ThreadLocal<>(); |
| | | |
| | | public LogAspect(LogService logService) { |
| | | this.logService = logService; |
| | | } |
| | | |
| | | /** |
| | | * 配置切入点 |
| | | */ |
| | | @Pointcut("@annotation(me.zhengjie.annotation.Log)") |
| | | public void logPointcut() { |
| | | // 该方法无方法体,主要为了让同类中其他方法使用此切入点 |
| | | } |
| | | |
| | | /** |
| | | * 配置环绕通知,使用在方法logPointcut()上注册的切入点 |
| | | * |
| | | * @param joinPoint join point for advice |
| | | */ |
| | | @Around("logPointcut()") |
| | | public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { |
| | | Object result; |
| | | currentTime.set(System.currentTimeMillis()); |
| | | result = joinPoint.proceed(); |
| | | Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get()); |
| | | currentTime.remove(); |
| | | HttpServletRequest request = RequestHolder.getHttpServletRequest(); |
| | | logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, log); |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * 配置异常通知 |
| | | * |
| | | * @param joinPoint join point for advice |
| | | * @param e exception |
| | | */ |
| | | @AfterThrowing(pointcut = "logPointcut()", throwing = "e") |
| | | public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { |
| | | Log log = new Log("ERROR",System.currentTimeMillis() - currentTime.get()); |
| | | currentTime.remove(); |
| | | log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); |
| | | HttpServletRequest request = RequestHolder.getHttpServletRequest(); |
| | | logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, log); |
| | | } |
| | | |
| | | public String getUsername() { |
| | | try { |
| | | return SecurityUtils.getCurrentUsername(); |
| | | }catch (Exception e){ |
| | | return ""; |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.domain; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.NoArgsConstructor; |
| | | import lombok.Setter; |
| | | import org.hibernate.annotations.CreationTimestamp; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name = "sys_log") |
| | | @NoArgsConstructor |
| | | public class Log implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "log_id") |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | /** 操作用户 */ |
| | | private String username; |
| | | |
| | | /** 描述 */ |
| | | private String description; |
| | | |
| | | /** 方法名 */ |
| | | private String method; |
| | | |
| | | /** 参数 */ |
| | | private String params; |
| | | |
| | | /** 日志类型 */ |
| | | private String logType; |
| | | |
| | | /** 请求ip */ |
| | | private String requestIp; |
| | | |
| | | /** 地址 */ |
| | | private String address; |
| | | |
| | | /** 浏览器 */ |
| | | private String browser; |
| | | |
| | | /** 请求耗时 */ |
| | | private Long time; |
| | | |
| | | /** 异常详细 */ |
| | | private byte[] exceptionDetail; |
| | | |
| | | /** 创建日期 */ |
| | | @CreationTimestamp |
| | | private Timestamp createTime; |
| | | |
| | | public Log(String logType, Long time) { |
| | | this.logType = logType; |
| | | this.time = time; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.repository; |
| | | |
| | | import me.zhengjie.domain.Log; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import org.springframework.data.jpa.repository.Modifying; |
| | | import org.springframework.data.jpa.repository.Query; |
| | | import org.springframework.stereotype.Repository; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Repository |
| | | public interface LogRepository extends JpaRepository<Log,Long>, JpaSpecificationExecutor<Log> { |
| | | |
| | | /** |
| | | * 根据日志类型删除信息 |
| | | * @param logType 日志类型 |
| | | */ |
| | | @Modifying |
| | | @Query(value = "delete from sys_log where log_type = ?1", nativeQuery = true) |
| | | void deleteByLogType(String logType); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.service.LogService; |
| | | import me.zhengjie.service.dto.LogQueryCriteria; |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/logs") |
| | | @Api(tags = "系统:日志管理") |
| | | public class LogController { |
| | | |
| | | private final LogService logService; |
| | | |
| | | @Log("导出数据") |
| | | @ApiOperation("导出数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check()") |
| | | public void exportLog(HttpServletResponse response, LogQueryCriteria criteria) throws IOException { |
| | | criteria.setLogType("INFO"); |
| | | logService.download(logService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @Log("导出错误数据") |
| | | @ApiOperation("导出错误数据") |
| | | @GetMapping(value = "/error/download") |
| | | @PreAuthorize("@el.check()") |
| | | public void exportErrorLog(HttpServletResponse response, LogQueryCriteria criteria) throws IOException { |
| | | criteria.setLogType("ERROR"); |
| | | logService.download(logService.queryAll(criteria), response); |
| | | } |
| | | @GetMapping |
| | | @ApiOperation("日志查询") |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> queryLog(LogQueryCriteria criteria, Pageable pageable){ |
| | | criteria.setLogType("INFO"); |
| | | return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK); |
| | | } |
| | | |
| | | @GetMapping(value = "/user") |
| | | @ApiOperation("用户日志查询") |
| | | public ResponseEntity<Object> queryUserLog(LogQueryCriteria criteria, Pageable pageable){ |
| | | criteria.setLogType("INFO"); |
| | | criteria.setUsername(SecurityUtils.getCurrentUsername()); |
| | | return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK); |
| | | } |
| | | |
| | | @GetMapping(value = "/error") |
| | | @ApiOperation("错误日志查询") |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> queryErrorLog(LogQueryCriteria criteria, Pageable pageable){ |
| | | criteria.setLogType("ERROR"); |
| | | return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK); |
| | | } |
| | | |
| | | @GetMapping(value = "/error/{id}") |
| | | @ApiOperation("日志异常详情查询") |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> queryErrorLogDetail(@PathVariable Long id){ |
| | | return new ResponseEntity<>(logService.findByErrDetail(id), HttpStatus.OK); |
| | | } |
| | | @DeleteMapping(value = "/del/error") |
| | | @Log("删除所有ERROR日志") |
| | | @ApiOperation("删除所有ERROR日志") |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> delAllErrorLog(){ |
| | | logService.delAllByError(); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @DeleteMapping(value = "/del/info") |
| | | @Log("删除所有INFO日志") |
| | | @ApiOperation("删除所有INFO日志") |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> delAllInfoLog(){ |
| | | logService.delAllByInfo(); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service; |
| | | |
| | | import me.zhengjie.domain.Log; |
| | | import me.zhengjie.service.dto.LogQueryCriteria; |
| | | import org.aspectj.lang.ProceedingJoinPoint; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | public interface LogService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 查询条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(LogQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria 查询条件 |
| | | * @return / |
| | | */ |
| | | List<Log> queryAll(LogQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 查询用户日志 |
| | | * @param criteria 查询条件 |
| | | * @param pageable 分页参数 |
| | | * @return - |
| | | */ |
| | | Object queryAllByUser(LogQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 保存日志数据 |
| | | * @param username 用户 |
| | | * @param browser 浏览器 |
| | | * @param ip 请求IP |
| | | * @param joinPoint / |
| | | * @param log 日志实体 |
| | | */ |
| | | @Async |
| | | void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, Log log); |
| | | |
| | | /** |
| | | * 查询异常详情 |
| | | * @param id 日志ID |
| | | * @return Object |
| | | */ |
| | | Object findByErrDetail(Long id); |
| | | |
| | | /** |
| | | * 导出日志 |
| | | * @param logs 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<Log> logs, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 删除所有错误日志 |
| | | */ |
| | | void delAllByError(); |
| | | |
| | | /** |
| | | * 删除所有INFO日志 |
| | | */ |
| | | void delAllByInfo(); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-5-22 |
| | | */ |
| | | @Data |
| | | public class LogErrorDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String username; |
| | | |
| | | private String description; |
| | | |
| | | private String method; |
| | | |
| | | private String params; |
| | | |
| | | private String browser; |
| | | |
| | | private String requestIp; |
| | | |
| | | private String address; |
| | | |
| | | private Timestamp createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 日志查询类 |
| | | * @author Zheng Jie |
| | | * @date 2019-6-4 09:23:07 |
| | | */ |
| | | @Data |
| | | public class LogQueryCriteria { |
| | | |
| | | @Query(blurry = "username,description,address,requestIp,method,params") |
| | | private String blurry; |
| | | |
| | | @Query |
| | | private String username; |
| | | |
| | | @Query |
| | | private String logType; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-5-22 |
| | | */ |
| | | @Data |
| | | public class LogSmallDTO implements Serializable { |
| | | |
| | | private String description; |
| | | |
| | | private String requestIp; |
| | | |
| | | private Long time; |
| | | |
| | | private String address; |
| | | |
| | | private String browser; |
| | | |
| | | private Timestamp createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.impl; |
| | | |
| | | import cn.hutool.core.lang.Dict; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import cn.hutool.json.JSONObject; |
| | | import cn.hutool.json.JSONUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.Log; |
| | | import me.zhengjie.repository.LogRepository; |
| | | import me.zhengjie.service.LogService; |
| | | import me.zhengjie.service.dto.LogQueryCriteria; |
| | | import me.zhengjie.service.mapstruct.LogErrorMapper; |
| | | import me.zhengjie.service.mapstruct.LogSmallMapper; |
| | | import me.zhengjie.utils.*; |
| | | import org.aspectj.lang.ProceedingJoinPoint; |
| | | import org.aspectj.lang.reflect.MethodSignature; |
| | | import org.springframework.data.domain.Page; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.stereotype.Service; |
| | | import org.springframework.transaction.annotation.Transactional; |
| | | import org.springframework.web.bind.annotation.RequestBody; |
| | | import org.springframework.web.bind.annotation.RequestParam; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.lang.reflect.Method; |
| | | import java.lang.reflect.Parameter; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-24 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class LogServiceImpl implements LogService { |
| | | private final LogRepository logRepository; |
| | | private final LogErrorMapper logErrorMapper; |
| | | private final LogSmallMapper logSmallMapper; |
| | | |
| | | @Override |
| | | public Object queryAll(LogQueryCriteria criteria, Pageable pageable) { |
| | | Page<Log> page = logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)), pageable); |
| | | String status = "ERROR"; |
| | | if (status.equals(criteria.getLogType())) { |
| | | return PageUtil.toPage(page.map(logErrorMapper::toDto)); |
| | | } |
| | | return page; |
| | | } |
| | | |
| | | @Override |
| | | public List<Log> queryAll(LogQueryCriteria criteria) { |
| | | return logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb))); |
| | | } |
| | | |
| | | @Override |
| | | public Object queryAllByUser(LogQueryCriteria criteria, Pageable pageable) { |
| | | Page<Log> page = logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)), pageable); |
| | | return PageUtil.toPage(page.map(logSmallMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, Log log) { |
| | | if (log == null) { |
| | | throw new IllegalArgumentException("Log 不能为 null!"); |
| | | } |
| | | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); |
| | | Method method = signature.getMethod(); |
| | | me.zhengjie.annotation.Log aopLog = method.getAnnotation(me.zhengjie.annotation.Log.class); |
| | | |
| | | // 方法路径 |
| | | String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()"; |
| | | |
| | | // 描述 |
| | | log.setDescription(aopLog.value()); |
| | | |
| | | log.setRequestIp(ip); |
| | | log.setAddress(StringUtils.getCityInfo(log.getRequestIp())); |
| | | log.setMethod(methodName); |
| | | log.setUsername(username); |
| | | log.setParams(getParameter(method, joinPoint.getArgs())); |
| | | // 记录登录用户,隐藏密码信息 |
| | | if(signature.getName().equals("login") && StringUtils.isNotEmpty(log.getParams())){ |
| | | JSONObject obj = JSONUtil.parseObj(log.getParams()); |
| | | log.setUsername(obj.getStr("username", "")); |
| | | log.setParams(JSONUtil.toJsonStr(Dict.create().set("username", log.getUsername()))); |
| | | } |
| | | log.setBrowser(browser); |
| | | logRepository.save(log); |
| | | } |
| | | |
| | | /** |
| | | * 根据方法和传入的参数获取请求参数 |
| | | */ |
| | | private String getParameter(Method method, Object[] args) { |
| | | List<Object> argList = new ArrayList<>(); |
| | | Parameter[] parameters = method.getParameters(); |
| | | for (int i = 0; i < parameters.length; i++) { |
| | | //将RequestBody注解修饰的参数作为请求参数 |
| | | RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class); |
| | | if (requestBody != null) { |
| | | argList.add(args[i]); |
| | | } |
| | | //将RequestParam注解修饰的参数作为请求参数 |
| | | RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class); |
| | | if (requestParam != null) { |
| | | Map<String, Object> map = new HashMap<>(2); |
| | | String key = parameters[i].getName(); |
| | | if (!StringUtils.isEmpty(requestParam.value())) { |
| | | key = requestParam.value(); |
| | | } |
| | | map.put(key, args[i]); |
| | | argList.add(map); |
| | | } |
| | | } |
| | | if (argList.isEmpty()) { |
| | | return ""; |
| | | } |
| | | return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList); |
| | | } |
| | | |
| | | @Override |
| | | public Object findByErrDetail(Long id) { |
| | | Log log = logRepository.findById(id).orElseGet(Log::new); |
| | | ValidationUtil.isNull(log.getId(), "Log", "id", id); |
| | | byte[] details = log.getExceptionDetail(); |
| | | return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes())); |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<Log> logs, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (Log log : logs) { |
| | | Map<String, Object> map = new LinkedHashMap<>(); |
| | | map.put("用户名", log.getUsername()); |
| | | map.put("IP", log.getRequestIp()); |
| | | map.put("IP来源", log.getAddress()); |
| | | map.put("描述", log.getDescription()); |
| | | map.put("浏览器", log.getBrowser()); |
| | | map.put("请求耗时/毫秒", log.getTime()); |
| | | map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes())); |
| | | map.put("创建日期", log.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delAllByError() { |
| | | logRepository.deleteByLogType("ERROR"); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delAllByInfo() { |
| | | logRepository.deleteByLogType("INFO"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.domain.Log; |
| | | import me.zhengjie.service.dto.LogErrorDTO; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-5-22 |
| | | */ |
| | | @Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface LogErrorMapper extends BaseMapper<LogErrorDTO, Log> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.domain.Log; |
| | | import me.zhengjie.service.dto.LogSmallDTO; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-5-22 |
| | | */ |
| | | @Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface LogSmallMapper extends BaseMapper<LogSmallDTO, Log> { |
| | | |
| | | } |
| New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <project xmlns="http://maven.apache.org/POM/4.0.0" |
| | | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| | | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| | | <parent> |
| | | <artifactId>eladmin</artifactId> |
| | | <groupId>me.zhengjie</groupId> |
| | | <version>2.6</version> |
| | | </parent> |
| | | <modelVersion>4.0.0</modelVersion> |
| | | |
| | | <artifactId>eladmin-system</artifactId> |
| | | <name>核心模块</name> |
| | | |
| | | <properties> |
| | | <jjwt.version>0.11.2</jjwt.version> |
| | | <!-- oshi监控需要指定jna版本, 问题详见 https://github.com/oshi/oshi/issues/1040 --> |
| | | <jna.version>5.8.0</jna.version> |
| | | </properties> |
| | | |
| | | <dependencies> |
| | | <!-- 代码生成模块 --> |
| | | <dependency> |
| | | <groupId>me.zhengjie</groupId> |
| | | <artifactId>eladmin-generator</artifactId> |
| | | <version>2.6</version> |
| | | <exclusions> |
| | | <exclusion> |
| | | <groupId>me.zhengjie</groupId> |
| | | <artifactId>eladmin-common</artifactId> |
| | | </exclusion> |
| | | </exclusions> |
| | | </dependency> |
| | | |
| | | <!-- tools 模块包含了 common 和 logging 模块 --> |
| | | <dependency> |
| | | <groupId>me.zhengjie</groupId> |
| | | <artifactId>eladmin-tools</artifactId> |
| | | <version>2.6</version> |
| | | </dependency> |
| | | |
| | | <!-- Spring boot websocket --> |
| | | <dependency> |
| | | <groupId>org.springframework.boot</groupId> |
| | | <artifactId>spring-boot-starter-websocket</artifactId> |
| | | </dependency> |
| | | |
| | | <!-- jwt --> |
| | | <dependency> |
| | | <groupId>io.jsonwebtoken</groupId> |
| | | <artifactId>jjwt-api</artifactId> |
| | | <version>${jjwt.version}</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>io.jsonwebtoken</groupId> |
| | | <artifactId>jjwt-impl</artifactId> |
| | | <version>${jjwt.version}</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>io.jsonwebtoken</groupId> |
| | | <artifactId>jjwt-jackson</artifactId> |
| | | <version>${jjwt.version}</version> |
| | | </dependency> |
| | | |
| | | <!-- quartz --> |
| | | <dependency> |
| | | <groupId>org.quartz-scheduler</groupId> |
| | | <artifactId>quartz</artifactId> |
| | | </dependency> |
| | | |
| | | <!-- linux的管理 --> |
| | | <dependency> |
| | | <groupId>ch.ethz.ganymed</groupId> |
| | | <artifactId>ganymed-ssh2</artifactId> |
| | | <version>build210</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>com.jcraft</groupId> |
| | | <artifactId>jsch</artifactId> |
| | | <version>0.1.55</version> |
| | | </dependency> |
| | | |
| | | <!-- 获取系统信息 --> |
| | | <dependency> |
| | | <groupId>com.github.oshi</groupId> |
| | | <artifactId>oshi-core</artifactId> |
| | | <version>6.1.4</version> |
| | | </dependency> |
| | | </dependencies> |
| | | |
| | | <!-- 打包 --> |
| | | <build> |
| | | <plugins> |
| | | <plugin> |
| | | <groupId>org.springframework.boot</groupId> |
| | | <artifactId>spring-boot-maven-plugin</artifactId> |
| | | </plugin> |
| | | <!-- 跳过单元测试 --> |
| | | <plugin> |
| | | <groupId>org.apache.maven.plugins</groupId> |
| | | <artifactId>maven-surefire-plugin</artifactId> |
| | | <configuration> |
| | | <skipTests>true</skipTests> |
| | | </configuration> |
| | | </plugin> |
| | | </plugins> |
| | | </build> |
| | | </project> |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import me.zhengjie.annotation.rest.AnonymousGetMapping; |
| | | import me.zhengjie.utils.SpringContextHolder; |
| | | import org.springframework.boot.SpringApplication; |
| | | import org.springframework.boot.autoconfigure.SpringBootApplication; |
| | | import org.springframework.boot.context.ApplicationPidFileWriter; |
| | | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; |
| | | import org.springframework.boot.web.servlet.server.ServletWebServerFactory; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; |
| | | import org.springframework.scheduling.annotation.EnableAsync; |
| | | import org.springframework.transaction.annotation.EnableTransactionManagement; |
| | | import org.springframework.web.bind.annotation.RestController; |
| | | |
| | | /** |
| | | * 开启审计功能 -> @EnableJpaAuditing |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2018/11/15 9:20:19 |
| | | */ |
| | | @EnableAsync |
| | | @RestController |
| | | @Api(hidden = true) |
| | | @SpringBootApplication |
| | | @EnableTransactionManagement |
| | | @EnableJpaAuditing(auditorAwareRef = "auditorAware") |
| | | public class AppRun { |
| | | |
| | | public static void main(String[] args) { |
| | | SpringApplication springApplication = new SpringApplication(AppRun.class); |
| | | // 监控应用的PID,启动时可指定PID路径:--spring.pid.file=/home/eladmin/app.pid |
| | | // 或者在 application.yml 添加文件路径,方便 kill,kill `cat /home/eladmin/app.pid` |
| | | springApplication.addListeners(new ApplicationPidFileWriter()); |
| | | springApplication.run(args); |
| | | } |
| | | |
| | | @Bean |
| | | public SpringContextHolder springContextHolder() { |
| | | return new SpringContextHolder(); |
| | | } |
| | | |
| | | /** |
| | | * 访问首页提示 |
| | | * |
| | | * @return / |
| | | */ |
| | | @AnonymousGetMapping("/") |
| | | public String index() { |
| | | return "Backend service started successfully"; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import com.alibaba.fastjson.serializer.SerializerFeature; |
| | | import com.alibaba.fastjson.support.config.FastJsonConfig; |
| | | import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.http.MediaType; |
| | | import org.springframework.http.converter.HttpMessageConverter; |
| | | import org.springframework.web.cors.CorsConfiguration; |
| | | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| | | import org.springframework.web.filter.CorsFilter; |
| | | import org.springframework.web.servlet.config.annotation.EnableWebMvc; |
| | | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; |
| | | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * WebMvcConfigurer |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2018-11-30 |
| | | */ |
| | | @Configuration |
| | | @EnableWebMvc |
| | | public class ConfigurerAdapter implements WebMvcConfigurer { |
| | | |
| | | /** 文件配置 */ |
| | | private final FileProperties properties; |
| | | |
| | | public ConfigurerAdapter(FileProperties properties) { |
| | | this.properties = properties; |
| | | } |
| | | |
| | | @Bean |
| | | public CorsFilter corsFilter() { |
| | | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
| | | CorsConfiguration config = new CorsConfiguration(); |
| | | config.setAllowCredentials(true); |
| | | config.addAllowedOriginPattern("*"); |
| | | config.addAllowedHeader("*"); |
| | | config.addAllowedMethod("*"); |
| | | source.registerCorsConfiguration("/**", config); |
| | | return new CorsFilter(source); |
| | | } |
| | | |
| | | @Override |
| | | public void addResourceHandlers(ResourceHandlerRegistry registry) { |
| | | FileProperties.ElPath path = properties.getPath(); |
| | | String avatarUtl = "file:" + path.getAvatar().replace("\\","/"); |
| | | String pathUtl = "file:" + path.getPath().replace("\\","/"); |
| | | registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0); |
| | | registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0); |
| | | registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); |
| | | } |
| | | |
| | | @Override |
| | | public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { |
| | | // 使用 fastjson 序列化,会导致 @JsonIgnore 失效,可以使用 @JSONField(serialize = false) 替换 |
| | | FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); |
| | | List<MediaType> supportMediaTypeList = new ArrayList<>(); |
| | | supportMediaTypeList.add(MediaType.APPLICATION_JSON); |
| | | FastJsonConfig config = new FastJsonConfig(); |
| | | config.setDateFormat("yyyy-MM-dd HH:mm:ss"); |
| | | config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); |
| | | converter.setFastJsonConfig(config); |
| | | converter.setSupportedMediaTypes(supportMediaTypeList); |
| | | converter.setDefaultCharset(StandardCharsets.UTF_8); |
| | | converters.add(converter); |
| | | } |
| | | } |
| New file |
| | |
| | | package me.zhengjie.config; |
| | | |
| | | import org.apache.catalina.connector.Connector; |
| | | import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; |
| | | import org.springframework.context.annotation.Configuration; |
| | | |
| | | /** |
| | | * @author bearBoy80 |
| | | */ |
| | | @Configuration(proxyBeanMethods = false) |
| | | public class RelaxedQueryCharsConnectorCustomizer implements TomcatConnectorCustomizer { |
| | | @Override |
| | | public void customize(Connector connector) { |
| | | connector.setProperty("relaxedQueryChars", "[]{}"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config; |
| | | |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.web.socket.server.standard.ServerEndpointExporter; |
| | | |
| | | /** |
| | | * @author ZhangHouYing |
| | | * @date 2019-08-24 15:44 |
| | | */ |
| | | @Configuration |
| | | public class WebSocketConfig { |
| | | |
| | | @Bean |
| | | public ServerEndpointExporter serverEndpointExporter() { |
| | | return new ServerEndpointExporter(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config.thread; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.scheduling.annotation.AsyncConfigurer; |
| | | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; |
| | | import java.util.concurrent.Executor; |
| | | import java.util.concurrent.ThreadPoolExecutor; |
| | | |
| | | /** |
| | | * 异步任务线程池装配类 |
| | | * @author https://juejin.im/entry/5abb8f6951882555677e9da2 |
| | | * @date 2019年10月31日15:06:18 |
| | | */ |
| | | @Slf4j |
| | | @Configuration |
| | | public class AsyncTaskExecutePool implements AsyncConfigurer { |
| | | |
| | | @Override |
| | | public Executor getAsyncExecutor() { |
| | | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| | | //核心线程池大小 |
| | | executor.setCorePoolSize(AsyncTaskProperties.corePoolSize); |
| | | //最大线程数 |
| | | executor.setMaxPoolSize(AsyncTaskProperties.maxPoolSize); |
| | | //队列容量 |
| | | executor.setQueueCapacity(AsyncTaskProperties.queueCapacity); |
| | | //活跃时间 |
| | | executor.setKeepAliveSeconds(AsyncTaskProperties.keepAliveSeconds); |
| | | //线程工厂 |
| | | executor.setThreadFactory(new TheadFactoryName("el-async")); |
| | | // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务 |
| | | // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行 |
| | | executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); |
| | | executor.initialize(); |
| | | return executor; |
| | | } |
| | | |
| | | @Override |
| | | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { |
| | | return (throwable, method, objects) -> { |
| | | log.error("===="+throwable.getMessage()+"====", throwable); |
| | | log.error("exception method:"+method.getName()); |
| | | }; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config.thread; |
| | | |
| | | import lombok.Data; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.boot.context.properties.ConfigurationProperties; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * 线程池配置属性类 |
| | | * @author https://juejin.im/entry/5abb8f6951882555677e9da2 |
| | | * @date 2019年10月31日14:58:18 |
| | | */ |
| | | @Data |
| | | @Component |
| | | public class AsyncTaskProperties { |
| | | |
| | | public static int corePoolSize; |
| | | |
| | | public static int maxPoolSize; |
| | | |
| | | public static int keepAliveSeconds; |
| | | |
| | | public static int queueCapacity; |
| | | |
| | | @Value("${task.pool.core-pool-size}") |
| | | public void setCorePoolSize(int corePoolSize) { |
| | | AsyncTaskProperties.corePoolSize = corePoolSize; |
| | | } |
| | | |
| | | @Value("${task.pool.max-pool-size}") |
| | | public void setMaxPoolSize(int maxPoolSize) { |
| | | AsyncTaskProperties.maxPoolSize = maxPoolSize; |
| | | } |
| | | |
| | | @Value("${task.pool.keep-alive-seconds}") |
| | | public void setKeepAliveSeconds(int keepAliveSeconds) { |
| | | AsyncTaskProperties.keepAliveSeconds = keepAliveSeconds; |
| | | } |
| | | |
| | | @Value("${task.pool.queue-capacity}") |
| | | public void setQueueCapacity(int queueCapacity) { |
| | | AsyncTaskProperties.queueCapacity = queueCapacity; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config.thread; |
| | | |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.springframework.stereotype.Component; |
| | | import java.util.concurrent.ThreadFactory; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | |
| | | /** |
| | | * 自定义线程名称 |
| | | * @author Zheng Jie |
| | | * @date 2019年10月31日17:49:55 |
| | | */ |
| | | @Component |
| | | public class TheadFactoryName implements ThreadFactory { |
| | | |
| | | private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); |
| | | private final ThreadGroup group; |
| | | private final AtomicInteger threadNumber = new AtomicInteger(1); |
| | | private final String namePrefix; |
| | | |
| | | private final static String DEF_NAME = "el-pool-"; |
| | | |
| | | public TheadFactoryName() { |
| | | this(DEF_NAME); |
| | | } |
| | | |
| | | public TheadFactoryName(String name){ |
| | | SecurityManager s = System.getSecurityManager(); |
| | | group = (s != null) ? s.getThreadGroup() : |
| | | Thread.currentThread().getThreadGroup(); |
| | | //此时namePrefix就是 name + 第几个用这个工厂创建线程池的 |
| | | this.namePrefix = (StringUtils.isNotBlank(name) ? name : DEF_NAME) + "-" + POOL_NUMBER.getAndIncrement(); |
| | | } |
| | | |
| | | @Override |
| | | public Thread newThread(Runnable r) { |
| | | //此时线程的名字 就是 namePrefix + -exec- + 这个线程池中第几个执行的线程 |
| | | Thread t = new Thread(group, r, |
| | | namePrefix + "-exec-"+threadNumber.getAndIncrement(), |
| | | 0); |
| | | if (t.isDaemon()) { |
| | | t.setDaemon(false); |
| | | } |
| | | if (t.getPriority() != Thread.NORM_PRIORITY) { |
| | | t.setPriority(Thread.NORM_PRIORITY); |
| | | } |
| | | return t; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.config.thread; |
| | | |
| | | import java.util.concurrent.ArrayBlockingQueue; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.ThreadPoolExecutor; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * 用于获取自定义线程池 |
| | | * @author Zheng Jie |
| | | * @date 2019年10月31日18:16:47 |
| | | */ |
| | | public class ThreadPoolExecutorUtil { |
| | | |
| | | public static ExecutorService getPoll(){ |
| | | return getPoll(null); |
| | | } |
| | | |
| | | public static ExecutorService getPoll(String threadName){ |
| | | return new ThreadPoolExecutor( |
| | | AsyncTaskProperties.corePoolSize, |
| | | AsyncTaskProperties.maxPoolSize, |
| | | AsyncTaskProperties.keepAliveSeconds, |
| | | TimeUnit.SECONDS, |
| | | new ArrayBlockingQueue<>(AsyncTaskProperties.queueCapacity), |
| | | new TheadFactoryName(threadName), |
| | | // 队列与线程池中线程都满了时使用调用者所在的线程来执行 |
| | | new ThreadPoolExecutor.CallerRunsPolicy() |
| | | ); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import cn.hutool.core.bean.BeanUtil; |
| | | import cn.hutool.core.bean.copier.CopyOptions; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="mnt_app") |
| | | public class App extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "app_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @ApiModelProperty(value = "名称") |
| | | private String name; |
| | | |
| | | @ApiModelProperty(value = "端口") |
| | | private int port; |
| | | |
| | | @ApiModelProperty(value = "上传路径") |
| | | private String uploadPath; |
| | | |
| | | @ApiModelProperty(value = "部署路径") |
| | | private String deployPath; |
| | | |
| | | @ApiModelProperty(value = "备份路径") |
| | | private String backupPath; |
| | | |
| | | @ApiModelProperty(value = "启动脚本") |
| | | private String startScript; |
| | | |
| | | @ApiModelProperty(value = "部署脚本") |
| | | private String deployScript; |
| | | |
| | | public void copy(App source){ |
| | | BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import cn.hutool.core.bean.BeanUtil; |
| | | import cn.hutool.core.bean.copier.CopyOptions; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="mnt_database") |
| | | public class Database extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "db_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | private String id; |
| | | |
| | | @ApiModelProperty(value = "数据库名称") |
| | | private String name; |
| | | |
| | | @ApiModelProperty(value = "数据库连接地址") |
| | | private String jdbcUrl; |
| | | |
| | | @ApiModelProperty(value = "数据库密码") |
| | | private String pwd; |
| | | |
| | | @ApiModelProperty(value = "用户名") |
| | | private String userName; |
| | | |
| | | public void copy(Database source){ |
| | | BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import cn.hutool.core.bean.BeanUtil; |
| | | import cn.hutool.core.bean.copier.CopyOptions; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="mnt_deploy") |
| | | public class Deploy extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "deploy_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @ManyToMany |
| | | @ApiModelProperty(name = "服务器", hidden = true) |
| | | @JoinTable(name = "mnt_deploy_server", |
| | | joinColumns = {@JoinColumn(name = "deploy_id",referencedColumnName = "deploy_id")}, |
| | | inverseJoinColumns = {@JoinColumn(name = "server_id",referencedColumnName = "server_id")}) |
| | | private Set<ServerDeploy> deploys; |
| | | |
| | | @ManyToOne |
| | | @JoinColumn(name = "app_id") |
| | | @ApiModelProperty(value = "应用编号") |
| | | private App app; |
| | | |
| | | public void copy(Deploy source){ |
| | | BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import cn.hutool.core.bean.BeanUtil; |
| | | import cn.hutool.core.bean.copier.CopyOptions; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import org.hibernate.annotations.CreationTimestamp; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="mnt_deploy_history") |
| | | public class DeployHistory implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "history_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | private String id; |
| | | |
| | | @ApiModelProperty(value = "应用名称") |
| | | private String appName; |
| | | |
| | | @ApiModelProperty(value = "IP") |
| | | private String ip; |
| | | |
| | | @CreationTimestamp |
| | | @ApiModelProperty(value = "部署时间") |
| | | private Timestamp deployDate; |
| | | |
| | | @ApiModelProperty(value = "部署者") |
| | | private String deployUser; |
| | | |
| | | @ApiModelProperty(value = "部署ID") |
| | | private Long deployId; |
| | | |
| | | public void copy(DeployHistory source){ |
| | | BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import cn.hutool.core.bean.BeanUtil; |
| | | import cn.hutool.core.bean.copier.CopyOptions; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="mnt_server") |
| | | public class ServerDeploy extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "server_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @ApiModelProperty(value = "服务器名称") |
| | | private String name; |
| | | |
| | | @ApiModelProperty(value = "IP") |
| | | private String ip; |
| | | |
| | | @ApiModelProperty(value = "端口") |
| | | private Integer port; |
| | | |
| | | @ApiModelProperty(value = "账号") |
| | | private String account; |
| | | |
| | | @ApiModelProperty(value = "密码") |
| | | private String password; |
| | | |
| | | public void copy(ServerDeploy source){ |
| | | BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); |
| | | } |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | ServerDeploy that = (ServerDeploy) o; |
| | | return Objects.equals(id, that.id) && |
| | | Objects.equals(name, that.name); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id, name); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.repository; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface AppRepository extends JpaRepository<App, Long>, JpaSpecificationExecutor<App> { |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.repository; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.Database; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface DatabaseRepository extends JpaRepository<Database, String>, JpaSpecificationExecutor<Database> { |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.repository; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface DeployHistoryRepository extends JpaRepository<DeployHistory, String>, JpaSpecificationExecutor<DeployHistory> { |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.repository; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.Deploy; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface DeployRepository extends JpaRepository<Deploy, Long>, JpaSpecificationExecutor<Deploy> { |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.repository; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface ServerDeployRepository extends JpaRepository<ServerDeploy, Long>, JpaSpecificationExecutor<ServerDeploy> { |
| | | |
| | | /** |
| | | * 根据IP查询 |
| | | * @param ip / |
| | | * @return / |
| | | */ |
| | | ServerDeploy findByIp(String ip); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import me.zhengjie.modules.mnt.service.AppService; |
| | | import me.zhengjie.modules.mnt.service.dto.AppQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "运维:应用管理") |
| | | @RequestMapping("/api/app") |
| | | public class AppController { |
| | | |
| | | private final AppService appService; |
| | | |
| | | @ApiOperation("导出应用数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('app:list')") |
| | | public void exportApp(HttpServletResponse response, AppQueryCriteria criteria) throws IOException { |
| | | appService.download(appService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation(value = "查询应用") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('app:list')") |
| | | public ResponseEntity<Object> queryApp(AppQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(appService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增应用") |
| | | @ApiOperation(value = "新增应用") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('app:add')") |
| | | public ResponseEntity<Object> createApp(@Validated @RequestBody App resources){ |
| | | appService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改应用") |
| | | @ApiOperation(value = "修改应用") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('app:edit')") |
| | | public ResponseEntity<Object> updateApp(@Validated @RequestBody App resources){ |
| | | appService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除应用") |
| | | @ApiOperation(value = "删除应用") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('app:del')") |
| | | public ResponseEntity<Object> deleteApp(@RequestBody Set<Long> ids){ |
| | | appService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.mnt.domain.Database; |
| | | import me.zhengjie.modules.mnt.service.DatabaseService; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseQueryCriteria; |
| | | import me.zhengjie.modules.mnt.util.SqlUtils; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.File; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Api(tags = "运维:数据库管理") |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/database") |
| | | public class DatabaseController { |
| | | |
| | | private final String fileSavePath = FileUtil.getTmpDirPath()+"/"; |
| | | private final DatabaseService databaseService; |
| | | |
| | | @ApiOperation("导出数据库数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('database:list')") |
| | | public void exportDatabase(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException { |
| | | databaseService.download(databaseService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation(value = "查询数据库") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('database:list')") |
| | | public ResponseEntity<Object> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增数据库") |
| | | @ApiOperation(value = "新增数据库") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('database:add')") |
| | | public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources){ |
| | | databaseService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改数据库") |
| | | @ApiOperation(value = "修改数据库") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('database:edit')") |
| | | public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources){ |
| | | databaseService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除数据库") |
| | | @ApiOperation(value = "删除数据库") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('database:del')") |
| | | public ResponseEntity<Object> deleteDatabase(@RequestBody Set<String> ids){ |
| | | databaseService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("测试数据库链接") |
| | | @ApiOperation(value = "测试数据库链接") |
| | | @PostMapping("/testConnect") |
| | | @PreAuthorize("@el.check('database:testConnect')") |
| | | public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){ |
| | | return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("执行SQL脚本") |
| | | @ApiOperation(value = "执行SQL脚本") |
| | | @PostMapping(value = "/upload") |
| | | @PreAuthorize("@el.check('database:add')") |
| | | public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{ |
| | | String id = request.getParameter("id"); |
| | | DatabaseDto database = databaseService.findById(id); |
| | | String fileName; |
| | | if(database != null){ |
| | | fileName = file.getOriginalFilename(); |
| | | File executeFile = new File(fileSavePath+fileName); |
| | | FileUtil.del(executeFile); |
| | | file.transferTo(executeFile); |
| | | String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile); |
| | | return new ResponseEntity<>(result,HttpStatus.OK); |
| | | }else{ |
| | | throw new BadRequestException("Database not exist"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.mnt.domain.Deploy; |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.service.DeployService; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployQueryCriteria; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.File; |
| | | import java.io.IOException; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @RestController |
| | | @Api(tags = "运维:部署管理") |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/deploy") |
| | | public class DeployController { |
| | | |
| | | private final String fileSavePath = FileUtil.getTmpDirPath()+"/"; |
| | | private final DeployService deployService; |
| | | |
| | | |
| | | @ApiOperation("导出部署数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('database:list')") |
| | | public void exportDeployData(HttpServletResponse response, DeployQueryCriteria criteria) throws IOException { |
| | | deployService.download(deployService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation(value = "查询部署") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('deploy:list')") |
| | | public ResponseEntity<Object> queryDeployData(DeployQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(deployService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增部署") |
| | | @ApiOperation(value = "新增部署") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('deploy:add')") |
| | | public ResponseEntity<Object> createDeploy(@Validated @RequestBody Deploy resources){ |
| | | deployService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改部署") |
| | | @ApiOperation(value = "修改部署") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> updateDeploy(@Validated @RequestBody Deploy resources){ |
| | | deployService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除部署") |
| | | @ApiOperation(value = "删除部署") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('deploy:del')") |
| | | public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids){ |
| | | deployService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("上传文件部署") |
| | | @ApiOperation(value = "上传文件部署") |
| | | @PostMapping(value = "/upload") |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{ |
| | | Long id = Long.valueOf(request.getParameter("id")); |
| | | String fileName = ""; |
| | | if(file != null){ |
| | | fileName = file.getOriginalFilename(); |
| | | File deployFile = new File(fileSavePath+fileName); |
| | | FileUtil.del(deployFile); |
| | | file.transferTo(deployFile); |
| | | //文件下一步要根据文件名字来 |
| | | deployService.deploy(fileSavePath+fileName ,id); |
| | | }else{ |
| | | System.out.println("没有找到相对应的文件"); |
| | | } |
| | | System.out.println("文件上传的原名称为:"+ Objects.requireNonNull(file).getOriginalFilename()); |
| | | Map<String,Object> map = new HashMap<>(2); |
| | | map.put("errno",0); |
| | | map.put("id",fileName); |
| | | return new ResponseEntity<>(map,HttpStatus.OK); |
| | | } |
| | | @Log("系统还原") |
| | | @ApiOperation(value = "系统还原") |
| | | @PostMapping(value = "/serverReduction") |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){ |
| | | String result = deployService.serverReduction(resources); |
| | | return new ResponseEntity<>(result,HttpStatus.OK); |
| | | } |
| | | @Log("服务运行状态") |
| | | @ApiOperation(value = "服务运行状态") |
| | | @PostMapping(value = "/serverStatus") |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){ |
| | | String result = deployService.serverStatus(resources); |
| | | return new ResponseEntity<>(result,HttpStatus.OK); |
| | | } |
| | | @Log("启动服务") |
| | | @ApiOperation(value = "启动服务") |
| | | @PostMapping(value = "/startServer") |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){ |
| | | String result = deployService.startServer(resources); |
| | | return new ResponseEntity<>(result,HttpStatus.OK); |
| | | } |
| | | @Log("停止服务") |
| | | @ApiOperation(value = "停止服务") |
| | | @PostMapping(value = "/stopServer") |
| | | @PreAuthorize("@el.check('deploy:edit')") |
| | | public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){ |
| | | String result = deployService.stopServer(resources); |
| | | return new ResponseEntity<>(result,HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.mnt.service.DeployHistoryService; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "运维:部署历史管理") |
| | | @RequestMapping("/api/deployHistory") |
| | | public class DeployHistoryController { |
| | | |
| | | private final DeployHistoryService deployhistoryService; |
| | | |
| | | @ApiOperation("导出部署历史数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('deployHistory:list')") |
| | | public void exportDeployHistory(HttpServletResponse response, DeployHistoryQueryCriteria criteria) throws IOException { |
| | | deployhistoryService.download(deployhistoryService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation(value = "查询部署历史") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('deployHistory:list')") |
| | | public ResponseEntity<Object> queryDeployHistory(DeployHistoryQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(deployhistoryService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("删除DeployHistory") |
| | | @ApiOperation(value = "删除部署历史") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('deployHistory:del')") |
| | | public ResponseEntity<Object> deleteDeployHistory(@RequestBody Set<String> ids){ |
| | | deployhistoryService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import me.zhengjie.modules.mnt.service.ServerDeployService; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @RestController |
| | | @Api(tags = "运维:服务器管理") |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/serverDeploy") |
| | | public class ServerDeployController { |
| | | |
| | | private final ServerDeployService serverDeployService; |
| | | |
| | | @ApiOperation("导出服务器数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('serverDeploy:list')") |
| | | public void exportServerDeploy(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException { |
| | | serverDeployService.download(serverDeployService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation(value = "查询服务器") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('serverDeploy:list')") |
| | | public ResponseEntity<Object> queryServerDeploy(ServerDeployQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增服务器") |
| | | @ApiOperation(value = "新增服务器") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('serverDeploy:add')") |
| | | public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources){ |
| | | serverDeployService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改服务器") |
| | | @ApiOperation(value = "修改服务器") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('serverDeploy:edit')") |
| | | public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources){ |
| | | serverDeployService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除服务器") |
| | | @ApiOperation(value = "删除Server") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('serverDeploy:del')") |
| | | public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids){ |
| | | serverDeployService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("测试连接服务器") |
| | | @ApiOperation(value = "测试连接服务器") |
| | | @PostMapping("/testConnect") |
| | | @PreAuthorize("@el.check('serverDeploy:add')") |
| | | public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources){ |
| | | return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import me.zhengjie.modules.mnt.service.dto.AppDto; |
| | | import me.zhengjie.modules.mnt.service.dto.AppQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface AppService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(AppQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<AppDto> queryAll(AppQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | AppDto findById(Long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(App resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(App resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll / |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.Database; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author ZhangHouYing |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface DatabaseService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | DatabaseDto findById(String id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(Database resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Database resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<String> ids); |
| | | |
| | | /** |
| | | * 测试连接数据库 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | boolean testConnection(Database resources); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll / |
| | | * @param response / |
| | | * @throws IOException e |
| | | */ |
| | | void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | */ |
| | | public interface DeployHistoryService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | DeployHistoryDto findById(String id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(DeployHistory resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<String> ids); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll / |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.Deploy; |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface DeployService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(DeployQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<DeployDto> queryAll(DeployQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | DeployDto findById(Long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(Deploy resources); |
| | | |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Deploy resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 部署文件到服务器 |
| | | * @param fileSavePath 文件路径 |
| | | * @param appId 应用ID |
| | | */ |
| | | void deploy(String fileSavePath, Long appId); |
| | | |
| | | /** |
| | | * 查询部署状态 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | String serverStatus(Deploy resources); |
| | | /** |
| | | * 启动服务 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | String startServer(Deploy resources); |
| | | /** |
| | | * 停止服务 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | String stopServer(Deploy resources); |
| | | |
| | | /** |
| | | * 停止服务 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | String serverReduction(DeployHistory resources); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll / |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service; |
| | | |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployDto; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | public interface ServerDeployService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | ServerDeployDto findById(Long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(ServerDeploy resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(ServerDeploy resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据IP查询 |
| | | * @param ip / |
| | | * @return / |
| | | */ |
| | | ServerDeployDto findByIp(String ip); |
| | | |
| | | /** |
| | | * 测试登录服务器 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | Boolean testConnect(ServerDeploy resources); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll / |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class AppDto extends BaseDTO implements Serializable { |
| | | |
| | | /** |
| | | * 应用编号 |
| | | */ |
| | | private Long id; |
| | | |
| | | /** |
| | | * 应用名称 |
| | | */ |
| | | private String name; |
| | | |
| | | /** |
| | | * 端口 |
| | | */ |
| | | private Integer port; |
| | | |
| | | /** |
| | | * 上传目录 |
| | | */ |
| | | private String uploadPath; |
| | | |
| | | /** |
| | | * 部署目录 |
| | | */ |
| | | private String deployPath; |
| | | |
| | | /** |
| | | * 备份目录 |
| | | */ |
| | | private String backupPath; |
| | | |
| | | /** |
| | | * 启动脚本 |
| | | */ |
| | | private String startScript; |
| | | |
| | | /** |
| | | * 部署脚本 |
| | | */ |
| | | private String deployScript; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class AppQueryCriteria{ |
| | | |
| | | /** |
| | | * 模糊 |
| | | */ |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String name; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DatabaseDto extends BaseDTO implements Serializable { |
| | | |
| | | /** |
| | | * id |
| | | */ |
| | | private String id; |
| | | |
| | | /** |
| | | * 数据库名称 |
| | | */ |
| | | private String name; |
| | | |
| | | /** |
| | | * 数据库连接地址 |
| | | */ |
| | | private String jdbcUrl; |
| | | |
| | | /** |
| | | * 数据库密码 |
| | | */ |
| | | private String pwd; |
| | | |
| | | /** |
| | | * 用户名 |
| | | */ |
| | | private String userName; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class DatabaseQueryCriteria{ |
| | | |
| | | /** |
| | | * 模糊 |
| | | */ |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String name; |
| | | |
| | | /** |
| | | * 精确 |
| | | */ |
| | | @Query |
| | | private String jdbcUrl; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | import java.util.stream.Collectors; |
| | | |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DeployDto extends BaseDTO implements Serializable { |
| | | |
| | | /** |
| | | * 部署编号 |
| | | */ |
| | | private String id; |
| | | |
| | | private AppDto app; |
| | | |
| | | /** |
| | | * 服务器 |
| | | */ |
| | | private Set<ServerDeployDto> deploys; |
| | | |
| | | private String servers; |
| | | |
| | | /** |
| | | * 服务状态 |
| | | */ |
| | | private String status; |
| | | |
| | | public String getServers() { |
| | | if(CollectionUtil.isNotEmpty(deploys)){ |
| | | return deploys.stream().map(ServerDeployDto::getName).collect(Collectors.joining(",")); |
| | | } |
| | | return servers; |
| | | } |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | DeployDto deployDto = (DeployDto) o; |
| | | return Objects.equals(id, deployDto.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class DeployHistoryDto implements Serializable { |
| | | |
| | | /** |
| | | * 编号 |
| | | */ |
| | | private String id; |
| | | |
| | | /** |
| | | * 应用名称 |
| | | */ |
| | | private String appName; |
| | | |
| | | /** |
| | | * 部署IP |
| | | */ |
| | | private String ip; |
| | | |
| | | /** |
| | | * 部署时间 |
| | | */ |
| | | private Timestamp deployDate; |
| | | |
| | | /** |
| | | * 部署人员 |
| | | */ |
| | | private String deployUser; |
| | | |
| | | /** |
| | | * 部署编号 |
| | | */ |
| | | private Long deployId; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class DeployHistoryQueryCriteria{ |
| | | |
| | | /** |
| | | * 精确 |
| | | */ |
| | | @Query(blurry = "appName,ip,deployUser") |
| | | private String blurry; |
| | | |
| | | @Query |
| | | private Long deployId; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> deployDate; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class DeployQueryCriteria{ |
| | | |
| | | /** |
| | | * 模糊 |
| | | */ |
| | | @Query(type = Query.Type.INNER_LIKE, propName = "name", joinName = "app") |
| | | private String appName; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class ServerDeployDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String name; |
| | | |
| | | private String ip; |
| | | |
| | | private Integer port; |
| | | |
| | | private String account; |
| | | |
| | | private String password; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | ServerDeployDto that = (ServerDeployDto) o; |
| | | return Objects.equals(id, that.id) && |
| | | Objects.equals(name, that.name); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id, name); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Data |
| | | public class ServerDeployQueryCriteria{ |
| | | |
| | | /** |
| | | * 模糊 |
| | | */ |
| | | @Query(blurry = "name,ip,account") |
| | | private String blurry; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import me.zhengjie.modules.mnt.repository.AppRepository; |
| | | import me.zhengjie.modules.mnt.service.AppService; |
| | | import me.zhengjie.modules.mnt.service.dto.AppDto; |
| | | import me.zhengjie.modules.mnt.service.dto.AppQueryCriteria; |
| | | import me.zhengjie.modules.mnt.service.mapstruct.AppMapper; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.QueryHelp; |
| | | import me.zhengjie.utils.ValidationUtil; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class AppServiceImpl implements AppService { |
| | | |
| | | private final AppRepository appRepository; |
| | | private final AppMapper appMapper; |
| | | |
| | | @Override |
| | | public Object queryAll(AppQueryCriteria criteria, Pageable pageable){ |
| | | Page<App> page = appRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(appMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<AppDto> queryAll(AppQueryCriteria criteria){ |
| | | return appMapper.toDto(appRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); |
| | | } |
| | | |
| | | @Override |
| | | public AppDto findById(Long id) { |
| | | App app = appRepository.findById(id).orElseGet(App::new); |
| | | ValidationUtil.isNull(app.getId(),"App","id",id); |
| | | return appMapper.toDto(app); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(App resources) { |
| | | verification(resources); |
| | | appRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(App resources) { |
| | | verification(resources); |
| | | App app = appRepository.findById(resources.getId()).orElseGet(App::new); |
| | | ValidationUtil.isNull(app.getId(),"App","id",resources.getId()); |
| | | app.copy(resources); |
| | | appRepository.save(app); |
| | | } |
| | | |
| | | private void verification(App resources){ |
| | | String opt = "/opt"; |
| | | String home = "/home"; |
| | | if (!(resources.getUploadPath().startsWith(opt) || resources.getUploadPath().startsWith(home))) { |
| | | throw new BadRequestException("文件只能上传在opt目录或者home目录 "); |
| | | } |
| | | if (!(resources.getDeployPath().startsWith(opt) || resources.getDeployPath().startsWith(home))) { |
| | | throw new BadRequestException("文件只能部署在opt目录或者home目录 "); |
| | | } |
| | | if (!(resources.getBackupPath().startsWith(opt) || resources.getBackupPath().startsWith(home))) { |
| | | throw new BadRequestException("文件只能备份在opt目录或者home目录 "); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | for (Long id : ids) { |
| | | appRepository.deleteById(id); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (AppDto appDto : queryAll) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("应用名称", appDto.getName()); |
| | | map.put("端口", appDto.getPort()); |
| | | map.put("上传目录", appDto.getUploadPath()); |
| | | map.put("部署目录", appDto.getDeployPath()); |
| | | map.put("备份目录", appDto.getBackupPath()); |
| | | map.put("启动脚本", appDto.getStartScript()); |
| | | map.put("部署脚本", appDto.getDeployScript()); |
| | | map.put("创建日期", appDto.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.impl; |
| | | |
| | | import cn.hutool.core.util.IdUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.modules.mnt.domain.Database; |
| | | import me.zhengjie.modules.mnt.repository.DatabaseRepository; |
| | | import me.zhengjie.modules.mnt.service.DatabaseService; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseQueryCriteria; |
| | | import me.zhengjie.modules.mnt.service.mapstruct.DatabaseMapper; |
| | | import me.zhengjie.modules.mnt.util.SqlUtils; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.QueryHelp; |
| | | import me.zhengjie.utils.ValidationUtil; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Slf4j |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class DatabaseServiceImpl implements DatabaseService { |
| | | |
| | | private final DatabaseRepository databaseRepository; |
| | | private final DatabaseMapper databaseMapper; |
| | | |
| | | @Override |
| | | public Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable){ |
| | | Page<Database> page = databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(databaseMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria){ |
| | | return databaseMapper.toDto(databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); |
| | | } |
| | | |
| | | @Override |
| | | public DatabaseDto findById(String id) { |
| | | Database database = databaseRepository.findById(id).orElseGet(Database::new); |
| | | ValidationUtil.isNull(database.getId(),"Database","id",id); |
| | | return databaseMapper.toDto(database); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Database resources) { |
| | | resources.setId(IdUtil.simpleUUID()); |
| | | databaseRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Database resources) { |
| | | Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new); |
| | | ValidationUtil.isNull(database.getId(),"Database","id",resources.getId()); |
| | | database.copy(resources); |
| | | databaseRepository.save(database); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<String> ids) { |
| | | for (String id : ids) { |
| | | databaseRepository.deleteById(id); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public boolean testConnection(Database resources) { |
| | | try { |
| | | return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd()); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage()); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (DatabaseDto databaseDto : queryAll) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("数据库名称", databaseDto.getName()); |
| | | map.put("数据库连接地址", databaseDto.getJdbcUrl()); |
| | | map.put("用户名", databaseDto.getUserName()); |
| | | map.put("创建日期", databaseDto.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.impl; |
| | | |
| | | import cn.hutool.core.util.IdUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.repository.DeployHistoryRepository; |
| | | import me.zhengjie.modules.mnt.service.DeployHistoryService; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryQueryCriteria; |
| | | import me.zhengjie.modules.mnt.service.mapstruct.DeployHistoryMapper; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.QueryHelp; |
| | | import me.zhengjie.utils.ValidationUtil; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class DeployHistoryServiceImpl implements DeployHistoryService { |
| | | |
| | | private final DeployHistoryRepository deployhistoryRepository; |
| | | private final DeployHistoryMapper deployhistoryMapper; |
| | | |
| | | @Override |
| | | public Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){ |
| | | Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(deployhistoryMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){ |
| | | return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); |
| | | } |
| | | |
| | | @Override |
| | | public DeployHistoryDto findById(String id) { |
| | | DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new); |
| | | ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id); |
| | | return deployhistoryMapper.toDto(deployhistory); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(DeployHistory resources) { |
| | | resources.setId(IdUtil.simpleUUID()); |
| | | deployhistoryRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<String> ids) { |
| | | for (String id : ids) { |
| | | deployhistoryRepository.deleteById(id); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (DeployHistoryDto deployHistoryDto : queryAll) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("部署编号", deployHistoryDto.getDeployId()); |
| | | map.put("应用名称", deployHistoryDto.getAppName()); |
| | | map.put("部署IP", deployHistoryDto.getIp()); |
| | | map.put("部署时间", deployHistoryDto.getDeployDate()); |
| | | map.put("部署人员", deployHistoryDto.getDeployUser()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.impl; |
| | | |
| | | import cn.hutool.core.date.DatePattern; |
| | | import cn.hutool.core.date.DateUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import me.zhengjie.modules.mnt.domain.Deploy; |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import me.zhengjie.modules.mnt.repository.DeployRepository; |
| | | import me.zhengjie.modules.mnt.service.DeployHistoryService; |
| | | import me.zhengjie.modules.mnt.service.DeployService; |
| | | import me.zhengjie.modules.mnt.service.ServerDeployService; |
| | | import me.zhengjie.modules.mnt.service.dto.AppDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployDto; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployQueryCriteria; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployDto; |
| | | import me.zhengjie.modules.mnt.service.mapstruct.DeployMapper; |
| | | import me.zhengjie.modules.mnt.util.ExecuteShellUtil; |
| | | import me.zhengjie.modules.mnt.util.ScpClientUtil; |
| | | import me.zhengjie.modules.mnt.websocket.MsgType; |
| | | import me.zhengjie.modules.mnt.websocket.SocketMsg; |
| | | import me.zhengjie.modules.mnt.websocket.WebSocketServer; |
| | | import me.zhengjie.utils.*; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Slf4j |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class DeployServiceImpl implements DeployService { |
| | | |
| | | private final String FILE_SEPARATOR = "/"; |
| | | private final DeployRepository deployRepository; |
| | | private final DeployMapper deployMapper; |
| | | private final ServerDeployService serverDeployService; |
| | | private final DeployHistoryService deployHistoryService; |
| | | /** |
| | | * 循环次数 |
| | | */ |
| | | private final Integer count = 30; |
| | | |
| | | |
| | | @Override |
| | | public Object queryAll(DeployQueryCriteria criteria, Pageable pageable) { |
| | | Page<Deploy> page = deployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); |
| | | return PageUtil.toPage(page.map(deployMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<DeployDto> queryAll(DeployQueryCriteria criteria) { |
| | | return deployMapper.toDto(deployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder))); |
| | | } |
| | | |
| | | @Override |
| | | public DeployDto findById(Long id) { |
| | | Deploy deploy = deployRepository.findById(id).orElseGet(Deploy::new); |
| | | ValidationUtil.isNull(deploy.getId(), "Deploy", "id", id); |
| | | return deployMapper.toDto(deploy); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Deploy resources) { |
| | | deployRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Deploy resources) { |
| | | Deploy deploy = deployRepository.findById(resources.getId()).orElseGet(Deploy::new); |
| | | ValidationUtil.isNull(deploy.getId(), "Deploy", "id", resources.getId()); |
| | | deploy.copy(resources); |
| | | deployRepository.save(deploy); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | for (Long id : ids) { |
| | | deployRepository.deleteById(id); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void deploy(String fileSavePath, Long id) { |
| | | deployApp(fileSavePath, id); |
| | | } |
| | | |
| | | /** |
| | | * @param fileSavePath 本机路径 |
| | | * @param id ID |
| | | */ |
| | | private void deployApp(String fileSavePath, Long id) { |
| | | |
| | | DeployDto deploy = findById(id); |
| | | if (deploy == null) { |
| | | sendMsg("部署信息不存在", MsgType.ERROR); |
| | | throw new BadRequestException("部署信息不存在"); |
| | | } |
| | | AppDto app = deploy.getApp(); |
| | | if (app == null) { |
| | | sendMsg("包对应应用信息不存在", MsgType.ERROR); |
| | | throw new BadRequestException("包对应应用信息不存在"); |
| | | } |
| | | int port = app.getPort(); |
| | | //这个是服务器部署路径 |
| | | String uploadPath = app.getUploadPath(); |
| | | StringBuilder sb = new StringBuilder(); |
| | | String msg; |
| | | Set<ServerDeployDto> deploys = deploy.getDeploys(); |
| | | for (ServerDeployDto deployDTO : deploys) { |
| | | String ip = deployDTO.getIp(); |
| | | ExecuteShellUtil executeShellUtil = getExecuteShellUtil(ip); |
| | | //判断是否第一次部署 |
| | | boolean flag = checkFile(executeShellUtil, app); |
| | | //第一步要确认服务器上有这个目录 |
| | | executeShellUtil.execute("mkdir -p " + app.getUploadPath()); |
| | | executeShellUtil.execute("mkdir -p " + app.getBackupPath()); |
| | | executeShellUtil.execute("mkdir -p " + app.getDeployPath()); |
| | | //上传文件 |
| | | msg = String.format("登陆到服务器:%s", ip); |
| | | ScpClientUtil scpClientUtil = getScpClientUtil(ip); |
| | | log.info(msg); |
| | | sendMsg(msg, MsgType.INFO); |
| | | msg = String.format("上传文件到服务器:%s<br>目录:%s下,请稍等...", ip, uploadPath); |
| | | sendMsg(msg, MsgType.INFO); |
| | | scpClientUtil.putFile(fileSavePath, uploadPath); |
| | | if (flag) { |
| | | sendMsg("停止原来应用", MsgType.INFO); |
| | | //停止应用 |
| | | stopApp(port, executeShellUtil); |
| | | sendMsg("备份原来应用", MsgType.INFO); |
| | | //备份应用 |
| | | backupApp(executeShellUtil, ip, app.getDeployPath()+FILE_SEPARATOR, app.getName(), app.getBackupPath()+FILE_SEPARATOR, id); |
| | | } |
| | | sendMsg("部署应用", MsgType.INFO); |
| | | //部署文件,并启动应用 |
| | | String deployScript = app.getDeployScript(); |
| | | executeShellUtil.execute(deployScript); |
| | | sleep(3); |
| | | sendMsg("应用部署中,请耐心等待部署结果,或者稍后手动查看部署状态", MsgType.INFO); |
| | | int i = 0; |
| | | boolean result = false; |
| | | // 由于启动应用需要时间,所以需要循环获取状态,如果超过30次,则认为是启动失败 |
| | | while (i++ < count){ |
| | | result = checkIsRunningStatus(port, executeShellUtil); |
| | | if(result){ |
| | | break; |
| | | } |
| | | // 休眠6秒 |
| | | sleep(6); |
| | | } |
| | | sb.append("服务器:").append(deployDTO.getName()).append("<br>应用:").append(app.getName()); |
| | | sendResultMsg(result, sb); |
| | | executeShellUtil.close(); |
| | | } |
| | | } |
| | | |
| | | private void sleep(int second) { |
| | | try { |
| | | Thread.sleep(second * 1000); |
| | | } catch (InterruptedException e) { |
| | | log.error(e.getMessage(),e); |
| | | } |
| | | } |
| | | |
| | | private void backupApp(ExecuteShellUtil executeShellUtil, String ip, String fileSavePath, String appName, String backupPath, Long id) { |
| | | String deployDate = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN); |
| | | StringBuilder sb = new StringBuilder(); |
| | | backupPath += appName + FILE_SEPARATOR + deployDate + "\n"; |
| | | sb.append("mkdir -p ").append(backupPath); |
| | | sb.append("mv -f ").append(fileSavePath); |
| | | sb.append(appName).append(" ").append(backupPath); |
| | | log.info("备份应用脚本:" + sb.toString()); |
| | | executeShellUtil.execute(sb.toString()); |
| | | //还原信息入库 |
| | | DeployHistory deployHistory = new DeployHistory(); |
| | | deployHistory.setAppName(appName); |
| | | deployHistory.setDeployUser(SecurityUtils.getCurrentUsername()); |
| | | deployHistory.setIp(ip); |
| | | deployHistory.setDeployId(id); |
| | | deployHistoryService.create(deployHistory); |
| | | } |
| | | |
| | | /** |
| | | * 停App |
| | | * |
| | | * @param port 端口 |
| | | * @param executeShellUtil / |
| | | */ |
| | | private void stopApp(int port, ExecuteShellUtil executeShellUtil) { |
| | | //发送停止命令 |
| | | executeShellUtil.execute(String.format("lsof -i :%d|grep -v \"PID\"|awk '{print \"kill -9\",$2}'|sh", port)); |
| | | |
| | | } |
| | | |
| | | /** |
| | | * 指定端口程序是否在运行 |
| | | * |
| | | * @param port 端口 |
| | | * @param executeShellUtil / |
| | | * @return true 正在运行 false 已经停止 |
| | | */ |
| | | private boolean checkIsRunningStatus(int port, ExecuteShellUtil executeShellUtil) { |
| | | String result = executeShellUtil.executeForResult(String.format("fuser -n tcp %d", port)); |
| | | return result.indexOf("/tcp:")>0; |
| | | } |
| | | |
| | | private void sendMsg(String msg, MsgType msgType) { |
| | | try { |
| | | WebSocketServer.sendInfo(new SocketMsg(msg, msgType), "deploy"); |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(),e); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public String serverStatus(Deploy resources) { |
| | | Set<ServerDeploy> serverDeploys = resources.getDeploys(); |
| | | App app = resources.getApp(); |
| | | for (ServerDeploy serverDeploy : serverDeploys) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | ExecuteShellUtil executeShellUtil = getExecuteShellUtil(serverDeploy.getIp()); |
| | | sb.append("服务器:").append(serverDeploy.getName()).append("<br>应用:").append(app.getName()); |
| | | boolean result = checkIsRunningStatus(app.getPort(), executeShellUtil); |
| | | if (result) { |
| | | sb.append("<br>正在运行"); |
| | | sendMsg(sb.toString(), MsgType.INFO); |
| | | } else { |
| | | sb.append("<br>已停止!"); |
| | | sendMsg(sb.toString(), MsgType.ERROR); |
| | | } |
| | | log.info(sb.toString()); |
| | | executeShellUtil.close(); |
| | | } |
| | | return "执行完毕"; |
| | | } |
| | | |
| | | private boolean checkFile(ExecuteShellUtil executeShellUtil, AppDto appDTO) { |
| | | String result = executeShellUtil.executeForResult("find " + appDTO.getDeployPath() + " -name " + appDTO.getName()); |
| | | return result.indexOf(appDTO.getName())>0; |
| | | } |
| | | |
| | | /** |
| | | * 启动服务 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | @Override |
| | | public String startServer(Deploy resources) { |
| | | Set<ServerDeploy> deploys = resources.getDeploys(); |
| | | App app = resources.getApp(); |
| | | for (ServerDeploy deploy : deploys) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | ExecuteShellUtil executeShellUtil = getExecuteShellUtil(deploy.getIp()); |
| | | //为了防止重复启动,这里先停止应用 |
| | | stopApp(app.getPort(), executeShellUtil); |
| | | sb.append("服务器:").append(deploy.getName()).append("<br>应用:").append(app.getName()); |
| | | sendMsg("下发启动命令", MsgType.INFO); |
| | | executeShellUtil.execute(app.getStartScript()); |
| | | sleep(3); |
| | | sendMsg("应用启动中,请耐心等待启动结果,或者稍后手动查看运行状态", MsgType.INFO); |
| | | int i = 0; |
| | | boolean result = false; |
| | | // 由于启动应用需要时间,所以需要循环获取状态,如果超过30次,则认为是启动失败 |
| | | while (i++ < count){ |
| | | result = checkIsRunningStatus(app.getPort(), executeShellUtil); |
| | | if(result){ |
| | | break; |
| | | } |
| | | // 休眠6秒 |
| | | sleep(6); |
| | | } |
| | | sendResultMsg(result, sb); |
| | | log.info(sb.toString()); |
| | | executeShellUtil.close(); |
| | | } |
| | | return "执行完毕"; |
| | | } |
| | | |
| | | /** |
| | | * 停止服务 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | @Override |
| | | public String stopServer(Deploy resources) { |
| | | Set<ServerDeploy> deploys = resources.getDeploys(); |
| | | App app = resources.getApp(); |
| | | for (ServerDeploy deploy : deploys) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | ExecuteShellUtil executeShellUtil = getExecuteShellUtil(deploy.getIp()); |
| | | sb.append("服务器:").append(deploy.getName()).append("<br>应用:").append(app.getName()); |
| | | sendMsg("下发停止命令", MsgType.INFO); |
| | | //停止应用 |
| | | stopApp(app.getPort(), executeShellUtil); |
| | | sleep(1); |
| | | boolean result = checkIsRunningStatus(app.getPort(), executeShellUtil); |
| | | if (result) { |
| | | sb.append("<br>关闭失败!"); |
| | | sendMsg(sb.toString(), MsgType.ERROR); |
| | | } else { |
| | | sb.append("<br>关闭成功!"); |
| | | sendMsg(sb.toString(), MsgType.INFO); |
| | | } |
| | | log.info(sb.toString()); |
| | | executeShellUtil.close(); |
| | | } |
| | | return "执行完毕"; |
| | | } |
| | | |
| | | @Override |
| | | public String serverReduction(DeployHistory resources) { |
| | | Long deployId = resources.getDeployId(); |
| | | Deploy deployInfo = deployRepository.findById(deployId).orElseGet(Deploy::new); |
| | | String deployDate = DateUtil.format(resources.getDeployDate(), DatePattern.PURE_DATETIME_PATTERN); |
| | | App app = deployInfo.getApp(); |
| | | if (app == null) { |
| | | sendMsg("应用信息不存在:" + resources.getAppName(), MsgType.ERROR); |
| | | throw new BadRequestException("应用信息不存在:" + resources.getAppName()); |
| | | } |
| | | String backupPath = app.getBackupPath()+FILE_SEPARATOR; |
| | | backupPath += resources.getAppName() + FILE_SEPARATOR + deployDate; |
| | | //这个是服务器部署路径 |
| | | String deployPath = app.getDeployPath(); |
| | | String ip = resources.getIp(); |
| | | ExecuteShellUtil executeShellUtil = getExecuteShellUtil(ip); |
| | | String msg; |
| | | |
| | | msg = String.format("登陆到服务器:%s", ip); |
| | | log.info(msg); |
| | | sendMsg(msg, MsgType.INFO); |
| | | sendMsg("停止原来应用", MsgType.INFO); |
| | | //停止应用 |
| | | stopApp(app.getPort(), executeShellUtil); |
| | | //删除原来应用 |
| | | sendMsg("删除应用", MsgType.INFO); |
| | | executeShellUtil.execute("rm -rf " + deployPath + FILE_SEPARATOR + resources.getAppName()); |
| | | //还原应用 |
| | | sendMsg("还原应用", MsgType.INFO); |
| | | executeShellUtil.execute("cp -r " + backupPath + "/. " + deployPath); |
| | | sendMsg("启动应用", MsgType.INFO); |
| | | executeShellUtil.execute(app.getStartScript()); |
| | | sendMsg("应用启动中,请耐心等待启动结果,或者稍后手动查看启动状态", MsgType.INFO); |
| | | int i = 0; |
| | | boolean result = false; |
| | | // 由于启动应用需要时间,所以需要循环获取状态,如果超过30次,则认为是启动失败 |
| | | while (i++ < count){ |
| | | result = checkIsRunningStatus(app.getPort(), executeShellUtil); |
| | | if(result){ |
| | | break; |
| | | } |
| | | // 休眠6秒 |
| | | sleep(6); |
| | | } |
| | | StringBuilder sb = new StringBuilder(); |
| | | sb.append("服务器:").append(ip).append("<br>应用:").append(resources.getAppName()); |
| | | sendResultMsg(result, sb); |
| | | executeShellUtil.close(); |
| | | return ""; |
| | | } |
| | | |
| | | private ExecuteShellUtil getExecuteShellUtil(String ip) { |
| | | ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip); |
| | | if (serverDeployDTO == null) { |
| | | sendMsg("IP对应服务器信息不存在:" + ip, MsgType.ERROR); |
| | | throw new BadRequestException("IP对应服务器信息不存在:" + ip); |
| | | } |
| | | return new ExecuteShellUtil(ip, serverDeployDTO.getAccount(), serverDeployDTO.getPassword(),serverDeployDTO.getPort()); |
| | | } |
| | | |
| | | private ScpClientUtil getScpClientUtil(String ip) { |
| | | ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip); |
| | | if (serverDeployDTO == null) { |
| | | sendMsg("IP对应服务器信息不存在:" + ip, MsgType.ERROR); |
| | | throw new BadRequestException("IP对应服务器信息不存在:" + ip); |
| | | } |
| | | return ScpClientUtil.getInstance(ip, serverDeployDTO.getPort(), serverDeployDTO.getAccount(), serverDeployDTO.getPassword()); |
| | | } |
| | | |
| | | private void sendResultMsg(boolean result, StringBuilder sb) { |
| | | if (result) { |
| | | sb.append("<br>启动成功!"); |
| | | sendMsg(sb.toString(), MsgType.INFO); |
| | | } else { |
| | | sb.append("<br>启动失败!"); |
| | | sendMsg(sb.toString(), MsgType.ERROR); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (DeployDto deployDto : queryAll) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("应用名称", deployDto.getApp().getName()); |
| | | map.put("服务器", deployDto.getServers()); |
| | | map.put("部署日期", deployDto.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import me.zhengjie.modules.mnt.repository.ServerDeployRepository; |
| | | import me.zhengjie.modules.mnt.service.ServerDeployService; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployDto; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployQueryCriteria; |
| | | import me.zhengjie.modules.mnt.service.mapstruct.ServerDeployMapper; |
| | | import me.zhengjie.modules.mnt.util.ExecuteShellUtil; |
| | | import me.zhengjie.utils.FileUtil; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.QueryHelp; |
| | | import me.zhengjie.utils.ValidationUtil; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | public class ServerDeployServiceImpl implements ServerDeployService { |
| | | |
| | | private final ServerDeployRepository serverDeployRepository; |
| | | private final ServerDeployMapper serverDeployMapper; |
| | | |
| | | @Override |
| | | public Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable){ |
| | | Page<ServerDeploy> page = serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(serverDeployMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria){ |
| | | return serverDeployMapper.toDto(serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); |
| | | } |
| | | |
| | | @Override |
| | | public ServerDeployDto findById(Long id) { |
| | | ServerDeploy server = serverDeployRepository.findById(id).orElseGet(ServerDeploy::new); |
| | | ValidationUtil.isNull(server.getId(),"ServerDeploy","id",id); |
| | | return serverDeployMapper.toDto(server); |
| | | } |
| | | |
| | | @Override |
| | | public ServerDeployDto findByIp(String ip) { |
| | | ServerDeploy deploy = serverDeployRepository.findByIp(ip); |
| | | return serverDeployMapper.toDto(deploy); |
| | | } |
| | | |
| | | @Override |
| | | public Boolean testConnect(ServerDeploy resources) { |
| | | ExecuteShellUtil executeShellUtil = null; |
| | | try { |
| | | executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort()); |
| | | return executeShellUtil.execute("ls")==0; |
| | | } catch (Exception e) { |
| | | return false; |
| | | }finally { |
| | | if (executeShellUtil != null) { |
| | | executeShellUtil.close(); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(ServerDeploy resources) { |
| | | serverDeployRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(ServerDeploy resources) { |
| | | ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new); |
| | | ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId()); |
| | | serverDeploy.copy(resources); |
| | | serverDeployRepository.save(serverDeploy); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | for (Long id : ids) { |
| | | serverDeployRepository.deleteById(id); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (ServerDeployDto deployDto : queryAll) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("服务器名称", deployDto.getName()); |
| | | map.put("服务器IP", deployDto.getIp()); |
| | | map.put("端口", deployDto.getPort()); |
| | | map.put("账号", deployDto.getAccount()); |
| | | map.put("创建日期", deployDto.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.modules.mnt.domain.App; |
| | | import me.zhengjie.modules.mnt.service.dto.AppDto; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface AppMapper extends BaseMapper<AppDto, App> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.modules.mnt.domain.Database; |
| | | import me.zhengjie.modules.mnt.service.dto.DatabaseDto; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface DatabaseMapper extends BaseMapper<DatabaseDto, Database> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.modules.mnt.domain.DeployHistory; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployHistoryDto; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface DeployHistoryMapper extends BaseMapper<DeployHistoryDto, DeployHistory> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.modules.mnt.domain.Deploy; |
| | | import me.zhengjie.modules.mnt.service.dto.DeployDto; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Mapper(componentModel = "spring",uses = {AppMapper.class, ServerDeployMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface DeployMapper extends BaseMapper<DeployDto, Deploy> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.service.mapstruct; |
| | | |
| | | import me.zhengjie.base.BaseMapper; |
| | | import me.zhengjie.modules.mnt.domain.ServerDeploy; |
| | | import me.zhengjie.modules.mnt.service.dto.ServerDeployDto; |
| | | import org.mapstruct.Mapper; |
| | | import org.mapstruct.ReportingPolicy; |
| | | |
| | | /** |
| | | * @author zhanghouying |
| | | * @date 2019-08-24 |
| | | */ |
| | | @Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE) |
| | | public interface ServerDeployMapper extends BaseMapper<ServerDeployDto, ServerDeploy> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * << |
| | | * Davinci |
| | | * == |
| | | * Copyright (C) 2016 - 2019 EDP |
| | | * == |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | * >> |
| | | * |
| | | */ |
| | | |
| | | package me.zhengjie.modules.mnt.util; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @Slf4j |
| | | @SuppressWarnings({"unchecked","all"}) |
| | | public enum DataTypeEnum { |
| | | |
| | | /** mysql */ |
| | | MYSQL("mysql", "mysql", "com.mysql.jdbc.Driver", "`", "`", "'", "'"), |
| | | |
| | | /** oracle */ |
| | | ORACLE("oracle", "oracle", "oracle.jdbc.driver.OracleDriver", "\"", "\"", "\"", "\""), |
| | | |
| | | /** sql server */ |
| | | SQLSERVER("sqlserver", "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "\"", "\"", "\"", "\""), |
| | | |
| | | /** h2 */ |
| | | H2("h2", "h2", "org.h2.Driver", "`", "`", "\"", "\""), |
| | | |
| | | /** phoenix */ |
| | | PHOENIX("phoenix", "hbase phoenix", "org.apache.phoenix.jdbc.PhoenixDriver", "", "", "\"", "\""), |
| | | |
| | | /** mongo */ |
| | | MONGODB("mongo", "mongodb", "mongodb.jdbc.MongoDriver", "`", "`", "\"", "\""), |
| | | |
| | | /** sql4es */ |
| | | ELASTICSEARCH("sql4es", "elasticsearch", "nl.anchormen.sql4es.jdbc.ESDriver", "", "", "'", "'"), |
| | | |
| | | /** presto */ |
| | | PRESTO("presto", "presto", "com.facebook.presto.jdbc.PrestoDriver", "", "", "\"", "\""), |
| | | |
| | | /** moonbox */ |
| | | MOONBOX("moonbox", "moonbox", "moonbox.jdbc.MbDriver", "`", "`", "`", "`"), |
| | | |
| | | /** cassandra */ |
| | | CASSANDRA("cassandra", "cassandra", "com.github.adejanovski.cassandra.jdbc.CassandraDriver", "", "", "'", "'"), |
| | | |
| | | /** click house */ |
| | | CLICKHOUSE("clickhouse", "clickhouse", "ru.yandex.clickhouse.ClickHouseDriver", "", "", "\"", "\""), |
| | | |
| | | /** kylin */ |
| | | KYLIN("kylin", "kylin", "org.apache.kylin.jdbc.Driver", "\"", "\"", "\"", "\""), |
| | | |
| | | /** vertica */ |
| | | VERTICA("vertica", "vertica", "com.vertica.jdbc.Driver", "", "", "'", "'"), |
| | | |
| | | /** sap */ |
| | | HANA("sap", "sap hana", "com.sap.db.jdbc.Driver", "", "", "'", "'"), |
| | | |
| | | /** impala */ |
| | | IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'"); |
| | | |
| | | private String feature; |
| | | private String desc; |
| | | private String driver; |
| | | private String keywordPrefix; |
| | | private String keywordSuffix; |
| | | private String aliasPrefix; |
| | | private String aliasSuffix; |
| | | |
| | | private static final String JDBC_URL_PREFIX = "jdbc:"; |
| | | |
| | | DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) { |
| | | this.feature = feature; |
| | | this.desc = desc; |
| | | this.driver = driver; |
| | | this.keywordPrefix = keywordPrefix; |
| | | this.keywordSuffix = keywordSuffix; |
| | | this.aliasPrefix = aliasPrefix; |
| | | this.aliasSuffix = aliasSuffix; |
| | | } |
| | | |
| | | public static DataTypeEnum urlOf(String jdbcUrl) { |
| | | String url = jdbcUrl.toLowerCase().trim(); |
| | | for (DataTypeEnum dataTypeEnum : values()) { |
| | | if (url.startsWith(JDBC_URL_PREFIX + dataTypeEnum.feature)) { |
| | | try { |
| | | Class<?> aClass = Class.forName(dataTypeEnum.getDriver()); |
| | | if (null == aClass) { |
| | | throw new RuntimeException("Unable to get driver instance for jdbcUrl: " + jdbcUrl); |
| | | } |
| | | } catch (ClassNotFoundException e) { |
| | | throw new RuntimeException("Unable to get driver instance: " + jdbcUrl); |
| | | } |
| | | return dataTypeEnum; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | public String getFeature() { |
| | | return feature; |
| | | } |
| | | |
| | | public String getDesc() { |
| | | return desc; |
| | | } |
| | | |
| | | public String getDriver() { |
| | | return driver; |
| | | } |
| | | |
| | | public String getKeywordPrefix() { |
| | | return keywordPrefix; |
| | | } |
| | | |
| | | public String getKeywordSuffix() { |
| | | return keywordSuffix; |
| | | } |
| | | |
| | | public String getAliasPrefix() { |
| | | return aliasPrefix; |
| | | } |
| | | |
| | | public String getAliasSuffix() { |
| | | return aliasSuffix; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.util; |
| | | |
| | | import cn.hutool.core.io.IoUtil; |
| | | import com.jcraft.jsch.ChannelShell; |
| | | import com.jcraft.jsch.JSch; |
| | | import com.jcraft.jsch.Session; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | |
| | | import java.io.*; |
| | | import java.util.Vector; |
| | | |
| | | /** |
| | | * 执行shell命令 |
| | | * |
| | | * @author: ZhangHouYing |
| | | * @date: 2019/8/10 |
| | | */ |
| | | @Slf4j |
| | | public class ExecuteShellUtil { |
| | | |
| | | private Vector<String> stdout; |
| | | |
| | | Session session; |
| | | |
| | | public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) { |
| | | try { |
| | | JSch jsch = new JSch(); |
| | | session = jsch.getSession(username, ipAddress, port); |
| | | session.setPassword(password); |
| | | session.setConfig("StrictHostKeyChecking", "no"); |
| | | session.connect(3000); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(),e); |
| | | } |
| | | |
| | | } |
| | | |
| | | public int execute(final String command) { |
| | | int returnCode = 0; |
| | | ChannelShell channel = null; |
| | | PrintWriter printWriter = null; |
| | | BufferedReader input = null; |
| | | stdout = new Vector<String>(); |
| | | try { |
| | | channel = (ChannelShell) session.openChannel("shell"); |
| | | channel.connect(); |
| | | input = new BufferedReader(new InputStreamReader(channel.getInputStream())); |
| | | printWriter = new PrintWriter(channel.getOutputStream()); |
| | | printWriter.println(command); |
| | | printWriter.println("exit"); |
| | | printWriter.flush(); |
| | | log.info("The remote command is: "); |
| | | String line; |
| | | while ((line = input.readLine()) != null) { |
| | | stdout.add(line); |
| | | System.out.println(line); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(),e); |
| | | return -1; |
| | | }finally { |
| | | IoUtil.close(printWriter); |
| | | IoUtil.close(input); |
| | | if (channel != null) { |
| | | channel.disconnect(); |
| | | } |
| | | } |
| | | return returnCode; |
| | | } |
| | | |
| | | public void close(){ |
| | | if (session != null) { |
| | | session.disconnect(); |
| | | } |
| | | } |
| | | |
| | | public String executeForResult(String command) { |
| | | execute(command); |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (String str : stdout) { |
| | | sb.append(str); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.util; |
| | | |
| | | import ch.ethz.ssh2.Connection; |
| | | import ch.ethz.ssh2.SCPClient; |
| | | import com.google.common.collect.Maps; |
| | | |
| | | import java.io.IOException; |
| | | import java.util.Map; |
| | | import java.util.logging.Level; |
| | | import java.util.logging.Logger; |
| | | |
| | | /** |
| | | * 远程执行linux命令 |
| | | * @author: ZhangHouYing |
| | | * @date: 2019-08-10 10:06 |
| | | */ |
| | | public class ScpClientUtil { |
| | | |
| | | static private Map<String,ScpClientUtil> instance = Maps.newHashMap(); |
| | | |
| | | static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String password) { |
| | | if (instance.get(ip) == null) { |
| | | instance.put(ip, new ScpClientUtil(ip, port, username, password)); |
| | | } |
| | | return instance.get(ip); |
| | | } |
| | | |
| | | public ScpClientUtil(String ip, int port, String username, String password) { |
| | | this.ip = ip; |
| | | this.port = port; |
| | | this.username = username; |
| | | this.password = password; |
| | | } |
| | | |
| | | public void getFile(String remoteFile, String localTargetDirectory) { |
| | | Connection conn = new Connection(ip, port); |
| | | try { |
| | | conn.connect(); |
| | | boolean isAuthenticated = conn.authenticateWithPassword(username, password); |
| | | if (!isAuthenticated) { |
| | | System.err.println("authentication failed"); |
| | | } |
| | | SCPClient client = new SCPClient(conn); |
| | | client.get(remoteFile, localTargetDirectory); |
| | | } catch (IOException ex) { |
| | | Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex); |
| | | }finally{ |
| | | conn.close(); |
| | | } |
| | | } |
| | | |
| | | public void putFile(String localFile, String remoteTargetDirectory) { |
| | | putFile(localFile, null, remoteTargetDirectory); |
| | | } |
| | | |
| | | public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) { |
| | | putFile(localFile, remoteFileName, remoteTargetDirectory,null); |
| | | } |
| | | |
| | | public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) { |
| | | Connection conn = new Connection(ip, port); |
| | | try { |
| | | conn.connect(); |
| | | boolean isAuthenticated = conn.authenticateWithPassword(username, password); |
| | | if (!isAuthenticated) { |
| | | System.err.println("authentication failed"); |
| | | } |
| | | SCPClient client = new SCPClient(conn); |
| | | if ((mode == null) || (mode.length() == 0)) { |
| | | mode = "0600"; |
| | | } |
| | | if (remoteFileName == null) { |
| | | client.put(localFile, remoteTargetDirectory); |
| | | } else { |
| | | client.put(localFile, remoteFileName, remoteTargetDirectory, mode); |
| | | } |
| | | } catch (IOException ex) { |
| | | Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex); |
| | | }finally{ |
| | | conn.close(); |
| | | } |
| | | } |
| | | |
| | | private String ip; |
| | | private int port; |
| | | private String username; |
| | | private String password; |
| | | |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.util; |
| | | |
| | | import com.alibaba.druid.pool.DruidDataSource; |
| | | import com.alibaba.druid.util.StringUtils; |
| | | import com.google.common.collect.Lists; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.utils.CloseUtil; |
| | | import javax.sql.DataSource; |
| | | import java.io.BufferedReader; |
| | | import java.io.File; |
| | | import java.io.FileInputStream; |
| | | import java.io.InputStreamReader; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.sql.*; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @Slf4j |
| | | public class SqlUtils { |
| | | |
| | | /** |
| | | * 获取数据源 |
| | | * |
| | | * @param jdbcUrl / |
| | | * @param userName / |
| | | * @param password / |
| | | * @return DataSource |
| | | */ |
| | | private static DataSource getDataSource(String jdbcUrl, String userName, String password) { |
| | | DruidDataSource druidDataSource = new DruidDataSource(); |
| | | String className; |
| | | try { |
| | | className = DriverManager.getDriver(jdbcUrl.trim()).getClass().getName(); |
| | | } catch (SQLException e) { |
| | | throw new RuntimeException("Get class name error: =" + jdbcUrl); |
| | | } |
| | | if (StringUtils.isEmpty(className)) { |
| | | DataTypeEnum dataTypeEnum = DataTypeEnum.urlOf(jdbcUrl); |
| | | if (null == dataTypeEnum) { |
| | | throw new RuntimeException("Not supported data type: jdbcUrl=" + jdbcUrl); |
| | | } |
| | | druidDataSource.setDriverClassName(dataTypeEnum.getDriver()); |
| | | } else { |
| | | druidDataSource.setDriverClassName(className); |
| | | } |
| | | |
| | | |
| | | druidDataSource.setUrl(jdbcUrl); |
| | | druidDataSource.setUsername(userName); |
| | | druidDataSource.setPassword(password); |
| | | // 配置获取连接等待超时的时间 |
| | | druidDataSource.setMaxWait(3000); |
| | | // 配置初始化大小、最小、最大 |
| | | druidDataSource.setInitialSize(1); |
| | | druidDataSource.setMinIdle(1); |
| | | druidDataSource.setMaxActive(1); |
| | | |
| | | // 如果链接出现异常则直接判定为失败而不是一直重试 |
| | | druidDataSource.setBreakAfterAcquireFailure(true); |
| | | try { |
| | | druidDataSource.init(); |
| | | } catch (SQLException e) { |
| | | log.error("Exception during pool initialization", e); |
| | | throw new RuntimeException(e.getMessage()); |
| | | } |
| | | |
| | | return druidDataSource; |
| | | } |
| | | |
| | | private static Connection getConnection(String jdbcUrl, String userName, String password) { |
| | | DataSource dataSource = getDataSource(jdbcUrl, userName, password); |
| | | Connection connection = null; |
| | | try { |
| | | connection = dataSource.getConnection(); |
| | | } catch (Exception ignored) {} |
| | | try { |
| | | int timeOut = 5; |
| | | if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) { |
| | | log.info("connection is closed or invalid, retry get connection!"); |
| | | connection = dataSource.getConnection(); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("create connection error, jdbcUrl: {}", jdbcUrl); |
| | | throw new RuntimeException("create connection error, jdbcUrl: " + jdbcUrl); |
| | | } finally { |
| | | CloseUtil.close(connection); |
| | | } |
| | | return connection; |
| | | } |
| | | |
| | | private static void releaseConnection(Connection connection) { |
| | | if (null != connection) { |
| | | try { |
| | | connection.close(); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(),e); |
| | | log.error("connection close error:" + e.getMessage()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | public static boolean testConnection(String jdbcUrl, String userName, String password) { |
| | | Connection connection = null; |
| | | try { |
| | | connection = getConnection(jdbcUrl, userName, password); |
| | | if (null != connection) { |
| | | return true; |
| | | } |
| | | } catch (Exception e) { |
| | | log.info("Get connection failed:" + e.getMessage()); |
| | | } finally { |
| | | releaseConnection(connection); |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | public static String executeFile(String jdbcUrl, String userName, String password, File sqlFile) { |
| | | Connection connection = getConnection(jdbcUrl, userName, password); |
| | | try { |
| | | batchExecute(connection, readSqlList(sqlFile)); |
| | | } catch (Exception e) { |
| | | log.error("sql脚本执行发生异常:{}",e.getMessage()); |
| | | return e.getMessage(); |
| | | }finally { |
| | | releaseConnection(connection); |
| | | } |
| | | return "success"; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 批量执行sql |
| | | * @param connection / |
| | | * @param sqlList / |
| | | */ |
| | | public static void batchExecute(Connection connection, List<String> sqlList) { |
| | | Statement st = null; |
| | | try { |
| | | st = connection.createStatement(); |
| | | for (String sql : sqlList) { |
| | | if (sql.endsWith(";")) { |
| | | sql = sql.substring(0, sql.length() - 1); |
| | | } |
| | | st.addBatch(sql); |
| | | } |
| | | st.executeBatch(); |
| | | } catch (SQLException throwables) { |
| | | throwables.printStackTrace(); |
| | | } finally { |
| | | CloseUtil.close(st); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 将文件中的sql语句以;为单位读取到列表中 |
| | | * @param sqlFile / |
| | | * @return / |
| | | * @throws Exception e |
| | | */ |
| | | private static List<String> readSqlList(File sqlFile) throws Exception { |
| | | List<String> sqlList = Lists.newArrayList(); |
| | | StringBuilder sb = new StringBuilder(); |
| | | try (BufferedReader reader = new BufferedReader(new InputStreamReader( |
| | | new FileInputStream(sqlFile), StandardCharsets.UTF_8))) { |
| | | String tmp; |
| | | while ((tmp = reader.readLine()) != null) { |
| | | log.info("line:{}", tmp); |
| | | if (tmp.endsWith(";")) { |
| | | sb.append(tmp); |
| | | sqlList.add(sb.toString()); |
| | | sb.delete(0, sb.length()); |
| | | } else { |
| | | sb.append(tmp); |
| | | } |
| | | } |
| | | if (!"".endsWith(sb.toString().trim())) { |
| | | sqlList.add(sb.toString()); |
| | | } |
| | | } |
| | | |
| | | return sqlList; |
| | | } |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.websocket; |
| | | |
| | | /** |
| | | * @author ZhangHouYing |
| | | * @date 2019-08-10 9:56 |
| | | */ |
| | | public enum MsgType { |
| | | /** 连接 */ |
| | | CONNECT, |
| | | /** 关闭 */ |
| | | CLOSE, |
| | | /** 信息 */ |
| | | INFO, |
| | | /** 错误 */ |
| | | ERROR |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.websocket; |
| | | |
| | | import lombok.Data; |
| | | |
| | | /** |
| | | * @author ZhangHouYing |
| | | * @date 2019-08-10 9:55 |
| | | */ |
| | | @Data |
| | | public class SocketMsg { |
| | | private String msg; |
| | | private MsgType msgType; |
| | | |
| | | public SocketMsg(String msg, MsgType msgType) { |
| | | this.msg = msg; |
| | | this.msgType = msgType; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.mnt.websocket; |
| | | |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.websocket.*; |
| | | import javax.websocket.server.PathParam; |
| | | import javax.websocket.server.ServerEndpoint; |
| | | import java.io.IOException; |
| | | import java.util.Objects; |
| | | import java.util.concurrent.CopyOnWriteArraySet; |
| | | /** |
| | | * @author ZhangHouYing |
| | | * @date 2019-08-10 15:46 |
| | | */ |
| | | @ServerEndpoint("/webSocket/{sid}") |
| | | @Slf4j |
| | | @Component |
| | | public class WebSocketServer { |
| | | |
| | | /** |
| | | * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 |
| | | */ |
| | | private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); |
| | | |
| | | /** |
| | | * 与某个客户端的连接会话,需要通过它来给客户端发送数据 |
| | | */ |
| | | private Session session; |
| | | |
| | | /** |
| | | * 接收sid |
| | | */ |
| | | private String sid=""; |
| | | /** |
| | | * 连接建立成功调用的方法 |
| | | * */ |
| | | @OnOpen |
| | | public void onOpen(Session session,@PathParam("sid") String sid) { |
| | | this.session = session; |
| | | //如果存在就先删除一个,防止重复推送消息 |
| | | for (WebSocketServer webSocket:webSocketSet) { |
| | | if (webSocket.sid.equals(sid)) { |
| | | webSocketSet.remove(webSocket); |
| | | } |
| | | } |
| | | webSocketSet.add(this); |
| | | this.sid=sid; |
| | | } |
| | | |
| | | /** |
| | | * 连接关闭调用的方法 |
| | | */ |
| | | @OnClose |
| | | public void onClose() { |
| | | webSocketSet.remove(this); |
| | | } |
| | | |
| | | /** |
| | | * 收到客户端消息后调用的方法 |
| | | * @param message 客户端发送过来的消息*/ |
| | | @OnMessage |
| | | public void onMessage(String message, Session session) { |
| | | log.info("收到来"+sid+"的信息:"+message); |
| | | //群发消息 |
| | | for (WebSocketServer item : webSocketSet) { |
| | | try { |
| | | item.sendMessage(message); |
| | | } catch (IOException e) { |
| | | log.error(e.getMessage(),e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @OnError |
| | | public void onError(Session session, Throwable error) { |
| | | log.error("发生错误"); |
| | | error.printStackTrace(); |
| | | } |
| | | /** |
| | | * 实现服务器主动推送 |
| | | */ |
| | | private void sendMessage(String message) throws IOException { |
| | | this.session.getBasicRemote().sendText(message); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 群发自定义消息 |
| | | * */ |
| | | public static void sendInfo(SocketMsg socketMsg,@PathParam("sid") String sid) throws IOException { |
| | | String message = JSONObject.toJSONString(socketMsg); |
| | | log.info("推送消息到"+sid+",推送内容:"+message); |
| | | for (WebSocketServer item : webSocketSet) { |
| | | try { |
| | | //这里可以设定只推送给这个sid的,为null则全部推送 |
| | | if(sid==null) { |
| | | item.sendMessage(message); |
| | | }else if(item.sid.equals(sid)){ |
| | | item.sendMessage(message); |
| | | } |
| | | } catch (IOException ignored) { } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | WebSocketServer that = (WebSocketServer) o; |
| | | return Objects.equals(session, that.session) && |
| | | Objects.equals(sid, that.sid); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(session, sid); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.config; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import me.zhengjie.modules.quartz.repository.QuartzJobRepository; |
| | | import me.zhengjie.modules.quartz.utils.QuartzManage; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.boot.ApplicationArguments; |
| | | import org.springframework.boot.ApplicationRunner; |
| | | import org.springframework.stereotype.Component; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Component |
| | | @RequiredArgsConstructor |
| | | public class JobRunner implements ApplicationRunner { |
| | | private static final Logger log = LoggerFactory.getLogger(JobRunner.class); |
| | | private final QuartzJobRepository quartzJobRepository; |
| | | private final QuartzManage quartzManage; |
| | | |
| | | /** |
| | | * 项目启动时重新激活启用的定时任务 |
| | | * |
| | | * @param applicationArguments / |
| | | */ |
| | | @Override |
| | | public void run(ApplicationArguments applicationArguments) { |
| | | List<QuartzJob> quartzJobs = quartzJobRepository.findByIsPauseIsFalse(); |
| | | quartzJobs.forEach(quartzManage::addJob); |
| | | log.info("Timing task injection complete"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.config; |
| | | |
| | | import org.quartz.spi.TriggerFiredBundle; |
| | | import org.springframework.beans.factory.config.AutowireCapableBeanFactory; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.scheduling.quartz.AdaptableJobFactory; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * 定时任务配置 |
| | | * @author / |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Configuration |
| | | public class QuartzConfig { |
| | | |
| | | /** |
| | | * 解决Job中注入Spring Bean为null的问题 |
| | | */ |
| | | @Component("quartzJobFactory") |
| | | public static class QuartzJobFactory extends AdaptableJobFactory { |
| | | |
| | | private final AutowireCapableBeanFactory capableBeanFactory; |
| | | |
| | | public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) { |
| | | this.capableBeanFactory = capableBeanFactory; |
| | | } |
| | | |
| | | @Override |
| | | protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { |
| | | //调用父类的方法,把Job注入到spring中 |
| | | Object jobInstance = super.createJobInstance(bundle); |
| | | capableBeanFactory.autowireBean(jobInstance); |
| | | return jobInstance; |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @Entity |
| | | @Table(name = "sys_quartz_job") |
| | | public class QuartzJob extends BaseEntity implements Serializable { |
| | | |
| | | public static final String JOB_KEY = "JOB_KEY"; |
| | | |
| | | @Id |
| | | @Column(name = "job_id") |
| | | @NotNull(groups = {Update.class}) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @Transient |
| | | @ApiModelProperty(value = "用于子任务唯一标识", hidden = true) |
| | | private String uuid; |
| | | |
| | | @ApiModelProperty(value = "定时器名称") |
| | | private String jobName; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "Bean名称") |
| | | private String beanName; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "方法名称") |
| | | private String methodName; |
| | | |
| | | @ApiModelProperty(value = "参数") |
| | | private String params; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "cron表达式") |
| | | private String cronExpression; |
| | | |
| | | @ApiModelProperty(value = "状态,暂时或启动") |
| | | private Boolean isPause = false; |
| | | |
| | | @ApiModelProperty(value = "负责人") |
| | | private String personInCharge; |
| | | |
| | | @ApiModelProperty(value = "报警邮箱") |
| | | private String email; |
| | | |
| | | @ApiModelProperty(value = "子任务") |
| | | private String subTask; |
| | | |
| | | @ApiModelProperty(value = "失败后暂停") |
| | | private Boolean pauseAfterFailure; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "备注") |
| | | private String description; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Data; |
| | | import org.hibernate.annotations.CreationTimestamp; |
| | | import javax.persistence.*; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Entity |
| | | @Data |
| | | @Table(name = "sys_quartz_log") |
| | | public class QuartzLog implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "log_id") |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @ApiModelProperty(value = "任务名称", hidden = true) |
| | | private String jobName; |
| | | |
| | | @ApiModelProperty(value = "bean名称", hidden = true) |
| | | private String beanName; |
| | | |
| | | @ApiModelProperty(value = "方法名称", hidden = true) |
| | | private String methodName; |
| | | |
| | | @ApiModelProperty(value = "参数", hidden = true) |
| | | private String params; |
| | | |
| | | @ApiModelProperty(value = "cron表达式", hidden = true) |
| | | private String cronExpression; |
| | | |
| | | @ApiModelProperty(value = "状态", hidden = true) |
| | | private Boolean isSuccess; |
| | | |
| | | @ApiModelProperty(value = "异常详情", hidden = true) |
| | | private String exceptionDetail; |
| | | |
| | | @ApiModelProperty(value = "执行耗时", hidden = true) |
| | | private Long time; |
| | | |
| | | @CreationTimestamp |
| | | @ApiModelProperty(value = "创建时间", hidden = true) |
| | | private Timestamp createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.repository; |
| | | |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor<QuartzJob> { |
| | | |
| | | /** |
| | | * 查询启用的任务 |
| | | * @return List |
| | | */ |
| | | List<QuartzJob> findByIsPauseIsFalse(); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.repository; |
| | | |
| | | import me.zhengjie.modules.quartz.domain.QuartzLog; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor<QuartzLog> { |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import me.zhengjie.modules.quartz.service.QuartzJobService; |
| | | import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria; |
| | | import me.zhengjie.utils.SpringContextHolder; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Slf4j |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/jobs") |
| | | @Api(tags = "系统:定时任务管理") |
| | | public class QuartzJobController { |
| | | |
| | | private static final String ENTITY_NAME = "quartzJob"; |
| | | private final QuartzJobService quartzJobService; |
| | | |
| | | @ApiOperation("查询定时任务") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('timing:list')") |
| | | public ResponseEntity<Object> queryQuartzJob(JobQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("导出任务数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('timing:list')") |
| | | public void exportQuartzJob(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { |
| | | quartzJobService.download(quartzJobService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("导出日志数据") |
| | | @GetMapping(value = "/logs/download") |
| | | @PreAuthorize("@el.check('timing:list')") |
| | | public void exportQuartzJobLog(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { |
| | | quartzJobService.downloadLog(quartzJobService.queryAllLog(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("查询任务执行日志") |
| | | @GetMapping(value = "/logs") |
| | | @PreAuthorize("@el.check('timing:list')") |
| | | public ResponseEntity<Object> queryQuartzJobLog(JobQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增定时任务") |
| | | @ApiOperation("新增定时任务") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('timing:add')") |
| | | public ResponseEntity<Object> createQuartzJob(@Validated @RequestBody QuartzJob resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | // 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义 |
| | | checkBean(resources.getBeanName()); |
| | | quartzJobService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改定时任务") |
| | | @ApiOperation("修改定时任务") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('timing:edit')") |
| | | public ResponseEntity<Object> updateQuartzJob(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){ |
| | | // 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义 |
| | | checkBean(resources.getBeanName()); |
| | | quartzJobService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("更改定时任务状态") |
| | | @ApiOperation("更改定时任务状态") |
| | | @PutMapping(value = "/{id}") |
| | | @PreAuthorize("@el.check('timing:edit')") |
| | | public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){ |
| | | quartzJobService.updateIsPause(quartzJobService.findById(id)); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("执行定时任务") |
| | | @ApiOperation("执行定时任务") |
| | | @PutMapping(value = "/exec/{id}") |
| | | @PreAuthorize("@el.check('timing:edit')") |
| | | public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){ |
| | | quartzJobService.execution(quartzJobService.findById(id)); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除定时任务") |
| | | @ApiOperation("删除定时任务") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('timing:del')") |
| | | public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){ |
| | | quartzJobService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | private void checkBean(String beanName){ |
| | | // 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类 |
| | | // 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。 |
| | | if(!SpringContextHolder.getAllServiceBeanName().contains(beanName)){ |
| | | throw new BadRequestException("非法的 Bean,请重新输入!"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.service; |
| | | |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import me.zhengjie.modules.quartz.domain.QuartzLog; |
| | | import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | public interface QuartzJobService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(JobQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<QuartzJob> queryAll(JobQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 分页查询日志 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAllLog(JobQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<QuartzLog> queryAllLog(JobQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(QuartzJob resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(QuartzJob resources); |
| | | |
| | | /** |
| | | * 删除任务 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id ID |
| | | * @return / |
| | | */ |
| | | QuartzJob findById(Long id); |
| | | |
| | | /** |
| | | * 更改定时任务状态 |
| | | * @param quartzJob / |
| | | */ |
| | | void updateIsPause(QuartzJob quartzJob); |
| | | |
| | | /** |
| | | * 立即执行定时任务 |
| | | * @param quartzJob / |
| | | */ |
| | | void execution(QuartzJob quartzJob); |
| | | |
| | | /** |
| | | * 导出定时任务 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<QuartzJob> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 导出定时任务日志 |
| | | * @param queryAllLog 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 执行子任务 |
| | | * @param tasks / |
| | | * @throws InterruptedException / |
| | | */ |
| | | void executionSubJob(String[] tasks) throws InterruptedException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-4 10:33:02 |
| | | */ |
| | | @Data |
| | | public class JobQueryCriteria { |
| | | |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String jobName; |
| | | |
| | | @Query |
| | | private Boolean isSuccess; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.service.impl; |
| | | |
| | | import cn.hutool.core.util.IdUtil; |
| | | import cn.hutool.core.util.StrUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import me.zhengjie.modules.quartz.domain.QuartzLog; |
| | | import me.zhengjie.modules.quartz.repository.QuartzJobRepository; |
| | | import me.zhengjie.modules.quartz.repository.QuartzLogRepository; |
| | | import me.zhengjie.modules.quartz.service.QuartzJobService; |
| | | import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria; |
| | | import me.zhengjie.modules.quartz.utils.QuartzManage; |
| | | import me.zhengjie.utils.*; |
| | | import org.quartz.CronExpression; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | import org.springframework.stereotype.Service; |
| | | import org.springframework.transaction.annotation.Transactional; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @RequiredArgsConstructor |
| | | @Service(value = "quartzJobService") |
| | | public class QuartzJobServiceImpl implements QuartzJobService { |
| | | |
| | | private final QuartzJobRepository quartzJobRepository; |
| | | private final QuartzLogRepository quartzLogRepository; |
| | | private final QuartzManage quartzManage; |
| | | private final RedisUtils redisUtils; |
| | | |
| | | @Override |
| | | public Object queryAll(JobQueryCriteria criteria, Pageable pageable){ |
| | | return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable)); |
| | | } |
| | | |
| | | @Override |
| | | public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable){ |
| | | return PageUtil.toPage(quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable)); |
| | | } |
| | | |
| | | @Override |
| | | public List<QuartzJob> queryAll(JobQueryCriteria criteria) { |
| | | return quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)); |
| | | } |
| | | |
| | | @Override |
| | | public List<QuartzLog> queryAllLog(JobQueryCriteria criteria) { |
| | | return quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)); |
| | | } |
| | | |
| | | @Override |
| | | public QuartzJob findById(Long id) { |
| | | QuartzJob quartzJob = quartzJobRepository.findById(id).orElseGet(QuartzJob::new); |
| | | ValidationUtil.isNull(quartzJob.getId(),"QuartzJob","id",id); |
| | | return quartzJob; |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(QuartzJob resources) { |
| | | if (!CronExpression.isValidExpression(resources.getCronExpression())){ |
| | | throw new BadRequestException("cron表达式格式错误"); |
| | | } |
| | | resources = quartzJobRepository.save(resources); |
| | | quartzManage.addJob(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(QuartzJob resources) { |
| | | if (!CronExpression.isValidExpression(resources.getCronExpression())){ |
| | | throw new BadRequestException("cron表达式格式错误"); |
| | | } |
| | | if(StringUtils.isNotBlank(resources.getSubTask())){ |
| | | List<String> tasks = Arrays.asList(resources.getSubTask().split("[,,]")); |
| | | if (tasks.contains(resources.getId().toString())) { |
| | | throw new BadRequestException("子任务中不能添加当前任务ID"); |
| | | } |
| | | } |
| | | resources = quartzJobRepository.save(resources); |
| | | quartzManage.updateJobCron(resources); |
| | | } |
| | | |
| | | @Override |
| | | public void updateIsPause(QuartzJob quartzJob) { |
| | | if (quartzJob.getIsPause()) { |
| | | quartzManage.resumeJob(quartzJob); |
| | | quartzJob.setIsPause(false); |
| | | } else { |
| | | quartzManage.pauseJob(quartzJob); |
| | | quartzJob.setIsPause(true); |
| | | } |
| | | quartzJobRepository.save(quartzJob); |
| | | } |
| | | |
| | | @Override |
| | | public void execution(QuartzJob quartzJob) { |
| | | quartzManage.runJobNow(quartzJob); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | for (Long id : ids) { |
| | | QuartzJob quartzJob = findById(id); |
| | | quartzManage.deleteJob(quartzJob); |
| | | quartzJobRepository.delete(quartzJob); |
| | | } |
| | | } |
| | | |
| | | @Async |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void executionSubJob(String[] tasks) throws InterruptedException { |
| | | for (String id : tasks) { |
| | | if (StrUtil.isBlank(id)) { |
| | | // 如果是手动清除子任务id,会出现id为空字符串的问题 |
| | | continue; |
| | | } |
| | | QuartzJob quartzJob = findById(Long.parseLong(id)); |
| | | // 执行任务 |
| | | String uuid = IdUtil.simpleUUID(); |
| | | quartzJob.setUuid(uuid); |
| | | // 执行任务 |
| | | execution(quartzJob); |
| | | // 获取执行状态,如果执行失败则停止后面的子任务执行 |
| | | Boolean result = (Boolean) redisUtils.get(uuid); |
| | | while (result == null) { |
| | | // 休眠5秒,再次获取子任务执行情况 |
| | | Thread.sleep(5000); |
| | | result = (Boolean) redisUtils.get(uuid); |
| | | } |
| | | if(!result){ |
| | | redisUtils.del(uuid); |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<QuartzJob> quartzJobs, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (QuartzJob quartzJob : quartzJobs) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("任务名称", quartzJob.getJobName()); |
| | | map.put("Bean名称", quartzJob.getBeanName()); |
| | | map.put("执行方法", quartzJob.getMethodName()); |
| | | map.put("参数", quartzJob.getParams()); |
| | | map.put("表达式", quartzJob.getCronExpression()); |
| | | map.put("状态", quartzJob.getIsPause() ? "暂停中" : "运行中"); |
| | | map.put("描述", quartzJob.getDescription()); |
| | | map.put("创建日期", quartzJob.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | @Override |
| | | public void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (QuartzLog quartzLog : queryAllLog) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("任务名称", quartzLog.getJobName()); |
| | | map.put("Bean名称", quartzLog.getBeanName()); |
| | | map.put("执行方法", quartzLog.getMethodName()); |
| | | map.put("参数", quartzLog.getParams()); |
| | | map.put("表达式", quartzLog.getCronExpression()); |
| | | map.put("异常详情", quartzLog.getExceptionDetail()); |
| | | map.put("耗时/毫秒", quartzLog.getTime()); |
| | | map.put("状态", quartzLog.getIsSuccess() ? "成功" : "失败"); |
| | | map.put("创建日期", quartzLog.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.task; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | /** |
| | | * 测试用 |
| | | * @author Zheng Jie |
| | | * @date 2019-01-08 |
| | | */ |
| | | @Slf4j |
| | | @Service |
| | | public class TestTask { |
| | | |
| | | public void run(){ |
| | | log.info("run 执行成功"); |
| | | } |
| | | |
| | | public void run1(String str){ |
| | | log.info("run1 执行成功,参数为: {}" + str); |
| | | } |
| | | |
| | | public void run2(){ |
| | | log.info("run2 执行成功"); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.utils; |
| | | |
| | | import cn.hutool.extra.template.Template; |
| | | import cn.hutool.extra.template.TemplateConfig; |
| | | import cn.hutool.extra.template.TemplateEngine; |
| | | import cn.hutool.extra.template.TemplateUtil; |
| | | import me.zhengjie.config.thread.ThreadPoolExecutorUtil; |
| | | import me.zhengjie.domain.vo.EmailVo; |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import me.zhengjie.modules.quartz.domain.QuartzLog; |
| | | import me.zhengjie.modules.quartz.repository.QuartzLogRepository; |
| | | import me.zhengjie.modules.quartz.service.QuartzJobService; |
| | | import me.zhengjie.service.EmailService; |
| | | import me.zhengjie.utils.RedisUtils; |
| | | import me.zhengjie.utils.SpringContextHolder; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import me.zhengjie.utils.ThrowableUtil; |
| | | import org.quartz.JobExecutionContext; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.scheduling.quartz.QuartzJobBean; |
| | | import java.util.*; |
| | | import java.util.concurrent.*; |
| | | |
| | | /** |
| | | * 参考人人开源,https://gitee.com/renrenio/renren-security |
| | | * @author / |
| | | * @date 2019-01-07 |
| | | */ |
| | | public class ExecutionJob extends QuartzJobBean { |
| | | |
| | | private final Logger logger = LoggerFactory.getLogger(this.getClass()); |
| | | |
| | | // 此处仅供参考,可根据任务执行情况自定义线程池参数 |
| | | private final static ExecutorService executor = ThreadPoolExecutorUtil.getPoll("el-quartz-job"); |
| | | |
| | | @Override |
| | | public void executeInternal(JobExecutionContext context) { |
| | | // 获取任务 |
| | | QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY); |
| | | // 获取spring bean |
| | | QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class); |
| | | QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class); |
| | | RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class); |
| | | |
| | | String uuid = quartzJob.getUuid(); |
| | | |
| | | QuartzLog log = new QuartzLog(); |
| | | log.setJobName(quartzJob.getJobName()); |
| | | log.setBeanName(quartzJob.getBeanName()); |
| | | log.setMethodName(quartzJob.getMethodName()); |
| | | log.setParams(quartzJob.getParams()); |
| | | long startTime = System.currentTimeMillis(); |
| | | log.setCronExpression(quartzJob.getCronExpression()); |
| | | try { |
| | | // 执行任务 |
| | | QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(), quartzJob.getParams()); |
| | | Future<?> future = executor.submit(task); |
| | | future.get(); |
| | | long times = System.currentTimeMillis() - startTime; |
| | | log.setTime(times); |
| | | if(StringUtils.isNotBlank(uuid)) { |
| | | redisUtils.set(uuid, true); |
| | | } |
| | | // 任务状态 |
| | | log.setIsSuccess(true); |
| | | logger.info("任务执行成功,任务名称:" + quartzJob.getJobName() + ", 执行时间:" + times + "毫秒"); |
| | | // 判断是否存在子任务 |
| | | if(StringUtils.isNotBlank(quartzJob.getSubTask())){ |
| | | String[] tasks = quartzJob.getSubTask().split("[,,]"); |
| | | // 执行子任务 |
| | | quartzJobService.executionSubJob(tasks); |
| | | } |
| | | } catch (Exception e) { |
| | | if(StringUtils.isNotBlank(uuid)) { |
| | | redisUtils.set(uuid, false); |
| | | } |
| | | logger.error("任务执行失败,任务名称:" + quartzJob.getJobName()); |
| | | long times = System.currentTimeMillis() - startTime; |
| | | log.setTime(times); |
| | | // 任务状态 0:成功 1:失败 |
| | | log.setIsSuccess(false); |
| | | log.setExceptionDetail(ThrowableUtil.getStackTrace(e)); |
| | | // 任务如果失败了则暂停 |
| | | if(quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()){ |
| | | quartzJob.setIsPause(false); |
| | | //更新状态 |
| | | quartzJobService.updateIsPause(quartzJob); |
| | | } |
| | | if(quartzJob.getEmail() != null){ |
| | | EmailService emailService = SpringContextHolder.getBean(EmailService.class); |
| | | // 邮箱报警 |
| | | if(StringUtils.isNoneBlank(quartzJob.getEmail())){ |
| | | EmailVo emailVo = taskAlarm(quartzJob, ThrowableUtil.getStackTrace(e)); |
| | | emailService.send(emailVo, emailService.find()); |
| | | } |
| | | } |
| | | } finally { |
| | | quartzLogRepository.save(log); |
| | | } |
| | | } |
| | | |
| | | private EmailVo taskAlarm(QuartzJob quartzJob, String msg) { |
| | | EmailVo emailVo = new EmailVo(); |
| | | emailVo.setSubject("定时任务【"+ quartzJob.getJobName() +"】执行失败,请尽快处理!"); |
| | | Map<String, Object> data = new HashMap<>(16); |
| | | data.put("task", quartzJob); |
| | | data.put("msg", msg); |
| | | TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); |
| | | Template template = engine.getTemplate("email/taskAlarm.ftl"); |
| | | emailVo.setContent(template.render(data)); |
| | | List<String> emails = Arrays.asList(quartzJob.getEmail().split("[,,]")); |
| | | emailVo.setTos(emails); |
| | | return emailVo; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.utils; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.quartz.domain.QuartzJob; |
| | | import org.quartz.*; |
| | | import org.quartz.impl.triggers.CronTriggerImpl; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.stereotype.Component; |
| | | import javax.annotation.Resource; |
| | | import java.util.Date; |
| | | import static org.quartz.TriggerBuilder.newTrigger; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-01-07 |
| | | */ |
| | | @Slf4j |
| | | @Component |
| | | public class QuartzManage { |
| | | |
| | | private static final String JOB_NAME = "TASK_"; |
| | | |
| | | @Resource |
| | | private Scheduler scheduler; |
| | | |
| | | public void addJob(QuartzJob quartzJob){ |
| | | try { |
| | | // 构建job信息 |
| | | JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class). |
| | | withIdentity(JOB_NAME + quartzJob.getId()).build(); |
| | | |
| | | //通过触发器名和cron 表达式创建 Trigger |
| | | Trigger cronTrigger = newTrigger() |
| | | .withIdentity(JOB_NAME + quartzJob.getId()) |
| | | .startNow() |
| | | .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression())) |
| | | .build(); |
| | | |
| | | cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob); |
| | | |
| | | //重置启动时间 |
| | | ((CronTriggerImpl)cronTrigger).setStartTime(new Date()); |
| | | |
| | | //执行定时任务 |
| | | scheduler.scheduleJob(jobDetail,cronTrigger); |
| | | |
| | | // 暂停任务 |
| | | if (quartzJob.getIsPause()) { |
| | | pauseJob(quartzJob); |
| | | } |
| | | } catch (Exception e){ |
| | | log.error("创建定时任务失败", e); |
| | | throw new BadRequestException("创建定时任务失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 更新job cron表达式 |
| | | * @param quartzJob / |
| | | */ |
| | | public void updateJobCron(QuartzJob quartzJob){ |
| | | try { |
| | | TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); |
| | | CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); |
| | | // 如果不存在则创建一个定时任务 |
| | | if(trigger == null){ |
| | | addJob(quartzJob); |
| | | trigger = (CronTrigger) scheduler.getTrigger(triggerKey); |
| | | } |
| | | CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()); |
| | | trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); |
| | | //重置启动时间 |
| | | ((CronTriggerImpl)trigger).setStartTime(new Date()); |
| | | trigger.getJobDataMap().put(QuartzJob.JOB_KEY,quartzJob); |
| | | |
| | | scheduler.rescheduleJob(triggerKey, trigger); |
| | | // 暂停任务 |
| | | if (quartzJob.getIsPause()) { |
| | | pauseJob(quartzJob); |
| | | } |
| | | } catch (Exception e){ |
| | | log.error("更新定时任务失败", e); |
| | | throw new BadRequestException("更新定时任务失败"); |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * 删除一个job |
| | | * @param quartzJob / |
| | | */ |
| | | public void deleteJob(QuartzJob quartzJob){ |
| | | try { |
| | | JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); |
| | | scheduler.pauseJob(jobKey); |
| | | scheduler.deleteJob(jobKey); |
| | | } catch (Exception e){ |
| | | log.error("删除定时任务失败", e); |
| | | throw new BadRequestException("删除定时任务失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 恢复一个job |
| | | * @param quartzJob / |
| | | */ |
| | | public void resumeJob(QuartzJob quartzJob){ |
| | | try { |
| | | TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); |
| | | CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); |
| | | // 如果不存在则创建一个定时任务 |
| | | if(trigger == null) { |
| | | addJob(quartzJob); |
| | | } |
| | | JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); |
| | | scheduler.resumeJob(jobKey); |
| | | } catch (Exception e){ |
| | | log.error("恢复定时任务失败", e); |
| | | throw new BadRequestException("恢复定时任务失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 立即执行job |
| | | * @param quartzJob / |
| | | */ |
| | | public void runJobNow(QuartzJob quartzJob){ |
| | | try { |
| | | TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); |
| | | CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); |
| | | // 如果不存在则创建一个定时任务 |
| | | if(trigger == null) { |
| | | addJob(quartzJob); |
| | | } |
| | | JobDataMap dataMap = new JobDataMap(); |
| | | dataMap.put(QuartzJob.JOB_KEY, quartzJob); |
| | | JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); |
| | | scheduler.triggerJob(jobKey,dataMap); |
| | | } catch (Exception e){ |
| | | log.error("定时任务执行失败", e); |
| | | throw new BadRequestException("定时任务执行失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 暂停一个job |
| | | * @param quartzJob / |
| | | */ |
| | | public void pauseJob(QuartzJob quartzJob){ |
| | | try { |
| | | JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); |
| | | scheduler.pauseJob(jobKey); |
| | | } catch (Exception e){ |
| | | log.error("定时任务暂停失败", e); |
| | | throw new BadRequestException("定时任务暂停失败"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.quartz.utils; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.utils.SpringContextHolder; |
| | | import org.apache.commons.lang3.StringUtils; |
| | | import org.springframework.util.ReflectionUtils; |
| | | import java.lang.reflect.Method; |
| | | import java.util.concurrent.Callable; |
| | | |
| | | /** |
| | | * 执行定时任务 |
| | | * @author / |
| | | */ |
| | | @Slf4j |
| | | public class QuartzRunnable implements Callable<Object> { |
| | | |
| | | private final Object target; |
| | | private final Method method; |
| | | private final String params; |
| | | |
| | | QuartzRunnable(String beanName, String methodName, String params) |
| | | throws NoSuchMethodException, SecurityException { |
| | | this.target = SpringContextHolder.getBean(beanName); |
| | | this.params = params; |
| | | if (StringUtils.isNotBlank(params)) { |
| | | this.method = target.getClass().getDeclaredMethod(methodName, String.class); |
| | | } else { |
| | | this.method = target.getClass().getDeclaredMethod(methodName); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | @SuppressWarnings("all") |
| | | public Object call() throws Exception { |
| | | ReflectionUtils.makeAccessible(method); |
| | | if (StringUtils.isNotBlank(params)) { |
| | | method.invoke(target, params); |
| | | } else { |
| | | method.invoke(target); |
| | | } |
| | | return null; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config; |
| | | |
| | | import me.zhengjie.modules.security.config.bean.LoginProperties; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import org.springframework.boot.context.properties.ConfigurationProperties; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | |
| | | /** |
| | | * @apiNote 配置文件转换Pojo类的 统一配置 类 |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/10 19:04 |
| | | */ |
| | | @Configuration |
| | | public class ConfigBeanConfiguration { |
| | | |
| | | @Bean |
| | | @ConfigurationProperties(prefix = "login") |
| | | public LoginProperties loginProperties() { |
| | | return new LoginProperties(); |
| | | } |
| | | |
| | | @Bean |
| | | @ConfigurationProperties(prefix = "jwt") |
| | | public SecurityProperties securityProperties() { |
| | | return new SecurityProperties(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.AnonymousAccess; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.modules.security.security.*; |
| | | import me.zhengjie.modules.security.service.OnlineUserService; |
| | | import me.zhengjie.modules.security.service.UserCacheManager; |
| | | import me.zhengjie.utils.enums.RequestMethodEnum; |
| | | import org.springframework.context.ApplicationContext; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.http.HttpMethod; |
| | | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; |
| | | import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| | | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| | | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| | | import org.springframework.security.config.core.GrantedAuthorityDefaults; |
| | | import org.springframework.security.config.http.SessionCreationPolicy; |
| | | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
| | | import org.springframework.security.crypto.password.PasswordEncoder; |
| | | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; |
| | | import org.springframework.web.bind.annotation.RequestMethod; |
| | | import org.springframework.web.filter.CorsFilter; |
| | | import org.springframework.web.method.HandlerMethod; |
| | | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; |
| | | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Configuration |
| | | @EnableWebSecurity |
| | | @RequiredArgsConstructor |
| | | @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) |
| | | public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { |
| | | |
| | | private final TokenProvider tokenProvider; |
| | | private final CorsFilter corsFilter; |
| | | private final JwtAuthenticationEntryPoint authenticationErrorHandler; |
| | | private final JwtAccessDeniedHandler jwtAccessDeniedHandler; |
| | | private final ApplicationContext applicationContext; |
| | | private final SecurityProperties properties; |
| | | private final OnlineUserService onlineUserService; |
| | | private final UserCacheManager userCacheManager; |
| | | |
| | | @Bean |
| | | GrantedAuthorityDefaults grantedAuthorityDefaults() { |
| | | // 去除 ROLE_ 前缀 |
| | | return new GrantedAuthorityDefaults(""); |
| | | } |
| | | |
| | | @Bean |
| | | public PasswordEncoder passwordEncoder() { |
| | | // 密码加密方式 |
| | | return new BCryptPasswordEncoder(); |
| | | } |
| | | |
| | | @Override |
| | | protected void configure(HttpSecurity httpSecurity) throws Exception { |
| | | // 搜寻匿名标记 url: @AnonymousAccess |
| | | RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping"); |
| | | Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods(); |
| | | // 获取匿名标记 |
| | | Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap); |
| | | httpSecurity |
| | | // 禁用 CSRF |
| | | .csrf().disable() |
| | | .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) |
| | | // 授权异常 |
| | | .exceptionHandling() |
| | | .authenticationEntryPoint(authenticationErrorHandler) |
| | | .accessDeniedHandler(jwtAccessDeniedHandler) |
| | | // 防止iframe 造成跨域 |
| | | .and() |
| | | .headers() |
| | | .frameOptions() |
| | | .disable() |
| | | // 不创建会话 |
| | | .and() |
| | | .sessionManagement() |
| | | .sessionCreationPolicy(SessionCreationPolicy.STATELESS) |
| | | .and() |
| | | .authorizeRequests() |
| | | // 静态资源等等 |
| | | .antMatchers( |
| | | HttpMethod.GET, |
| | | "/*.html", |
| | | "/**/*.html", |
| | | "/**/*.css", |
| | | "/**/*.js", |
| | | "/webSocket/**" |
| | | ).permitAll() |
| | | // swagger 文档 |
| | | .antMatchers("/swagger-ui.html").permitAll() |
| | | .antMatchers("/swagger-resources/**").permitAll() |
| | | .antMatchers("/webjars/**").permitAll() |
| | | .antMatchers("/*/api-docs").permitAll() |
| | | // 文件 |
| | | .antMatchers("/avatar/**").permitAll() |
| | | .antMatchers("/file/**").permitAll() |
| | | // 阿里巴巴 druid |
| | | .antMatchers("/druid/**").permitAll() |
| | | // 放行OPTIONS请求 |
| | | .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() |
| | | // 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型 |
| | | // GET |
| | | .antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll() |
| | | // POST |
| | | .antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll() |
| | | // PUT |
| | | .antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll() |
| | | // PATCH |
| | | .antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll() |
| | | // DELETE |
| | | .antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll() |
| | | // 所有类型的接口都放行 |
| | | .antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll() |
| | | // 所有请求都需要认证 |
| | | .anyRequest().authenticated() |
| | | .and().apply(securityConfigurerAdapter()); |
| | | } |
| | | |
| | | private TokenConfigurer securityConfigurerAdapter() { |
| | | return new TokenConfigurer(tokenProvider, properties, onlineUserService, userCacheManager); |
| | | } |
| | | |
| | | private Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) { |
| | | Map<String, Set<String>> anonymousUrls = new HashMap<>(8); |
| | | Set<String> get = new HashSet<>(); |
| | | Set<String> post = new HashSet<>(); |
| | | Set<String> put = new HashSet<>(); |
| | | Set<String> patch = new HashSet<>(); |
| | | Set<String> delete = new HashSet<>(); |
| | | Set<String> all = new HashSet<>(); |
| | | for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) { |
| | | HandlerMethod handlerMethod = infoEntry.getValue(); |
| | | AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); |
| | | if (null != anonymousAccess) { |
| | | List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods()); |
| | | RequestMethodEnum request = RequestMethodEnum.find(requestMethods.size() == 0 ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name()); |
| | | switch (Objects.requireNonNull(request)) { |
| | | case GET: |
| | | get.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | case POST: |
| | | post.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | case PUT: |
| | | put.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | case PATCH: |
| | | patch.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | case DELETE: |
| | | delete.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | default: |
| | | all.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | anonymousUrls.put(RequestMethodEnum.GET.getType(), get); |
| | | anonymousUrls.put(RequestMethodEnum.POST.getType(), post); |
| | | anonymousUrls.put(RequestMethodEnum.PUT.getType(), put); |
| | | anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch); |
| | | anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete); |
| | | anonymousUrls.put(RequestMethodEnum.ALL.getType(), all); |
| | | return anonymousUrls; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config.bean; |
| | | |
| | | import lombok.Data; |
| | | |
| | | /** |
| | | * 登录验证码配置信息 |
| | | * |
| | | * @author liaojinlong |
| | | * @date 2020/6/10 18:53 |
| | | */ |
| | | @Data |
| | | public class LoginCode { |
| | | |
| | | /** |
| | | * 验证码配置 |
| | | */ |
| | | private LoginCodeEnum codeType; |
| | | /** |
| | | * 验证码有效期 分钟 |
| | | */ |
| | | private Long expiration = 2L; |
| | | /** |
| | | * 验证码内容长度 |
| | | */ |
| | | private int length = 2; |
| | | /** |
| | | * 验证码宽度 |
| | | */ |
| | | private int width = 111; |
| | | /** |
| | | * 验证码高度 |
| | | */ |
| | | private int height = 36; |
| | | /** |
| | | * 验证码字体 |
| | | */ |
| | | private String fontName; |
| | | /** |
| | | * 字体大小 |
| | | */ |
| | | private int fontSize = 25; |
| | | |
| | | public LoginCodeEnum getCodeType() { |
| | | return codeType; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config.bean; |
| | | |
| | | /** |
| | | * 验证码配置枚举 |
| | | * |
| | | * @author: liaojinlong |
| | | * @date: 2020/6/10 17:40 |
| | | */ |
| | | |
| | | public enum LoginCodeEnum { |
| | | /** |
| | | * 算数 |
| | | */ |
| | | ARITHMETIC, |
| | | /** |
| | | * 中文 |
| | | */ |
| | | CHINESE, |
| | | /** |
| | | * 中文闪图 |
| | | */ |
| | | CHINESE_GIF, |
| | | /** |
| | | * 闪图 |
| | | */ |
| | | GIF, |
| | | SPEC |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 the original author or authors. |
| | | * |
| | | * Licensed under the Apache License, Version loginCode.length.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-loginCode.length.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config.bean; |
| | | |
| | | import com.wf.captcha.*; |
| | | import com.wf.captcha.base.Captcha; |
| | | import lombok.Data; |
| | | import me.zhengjie.exception.BadConfigurationException; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import java.awt.*; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * 配置文件读取 |
| | | * |
| | | * @author liaojinlong |
| | | * @date loginCode.length0loginCode.length0/6/10 17:loginCode.length6 |
| | | */ |
| | | @Data |
| | | public class LoginProperties { |
| | | |
| | | /** |
| | | * 账号单用户 登录 |
| | | */ |
| | | private boolean singleLogin = false; |
| | | |
| | | private LoginCode loginCode; |
| | | |
| | | public static final String cacheKey = "USER-LOGIN-DATA"; |
| | | |
| | | public boolean isSingleLogin() { |
| | | return singleLogin; |
| | | } |
| | | |
| | | /** |
| | | * 获取验证码生产类 |
| | | * |
| | | * @return / |
| | | */ |
| | | public Captcha getCaptcha() { |
| | | if (Objects.isNull(loginCode)) { |
| | | loginCode = new LoginCode(); |
| | | if (Objects.isNull(loginCode.getCodeType())) { |
| | | loginCode.setCodeType(LoginCodeEnum.ARITHMETIC); |
| | | } |
| | | } |
| | | return switchCaptcha(loginCode); |
| | | } |
| | | |
| | | /** |
| | | * 依据配置信息生产验证码 |
| | | * |
| | | * @param loginCode 验证码配置信息 |
| | | * @return / |
| | | */ |
| | | private Captcha switchCaptcha(LoginCode loginCode) { |
| | | Captcha captcha; |
| | | switch (loginCode.getCodeType()) { |
| | | case ARITHMETIC: |
| | | // 算术类型 https://gitee.com/whvse/EasyCaptcha |
| | | captcha = new FixedArithmeticCaptcha(loginCode.getWidth(), loginCode.getHeight()); |
| | | // 几位数运算,默认是两位 |
| | | captcha.setLen(loginCode.getLength()); |
| | | break; |
| | | case CHINESE: |
| | | captcha = new ChineseCaptcha(loginCode.getWidth(), loginCode.getHeight()); |
| | | captcha.setLen(loginCode.getLength()); |
| | | break; |
| | | case CHINESE_GIF: |
| | | captcha = new ChineseGifCaptcha(loginCode.getWidth(), loginCode.getHeight()); |
| | | captcha.setLen(loginCode.getLength()); |
| | | break; |
| | | case GIF: |
| | | captcha = new GifCaptcha(loginCode.getWidth(), loginCode.getHeight()); |
| | | captcha.setLen(loginCode.getLength()); |
| | | break; |
| | | case SPEC: |
| | | captcha = new SpecCaptcha(loginCode.getWidth(), loginCode.getHeight()); |
| | | captcha.setLen(loginCode.getLength()); |
| | | break; |
| | | default: |
| | | throw new BadConfigurationException("验证码配置信息错误!正确配置查看 LoginCodeEnum "); |
| | | } |
| | | if(StringUtils.isNotBlank(loginCode.getFontName())){ |
| | | captcha.setFont(new Font(loginCode.getFontName(), Font.PLAIN, loginCode.getFontSize())); |
| | | } |
| | | return captcha; |
| | | } |
| | | |
| | | static class FixedArithmeticCaptcha extends ArithmeticCaptcha { |
| | | public FixedArithmeticCaptcha(int width, int height) { |
| | | super(width, height); |
| | | } |
| | | |
| | | @Override |
| | | protected char[] alphas() { |
| | | // 生成随机数字和运算符 |
| | | int n1 = num(1, 10), n2 = num(1, 10); |
| | | int opt = num(3); |
| | | |
| | | // 计算结果 |
| | | int res = new int[]{n1 + n2, n1 - n2, n1 * n2}[opt]; |
| | | // 转换为字符运算符 |
| | | char optChar = "+-x".charAt(opt); |
| | | |
| | | this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2)); |
| | | this.chars = String.valueOf(res); |
| | | |
| | | return chars.toCharArray(); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.config.bean; |
| | | |
| | | import lombok.Data; |
| | | |
| | | /** |
| | | * Jwt参数配置 |
| | | * |
| | | * @author Zheng Jie |
| | | * @date 2019年11月28日 |
| | | */ |
| | | @Data |
| | | public class SecurityProperties { |
| | | |
| | | /** |
| | | * Request Headers : Authorization |
| | | */ |
| | | private String header; |
| | | |
| | | /** |
| | | * 令牌前缀,最后留个空格 Bearer |
| | | */ |
| | | private String tokenStartWith; |
| | | |
| | | /** |
| | | * 必须使用最少88位的Base64对该令牌进行编码 |
| | | */ |
| | | private String base64Secret; |
| | | |
| | | /** |
| | | * 令牌过期时间 此处单位/毫秒 |
| | | */ |
| | | private Long tokenValidityInSeconds; |
| | | |
| | | /** |
| | | * 在线用户 key,根据 key 查询 redis 中在线用户的数据 |
| | | */ |
| | | private String onlineKey; |
| | | |
| | | /** |
| | | * 验证码 key |
| | | */ |
| | | private String codeKey; |
| | | |
| | | /** |
| | | * token 续期检查 |
| | | */ |
| | | private Long detect; |
| | | |
| | | /** |
| | | * 续期时间 |
| | | */ |
| | | private Long renew; |
| | | |
| | | public String getTokenStartWith() { |
| | | return tokenStartWith + " "; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.rest; |
| | | |
| | | import cn.hutool.core.util.IdUtil; |
| | | import com.wf.captcha.base.Captcha; |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.annotation.rest.AnonymousDeleteMapping; |
| | | import me.zhengjie.annotation.rest.AnonymousGetMapping; |
| | | import me.zhengjie.annotation.rest.AnonymousPostMapping; |
| | | import me.zhengjie.config.RsaProperties; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.security.config.bean.LoginCodeEnum; |
| | | import me.zhengjie.modules.security.config.bean.LoginProperties; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.modules.security.security.TokenProvider; |
| | | import me.zhengjie.modules.security.service.dto.AuthUserDto; |
| | | import me.zhengjie.modules.security.service.dto.JwtUserDto; |
| | | import me.zhengjie.modules.security.service.OnlineUserService; |
| | | import me.zhengjie.utils.RsaUtils; |
| | | import me.zhengjie.utils.RedisUtils; |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| | | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; |
| | | import org.springframework.security.core.Authentication; |
| | | import org.springframework.security.core.context.SecurityContextHolder; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.annotation.Resource; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | * 授权、根据token获取用户详细信息 |
| | | */ |
| | | @Slf4j |
| | | @RestController |
| | | @RequestMapping("/auth") |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:系统授权接口") |
| | | public class AuthorizationController { |
| | | private final SecurityProperties properties; |
| | | private final RedisUtils redisUtils; |
| | | private final OnlineUserService onlineUserService; |
| | | private final TokenProvider tokenProvider; |
| | | private final AuthenticationManagerBuilder authenticationManagerBuilder; |
| | | @Resource |
| | | private LoginProperties loginProperties; |
| | | |
| | | @Log("用户登录") |
| | | @ApiOperation("登录授权") |
| | | @AnonymousPostMapping(value = "/login") |
| | | public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception { |
| | | // 密码解密 |
| | | String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword()); |
| | | // 查询验证码 |
| | | String code = (String) redisUtils.get(authUser.getUuid()); |
| | | // 清除验证码 |
| | | redisUtils.del(authUser.getUuid()); |
| | | if (StringUtils.isBlank(code)) { |
| | | throw new BadRequestException("验证码不存在或已过期"); |
| | | } |
| | | if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { |
| | | throw new BadRequestException("验证码错误"); |
| | | } |
| | | UsernamePasswordAuthenticationToken authenticationToken = |
| | | new UsernamePasswordAuthenticationToken(authUser.getUsername(), password); |
| | | Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); |
| | | SecurityContextHolder.getContext().setAuthentication(authentication); |
| | | // 生成令牌与第三方系统获取令牌方式 |
| | | // UserDetails userDetails = userDetailsService.loadUserByUsername(userInfo.getUsername()); |
| | | // Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); |
| | | // SecurityContextHolder.getContext().setAuthentication(authentication); |
| | | String token = tokenProvider.createToken(authentication); |
| | | final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal(); |
| | | // 保存在线信息 |
| | | onlineUserService.save(jwtUserDto, token, request); |
| | | // 返回 token 与 用户信息 |
| | | Map<String, Object> authInfo = new HashMap<String, Object>(2) {{ |
| | | put("token", properties.getTokenStartWith() + token); |
| | | put("user", jwtUserDto); |
| | | }}; |
| | | if (loginProperties.isSingleLogin()) { |
| | | //踢掉之前已经登录的token |
| | | onlineUserService.checkLoginOnUser(authUser.getUsername(), token); |
| | | } |
| | | return ResponseEntity.ok(authInfo); |
| | | } |
| | | |
| | | @ApiOperation("获取用户信息") |
| | | @GetMapping(value = "/info") |
| | | public ResponseEntity<Object> getUserInfo() { |
| | | return ResponseEntity.ok(SecurityUtils.getCurrentUser()); |
| | | } |
| | | |
| | | @ApiOperation("获取验证码") |
| | | @AnonymousGetMapping(value = "/code") |
| | | public ResponseEntity<Object> getCode() { |
| | | // 获取运算的结果 |
| | | Captcha captcha = loginProperties.getCaptcha(); |
| | | String uuid = properties.getCodeKey() + IdUtil.simpleUUID(); |
| | | //当验证码类型为 arithmetic时且长度 >= 2 时,captcha.text()的结果有几率为浮点型 |
| | | String captchaValue = captcha.text(); |
| | | if (captcha.getCharType() - 1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")) { |
| | | captchaValue = captchaValue.split("\\.")[0]; |
| | | } |
| | | // 保存 |
| | | redisUtils.set(uuid, captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES); |
| | | // 验证码信息 |
| | | Map<String, Object> imgResult = new HashMap<String, Object>(2) {{ |
| | | put("img", captcha.toBase64()); |
| | | put("uuid", uuid); |
| | | }}; |
| | | return ResponseEntity.ok(imgResult); |
| | | } |
| | | |
| | | @ApiOperation("退出登录") |
| | | @AnonymousDeleteMapping(value = "/logout") |
| | | public ResponseEntity<Object> logout(HttpServletRequest request) { |
| | | onlineUserService.logout(tokenProvider.getToken(request)); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.security.service.OnlineUserService; |
| | | import me.zhengjie.utils.EncryptUtils; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/auth/online") |
| | | @Api(tags = "系统:在线用户管理") |
| | | public class OnlineController { |
| | | |
| | | private final OnlineUserService onlineUserService; |
| | | |
| | | @ApiOperation("查询在线用户") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> queryOnlineUser(String filter, Pageable pageable){ |
| | | return new ResponseEntity<>(onlineUserService.getAll(filter, pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("导出数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check()") |
| | | public void exportOnlineUser(HttpServletResponse response, String filter) throws IOException { |
| | | onlineUserService.download(onlineUserService.getAll(filter), response); |
| | | } |
| | | |
| | | @ApiOperation("踢出用户") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check()") |
| | | public ResponseEntity<Object> deleteOnlineUser(@RequestBody Set<String> keys) throws Exception { |
| | | for (String key : keys) { |
| | | // 解密Key |
| | | key = EncryptUtils.desDecrypt(key); |
| | | onlineUserService.kickOut(key); |
| | | } |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.security; |
| | | |
| | | import org.springframework.security.access.AccessDeniedException; |
| | | import org.springframework.security.web.access.AccessDeniedHandler; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Component |
| | | public class JwtAccessDeniedHandler implements AccessDeniedHandler { |
| | | |
| | | @Override |
| | | public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { |
| | | //当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应 |
| | | response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage()); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.security; |
| | | |
| | | import org.springframework.security.core.AuthenticationException; |
| | | import org.springframework.security.web.AuthenticationEntryPoint; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Component |
| | | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { |
| | | |
| | | @Override |
| | | public void commence(HttpServletRequest request, |
| | | HttpServletResponse response, |
| | | AuthenticationException authException) throws IOException { |
| | | // 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应 |
| | | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage()); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.security; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.modules.security.service.OnlineUserService; |
| | | import me.zhengjie.modules.security.service.UserCacheManager; |
| | | import org.springframework.security.config.annotation.SecurityConfigurerAdapter; |
| | | import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| | | import org.springframework.security.web.DefaultSecurityFilterChain; |
| | | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @RequiredArgsConstructor |
| | | public class TokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { |
| | | |
| | | private final TokenProvider tokenProvider; |
| | | private final SecurityProperties properties; |
| | | private final OnlineUserService onlineUserService; |
| | | private final UserCacheManager userCacheManager; |
| | | |
| | | @Override |
| | | public void configure(HttpSecurity http) { |
| | | TokenFilter customFilter = new TokenFilter(tokenProvider, properties, onlineUserService, userCacheManager); |
| | | http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.security; |
| | | |
| | | import cn.hutool.core.util.StrUtil; |
| | | import io.jsonwebtoken.ExpiredJwtException; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.modules.security.service.UserCacheManager; |
| | | import me.zhengjie.modules.security.service.dto.OnlineUserDto; |
| | | import me.zhengjie.modules.security.service.OnlineUserService; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.security.core.Authentication; |
| | | import org.springframework.security.core.context.SecurityContextHolder; |
| | | import org.springframework.util.StringUtils; |
| | | import org.springframework.web.filter.GenericFilterBean; |
| | | import javax.servlet.FilterChain; |
| | | import javax.servlet.ServletException; |
| | | import javax.servlet.ServletRequest; |
| | | import javax.servlet.ServletResponse; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.io.IOException; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | public class TokenFilter extends GenericFilterBean { |
| | | private static final Logger log = LoggerFactory.getLogger(TokenFilter.class); |
| | | |
| | | |
| | | private final TokenProvider tokenProvider; |
| | | private final SecurityProperties properties; |
| | | private final OnlineUserService onlineUserService; |
| | | private final UserCacheManager userCacheManager; |
| | | |
| | | /** |
| | | * @param tokenProvider Token |
| | | * @param properties JWT |
| | | * @param onlineUserService 用户在线 |
| | | * @param userCacheManager 用户缓存工具 |
| | | */ |
| | | public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService, UserCacheManager userCacheManager) { |
| | | this.properties = properties; |
| | | this.onlineUserService = onlineUserService; |
| | | this.tokenProvider = tokenProvider; |
| | | this.userCacheManager = userCacheManager; |
| | | } |
| | | |
| | | @Override |
| | | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) |
| | | throws IOException, ServletException { |
| | | HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; |
| | | String token = resolveToken(httpServletRequest); |
| | | // 对于 Token 为空的不需要去查 Redis |
| | | if (StrUtil.isNotBlank(token)) { |
| | | OnlineUserDto onlineUserDto = null; |
| | | boolean cleanUserCache = false; |
| | | try { |
| | | onlineUserDto = onlineUserService.getOne(properties.getOnlineKey() + token); |
| | | } catch (ExpiredJwtException e) { |
| | | log.error(e.getMessage()); |
| | | cleanUserCache = true; |
| | | } finally { |
| | | if (cleanUserCache || Objects.isNull(onlineUserDto)) { |
| | | userCacheManager.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY))); |
| | | } |
| | | } |
| | | if (onlineUserDto != null && StringUtils.hasText(token)) { |
| | | Authentication authentication = tokenProvider.getAuthentication(token); |
| | | SecurityContextHolder.getContext().setAuthentication(authentication); |
| | | // Token 续期 |
| | | tokenProvider.checkRenewal(token); |
| | | } |
| | | } |
| | | filterChain.doFilter(servletRequest, servletResponse); |
| | | } |
| | | |
| | | /** |
| | | * 初步检测Token |
| | | * |
| | | * @param request / |
| | | * @return / |
| | | */ |
| | | private String resolveToken(HttpServletRequest request) { |
| | | String bearerToken = request.getHeader(properties.getHeader()); |
| | | if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) { |
| | | // 去掉令牌前缀 |
| | | return bearerToken.replace(properties.getTokenStartWith(), ""); |
| | | } else { |
| | | log.debug("非法Token:{}", bearerToken); |
| | | } |
| | | return null; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.security; |
| | | |
| | | import cn.hutool.core.date.DateField; |
| | | import cn.hutool.core.date.DateUtil; |
| | | import cn.hutool.core.util.IdUtil; |
| | | import io.jsonwebtoken.*; |
| | | import io.jsonwebtoken.io.Decoders; |
| | | import io.jsonwebtoken.security.Keys; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.utils.RedisUtils; |
| | | import org.springframework.beans.factory.InitializingBean; |
| | | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| | | import org.springframework.security.core.Authentication; |
| | | import org.springframework.security.core.userdetails.User; |
| | | import org.springframework.stereotype.Component; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.security.Key; |
| | | import java.util.*; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * @author / |
| | | */ |
| | | @Slf4j |
| | | @Component |
| | | public class TokenProvider implements InitializingBean { |
| | | |
| | | private final SecurityProperties properties; |
| | | private final RedisUtils redisUtils; |
| | | public static final String AUTHORITIES_KEY = "user"; |
| | | private JwtParser jwtParser; |
| | | private JwtBuilder jwtBuilder; |
| | | |
| | | public TokenProvider(SecurityProperties properties, RedisUtils redisUtils) { |
| | | this.properties = properties; |
| | | this.redisUtils = redisUtils; |
| | | } |
| | | |
| | | @Override |
| | | public void afterPropertiesSet() { |
| | | byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret()); |
| | | Key key = Keys.hmacShaKeyFor(keyBytes); |
| | | jwtParser = Jwts.parserBuilder() |
| | | .setSigningKey(key) |
| | | .build(); |
| | | jwtBuilder = Jwts.builder() |
| | | .signWith(key, SignatureAlgorithm.HS512); |
| | | } |
| | | |
| | | /** |
| | | * 创建Token 设置永不过期, |
| | | * Token 的时间有效性转到Redis 维护 |
| | | * |
| | | * @param authentication / |
| | | * @return / |
| | | */ |
| | | public String createToken(Authentication authentication) { |
| | | return jwtBuilder |
| | | // 加入ID确保生成的 Token 都不一致 |
| | | .setId(IdUtil.simpleUUID()) |
| | | .claim(AUTHORITIES_KEY, authentication.getName()) |
| | | .setSubject(authentication.getName()) |
| | | .compact(); |
| | | } |
| | | |
| | | /** |
| | | * 依据Token 获取鉴权信息 |
| | | * |
| | | * @param token / |
| | | * @return / |
| | | */ |
| | | Authentication getAuthentication(String token) { |
| | | Claims claims = getClaims(token); |
| | | User principal = new User(claims.getSubject(), "******", new ArrayList<>()); |
| | | return new UsernamePasswordAuthenticationToken(principal, token, new ArrayList<>()); |
| | | } |
| | | |
| | | public Claims getClaims(String token) { |
| | | return jwtParser |
| | | .parseClaimsJws(token) |
| | | .getBody(); |
| | | } |
| | | |
| | | /** |
| | | * @param token 需要检查的token |
| | | */ |
| | | public void checkRenewal(String token) { |
| | | // 判断是否续期token,计算token的过期时间 |
| | | long time = redisUtils.getExpire(properties.getOnlineKey() + token) * 1000; |
| | | Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time); |
| | | // 判断当前时间与过期时间的时间差 |
| | | long differ = expireDate.getTime() - System.currentTimeMillis(); |
| | | // 如果在续期检查的范围内,则续期 |
| | | if (differ <= properties.getDetect()) { |
| | | long renew = time + properties.getRenew(); |
| | | redisUtils.expire(properties.getOnlineKey() + token, renew, TimeUnit.MILLISECONDS); |
| | | } |
| | | } |
| | | |
| | | public String getToken(HttpServletRequest request) { |
| | | final String requestHeader = request.getHeader(properties.getHeader()); |
| | | if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) { |
| | | return requestHeader.substring(7); |
| | | } |
| | | return null; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.modules.security.config.bean.SecurityProperties; |
| | | import me.zhengjie.modules.security.service.dto.JwtUserDto; |
| | | import me.zhengjie.modules.security.service.dto.OnlineUserDto; |
| | | import me.zhengjie.utils.*; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | import org.springframework.stereotype.Service; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019年10月26日21:56:27 |
| | | */ |
| | | @Service |
| | | @Slf4j |
| | | public class OnlineUserService { |
| | | |
| | | private final SecurityProperties properties; |
| | | private final RedisUtils redisUtils; |
| | | |
| | | public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) { |
| | | this.properties = properties; |
| | | this.redisUtils = redisUtils; |
| | | } |
| | | |
| | | /** |
| | | * 保存在线用户信息 |
| | | * @param jwtUserDto / |
| | | * @param token / |
| | | * @param request / |
| | | */ |
| | | public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){ |
| | | String dept = jwtUserDto.getUser().getDept().getName(); |
| | | String ip = StringUtils.getIp(request); |
| | | String browser = StringUtils.getBrowser(request); |
| | | String address = StringUtils.getCityInfo(ip); |
| | | OnlineUserDto onlineUserDto = null; |
| | | try { |
| | | onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), jwtUserDto.getUser().getNickName(), dept, browser , ip, address, EncryptUtils.desEncrypt(token), new Date()); |
| | | } catch (Exception e) { |
| | | log.error(e.getMessage(),e); |
| | | } |
| | | redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000); |
| | | } |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param filter / |
| | | * @param pageable / |
| | | * @return / |
| | | */ |
| | | public Map<String,Object> getAll(String filter, Pageable pageable){ |
| | | List<OnlineUserDto> onlineUserDtos = getAll(filter); |
| | | return PageUtil.toPage( |
| | | PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(), onlineUserDtos), |
| | | onlineUserDtos.size() |
| | | ); |
| | | } |
| | | |
| | | /** |
| | | * 查询全部数据,不分页 |
| | | * @param filter / |
| | | * @return / |
| | | */ |
| | | public List<OnlineUserDto> getAll(String filter){ |
| | | List<String> keys = redisUtils.scan(properties.getOnlineKey() + "*"); |
| | | Collections.reverse(keys); |
| | | List<OnlineUserDto> onlineUserDtos = new ArrayList<>(); |
| | | for (String key : keys) { |
| | | OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key); |
| | | if(StringUtils.isNotBlank(filter)){ |
| | | if(onlineUserDto.toString().contains(filter)){ |
| | | onlineUserDtos.add(onlineUserDto); |
| | | } |
| | | } else { |
| | | onlineUserDtos.add(onlineUserDto); |
| | | } |
| | | } |
| | | onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime())); |
| | | return onlineUserDtos; |
| | | } |
| | | |
| | | /** |
| | | * 踢出用户 |
| | | * @param key / |
| | | */ |
| | | public void kickOut(String key){ |
| | | key = properties.getOnlineKey() + key; |
| | | redisUtils.del(key); |
| | | } |
| | | |
| | | /** |
| | | * 退出登录 |
| | | * @param token / |
| | | */ |
| | | public void logout(String token) { |
| | | String key = properties.getOnlineKey() + token; |
| | | redisUtils.del(key); |
| | | } |
| | | |
| | | /** |
| | | * 导出 |
| | | * @param all / |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | public void download(List<OnlineUserDto> all, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (OnlineUserDto user : all) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("用户名", user.getUserName()); |
| | | map.put("部门", user.getDept()); |
| | | map.put("登录IP", user.getIp()); |
| | | map.put("登录地点", user.getAddress()); |
| | | map.put("浏览器", user.getBrowser()); |
| | | map.put("登录日期", user.getLoginTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | /** |
| | | * 查询用户 |
| | | * @param key / |
| | | * @return / |
| | | */ |
| | | public OnlineUserDto getOne(String key) { |
| | | return (OnlineUserDto)redisUtils.get(key); |
| | | } |
| | | |
| | | /** |
| | | * 检测用户是否在之前已经登录,已经登录踢下线 |
| | | * @param userName 用户名 |
| | | */ |
| | | public void checkLoginOnUser(String userName, String igoreToken){ |
| | | List<OnlineUserDto> onlineUserDtos = getAll(userName); |
| | | if(onlineUserDtos ==null || onlineUserDtos.isEmpty()){ |
| | | return; |
| | | } |
| | | for(OnlineUserDto onlineUserDto : onlineUserDtos){ |
| | | if(onlineUserDto.getUserName().equals(userName)){ |
| | | try { |
| | | String token =EncryptUtils.desDecrypt(onlineUserDto.getKey()); |
| | | if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){ |
| | | this.kickOut(token); |
| | | }else if(StringUtils.isBlank(igoreToken)){ |
| | | this.kickOut(token); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("checkUser is error",e); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据用户名强退用户 |
| | | * @param username / |
| | | */ |
| | | @Async |
| | | public void kickOutForUsername(String username) throws Exception { |
| | | List<OnlineUserDto> onlineUsers = getAll(username); |
| | | for (OnlineUserDto onlineUser : onlineUsers) { |
| | | if (onlineUser.getUserName().equals(username)) { |
| | | String token =EncryptUtils.desDecrypt(onlineUser.getKey()); |
| | | kickOut(token); |
| | | } |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service; |
| | | |
| | | import cn.hutool.core.util.RandomUtil; |
| | | import me.zhengjie.modules.security.config.bean.LoginProperties; |
| | | import me.zhengjie.modules.security.service.dto.JwtUserDto; |
| | | import me.zhengjie.utils.RedisUtils; |
| | | import me.zhengjie.utils.StringUtils; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | import org.springframework.stereotype.Component; |
| | | import javax.annotation.Resource; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @description 用户缓存管理 |
| | | * @date 2022-05-26 |
| | | **/ |
| | | @Component |
| | | public class UserCacheManager { |
| | | |
| | | @Resource |
| | | private RedisUtils redisUtils; |
| | | @Value("${login.user-cache.idle-time}") |
| | | private long idleTime; |
| | | |
| | | /** |
| | | * 返回用户缓存 |
| | | * @param userName 用户名 |
| | | * @return JwtUserDto |
| | | */ |
| | | public JwtUserDto getUserCache(String userName) { |
| | | if (StringUtils.isNotEmpty(userName)) { |
| | | // 获取数据 |
| | | Object obj = redisUtils.hget(LoginProperties.cacheKey, userName); |
| | | if(obj != null){ |
| | | return (JwtUserDto)obj; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 添加缓存到Redis |
| | | * @param userName 用户名 |
| | | */ |
| | | @Async |
| | | public void addUserCache(String userName, JwtUserDto user) { |
| | | if (StringUtils.isNotEmpty(userName)) { |
| | | // 添加数据, 避免数据同时过期 |
| | | long time = idleTime + RandomUtil.randomInt(900, 1800); |
| | | redisUtils.hset(LoginProperties.cacheKey, userName, user, time); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 清理用户缓存信息 |
| | | * 用户信息变更时 |
| | | * @param userName 用户名 |
| | | */ |
| | | @Async |
| | | public void cleanUserCache(String userName) { |
| | | if (StringUtils.isNotEmpty(userName)) { |
| | | // 清除数据 |
| | | redisUtils.hdel(LoginProperties.cacheKey, userName); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.exception.EntityNotFoundException; |
| | | import me.zhengjie.modules.security.service.dto.JwtUserDto; |
| | | import me.zhengjie.modules.system.service.DataService; |
| | | import me.zhengjie.modules.system.service.RoleService; |
| | | import me.zhengjie.modules.system.service.UserService; |
| | | import me.zhengjie.modules.system.service.dto.UserLoginDto; |
| | | import org.springframework.security.core.userdetails.UserDetailsService; |
| | | import org.springframework.security.core.userdetails.UsernameNotFoundException; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-22 |
| | | */ |
| | | @Slf4j |
| | | @RequiredArgsConstructor |
| | | @Service("userDetailsService") |
| | | public class UserDetailsServiceImpl implements UserDetailsService { |
| | | private final UserService userService; |
| | | private final RoleService roleService; |
| | | private final DataService dataService; |
| | | private final UserCacheManager userCacheManager; |
| | | |
| | | @Override |
| | | public JwtUserDto loadUserByUsername(String username) { |
| | | JwtUserDto jwtUserDto = userCacheManager.getUserCache(username); |
| | | if(jwtUserDto == null){ |
| | | UserLoginDto user; |
| | | try { |
| | | user = userService.getLoginData(username); |
| | | } catch (EntityNotFoundException e) { |
| | | // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException |
| | | throw new UsernameNotFoundException(username, e); |
| | | } |
| | | if (user == null) { |
| | | throw new UsernameNotFoundException(""); |
| | | } else { |
| | | if (!user.getEnabled()) { |
| | | throw new BadRequestException("账号未激活!"); |
| | | } |
| | | jwtUserDto = new JwtUserDto( |
| | | user, |
| | | dataService.getDeptIds(user), |
| | | roleService.mapToGrantedAuthorities(user) |
| | | ); |
| | | // 添加缓存数据 |
| | | userCacheManager.addUserCache(username, jwtUserDto); |
| | | } |
| | | } |
| | | return jwtUserDto; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import javax.validation.constraints.NotBlank; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-30 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class AuthUserDto { |
| | | |
| | | @NotBlank |
| | | private String username; |
| | | |
| | | @NotBlank |
| | | private String password; |
| | | |
| | | private String code; |
| | | |
| | | private String uuid = ""; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service.dto; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | import org.springframework.security.core.GrantedAuthority; |
| | | |
| | | /** |
| | | * 避免序列化问题 |
| | | * @author Zheng Jie |
| | | * @date 2018-11-30 |
| | | */ |
| | | @Data |
| | | @NoArgsConstructor |
| | | @AllArgsConstructor |
| | | public class AuthorityDto implements GrantedAuthority { |
| | | |
| | | private String authority; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service.dto; |
| | | |
| | | import com.alibaba.fastjson.annotation.JSONField; |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Getter; |
| | | import me.zhengjie.modules.system.service.dto.UserLoginDto; |
| | | import org.springframework.security.core.userdetails.UserDetails; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Getter |
| | | @AllArgsConstructor |
| | | public class JwtUserDto implements UserDetails { |
| | | |
| | | private final UserLoginDto user; |
| | | |
| | | private final List<Long> dataScopes; |
| | | |
| | | private final List<AuthorityDto> authorities; |
| | | |
| | | public Set<String> getRoles() { |
| | | return authorities.stream().map(AuthorityDto::getAuthority).collect(Collectors.toSet()); |
| | | } |
| | | |
| | | @Override |
| | | @JSONField(serialize = false) |
| | | public String getPassword() { |
| | | return user.getPassword(); |
| | | } |
| | | |
| | | @Override |
| | | @JSONField(serialize = false) |
| | | public String getUsername() { |
| | | return user.getUsername(); |
| | | } |
| | | |
| | | @JSONField(serialize = false) |
| | | @Override |
| | | public boolean isAccountNonExpired() { |
| | | return true; |
| | | } |
| | | |
| | | @JSONField(serialize = false) |
| | | @Override |
| | | public boolean isAccountNonLocked() { |
| | | return true; |
| | | } |
| | | |
| | | @JSONField(serialize = false) |
| | | @Override |
| | | public boolean isCredentialsNonExpired() { |
| | | return true; |
| | | } |
| | | |
| | | @Override |
| | | @JSONField(serialize = false) |
| | | public boolean isEnabled() { |
| | | return user.getEnabled(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.security.service.dto; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | import java.util.Date; |
| | | |
| | | /** |
| | | * 在线用户 |
| | | * @author Zheng Jie |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @NoArgsConstructor |
| | | public class OnlineUserDto { |
| | | |
| | | /** |
| | | * 用户名 |
| | | */ |
| | | private String userName; |
| | | |
| | | /** |
| | | * 昵称 |
| | | */ |
| | | private String nickName; |
| | | |
| | | /** |
| | | * 岗位 |
| | | */ |
| | | private String dept; |
| | | |
| | | /** |
| | | * 浏览器 |
| | | */ |
| | | private String browser; |
| | | |
| | | /** |
| | | * IP |
| | | */ |
| | | private String ip; |
| | | |
| | | /** |
| | | * 地址 |
| | | */ |
| | | private String address; |
| | | |
| | | /** |
| | | * token |
| | | */ |
| | | private String key; |
| | | |
| | | /** |
| | | * 登录时间 |
| | | */ |
| | | private Date loginTime; |
| | | |
| | | |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import com.alibaba.fastjson.annotation.JSONField; |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="sys_dept") |
| | | public class Dept extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "dept_id") |
| | | @NotNull(groups = Update.class) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @JSONField(serialize = false) |
| | | @ManyToMany(mappedBy = "depts") |
| | | @ApiModelProperty(value = "角色") |
| | | private Set<Role> roles; |
| | | |
| | | @ApiModelProperty(value = "排序") |
| | | private Integer deptSort; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "部门名称") |
| | | private String name; |
| | | |
| | | @NotNull |
| | | @ApiModelProperty(value = "是否启用") |
| | | private Boolean enabled; |
| | | |
| | | @ApiModelProperty(value = "上级部门") |
| | | private Long pid; |
| | | |
| | | @ApiModelProperty(value = "子节点数目", hidden = true) |
| | | private Integer subCount = 0; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | Dept dept = (Dept) o; |
| | | return Objects.equals(id, dept.id) && |
| | | Objects.equals(name, dept.name); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id, name); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="sys_dict") |
| | | public class Dict extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "dict_id") |
| | | @NotNull(groups = Update.class) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @OneToMany(mappedBy = "dict",cascade={CascadeType.PERSIST,CascadeType.REMOVE}) |
| | | private List<DictDetail> dictDetails; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "名称") |
| | | private String name; |
| | | |
| | | @ApiModelProperty(value = "描述") |
| | | private String description; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="sys_dict_detail") |
| | | public class DictDetail extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "detail_id") |
| | | @NotNull(groups = Update.class) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @JoinColumn(name = "dict_id") |
| | | @ManyToOne(fetch=FetchType.LAZY) |
| | | @ApiModelProperty(value = "字典", hidden = true) |
| | | private Dict dict; |
| | | |
| | | @ApiModelProperty(value = "字典标签") |
| | | private String label; |
| | | |
| | | @ApiModelProperty(value = "字典值") |
| | | private String value; |
| | | |
| | | @ApiModelProperty(value = "排序") |
| | | private Integer dictSort = 999; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="sys_job") |
| | | public class Job extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "job_id") |
| | | @NotNull(groups = Update.class) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "岗位名称") |
| | | private String name; |
| | | |
| | | @NotNull |
| | | @ApiModelProperty(value = "岗位排序") |
| | | private Long jobSort; |
| | | |
| | | @NotNull |
| | | @ApiModelProperty(value = "是否启用") |
| | | private Boolean enabled; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | Job job = (Job) o; |
| | | return Objects.equals(id, job.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import com.alibaba.fastjson.annotation.JSONField; |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-17 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name = "sys_menu") |
| | | public class Menu extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "menu_id") |
| | | @NotNull(groups = {Update.class}) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | private Long id; |
| | | |
| | | @JSONField(serialize = false) |
| | | @ManyToMany(mappedBy = "menus") |
| | | @ApiModelProperty(value = "菜单角色") |
| | | private Set<Role> roles; |
| | | |
| | | @ApiModelProperty(value = "菜单标题") |
| | | private String title; |
| | | |
| | | @Column(name = "name") |
| | | @ApiModelProperty(value = "菜单组件名称") |
| | | private String componentName; |
| | | |
| | | @ApiModelProperty(value = "排序") |
| | | private Integer menuSort = 999; |
| | | |
| | | @ApiModelProperty(value = "组件路径") |
| | | private String component; |
| | | |
| | | @ApiModelProperty(value = "路由地址") |
| | | private String path; |
| | | |
| | | @ApiModelProperty(value = "菜单类型,目录、菜单、按钮") |
| | | private Integer type; |
| | | |
| | | @ApiModelProperty(value = "权限标识") |
| | | private String permission; |
| | | |
| | | @ApiModelProperty(value = "菜单图标") |
| | | private String icon; |
| | | |
| | | @Column(columnDefinition = "bit(1) default 0") |
| | | @ApiModelProperty(value = "缓存") |
| | | private Boolean cache; |
| | | |
| | | @Column(columnDefinition = "bit(1) default 0") |
| | | @ApiModelProperty(value = "是否隐藏") |
| | | private Boolean hidden; |
| | | |
| | | @ApiModelProperty(value = "上级菜单") |
| | | private Long pid; |
| | | |
| | | @ApiModelProperty(value = "子节点数目", hidden = true) |
| | | private Integer subCount = 0; |
| | | |
| | | @ApiModelProperty(value = "外链菜单") |
| | | private Boolean iFrame; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | Menu menu = (Menu) o; |
| | | return Objects.equals(id, menu.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import com.alibaba.fastjson.annotation.JSONField; |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import me.zhengjie.utils.enums.DataScopeEnum; |
| | | |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * 角色 |
| | | * @author Zheng Jie |
| | | * @date 2018-11-22 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @Entity |
| | | @Table(name = "sys_role") |
| | | public class Role extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "role_id") |
| | | @NotNull(groups = {Update.class}) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | private Long id; |
| | | |
| | | @JSONField(serialize = false) |
| | | @ManyToMany(mappedBy = "roles") |
| | | @ApiModelProperty(value = "用户", hidden = true) |
| | | private Set<User> users; |
| | | |
| | | @ManyToMany(fetch = FetchType.EAGER) |
| | | @JoinTable(name = "sys_roles_menus", |
| | | joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")}, |
| | | inverseJoinColumns = {@JoinColumn(name = "menu_id",referencedColumnName = "menu_id")}) |
| | | @ApiModelProperty(value = "菜单", hidden = true) |
| | | private Set<Menu> menus; |
| | | |
| | | @ManyToMany |
| | | @JoinTable(name = "sys_roles_depts", |
| | | joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")}, |
| | | inverseJoinColumns = {@JoinColumn(name = "dept_id",referencedColumnName = "dept_id")}) |
| | | @ApiModelProperty(value = "部门", hidden = true) |
| | | private Set<Dept> depts; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "名称", hidden = true) |
| | | private String name; |
| | | |
| | | @ApiModelProperty(value = "数据权限,全部 、 本级 、 自定义") |
| | | private String dataScope = DataScopeEnum.THIS_LEVEL.getValue(); |
| | | |
| | | @Column(name = "level") |
| | | @ApiModelProperty(value = "级别,数值越小,级别越大") |
| | | private Integer level = 3; |
| | | |
| | | @ApiModelProperty(value = "描述") |
| | | private String description; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | Role role = (Role) o; |
| | | return Objects.equals(id, role.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain; |
| | | |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseEntity; |
| | | import javax.persistence.*; |
| | | import javax.validation.constraints.Email; |
| | | import javax.validation.constraints.NotBlank; |
| | | import javax.validation.constraints.NotNull; |
| | | import java.io.Serializable; |
| | | import java.util.Date; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-22 |
| | | */ |
| | | @Entity |
| | | @Getter |
| | | @Setter |
| | | @Table(name="sys_user") |
| | | public class User extends BaseEntity implements Serializable { |
| | | |
| | | @Id |
| | | @Column(name = "user_id") |
| | | @NotNull(groups = Update.class) |
| | | @GeneratedValue(strategy = GenerationType.IDENTITY) |
| | | @ApiModelProperty(value = "ID", hidden = true) |
| | | private Long id; |
| | | |
| | | @ManyToMany(fetch = FetchType.EAGER) |
| | | @ApiModelProperty(value = "用户角色") |
| | | @JoinTable(name = "sys_users_roles", |
| | | joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "user_id")}, |
| | | inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")}) |
| | | private Set<Role> roles; |
| | | |
| | | @ManyToMany(fetch = FetchType.EAGER) |
| | | @ApiModelProperty(value = "用户岗位") |
| | | @JoinTable(name = "sys_users_jobs", |
| | | joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "user_id")}, |
| | | inverseJoinColumns = {@JoinColumn(name = "job_id",referencedColumnName = "job_id")}) |
| | | private Set<Job> jobs; |
| | | |
| | | @OneToOne |
| | | @JoinColumn(name = "dept_id") |
| | | @ApiModelProperty(value = "用户部门") |
| | | private Dept dept; |
| | | |
| | | @NotBlank |
| | | @Column(unique = true) |
| | | @ApiModelProperty(value = "用户名称") |
| | | private String username; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "用户昵称") |
| | | private String nickName; |
| | | |
| | | @Email |
| | | @NotBlank |
| | | @ApiModelProperty(value = "邮箱") |
| | | private String email; |
| | | |
| | | @NotBlank |
| | | @ApiModelProperty(value = "电话号码") |
| | | private String phone; |
| | | |
| | | @ApiModelProperty(value = "用户性别") |
| | | private String gender; |
| | | |
| | | @ApiModelProperty(value = "头像真实名称",hidden = true) |
| | | private String avatarName; |
| | | |
| | | @ApiModelProperty(value = "头像存储的路径", hidden = true) |
| | | private String avatarPath; |
| | | |
| | | @ApiModelProperty(value = "密码") |
| | | private String password; |
| | | |
| | | @NotNull |
| | | @ApiModelProperty(value = "是否启用") |
| | | private Boolean enabled; |
| | | |
| | | @ApiModelProperty(value = "是否为admin账号", hidden = true) |
| | | private Boolean isAdmin = false; |
| | | |
| | | @Column(name = "pwd_reset_time") |
| | | @ApiModelProperty(value = "最后修改密码的时间", hidden = true) |
| | | private Date pwdResetTime; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | User user = (User) o; |
| | | return Objects.equals(id, user.id) && |
| | | Objects.equals(username, user.username); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id, username); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain.vo; |
| | | |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-20 |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | public class MenuMetaVo implements Serializable { |
| | | |
| | | private String title; |
| | | |
| | | private String icon; |
| | | |
| | | private Boolean noCache; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain.vo; |
| | | |
| | | import com.fasterxml.jackson.annotation.JsonInclude; |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 构建前端路由时用到 |
| | | * @author Zheng Jie |
| | | * @date 2018-12-20 |
| | | */ |
| | | @Data |
| | | @JsonInclude(JsonInclude.Include.NON_EMPTY) |
| | | public class MenuVo implements Serializable { |
| | | |
| | | private String name; |
| | | |
| | | private String path; |
| | | |
| | | private Boolean hidden; |
| | | |
| | | private String redirect; |
| | | |
| | | private String component; |
| | | |
| | | private Boolean alwaysShow; |
| | | |
| | | private MenuMetaVo meta; |
| | | |
| | | private List<MenuVo> children; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.domain.vo; |
| | | |
| | | import lombok.Data; |
| | | |
| | | /** |
| | | * 修改密码的 Vo 类 |
| | | * @author Zheng Jie |
| | | * @date 2019年7月11日13:59:49 |
| | | */ |
| | | @Data |
| | | public class UserPassVo { |
| | | |
| | | private String oldPass; |
| | | |
| | | private String newPass; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import org.springframework.data.jpa.repository.Modifying; |
| | | import org.springframework.data.jpa.repository.Query; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificationExecutor<Dept> { |
| | | |
| | | /** |
| | | * 根据 PID 查询 |
| | | * @param id pid |
| | | * @return / |
| | | */ |
| | | List<Dept> findByPid(Long id); |
| | | |
| | | /** |
| | | * 获取顶级部门 |
| | | * @return / |
| | | */ |
| | | List<Dept> findByPidIsNull(); |
| | | |
| | | /** |
| | | * 根据角色ID 查询 |
| | | * @param roleId 角色ID |
| | | * @return / |
| | | */ |
| | | @Query(value = "select d.* from sys_dept d, sys_roles_depts r where " + |
| | | "d.dept_id = r.dept_id and r.role_id = ?1", nativeQuery = true) |
| | | Set<Dept> findByRoleId(Long roleId); |
| | | |
| | | /** |
| | | * 判断是否存在子节点 |
| | | * @param pid / |
| | | * @return / |
| | | */ |
| | | int countByPid(Long pid); |
| | | |
| | | /** |
| | | * 根据ID更新sub_count |
| | | * @param count / |
| | | * @param id / |
| | | */ |
| | | @Modifying |
| | | @Query(value = " update sys_dept set sub_count = ?1 where dept_id = ?2 ",nativeQuery = true) |
| | | void updateSubCntById(Integer count, Long id); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.DictDetail; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | public interface DictDetailRepository extends JpaRepository<DictDetail, Long>, JpaSpecificationExecutor<DictDetail> { |
| | | |
| | | /** |
| | | * 根据字典名称查询 |
| | | * @param name / |
| | | * @return / |
| | | */ |
| | | List<DictDetail> findByDictName(String name); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.Dict; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor<Dict> { |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void deleteByIdIn(Set<Long> ids); |
| | | |
| | | /** |
| | | * 查询 |
| | | * @param ids / |
| | | * @return / |
| | | */ |
| | | List<Dict> findByIdIn(Set<Long> ids); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.Job; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificationExecutor<Job> { |
| | | |
| | | /** |
| | | * 根据名称查询 |
| | | * @param name 名称 |
| | | * @return / |
| | | */ |
| | | Job findByName(String name); |
| | | |
| | | /** |
| | | * 根据Id删除 |
| | | * @param ids / |
| | | */ |
| | | void deleteAllByIdIn(Set<Long> ids); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.Menu; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import org.springframework.data.jpa.repository.Modifying; |
| | | import org.springframework.data.jpa.repository.Query; |
| | | import java.util.LinkedHashSet; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-17 |
| | | */ |
| | | public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificationExecutor<Menu> { |
| | | |
| | | /** |
| | | * 根据菜单标题查询 |
| | | * @param title 菜单标题 |
| | | * @return / |
| | | */ |
| | | Menu findByTitle(String title); |
| | | |
| | | /** |
| | | * 根据组件名称查询 |
| | | * @param name 组件名称 |
| | | * @return / |
| | | */ |
| | | Menu findByComponentName(String name); |
| | | |
| | | /** |
| | | * 根据菜单的 PID 查询 |
| | | * @param pid / |
| | | * @return / |
| | | */ |
| | | List<Menu> findByPidOrderByMenuSort(long pid); |
| | | |
| | | /** |
| | | * 查询顶级菜单 |
| | | * @return / |
| | | */ |
| | | List<Menu> findByPidIsNullOrderByMenuSort(); |
| | | |
| | | /** |
| | | * 根据角色ID与菜单类型查询菜单 |
| | | * @param roleIds roleIDs |
| | | * @param type 类型 |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT m.* FROM sys_menu m, sys_roles_menus r WHERE " + |
| | | "m.menu_id = r.menu_id AND r.role_id IN ?1 AND type != ?2 order by m.menu_sort asc",nativeQuery = true) |
| | | LinkedHashSet<Menu> findByRoleIdsAndTypeNot(Set<Long> roleIds, int type); |
| | | |
| | | /** |
| | | * 获取节点数量 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | int countByPid(Long id); |
| | | |
| | | /** |
| | | * 更新节点数目 |
| | | * @param count / |
| | | * @param menuId / |
| | | */ |
| | | @Modifying |
| | | @Query(value = " update sys_menu set sub_count = ?1 where menu_id = ?2 ",nativeQuery = true) |
| | | void updateSubCntById(int count, Long menuId); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.Role; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import org.springframework.data.jpa.repository.Modifying; |
| | | import org.springframework.data.jpa.repository.Query; |
| | | |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-03 |
| | | */ |
| | | public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificationExecutor<Role> { |
| | | |
| | | /** |
| | | * 根据名称查询 |
| | | * @param name / |
| | | * @return / |
| | | */ |
| | | Role findByName(String name); |
| | | |
| | | /** |
| | | * 删除多个角色 |
| | | * @param ids / |
| | | */ |
| | | void deleteAllByIdIn(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据用户ID查询 |
| | | * @param id 用户ID |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT r.* FROM sys_role r, sys_users_roles u WHERE " + |
| | | "r.role_id = u.role_id AND u.user_id = ?1",nativeQuery = true) |
| | | Set<Role> findByUserId(Long id); |
| | | |
| | | /** |
| | | * 解绑角色菜单 |
| | | * @param id 菜单ID |
| | | */ |
| | | @Modifying |
| | | @Query(value = "delete from sys_roles_menus where menu_id = ?1",nativeQuery = true) |
| | | void untiedMenu(Long id); |
| | | |
| | | /** |
| | | * 根据部门查询 |
| | | * @param deptIds / |
| | | * @return / |
| | | */ |
| | | @Query(value = "select count(1) from sys_role r, sys_roles_depts d where " + |
| | | "r.role_id = d.role_id and d.dept_id in ?1",nativeQuery = true) |
| | | int countByDepts(Set<Long> deptIds); |
| | | |
| | | /** |
| | | * 根据菜单Id查询 |
| | | * @param menuIds / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT r.* FROM sys_role r, sys_roles_menus m WHERE " + |
| | | "r.role_id = m.role_id AND m.menu_id in ?1",nativeQuery = true) |
| | | List<Role> findInMenuId(List<Long> menuIds); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.repository; |
| | | |
| | | import me.zhengjie.modules.system.domain.User; |
| | | import org.springframework.data.jpa.repository.JpaRepository; |
| | | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; |
| | | import org.springframework.data.jpa.repository.Modifying; |
| | | import org.springframework.data.jpa.repository.Query; |
| | | import java.util.Date; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-22 |
| | | */ |
| | | public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> { |
| | | |
| | | /** |
| | | * 根据用户名查询 |
| | | * @param username 用户名 |
| | | * @return / |
| | | */ |
| | | User findByUsername(String username); |
| | | |
| | | /** |
| | | * 根据邮箱查询 |
| | | * @param email 邮箱 |
| | | * @return / |
| | | */ |
| | | User findByEmail(String email); |
| | | |
| | | /** |
| | | * 根据手机号查询 |
| | | * @param phone 手机号 |
| | | * @return / |
| | | */ |
| | | User findByPhone(String phone); |
| | | |
| | | /** |
| | | * 修改密码 |
| | | * @param username 用户名 |
| | | * @param pass 密码 |
| | | * @param lastPasswordResetTime / |
| | | */ |
| | | @Modifying |
| | | @Query(value = "update sys_user set password = ?2 , pwd_reset_time = ?3 where username = ?1",nativeQuery = true) |
| | | void updatePass(String username, String pass, Date lastPasswordResetTime); |
| | | |
| | | /** |
| | | * 修改邮箱 |
| | | * @param username 用户名 |
| | | * @param email 邮箱 |
| | | */ |
| | | @Modifying |
| | | @Query(value = "update sys_user set email = ?2 where username = ?1",nativeQuery = true) |
| | | void updateEmail(String username, String email); |
| | | |
| | | /** |
| | | * 根据角色查询用户 |
| | | * @param roleId / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT u.* FROM sys_user u, sys_users_roles r WHERE" + |
| | | " u.user_id = r.user_id AND r.role_id = ?1", nativeQuery = true) |
| | | List<User> findByRoleId(Long roleId); |
| | | |
| | | /** |
| | | * 根据角色中的部门查询 |
| | | * @param deptId / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT u.* FROM sys_user u, sys_users_roles r, sys_roles_depts d WHERE " + |
| | | "u.user_id = r.user_id AND r.role_id = d.role_id AND d.dept_id = ?1 group by u.user_id", nativeQuery = true) |
| | | List<User> findByRoleDeptId(Long deptId); |
| | | |
| | | /** |
| | | * 根据菜单查询 |
| | | * @param id 菜单ID |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT u.* FROM sys_user u, sys_users_roles ur, sys_roles_menus rm WHERE\n" + |
| | | "u.user_id = ur.user_id AND ur.role_id = rm.role_id AND rm.menu_id = ?1 group by u.user_id", nativeQuery = true) |
| | | List<User> findByMenuId(Long id); |
| | | |
| | | /** |
| | | * 根据Id删除 |
| | | * @param ids / |
| | | */ |
| | | void deleteAllByIdIn(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据岗位查询 |
| | | * @param ids / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT count(1) FROM sys_user u, sys_users_jobs j WHERE u.user_id = j.user_id AND j.job_id IN ?1", nativeQuery = true) |
| | | int countByJobs(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据部门查询 |
| | | * @param deptIds / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT count(1) FROM sys_user u WHERE u.dept_id IN ?1", nativeQuery = true) |
| | | int countByDepts(Set<Long> deptIds); |
| | | |
| | | /** |
| | | * 根据角色查询 |
| | | * @param ids / |
| | | * @return / |
| | | */ |
| | | @Query(value = "SELECT count(1) FROM sys_user u, sys_users_roles r WHERE " + |
| | | "u.user_id = r.user_id AND r.role_id in ?1", nativeQuery = true) |
| | | int countByRoles(Set<Long> ids); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import me.zhengjie.modules.system.service.DeptService; |
| | | import me.zhengjie.modules.system.service.dto.DeptDto; |
| | | import me.zhengjie.modules.system.service.dto.DeptQueryCriteria; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:部门管理") |
| | | @RequestMapping("/api/dept") |
| | | public class DeptController { |
| | | |
| | | private final DeptService deptService; |
| | | private static final String ENTITY_NAME = "dept"; |
| | | |
| | | @ApiOperation("导出部门数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('dept:list')") |
| | | public void exportDept(HttpServletResponse response, DeptQueryCriteria criteria) throws Exception { |
| | | deptService.download(deptService.queryAll(criteria, false), response); |
| | | } |
| | | |
| | | @ApiOperation("查询部门") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('user:list','dept:list')") |
| | | public ResponseEntity<Object> queryDept(DeptQueryCriteria criteria) throws Exception { |
| | | List<DeptDto> deptDtos = deptService.queryAll(criteria, true); |
| | | return new ResponseEntity<>(PageUtil.toPage(deptDtos, deptDtos.size()),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询部门:根据ID获取同级与上级数据") |
| | | @PostMapping("/superior") |
| | | @PreAuthorize("@el.check('user:list','dept:list')") |
| | | public ResponseEntity<Object> getDeptSuperior(@RequestBody List<Long> ids) { |
| | | Set<DeptDto> deptDtos = new LinkedHashSet<>(); |
| | | for (Long id : ids) { |
| | | DeptDto deptDto = deptService.findById(id); |
| | | List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>()); |
| | | deptDtos.addAll(depts); |
| | | } |
| | | return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptDtos)),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增部门") |
| | | @ApiOperation("新增部门") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('dept:add')") |
| | | public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | deptService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改部门") |
| | | @ApiOperation("修改部门") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('dept:edit')") |
| | | public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){ |
| | | deptService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除部门") |
| | | @ApiOperation("删除部门") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('dept:del')") |
| | | public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){ |
| | | Set<DeptDto> deptDtos = new HashSet<>(); |
| | | for (Long id : ids) { |
| | | List<Dept> deptList = deptService.findByPid(id); |
| | | deptDtos.add(deptService.findById(id)); |
| | | if(CollectionUtil.isNotEmpty(deptList)){ |
| | | deptDtos = deptService.getDeleteDepts(deptList, deptDtos); |
| | | } |
| | | } |
| | | // 验证是否被角色或用户关联 |
| | | deptService.verification(deptDtos); |
| | | deptService.delete(deptDtos); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.Dict; |
| | | import me.zhengjie.modules.system.service.DictService; |
| | | import me.zhengjie.modules.system.service.dto.DictQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:字典管理") |
| | | @RequestMapping("/api/dict") |
| | | public class DictController { |
| | | |
| | | private final DictService dictService; |
| | | private static final String ENTITY_NAME = "dict"; |
| | | |
| | | @ApiOperation("导出字典数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('dict:list')") |
| | | public void exportDict(HttpServletResponse response, DictQueryCriteria criteria) throws IOException { |
| | | dictService.download(dictService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("查询字典") |
| | | @GetMapping(value = "/all") |
| | | @PreAuthorize("@el.check('dict:list')") |
| | | public ResponseEntity<Object> queryAllDict(){ |
| | | return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询字典") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('dict:list')") |
| | | public ResponseEntity<Object> queryDict(DictQueryCriteria resources, Pageable pageable){ |
| | | return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增字典") |
| | | @ApiOperation("新增字典") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('dict:add')") |
| | | public ResponseEntity<Object> createDict(@Validated @RequestBody Dict resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | dictService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改字典") |
| | | @ApiOperation("修改字典") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('dict:edit')") |
| | | public ResponseEntity<Object> updateDict(@Validated(Dict.Update.class) @RequestBody Dict resources){ |
| | | dictService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除字典") |
| | | @ApiOperation("删除字典") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('dict:del')") |
| | | public ResponseEntity<Object> deleteDict(@RequestBody Set<Long> ids){ |
| | | dictService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.DictDetail; |
| | | import me.zhengjie.modules.system.service.DictDetailService; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailDto; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.data.domain.Sort; |
| | | import org.springframework.data.web.PageableDefault; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:字典详情管理") |
| | | @RequestMapping("/api/dictDetail") |
| | | public class DictDetailController { |
| | | |
| | | private final DictDetailService dictDetailService; |
| | | private static final String ENTITY_NAME = "dictDetail"; |
| | | |
| | | @ApiOperation("查询字典详情") |
| | | @GetMapping |
| | | public ResponseEntity<Object> queryDictDetail(DictDetailQueryCriteria criteria, |
| | | @PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable){ |
| | | return new ResponseEntity<>(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询多个字典详情") |
| | | @GetMapping(value = "/map") |
| | | public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){ |
| | | String[] names = dictName.split("[,,]"); |
| | | Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16); |
| | | for (String name : names) { |
| | | dictMap.put(name, dictDetailService.getDictByName(name)); |
| | | } |
| | | return new ResponseEntity<>(dictMap, HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增字典详情") |
| | | @ApiOperation("新增字典详情") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('dict:add')") |
| | | public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | dictDetailService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改字典详情") |
| | | @ApiOperation("修改字典详情") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('dict:edit')") |
| | | public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){ |
| | | dictDetailService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除字典详情") |
| | | @ApiOperation("删除字典详情") |
| | | @DeleteMapping(value = "/{id}") |
| | | @PreAuthorize("@el.check('dict:del')") |
| | | public ResponseEntity<Object> deleteDictDetail(@PathVariable Long id){ |
| | | dictDetailService.delete(id); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.Job; |
| | | import me.zhengjie.modules.system.service.JobService; |
| | | import me.zhengjie.modules.system.service.dto.JobQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:岗位管理") |
| | | @RequestMapping("/api/job") |
| | | public class JobController { |
| | | |
| | | private final JobService jobService; |
| | | private static final String ENTITY_NAME = "job"; |
| | | |
| | | @ApiOperation("导出岗位数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('job:list')") |
| | | public void exportJob(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { |
| | | jobService.download(jobService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("查询岗位") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('job:list','user:list')") |
| | | public ResponseEntity<Object> queryJob(JobQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增岗位") |
| | | @ApiOperation("新增岗位") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('job:add')") |
| | | public ResponseEntity<Object> createJob(@Validated @RequestBody Job resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | jobService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改岗位") |
| | | @ApiOperation("修改岗位") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('job:edit')") |
| | | public ResponseEntity<Object> updateJob(@Validated(Job.Update.class) @RequestBody Job resources){ |
| | | jobService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除岗位") |
| | | @ApiOperation("删除岗位") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('job:del')") |
| | | public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids){ |
| | | // 验证是否被用户关联 |
| | | jobService.verification(ids); |
| | | jobService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import me.zhengjie.annotation.Limit; |
| | | import me.zhengjie.annotation.rest.AnonymousGetMapping; |
| | | import org.springframework.web.bind.annotation.RequestMapping; |
| | | import org.springframework.web.bind.annotation.RestController; |
| | | |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | |
| | | /** |
| | | * @author / |
| | | * 接口限流测试类 |
| | | */ |
| | | @RestController |
| | | @RequestMapping("/api/limit") |
| | | @Api(tags = "系统:限流测试管理") |
| | | public class LimitController { |
| | | |
| | | private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(); |
| | | |
| | | /** |
| | | * 测试限流注解,下面配置说明该接口 60秒内最多只能访问 10次,保存到redis的键名为 limit_test, |
| | | */ |
| | | @AnonymousGetMapping |
| | | @ApiOperation("测试") |
| | | @Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit") |
| | | public int testLimit() { |
| | | return ATOMIC_INTEGER.incrementAndGet(); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.system.domain.Menu; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.service.MenuService; |
| | | import me.zhengjie.modules.system.service.dto.MenuDto; |
| | | import me.zhengjie.modules.system.service.dto.MenuQueryCriteria; |
| | | import me.zhengjie.modules.system.service.mapstruct.MenuMapper; |
| | | import me.zhengjie.utils.PageUtil; |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.util.*; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-03 |
| | | */ |
| | | |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:菜单管理") |
| | | @RequestMapping("/api/menus") |
| | | public class MenuController { |
| | | |
| | | private final MenuService menuService; |
| | | private final MenuMapper menuMapper; |
| | | private static final String ENTITY_NAME = "menu"; |
| | | |
| | | @ApiOperation("导出菜单数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('menu:list')") |
| | | public void exportMenu(HttpServletResponse response, MenuQueryCriteria criteria) throws Exception { |
| | | menuService.download(menuService.queryAll(criteria, false), response); |
| | | } |
| | | |
| | | @GetMapping(value = "/build") |
| | | @ApiOperation("获取前端所需菜单") |
| | | public ResponseEntity<Object> buildMenus(){ |
| | | List<MenuDto> menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId()); |
| | | List<MenuDto> menuDtos = menuService.buildTree(menuDtoList); |
| | | return new ResponseEntity<>(menuService.buildMenus(menuDtos),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("返回全部的菜单") |
| | | @GetMapping(value = "/lazy") |
| | | @PreAuthorize("@el.check('menu:list','roles:list')") |
| | | public ResponseEntity<Object> queryAllMenu(@RequestParam Long pid){ |
| | | return new ResponseEntity<>(menuService.getMenus(pid),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("根据菜单ID返回所有子节点ID,包含自身ID") |
| | | @GetMapping(value = "/child") |
| | | @PreAuthorize("@el.check('menu:list','roles:list')") |
| | | public ResponseEntity<Object> childMenu(@RequestParam Long id){ |
| | | Set<Menu> menuSet = new HashSet<>(); |
| | | List<MenuDto> menuList = menuService.getMenus(id); |
| | | menuSet.add(menuService.findOne(id)); |
| | | menuSet = menuService.getChildMenus(menuMapper.toEntity(menuList), menuSet); |
| | | Set<Long> ids = menuSet.stream().map(Menu::getId).collect(Collectors.toSet()); |
| | | return new ResponseEntity<>(ids,HttpStatus.OK); |
| | | } |
| | | |
| | | @GetMapping |
| | | @ApiOperation("查询菜单") |
| | | @PreAuthorize("@el.check('menu:list')") |
| | | public ResponseEntity<Object> queryMenu(MenuQueryCriteria criteria) throws Exception { |
| | | List<MenuDto> menuDtoList = menuService.queryAll(criteria, true); |
| | | return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询菜单:根据ID获取同级与上级数据") |
| | | @PostMapping("/superior") |
| | | @PreAuthorize("@el.check('menu:list')") |
| | | public ResponseEntity<Object> getMenuSuperior(@RequestBody List<Long> ids) { |
| | | Set<MenuDto> menuDtos = new LinkedHashSet<>(); |
| | | if(CollectionUtil.isNotEmpty(ids)){ |
| | | for (Long id : ids) { |
| | | MenuDto menuDto = menuService.findById(id); |
| | | menuDtos.addAll(menuService.getSuperior(menuDto, new ArrayList<>())); |
| | | } |
| | | return new ResponseEntity<>(menuService.buildTree(new ArrayList<>(menuDtos)),HttpStatus.OK); |
| | | } |
| | | return new ResponseEntity<>(menuService.getMenus(null),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增菜单") |
| | | @ApiOperation("新增菜单") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('menu:add')") |
| | | public ResponseEntity<Object> createMenu(@Validated @RequestBody Menu resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | menuService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改菜单") |
| | | @ApiOperation("修改菜单") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('menu:edit')") |
| | | public ResponseEntity<Object> updateMenu(@Validated(Menu.Update.class) @RequestBody Menu resources){ |
| | | menuService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除菜单") |
| | | @ApiOperation("删除菜单") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('menu:del')") |
| | | public ResponseEntity<Object> deleteMenu(@RequestBody Set<Long> ids){ |
| | | Set<Menu> menuSet = new HashSet<>(); |
| | | for (Long id : ids) { |
| | | List<MenuDto> menuList = menuService.getMenus(id); |
| | | menuSet.add(menuService.findOne(id)); |
| | | menuSet = menuService.getChildMenus(menuMapper.toEntity(menuList), menuSet); |
| | | } |
| | | menuService.delete(menuSet); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.system.service.MonitorService; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2020-05-02 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统-服务监控管理") |
| | | @RequestMapping("/api/monitor") |
| | | public class MonitorController { |
| | | |
| | | private final MonitorService serverService; |
| | | |
| | | @GetMapping |
| | | @ApiOperation("查询服务监控") |
| | | @PreAuthorize("@el.check('monitor:list')") |
| | | public ResponseEntity<Object> queryMonitor(){ |
| | | return new ResponseEntity<>(serverService.getServers(),HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import cn.hutool.core.lang.Dict; |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.modules.system.domain.Role; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.service.RoleService; |
| | | import me.zhengjie.modules.system.service.dto.RoleDto; |
| | | import me.zhengjie.modules.system.service.dto.RoleQueryCriteria; |
| | | import me.zhengjie.modules.system.service.dto.RoleSmallDto; |
| | | import me.zhengjie.utils.SecurityUtils; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-03 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @Api(tags = "系统:角色管理") |
| | | @RequestMapping("/api/roles") |
| | | public class RoleController { |
| | | |
| | | private final RoleService roleService; |
| | | |
| | | private static final String ENTITY_NAME = "role"; |
| | | |
| | | @ApiOperation("获取单个role") |
| | | @GetMapping(value = "/{id}") |
| | | @PreAuthorize("@el.check('roles:list')") |
| | | public ResponseEntity<Object> findRoleById(@PathVariable Long id){ |
| | | return new ResponseEntity<>(roleService.findById(id), HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("导出角色数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('role:list')") |
| | | public void exportRole(HttpServletResponse response, RoleQueryCriteria criteria) throws IOException { |
| | | roleService.download(roleService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("返回全部的角色") |
| | | @GetMapping(value = "/all") |
| | | @PreAuthorize("@el.check('roles:list','user:add','user:edit')") |
| | | public ResponseEntity<Object> queryAllRole(){ |
| | | return new ResponseEntity<>(roleService.queryAll(),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("查询角色") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('roles:list')") |
| | | public ResponseEntity<Object> queryRole(RoleQueryCriteria criteria, Pageable pageable){ |
| | | return new ResponseEntity<>(roleService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("获取用户级别") |
| | | @GetMapping(value = "/level") |
| | | public ResponseEntity<Object> getRoleLevel(){ |
| | | return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增角色") |
| | | @ApiOperation("新增角色") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('roles:add')") |
| | | public ResponseEntity<Object> createRole(@Validated @RequestBody Role resources){ |
| | | if (resources.getId() != null) { |
| | | throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); |
| | | } |
| | | getLevels(resources.getLevel()); |
| | | roleService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改角色") |
| | | @ApiOperation("修改角色") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('roles:edit')") |
| | | public ResponseEntity<Object> updateRole(@Validated(Role.Update.class) @RequestBody Role resources){ |
| | | getLevels(resources.getLevel()); |
| | | roleService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("修改角色菜单") |
| | | @ApiOperation("修改角色菜单") |
| | | @PutMapping(value = "/menu") |
| | | @PreAuthorize("@el.check('roles:edit')") |
| | | public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){ |
| | | RoleDto role = roleService.findById(resources.getId()); |
| | | getLevels(role.getLevel()); |
| | | roleService.updateMenu(resources,role); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除角色") |
| | | @ApiOperation("删除角色") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('roles:del')") |
| | | public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){ |
| | | for (Long id : ids) { |
| | | RoleDto role = roleService.findById(id); |
| | | getLevels(role.getLevel()); |
| | | } |
| | | // 验证是否被用户关联 |
| | | roleService.verification(ids); |
| | | roleService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | /** |
| | | * 获取用户的角色级别 |
| | | * @return / |
| | | */ |
| | | private int getLevels(Integer level){ |
| | | List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()); |
| | | int min = Collections.min(levels); |
| | | if(level != null){ |
| | | if(level < min){ |
| | | throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level); |
| | | } |
| | | } |
| | | return min; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.annotation.Log; |
| | | import me.zhengjie.config.RsaProperties; |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import me.zhengjie.modules.system.service.DataService; |
| | | import me.zhengjie.modules.system.domain.User; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.vo.UserPassVo; |
| | | import me.zhengjie.modules.system.service.DeptService; |
| | | import me.zhengjie.modules.system.service.RoleService; |
| | | import me.zhengjie.modules.system.service.dto.RoleSmallDto; |
| | | import me.zhengjie.modules.system.service.dto.UserDto; |
| | | import me.zhengjie.modules.system.service.dto.UserQueryCriteria; |
| | | import me.zhengjie.modules.system.service.VerifyService; |
| | | import me.zhengjie.utils.*; |
| | | import me.zhengjie.modules.system.service.UserService; |
| | | import me.zhengjie.utils.enums.CodeEnum; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.security.crypto.password.PasswordEncoder; |
| | | import org.springframework.util.CollectionUtils; |
| | | import org.springframework.util.ObjectUtils; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Api(tags = "系统:用户管理") |
| | | @RestController |
| | | @RequestMapping("/api/users") |
| | | @RequiredArgsConstructor |
| | | public class UserController { |
| | | |
| | | private final PasswordEncoder passwordEncoder; |
| | | private final UserService userService; |
| | | private final DataService dataService; |
| | | private final DeptService deptService; |
| | | private final RoleService roleService; |
| | | private final VerifyService verificationCodeService; |
| | | |
| | | @ApiOperation("导出用户数据") |
| | | @GetMapping(value = "/download") |
| | | @PreAuthorize("@el.check('user:list')") |
| | | public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { |
| | | userService.download(userService.queryAll(criteria), response); |
| | | } |
| | | |
| | | @ApiOperation("查询用户") |
| | | @GetMapping |
| | | @PreAuthorize("@el.check('user:list')") |
| | | public ResponseEntity<Object> queryUser(UserQueryCriteria criteria, Pageable pageable){ |
| | | if (!ObjectUtils.isEmpty(criteria.getDeptId())) { |
| | | criteria.getDeptIds().add(criteria.getDeptId()); |
| | | // 先查找是否存在子节点 |
| | | List<Dept> data = deptService.findByPid(criteria.getDeptId()); |
| | | // 然后把子节点的ID都加入到集合中 |
| | | criteria.getDeptIds().addAll(deptService.getDeptChildren(data)); |
| | | } |
| | | // 数据权限 |
| | | List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername())); |
| | | // criteria.getDeptIds() 不为空并且数据权限不为空则取交集 |
| | | if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){ |
| | | // 取交集 |
| | | criteria.getDeptIds().retainAll(dataScopes); |
| | | if(!CollectionUtil.isEmpty(criteria.getDeptIds())){ |
| | | return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | } else { |
| | | // 否则取并集 |
| | | criteria.getDeptIds().addAll(dataScopes); |
| | | return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK); |
| | | } |
| | | return new ResponseEntity<>(PageUtil.toPage(null,0),HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("新增用户") |
| | | @ApiOperation("新增用户") |
| | | @PostMapping |
| | | @PreAuthorize("@el.check('user:add')") |
| | | public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){ |
| | | checkLevel(resources); |
| | | // 默认密码 123456 |
| | | resources.setPassword(passwordEncoder.encode("123456")); |
| | | userService.create(resources); |
| | | return new ResponseEntity<>(HttpStatus.CREATED); |
| | | } |
| | | |
| | | @Log("修改用户") |
| | | @ApiOperation("修改用户") |
| | | @PutMapping |
| | | @PreAuthorize("@el.check('user:edit')") |
| | | public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception { |
| | | checkLevel(resources); |
| | | userService.update(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("修改用户:个人中心") |
| | | @ApiOperation("修改用户:个人中心") |
| | | @PutMapping(value = "center") |
| | | public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){ |
| | | if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){ |
| | | throw new BadRequestException("不能修改他人资料"); |
| | | } |
| | | userService.updateCenter(resources); |
| | | return new ResponseEntity<>(HttpStatus.NO_CONTENT); |
| | | } |
| | | |
| | | @Log("删除用户") |
| | | @ApiOperation("删除用户") |
| | | @DeleteMapping |
| | | @PreAuthorize("@el.check('user:del')") |
| | | public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){ |
| | | for (Long id : ids) { |
| | | Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); |
| | | Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); |
| | | if (currentLevel > optLevel) { |
| | | throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); |
| | | } |
| | | } |
| | | userService.delete(ids); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("修改密码") |
| | | @PostMapping(value = "/updatePass") |
| | | public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception { |
| | | String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass()); |
| | | String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass()); |
| | | UserDto user = userService.findByName(SecurityUtils.getCurrentUsername()); |
| | | if(!passwordEncoder.matches(oldPass, user.getPassword())){ |
| | | throw new BadRequestException("修改失败,旧密码错误"); |
| | | } |
| | | if(passwordEncoder.matches(newPass, user.getPassword())){ |
| | | throw new BadRequestException("新密码不能与旧密码相同"); |
| | | } |
| | | userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass)); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @ApiOperation("修改头像") |
| | | @PostMapping(value = "/updateAvatar") |
| | | public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){ |
| | | return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); |
| | | } |
| | | |
| | | @Log("修改邮箱") |
| | | @ApiOperation("修改邮箱") |
| | | @PostMapping(value = "/updateEmail/{code}") |
| | | public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception { |
| | | String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword()); |
| | | UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername()); |
| | | if(!passwordEncoder.matches(password, userDto.getPassword())){ |
| | | throw new BadRequestException("密码错误"); |
| | | } |
| | | verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code); |
| | | userService.updateEmail(userDto.getUsername(),user.getEmail()); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | /** |
| | | * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误 |
| | | * @param resources / |
| | | */ |
| | | private void checkLevel(User resources) { |
| | | Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); |
| | | Integer optLevel = roleService.findByRoles(resources.getRoles()); |
| | | if (currentLevel > optLevel) { |
| | | throw new BadRequestException("角色权限不足"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.rest; |
| | | |
| | | import io.swagger.annotations.Api; |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.domain.vo.EmailVo; |
| | | import me.zhengjie.service.EmailService; |
| | | import me.zhengjie.modules.system.service.VerifyService; |
| | | import me.zhengjie.utils.enums.CodeBiEnum; |
| | | import me.zhengjie.utils.enums.CodeEnum; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.ResponseEntity; |
| | | import org.springframework.web.bind.annotation.*; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-26 |
| | | */ |
| | | @RestController |
| | | @RequiredArgsConstructor |
| | | @RequestMapping("/api/code") |
| | | @Api(tags = "系统:验证码管理") |
| | | public class VerifyController { |
| | | |
| | | private final VerifyService verificationCodeService; |
| | | private final EmailService emailService; |
| | | |
| | | @PostMapping(value = "/resetEmail") |
| | | @ApiOperation("重置邮箱,发送验证码") |
| | | public ResponseEntity<Object> resetEmail(@RequestParam String email){ |
| | | EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey()); |
| | | emailService.send(emailVo,emailService.find()); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @PostMapping(value = "/email/resetPass") |
| | | @ApiOperation("重置密码,发送验证码") |
| | | public ResponseEntity<Object> resetPass(@RequestParam String email){ |
| | | EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_PWD_CODE.getKey()); |
| | | emailService.send(emailVo,emailService.find()); |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | |
| | | @GetMapping(value = "/validated") |
| | | @ApiOperation("验证码验证") |
| | | public ResponseEntity<Object> validated(@RequestParam String email, @RequestParam String code, @RequestParam Integer codeBi){ |
| | | CodeBiEnum biEnum = CodeBiEnum.find(codeBi); |
| | | switch (Objects.requireNonNull(biEnum)){ |
| | | case ONE: |
| | | verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + email ,code); |
| | | break; |
| | | case TWO: |
| | | verificationCodeService.validated(CodeEnum.EMAIL_RESET_PWD_CODE.getKey() + email ,code); |
| | | break; |
| | | default: |
| | | break; |
| | | } |
| | | return new ResponseEntity<>(HttpStatus.OK); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.service.dto.UserDto; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 数据权限服务类 |
| | | * @author Zheng Jie |
| | | * @date 2020-05-07 |
| | | */ |
| | | public interface DataService { |
| | | |
| | | /** |
| | | * 获取数据权限 |
| | | * @param user / |
| | | * @return / |
| | | */ |
| | | List<Long> getDeptIds(UserDto user); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import me.zhengjie.modules.system.service.dto.DeptDto; |
| | | import me.zhengjie.modules.system.service.dto.DeptQueryCriteria; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | public interface DeptService { |
| | | |
| | | /** |
| | | * 查询所有数据 |
| | | * @param criteria 条件 |
| | | * @param isQuery / |
| | | * @throws Exception / |
| | | * @return / |
| | | */ |
| | | List<DeptDto> queryAll(DeptQueryCriteria criteria, Boolean isQuery) throws Exception; |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | DeptDto findById(Long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(Dept resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Dept resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param deptDtos / |
| | | * |
| | | */ |
| | | void delete(Set<DeptDto> deptDtos); |
| | | |
| | | /** |
| | | * 根据PID查询 |
| | | * @param pid / |
| | | * @return / |
| | | */ |
| | | List<Dept> findByPid(long pid); |
| | | |
| | | /** |
| | | * 根据角色ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | Set<Dept> findByRoleId(Long id); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<DeptDto> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 获取待删除的部门 |
| | | * @param deptList / |
| | | * @param deptDtos / |
| | | * @return / |
| | | */ |
| | | Set<DeptDto> getDeleteDepts(List<Dept> deptList, Set<DeptDto> deptDtos); |
| | | |
| | | /** |
| | | * 根据ID获取同级与上级数据 |
| | | * @param deptDto / |
| | | * @param depts / |
| | | * @return / |
| | | */ |
| | | List<DeptDto> getSuperior(DeptDto deptDto, List<Dept> depts); |
| | | |
| | | /** |
| | | * 构建树形数据 |
| | | * @param deptDtos / |
| | | * @return / |
| | | */ |
| | | Object buildTree(List<DeptDto> deptDtos); |
| | | |
| | | /** |
| | | * 获取 |
| | | * @param deptList |
| | | * @return |
| | | */ |
| | | List<Long> getDeptChildren(List<Dept> deptList); |
| | | |
| | | /** |
| | | * 验证是否被角色或用户关联 |
| | | * @param deptDtos / |
| | | */ |
| | | void verification(Set<DeptDto> deptDtos); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.DictDetail; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailDto; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | public interface DictDetailService { |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(DictDetail resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(DictDetail resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param id / |
| | | */ |
| | | void delete(Long id); |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 根据字典名称获取字典详情 |
| | | * @param name 字典名称 |
| | | * @return / |
| | | */ |
| | | List<DictDetailDto> getDictByName(String name); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.Dict; |
| | | import me.zhengjie.modules.system.service.dto.DictDto; |
| | | import me.zhengjie.modules.system.service.dto.DictQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | public interface DictService { |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Map<String,Object> queryAll(DictQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param dict / |
| | | * @return / |
| | | */ |
| | | List<DictDto> queryAll(DictQueryCriteria dict); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | void create(Dict resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Dict resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<DictDto> queryAll, HttpServletResponse response) throws IOException; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.Job; |
| | | import me.zhengjie.modules.system.service.dto.JobDto; |
| | | import me.zhengjie.modules.system.service.dto.JobQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | public interface JobService { |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | JobDto findById(Long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | * @return / |
| | | */ |
| | | void create(Job resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Job resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Map<String,Object> queryAll(JobQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria / |
| | | * @return / |
| | | */ |
| | | List<JobDto> queryAll(JobQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<JobDto> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 验证是否被用户关联 |
| | | * @param ids / |
| | | */ |
| | | void verification(Set<Long> ids); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.Menu; |
| | | import me.zhengjie.modules.system.service.dto.MenuDto; |
| | | import me.zhengjie.modules.system.service.dto.MenuQueryCriteria; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-17 |
| | | */ |
| | | public interface MenuService { |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @param criteria 条件 |
| | | * @param isQuery / |
| | | * @throws Exception / |
| | | * @return / |
| | | */ |
| | | List<MenuDto> queryAll(MenuQueryCriteria criteria, Boolean isQuery) throws Exception; |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | MenuDto findById(long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(Menu resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Menu resources); |
| | | |
| | | /** |
| | | * 获取所有子节点,包含自身ID |
| | | * @param menuList / |
| | | * @param menuSet / |
| | | * @return / |
| | | */ |
| | | Set<Menu> getChildMenus(List<Menu> menuList, Set<Menu> menuSet); |
| | | |
| | | /** |
| | | * 构建菜单树 |
| | | * @param menuDtos 原始数据 |
| | | * @return / |
| | | */ |
| | | List<MenuDto> buildTree(List<MenuDto> menuDtos); |
| | | |
| | | /** |
| | | * 构建菜单树 |
| | | * @param menuDtos / |
| | | * @return / |
| | | */ |
| | | Object buildMenus(List<MenuDto> menuDtos); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | Menu findOne(Long id); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param menuSet / |
| | | */ |
| | | void delete(Set<Menu> menuSet); |
| | | |
| | | /** |
| | | * 导出 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<MenuDto> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 懒加载菜单数据 |
| | | * @param pid / |
| | | * @return / |
| | | */ |
| | | List<MenuDto> getMenus(Long pid); |
| | | |
| | | /** |
| | | * 根据ID获取同级与上级数据 |
| | | * @param menuDto / |
| | | * @param objects / |
| | | * @return / |
| | | */ |
| | | List<MenuDto> getSuperior(MenuDto menuDto, List<Menu> objects); |
| | | |
| | | /** |
| | | * 根据当前用户获取菜单 |
| | | * @param currentUserId / |
| | | * @return / |
| | | */ |
| | | List<MenuDto> findByUser(Long currentUserId); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2020-05-02 |
| | | */ |
| | | public interface MonitorService { |
| | | |
| | | /** |
| | | * 查询数据分页 |
| | | * @return Map<String,Object> |
| | | */ |
| | | Map<String,Object> getServers(); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.security.service.dto.AuthorityDto; |
| | | import me.zhengjie.modules.system.domain.Role; |
| | | import me.zhengjie.modules.system.service.dto.RoleDto; |
| | | import me.zhengjie.modules.system.service.dto.RoleQueryCriteria; |
| | | import me.zhengjie.modules.system.service.dto.RoleSmallDto; |
| | | import me.zhengjie.modules.system.service.dto.UserDto; |
| | | import org.springframework.data.domain.Pageable; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-03 |
| | | */ |
| | | public interface RoleService { |
| | | |
| | | /** |
| | | * 查询全部数据 |
| | | * @return / |
| | | */ |
| | | List<RoleDto> queryAll(); |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id / |
| | | * @return / |
| | | */ |
| | | RoleDto findById(long id); |
| | | |
| | | /** |
| | | * 创建 |
| | | * @param resources / |
| | | */ |
| | | void create(Role resources); |
| | | |
| | | /** |
| | | * 编辑 |
| | | * @param resources / |
| | | */ |
| | | void update(Role resources); |
| | | |
| | | /** |
| | | * 删除 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据用户ID查询 |
| | | * @param id 用户ID |
| | | * @return / |
| | | */ |
| | | List<RoleSmallDto> findByUsersId(Long id); |
| | | |
| | | /** |
| | | * 根据角色查询角色级别 |
| | | * @param roles / |
| | | * @return / |
| | | */ |
| | | Integer findByRoles(Set<Role> roles); |
| | | |
| | | /** |
| | | * 修改绑定的菜单 |
| | | * @param resources / |
| | | * @param roleDTO / |
| | | */ |
| | | void updateMenu(Role resources, RoleDto roleDTO); |
| | | |
| | | /** |
| | | * 解绑菜单 |
| | | * @param id / |
| | | */ |
| | | void untiedMenu(Long id); |
| | | |
| | | /** |
| | | * 待条件分页查询 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(RoleQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<RoleDto> queryAll(RoleQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<RoleDto> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 获取用户权限信息 |
| | | * @param user 用户信息 |
| | | * @return 权限信息 |
| | | */ |
| | | List<AuthorityDto> mapToGrantedAuthorities(UserDto user); |
| | | |
| | | /** |
| | | * 验证是否被用户关联 |
| | | * @param ids / |
| | | */ |
| | | void verification(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据菜单Id查询 |
| | | * @param menuIds / |
| | | * @return / |
| | | */ |
| | | List<Role> findInMenuId(List<Long> menuIds); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.modules.system.domain.User; |
| | | import me.zhengjie.modules.system.service.dto.UserDto; |
| | | import me.zhengjie.modules.system.service.dto.UserLoginDto; |
| | | import me.zhengjie.modules.system.service.dto.UserQueryCriteria; |
| | | import org.springframework.data.domain.Pageable; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | public interface UserService { |
| | | |
| | | /** |
| | | * 根据ID查询 |
| | | * @param id ID |
| | | * @return / |
| | | */ |
| | | UserDto findById(long id); |
| | | |
| | | /** |
| | | * 新增用户 |
| | | * @param resources / |
| | | */ |
| | | void create(User resources); |
| | | |
| | | /** |
| | | * 编辑用户 |
| | | * @param resources / |
| | | * @throws Exception / |
| | | */ |
| | | void update(User resources) throws Exception; |
| | | |
| | | /** |
| | | * 删除用户 |
| | | * @param ids / |
| | | */ |
| | | void delete(Set<Long> ids); |
| | | |
| | | /** |
| | | * 根据用户名查询 |
| | | * @param userName / |
| | | * @return / |
| | | */ |
| | | UserDto findByName(String userName); |
| | | |
| | | /** |
| | | * 根据用户名查询 |
| | | * @param userName / |
| | | * @return / |
| | | */ |
| | | UserLoginDto getLoginData(String userName); |
| | | |
| | | /** |
| | | * 修改密码 |
| | | * @param username 用户名 |
| | | * @param encryptPassword 密码 |
| | | */ |
| | | void updatePass(String username, String encryptPassword); |
| | | |
| | | /** |
| | | * 修改头像 |
| | | * @param file 文件 |
| | | * @return / |
| | | */ |
| | | Map<String, String> updateAvatar(MultipartFile file); |
| | | |
| | | /** |
| | | * 修改邮箱 |
| | | * @param username 用户名 |
| | | * @param email 邮箱 |
| | | */ |
| | | void updateEmail(String username, String email); |
| | | |
| | | /** |
| | | * 查询全部 |
| | | * @param criteria 条件 |
| | | * @param pageable 分页参数 |
| | | * @return / |
| | | */ |
| | | Object queryAll(UserQueryCriteria criteria, Pageable pageable); |
| | | |
| | | /** |
| | | * 查询全部不分页 |
| | | * @param criteria 条件 |
| | | * @return / |
| | | */ |
| | | List<UserDto> queryAll(UserQueryCriteria criteria); |
| | | |
| | | /** |
| | | * 导出数据 |
| | | * @param queryAll 待导出的数据 |
| | | * @param response / |
| | | * @throws IOException / |
| | | */ |
| | | void download(List<UserDto> queryAll, HttpServletResponse response) throws IOException; |
| | | |
| | | /** |
| | | * 用户自助修改资料 |
| | | * @param resources / |
| | | */ |
| | | void updateCenter(User resources); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service; |
| | | |
| | | import me.zhengjie.domain.vo.EmailVo; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-26 |
| | | */ |
| | | public interface VerifyService { |
| | | |
| | | /** |
| | | * 发送验证码 |
| | | * @param email / |
| | | * @param key / |
| | | * @return / |
| | | */ |
| | | EmailVo sendEmail(String email, String key); |
| | | |
| | | |
| | | /** |
| | | * 验证 |
| | | * @param code / |
| | | * @param key / |
| | | */ |
| | | void validated(String key, String code); |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import com.fasterxml.jackson.annotation.JsonInclude; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.List; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DeptDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String name; |
| | | |
| | | private Boolean enabled; |
| | | |
| | | private Integer deptSort; |
| | | |
| | | @JsonInclude(JsonInclude.Include.NON_EMPTY) |
| | | private List<DeptDto> children; |
| | | |
| | | private Long pid; |
| | | |
| | | private Integer subCount; |
| | | |
| | | public Boolean getHasChildren() { |
| | | return subCount > 0; |
| | | } |
| | | |
| | | public Boolean getLeaf() { |
| | | return subCount <= 0; |
| | | } |
| | | |
| | | public String getLabel() { |
| | | return name; |
| | | } |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | DeptDto deptDto = (DeptDto) o; |
| | | return Objects.equals(id, deptDto.id) && |
| | | Objects.equals(name, deptDto.name); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id, name); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.DataPermission; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | @Data |
| | | @DataPermission(fieldName = "id") |
| | | public class DeptQueryCriteria{ |
| | | |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String name; |
| | | |
| | | @Query |
| | | private Boolean enabled; |
| | | |
| | | @Query |
| | | private Long pid; |
| | | |
| | | @Query(type = Query.Type.IS_NULL, propName = "pid") |
| | | private Boolean pidIsNull; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-10 16:32:18 |
| | | */ |
| | | @Data |
| | | public class DeptSmallDto implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String name; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DictDetailDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private DictSmallDto dict; |
| | | |
| | | private String label; |
| | | |
| | | private String value; |
| | | |
| | | private Integer dictSort; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Data |
| | | public class DictDetailQueryCriteria { |
| | | |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String label; |
| | | |
| | | @Query(propName = "name",joinName = "dict") |
| | | private String dictName; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DictDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private List<DictDetailDto> dictDetails; |
| | | |
| | | private String name; |
| | | |
| | | private String description; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 公共查询类 |
| | | */ |
| | | @Data |
| | | public class DictQueryCriteria { |
| | | |
| | | @Query(blurry = "name,description") |
| | | private String blurry; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class DictSmallDto implements Serializable { |
| | | |
| | | private Long id; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.NoArgsConstructor; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | @NoArgsConstructor |
| | | public class JobDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private Integer jobSort; |
| | | |
| | | private String name; |
| | | |
| | | private Boolean enabled; |
| | | |
| | | public JobDto(String name, Boolean enabled) { |
| | | this.name = name; |
| | | this.enabled = enabled; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-4 14:49:34 |
| | | */ |
| | | @Data |
| | | @NoArgsConstructor |
| | | public class JobQueryCriteria { |
| | | |
| | | @Query(type = Query.Type.INNER_LIKE) |
| | | private String name; |
| | | |
| | | @Query |
| | | private Boolean enabled; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-6-10 16:32:18 |
| | | */ |
| | | @Data |
| | | @NoArgsConstructor |
| | | public class JobSmallDto implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String name; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.List; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-12-17 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class MenuDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private List<MenuDto> children; |
| | | |
| | | private Integer type; |
| | | |
| | | private String permission; |
| | | |
| | | private String title; |
| | | |
| | | private Integer menuSort; |
| | | |
| | | private String path; |
| | | |
| | | private String component; |
| | | |
| | | private Long pid; |
| | | |
| | | private Integer subCount; |
| | | |
| | | private Boolean iFrame; |
| | | |
| | | private Boolean cache; |
| | | |
| | | private Boolean hidden; |
| | | |
| | | private String componentName; |
| | | |
| | | private String icon; |
| | | |
| | | public Boolean getHasChildren() { |
| | | return subCount > 0; |
| | | } |
| | | |
| | | public Boolean getLeaf() { |
| | | return subCount <= 0; |
| | | } |
| | | |
| | | public String getLabel() { |
| | | return title; |
| | | } |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | MenuDto menuDto = (MenuDto) o; |
| | | return Objects.equals(id, menuDto.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 公共查询类 |
| | | */ |
| | | @Data |
| | | public class MenuQueryCriteria { |
| | | |
| | | @Query(blurry = "title,component,permission") |
| | | private String blurry; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | |
| | | @Query(type = Query.Type.IS_NULL, propName = "pid") |
| | | private Boolean pidIsNull; |
| | | |
| | | @Query |
| | | private Long pid; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.Objects; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class RoleDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private Set<MenuDto> menus; |
| | | |
| | | private Set<DeptDto> depts; |
| | | |
| | | private String name; |
| | | |
| | | private String dataScope; |
| | | |
| | | private Integer level; |
| | | |
| | | private String description; |
| | | |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (this == o) { |
| | | return true; |
| | | } |
| | | if (o == null || getClass() != o.getClass()) { |
| | | return false; |
| | | } |
| | | RoleDto roleDto = (RoleDto) o; |
| | | return Objects.equals(id, roleDto.id); |
| | | } |
| | | |
| | | @Override |
| | | public int hashCode() { |
| | | return Objects.hash(id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | |
| | | import java.sql.Timestamp; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * 公共查询类 |
| | | */ |
| | | @Data |
| | | public class RoleQueryCriteria { |
| | | |
| | | @Query(blurry = "name,description") |
| | | private String blurry; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Data |
| | | public class RoleSmallDto implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private String name; |
| | | |
| | | private Integer level; |
| | | |
| | | private String dataScope; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import com.alibaba.fastjson.annotation.JSONField; |
| | | import lombok.Getter; |
| | | import lombok.Setter; |
| | | import me.zhengjie.base.BaseDTO; |
| | | import java.io.Serializable; |
| | | import java.util.Date; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Getter |
| | | @Setter |
| | | public class UserDto extends BaseDTO implements Serializable { |
| | | |
| | | private Long id; |
| | | |
| | | private Set<RoleSmallDto> roles; |
| | | |
| | | private Set<JobSmallDto> jobs; |
| | | |
| | | private DeptSmallDto dept; |
| | | |
| | | private Long deptId; |
| | | |
| | | private String username; |
| | | |
| | | private String nickName; |
| | | |
| | | private String email; |
| | | |
| | | private String phone; |
| | | |
| | | private String gender; |
| | | |
| | | private String avatarName; |
| | | |
| | | private String avatarPath; |
| | | |
| | | @JSONField(serialize = false) |
| | | private String password; |
| | | |
| | | private Boolean enabled; |
| | | |
| | | @JSONField(serialize = false) |
| | | private Boolean isAdmin = false; |
| | | |
| | | private Date pwdResetTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @description 用户缓存时使用 |
| | | * @date 2022-05-26 |
| | | **/ |
| | | public class UserLoginDto extends UserDto { |
| | | |
| | | private String password; |
| | | |
| | | private Boolean isAdmin; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.dto; |
| | | |
| | | import lombok.Data; |
| | | import me.zhengjie.annotation.Query; |
| | | import java.io.Serializable; |
| | | import java.sql.Timestamp; |
| | | import java.util.HashSet; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2018-11-23 |
| | | */ |
| | | @Data |
| | | public class UserQueryCriteria implements Serializable { |
| | | |
| | | @Query |
| | | private Long id; |
| | | |
| | | @Query(propName = "id", type = Query.Type.IN, joinName = "dept") |
| | | private Set<Long> deptIds = new HashSet<>(); |
| | | |
| | | @Query(blurry = "email,username,nickName") |
| | | private String blurry; |
| | | |
| | | @Query |
| | | private Boolean enabled; |
| | | |
| | | private Long deptId; |
| | | |
| | | @Query(type = Query.Type.BETWEEN) |
| | | private List<Timestamp> createTime; |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import me.zhengjie.modules.system.service.DataService; |
| | | import me.zhengjie.modules.system.service.DeptService; |
| | | import me.zhengjie.modules.system.service.RoleService; |
| | | import me.zhengjie.modules.system.service.dto.RoleSmallDto; |
| | | import me.zhengjie.modules.system.service.dto.UserDto; |
| | | import me.zhengjie.utils.enums.DataScopeEnum; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | import org.springframework.stereotype.Service; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @website https://eladmin.vip |
| | | * @description 数据权限服务实现 |
| | | * @date 2020-05-07 |
| | | **/ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "data") |
| | | public class DataServiceImpl implements DataService { |
| | | |
| | | private final RoleService roleService; |
| | | private final DeptService deptService; |
| | | |
| | | /** |
| | | * 用户角色和用户部门改变时需清理缓存 |
| | | * @param user / |
| | | * @return / |
| | | */ |
| | | @Override |
| | | @Cacheable(key = "'user:' + #p0.id") |
| | | public List<Long> getDeptIds(UserDto user) { |
| | | // 用于存储部门id |
| | | Set<Long> deptIds = new HashSet<>(); |
| | | // 查询用户角色 |
| | | List<RoleSmallDto> roleSet = roleService.findByUsersId(user.getId()); |
| | | // 获取对应的部门ID |
| | | for (RoleSmallDto role : roleSet) { |
| | | DataScopeEnum dataScopeEnum = DataScopeEnum.find(role.getDataScope()); |
| | | switch (Objects.requireNonNull(dataScopeEnum)) { |
| | | case THIS_LEVEL: |
| | | deptIds.add(user.getDept().getId()); |
| | | break; |
| | | case CUSTOMIZE: |
| | | deptIds.addAll(getCustomize(deptIds, role)); |
| | | break; |
| | | default: |
| | | return new ArrayList<>(deptIds); |
| | | } |
| | | } |
| | | return new ArrayList<>(deptIds); |
| | | } |
| | | |
| | | /** |
| | | * 获取自定义的数据权限 |
| | | * @param deptIds 部门ID |
| | | * @param role 角色 |
| | | * @return 数据权限ID |
| | | */ |
| | | public Set<Long> getCustomize(Set<Long> deptIds, RoleSmallDto role){ |
| | | Set<Dept> depts = deptService.findByRoleId(role.getId()); |
| | | for (Dept dept : depts) { |
| | | deptIds.add(dept.getId()); |
| | | List<Dept> deptChildren = deptService.findByPid(dept.getId()); |
| | | if (deptChildren != null && deptChildren.size() != 0) { |
| | | deptIds.addAll(deptService.getDeptChildren(deptChildren)); |
| | | } |
| | | } |
| | | return deptIds; |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.modules.system.domain.Dept; |
| | | import me.zhengjie.modules.system.domain.User; |
| | | import me.zhengjie.modules.system.repository.RoleRepository; |
| | | import me.zhengjie.modules.system.repository.UserRepository; |
| | | import me.zhengjie.modules.system.service.dto.DeptDto; |
| | | import me.zhengjie.modules.system.service.dto.DeptQueryCriteria; |
| | | import me.zhengjie.utils.*; |
| | | import me.zhengjie.modules.system.repository.DeptRepository; |
| | | import me.zhengjie.modules.system.service.DeptService; |
| | | import me.zhengjie.modules.system.service.mapstruct.DeptMapper; |
| | | import me.zhengjie.utils.enums.DataScopeEnum; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | import org.springframework.data.domain.Sort; |
| | | import org.springframework.stereotype.Service; |
| | | import org.springframework.transaction.annotation.Transactional; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.lang.reflect.Field; |
| | | import java.util.*; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-25 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "dept") |
| | | public class DeptServiceImpl implements DeptService { |
| | | |
| | | private final DeptRepository deptRepository; |
| | | private final DeptMapper deptMapper; |
| | | private final UserRepository userRepository; |
| | | private final RedisUtils redisUtils; |
| | | private final RoleRepository roleRepository; |
| | | |
| | | @Override |
| | | public List<DeptDto> queryAll(DeptQueryCriteria criteria, Boolean isQuery) throws Exception { |
| | | Sort sort = Sort.by(Sort.Direction.ASC, "deptSort"); |
| | | String dataScopeType = SecurityUtils.getDataScopeType(); |
| | | if (isQuery) { |
| | | if(dataScopeType.equals(DataScopeEnum.ALL.getValue())){ |
| | | criteria.setPidIsNull(true); |
| | | } |
| | | List<Field> fields = QueryHelp.getAllFields(criteria.getClass(), new ArrayList<>()); |
| | | List<String> fieldNames = new ArrayList<String>(){{ add("pidIsNull");add("enabled");}}; |
| | | for (Field field : fields) { |
| | | //设置对象的访问权限,保证对private的属性的访问 |
| | | field.setAccessible(true); |
| | | Object val = field.get(criteria); |
| | | if(fieldNames.contains(field.getName())){ |
| | | continue; |
| | | } |
| | | if (ObjectUtil.isNotNull(val)) { |
| | | criteria.setPidIsNull(null); |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | List<DeptDto> list = deptMapper.toDto(deptRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort)); |
| | | // 如果为空,就代表为自定义权限或者本级权限,就需要去重,不理解可以注释掉,看查询结果 |
| | | if(StringUtils.isBlank(dataScopeType)){ |
| | | return deduplication(list); |
| | | } |
| | | return list; |
| | | } |
| | | |
| | | @Override |
| | | @Cacheable(key = "'id:' + #p0") |
| | | public DeptDto findById(Long id) { |
| | | Dept dept = deptRepository.findById(id).orElseGet(Dept::new); |
| | | ValidationUtil.isNull(dept.getId(),"Dept","id",id); |
| | | return deptMapper.toDto(dept); |
| | | } |
| | | |
| | | @Override |
| | | public List<Dept> findByPid(long pid) { |
| | | return deptRepository.findByPid(pid); |
| | | } |
| | | |
| | | @Override |
| | | public Set<Dept> findByRoleId(Long id) { |
| | | return deptRepository.findByRoleId(id); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Dept resources) { |
| | | deptRepository.save(resources); |
| | | // 计算子节点数目 |
| | | resources.setSubCount(0); |
| | | // 清理缓存 |
| | | updateSubCnt(resources.getPid()); |
| | | // 清理自定义角色权限的datascope缓存 |
| | | delCaches(resources.getPid()); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Dept resources) { |
| | | // 旧的部门 |
| | | Long oldPid = findById(resources.getId()).getPid(); |
| | | Long newPid = resources.getPid(); |
| | | if(resources.getPid() != null && resources.getId().equals(resources.getPid())) { |
| | | throw new BadRequestException("上级不能为自己"); |
| | | } |
| | | Dept dept = deptRepository.findById(resources.getId()).orElseGet(Dept::new); |
| | | ValidationUtil.isNull( dept.getId(),"Dept","id",resources.getId()); |
| | | resources.setId(dept.getId()); |
| | | deptRepository.save(resources); |
| | | // 更新父节点中子节点数目 |
| | | updateSubCnt(oldPid); |
| | | updateSubCnt(newPid); |
| | | // 清理缓存 |
| | | delCaches(resources.getId()); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<DeptDto> deptDtos) { |
| | | for (DeptDto deptDto : deptDtos) { |
| | | // 清理缓存 |
| | | delCaches(deptDto.getId()); |
| | | deptRepository.deleteById(deptDto.getId()); |
| | | updateSubCnt(deptDto.getPid()); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<DeptDto> deptDtos, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (DeptDto deptDTO : deptDtos) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("部门名称", deptDTO.getName()); |
| | | map.put("部门状态", deptDTO.getEnabled() ? "启用" : "停用"); |
| | | map.put("创建日期", deptDTO.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | @Override |
| | | public Set<DeptDto> getDeleteDepts(List<Dept> menuList, Set<DeptDto> deptDtos) { |
| | | for (Dept dept : menuList) { |
| | | deptDtos.add(deptMapper.toDto(dept)); |
| | | List<Dept> depts = deptRepository.findByPid(dept.getId()); |
| | | if(depts!=null && depts.size()!=0){ |
| | | getDeleteDepts(depts, deptDtos); |
| | | } |
| | | } |
| | | return deptDtos; |
| | | } |
| | | |
| | | @Override |
| | | public List<Long> getDeptChildren(List<Dept> deptList) { |
| | | List<Long> list = new ArrayList<>(); |
| | | deptList.forEach(dept -> { |
| | | if (dept!=null && dept.getEnabled()) { |
| | | List<Dept> depts = deptRepository.findByPid(dept.getId()); |
| | | if (depts.size() != 0) { |
| | | list.addAll(getDeptChildren(depts)); |
| | | } |
| | | list.add(dept.getId()); |
| | | } |
| | | } |
| | | ); |
| | | return list; |
| | | } |
| | | |
| | | @Override |
| | | public List<DeptDto> getSuperior(DeptDto deptDto, List<Dept> depts) { |
| | | if(deptDto.getPid() == null){ |
| | | depts.addAll(deptRepository.findByPidIsNull()); |
| | | return deptMapper.toDto(depts); |
| | | } |
| | | depts.addAll(deptRepository.findByPid(deptDto.getPid())); |
| | | return getSuperior(findById(deptDto.getPid()), depts); |
| | | } |
| | | |
| | | @Override |
| | | public Object buildTree(List<DeptDto> deptDtos) { |
| | | Set<DeptDto> trees = new LinkedHashSet<>(); |
| | | Set<DeptDto> depts= new LinkedHashSet<>(); |
| | | List<String> deptNames = deptDtos.stream().map(DeptDto::getName).collect(Collectors.toList()); |
| | | boolean isChild; |
| | | for (DeptDto deptDTO : deptDtos) { |
| | | isChild = false; |
| | | if (deptDTO.getPid() == null) { |
| | | trees.add(deptDTO); |
| | | } |
| | | for (DeptDto it : deptDtos) { |
| | | if (it.getPid() != null && deptDTO.getId().equals(it.getPid())) { |
| | | isChild = true; |
| | | if (deptDTO.getChildren() == null) { |
| | | deptDTO.setChildren(new ArrayList<>()); |
| | | } |
| | | deptDTO.getChildren().add(it); |
| | | } |
| | | } |
| | | if(isChild) { |
| | | depts.add(deptDTO); |
| | | } else if(deptDTO.getPid() != null && !deptNames.contains(findById(deptDTO.getPid()).getName())) { |
| | | depts.add(deptDTO); |
| | | } |
| | | } |
| | | |
| | | if (CollectionUtil.isEmpty(trees)) { |
| | | trees = depts; |
| | | } |
| | | Map<String,Object> map = new HashMap<>(2); |
| | | map.put("totalElements",deptDtos.size()); |
| | | map.put("content",CollectionUtil.isEmpty(trees)? deptDtos :trees); |
| | | return map; |
| | | } |
| | | |
| | | @Override |
| | | public void verification(Set<DeptDto> deptDtos) { |
| | | Set<Long> deptIds = deptDtos.stream().map(DeptDto::getId).collect(Collectors.toSet()); |
| | | if(userRepository.countByDepts(deptIds) > 0){ |
| | | throw new BadRequestException("所选部门存在用户关联,请解除后再试!"); |
| | | } |
| | | if(roleRepository.countByDepts(deptIds) > 0){ |
| | | throw new BadRequestException("所选部门存在角色关联,请解除后再试!"); |
| | | } |
| | | } |
| | | |
| | | private void updateSubCnt(Long deptId){ |
| | | if(deptId != null){ |
| | | int count = deptRepository.countByPid(deptId); |
| | | deptRepository.updateSubCntById(count, deptId); |
| | | } |
| | | } |
| | | |
| | | private List<DeptDto> deduplication(List<DeptDto> list) { |
| | | List<DeptDto> deptDtos = new ArrayList<>(); |
| | | for (DeptDto deptDto : list) { |
| | | boolean flag = true; |
| | | for (DeptDto dto : list) { |
| | | if (dto.getId().equals(deptDto.getPid())) { |
| | | flag = false; |
| | | break; |
| | | } |
| | | } |
| | | if (flag){ |
| | | deptDtos.add(deptDto); |
| | | } |
| | | } |
| | | return deptDtos; |
| | | } |
| | | |
| | | /** |
| | | * 清理缓存 |
| | | * @param id / |
| | | */ |
| | | public void delCaches(Long id){ |
| | | List<User> users = userRepository.findByRoleDeptId(id); |
| | | // 删除数据权限 |
| | | redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(User::getId).collect(Collectors.toSet())); |
| | | redisUtils.del(CacheKey.DEPT_ID + id); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.system.domain.Dict; |
| | | import me.zhengjie.modules.system.domain.DictDetail; |
| | | import me.zhengjie.modules.system.repository.DictRepository; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria; |
| | | import me.zhengjie.utils.*; |
| | | import me.zhengjie.modules.system.repository.DictDetailRepository; |
| | | import me.zhengjie.modules.system.service.DictDetailService; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailDto; |
| | | import me.zhengjie.modules.system.service.mapstruct.DictDetailMapper; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | 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.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "dict") |
| | | public class DictDetailServiceImpl implements DictDetailService { |
| | | |
| | | private final DictRepository dictRepository; |
| | | private final DictDetailRepository dictDetailRepository; |
| | | private final DictDetailMapper dictDetailMapper; |
| | | private final RedisUtils redisUtils; |
| | | |
| | | @Override |
| | | public Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) { |
| | | Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(dictDetailMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(DictDetail resources) { |
| | | dictDetailRepository.save(resources); |
| | | // 清理缓存 |
| | | delCaches(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(DictDetail resources) { |
| | | DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new); |
| | | ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId()); |
| | | resources.setId(dictDetail.getId()); |
| | | dictDetailRepository.save(resources); |
| | | // 清理缓存 |
| | | delCaches(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Cacheable(key = "'name:' + #p0") |
| | | public List<DictDetailDto> getDictByName(String name) { |
| | | return dictDetailMapper.toDto(dictDetailRepository.findByDictName(name)); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Long id) { |
| | | DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new); |
| | | // 清理缓存 |
| | | delCaches(dictDetail); |
| | | dictDetailRepository.deleteById(id); |
| | | } |
| | | |
| | | public void delCaches(DictDetail dictDetail){ |
| | | Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new); |
| | | redisUtils.del(CacheKey.DICT_NAME + dict.getName()); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.system.domain.Dict; |
| | | import me.zhengjie.modules.system.service.dto.DictDetailDto; |
| | | import me.zhengjie.modules.system.service.dto.DictQueryCriteria; |
| | | import me.zhengjie.utils.*; |
| | | import me.zhengjie.modules.system.repository.DictRepository; |
| | | import me.zhengjie.modules.system.service.DictService; |
| | | import me.zhengjie.modules.system.service.dto.DictDto; |
| | | import me.zhengjie.modules.system.service.mapstruct.DictMapper; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-04-10 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "dict") |
| | | public class DictServiceImpl implements DictService { |
| | | |
| | | private final DictRepository dictRepository; |
| | | private final DictMapper dictMapper; |
| | | private final RedisUtils redisUtils; |
| | | |
| | | @Override |
| | | public Map<String, Object> queryAll(DictQueryCriteria dict, Pageable pageable){ |
| | | Page<Dict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable); |
| | | return PageUtil.toPage(page.map(dictMapper::toDto)); |
| | | } |
| | | |
| | | @Override |
| | | public List<DictDto> queryAll(DictQueryCriteria dict) { |
| | | List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb)); |
| | | return dictMapper.toDto(list); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Dict resources) { |
| | | dictRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Dict resources) { |
| | | // 清理缓存 |
| | | delCaches(resources); |
| | | Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new); |
| | | ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId()); |
| | | dict.setName(resources.getName()); |
| | | dict.setDescription(resources.getDescription()); |
| | | dictRepository.save(dict); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | // 清理缓存 |
| | | List<Dict> dicts = dictRepository.findByIdIn(ids); |
| | | for (Dict dict : dicts) { |
| | | delCaches(dict); |
| | | } |
| | | dictRepository.deleteByIdIn(ids); |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (DictDto dictDTO : dictDtos) { |
| | | if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){ |
| | | for (DictDetailDto dictDetail : dictDTO.getDictDetails()) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("字典名称", dictDTO.getName()); |
| | | map.put("字典描述", dictDTO.getDescription()); |
| | | map.put("字典标签", dictDetail.getLabel()); |
| | | map.put("字典值", dictDetail.getValue()); |
| | | map.put("创建日期", dictDetail.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | } else { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("字典名称", dictDTO.getName()); |
| | | map.put("字典描述", dictDTO.getDescription()); |
| | | map.put("字典标签", null); |
| | | map.put("字典值", null); |
| | | map.put("创建日期", dictDTO.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | public void delCaches(Dict dict){ |
| | | redisUtils.del(CacheKey.DICT_NAME + dict.getName()); |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.exception.EntityExistException; |
| | | import me.zhengjie.modules.system.domain.Job; |
| | | import me.zhengjie.modules.system.repository.UserRepository; |
| | | import me.zhengjie.modules.system.service.dto.JobQueryCriteria; |
| | | import me.zhengjie.utils.*; |
| | | import me.zhengjie.modules.system.repository.JobRepository; |
| | | import me.zhengjie.modules.system.service.JobService; |
| | | import me.zhengjie.modules.system.service.dto.JobDto; |
| | | import me.zhengjie.modules.system.service.mapstruct.JobMapper; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.CacheEvict; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | 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.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | * @date 2019-03-29 |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "job") |
| | | public class JobServiceImpl implements JobService { |
| | | |
| | | private final JobRepository jobRepository; |
| | | private final JobMapper jobMapper; |
| | | private final RedisUtils redisUtils; |
| | | private final UserRepository userRepository; |
| | | |
| | | @Override |
| | | public Map<String,Object> queryAll(JobQueryCriteria criteria, Pageable pageable) { |
| | | Page<Job> page = jobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); |
| | | return PageUtil.toPage(page.map(jobMapper::toDto).getContent(),page.getTotalElements()); |
| | | } |
| | | |
| | | @Override |
| | | public List<JobDto> queryAll(JobQueryCriteria criteria) { |
| | | List<Job> list = jobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)); |
| | | return jobMapper.toDto(list); |
| | | } |
| | | |
| | | @Override |
| | | @Cacheable(key = "'id:' + #p0") |
| | | public JobDto findById(Long id) { |
| | | Job job = jobRepository.findById(id).orElseGet(Job::new); |
| | | ValidationUtil.isNull(job.getId(),"Job","id",id); |
| | | return jobMapper.toDto(job); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Job resources) { |
| | | Job job = jobRepository.findByName(resources.getName()); |
| | | if(job != null){ |
| | | throw new EntityExistException(Job.class,"name",resources.getName()); |
| | | } |
| | | jobRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @CacheEvict(key = "'id:' + #p0.id") |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Job resources) { |
| | | Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new); |
| | | Job old = jobRepository.findByName(resources.getName()); |
| | | if(old != null && !old.getId().equals(resources.getId())){ |
| | | throw new EntityExistException(Job.class,"name",resources.getName()); |
| | | } |
| | | ValidationUtil.isNull( job.getId(),"Job","id",resources.getId()); |
| | | resources.setId(job.getId()); |
| | | jobRepository.save(resources); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Long> ids) { |
| | | jobRepository.deleteAllByIdIn(ids); |
| | | // 删除缓存 |
| | | redisUtils.delByKeys(CacheKey.JOB_ID, ids); |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<JobDto> jobDtos, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (JobDto jobDTO : jobDtos) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("岗位名称", jobDTO.getName()); |
| | | map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用"); |
| | | map.put("创建日期", jobDTO.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | @Override |
| | | public void verification(Set<Long> ids) { |
| | | if(userRepository.countByJobs(ids) > 0){ |
| | | throw new BadRequestException("所选的岗位中存在用户关联,请解除关联再试!"); |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | /* |
| | | * Copyright 2019-2020 Zheng Jie |
| | | * |
| | | * Licensed under the Apache License, Version 2.0 (the "License"); |
| | | * you may not use this file except in compliance with the License. |
| | | * You may obtain a copy of the License at |
| | | * |
| | | * http://www.apache.org/licenses/LICENSE-2.0 |
| | | * |
| | | * Unless required by applicable law or agreed to in writing, software |
| | | * distributed under the License is distributed on an "AS IS" BASIS, |
| | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | * See the License for the specific language governing permissions and |
| | | * limitations under the License. |
| | | */ |
| | | package me.zhengjie.modules.system.service.impl; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import lombok.RequiredArgsConstructor; |
| | | import me.zhengjie.modules.system.domain.Menu; |
| | | import me.zhengjie.modules.system.domain.Role; |
| | | import me.zhengjie.modules.system.domain.User; |
| | | import me.zhengjie.modules.system.domain.vo.MenuMetaVo; |
| | | import me.zhengjie.modules.system.domain.vo.MenuVo; |
| | | import me.zhengjie.exception.BadRequestException; |
| | | import me.zhengjie.exception.EntityExistException; |
| | | import me.zhengjie.modules.system.repository.MenuRepository; |
| | | import me.zhengjie.modules.system.repository.UserRepository; |
| | | import me.zhengjie.modules.system.service.MenuService; |
| | | import me.zhengjie.modules.system.service.RoleService; |
| | | import me.zhengjie.modules.system.service.dto.MenuDto; |
| | | import me.zhengjie.modules.system.service.dto.MenuQueryCriteria; |
| | | import me.zhengjie.modules.system.service.dto.RoleSmallDto; |
| | | import me.zhengjie.modules.system.service.mapstruct.MenuMapper; |
| | | import me.zhengjie.utils.*; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | import org.springframework.data.domain.Sort; |
| | | import org.springframework.stereotype.Service; |
| | | import org.springframework.transaction.annotation.Transactional; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | | import java.lang.reflect.Field; |
| | | import java.util.*; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author Zheng Jie |
| | | */ |
| | | @Service |
| | | @RequiredArgsConstructor |
| | | @CacheConfig(cacheNames = "menu") |
| | | public class MenuServiceImpl implements MenuService { |
| | | |
| | | private final MenuRepository menuRepository; |
| | | private final UserRepository userRepository; |
| | | private final MenuMapper menuMapper; |
| | | private final RoleService roleService; |
| | | private final RedisUtils redisUtils; |
| | | |
| | | private static final String HTTP_PRE = "http://"; |
| | | private static final String HTTPS_PRE = "https://"; |
| | | private static final String YES_STR = "是"; |
| | | private static final String NO_STR = "否"; |
| | | private static final String BAD_REQUEST = "外链必须以http://或者https://开头"; |
| | | |
| | | @Override |
| | | public List<MenuDto> queryAll(MenuQueryCriteria criteria, Boolean isQuery) throws Exception { |
| | | Sort sort = Sort.by(Sort.Direction.ASC, "menuSort"); |
| | | if(Boolean.TRUE.equals(isQuery)){ |
| | | criteria.setPidIsNull(true); |
| | | List<Field> fields = QueryHelp.getAllFields(criteria.getClass(), new ArrayList<>()); |
| | | for (Field field : fields) { |
| | | //设置对象的访问权限,保证对private的属性的访问 |
| | | field.setAccessible(true); |
| | | Object val = field.get(criteria); |
| | | if("pidIsNull".equals(field.getName())){ |
| | | continue; |
| | | } |
| | | if (ObjectUtil.isNotNull(val)) { |
| | | criteria.setPidIsNull(null); |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | return menuMapper.toDto(menuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort)); |
| | | } |
| | | |
| | | @Override |
| | | @Cacheable(key = "'id:' + #p0") |
| | | public MenuDto findById(long id) { |
| | | Menu menu = menuRepository.findById(id).orElseGet(Menu::new); |
| | | ValidationUtil.isNull(menu.getId(),"Menu","id",id); |
| | | return menuMapper.toDto(menu); |
| | | } |
| | | |
| | | /** |
| | | * 用户角色改变时需清理缓存 |
| | | * @param currentUserId / |
| | | * @return / |
| | | */ |
| | | @Override |
| | | @Cacheable(key = "'user:' + #p0") |
| | | public List<MenuDto> findByUser(Long currentUserId) { |
| | | List<RoleSmallDto> roles = roleService.findByUsersId(currentUserId); |
| | | Set<Long> roleIds = roles.stream().map(RoleSmallDto::getId).collect(Collectors.toSet()); |
| | | LinkedHashSet<Menu> menus = menuRepository.findByRoleIdsAndTypeNot(roleIds, 2); |
| | | return menus.stream().map(menuMapper::toDto).collect(Collectors.toList()); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void create(Menu resources) { |
| | | if(menuRepository.findByTitle(resources.getTitle()) != null){ |
| | | throw new EntityExistException(Menu.class,"title",resources.getTitle()); |
| | | } |
| | | if(StringUtils.isNotBlank(resources.getComponentName())){ |
| | | if(menuRepository.findByComponentName(resources.getComponentName()) != null){ |
| | | throw new EntityExistException(Menu.class,"componentName",resources.getComponentName()); |
| | | } |
| | | } |
| | | if (Long.valueOf(0L).equals(resources.getPid())) { |
| | | resources.setPid(null); |
| | | } |
| | | if(resources.getIFrame()){ |
| | | if (!(resources.getPath().toLowerCase().startsWith(HTTP_PRE)||resources.getPath().toLowerCase().startsWith(HTTPS_PRE))) { |
| | | throw new BadRequestException(BAD_REQUEST); |
| | | } |
| | | } |
| | | menuRepository.save(resources); |
| | | // 计算子节点数目 |
| | | resources.setSubCount(0); |
| | | // 更新父节点菜单数目 |
| | | updateSubCnt(resources.getPid()); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void update(Menu resources) { |
| | | if(resources.getId().equals(resources.getPid())) { |
| | | throw new BadRequestException("上级不能为自己"); |
| | | } |
| | | Menu menu = menuRepository.findById(resources.getId()).orElseGet(Menu::new); |
| | | ValidationUtil.isNull(menu.getId(),"Permission","id",resources.getId()); |
| | | |
| | | if(resources.getIFrame()){ |
| | | if (!(resources.getPath().toLowerCase().startsWith(HTTP_PRE)||resources.getPath().toLowerCase().startsWith(HTTPS_PRE))) { |
| | | throw new BadRequestException(BAD_REQUEST); |
| | | } |
| | | } |
| | | Menu menu1 = menuRepository.findByTitle(resources.getTitle()); |
| | | |
| | | if(menu1 != null && !menu1.getId().equals(menu.getId())){ |
| | | throw new EntityExistException(Menu.class,"title",resources.getTitle()); |
| | | } |
| | | |
| | | if(resources.getPid().equals(0L)){ |
| | | resources.setPid(null); |
| | | } |
| | | |
| | | // 记录的父节点ID |
| | | Long oldPid = menu.getPid(); |
| | | Long newPid = resources.getPid(); |
| | | |
| | | if(StringUtils.isNotBlank(resources.getComponentName())){ |
| | | menu1 = menuRepository.findByComponentName(resources.getComponentName()); |
| | | if(menu1 != null && !menu1.getId().equals(menu.getId())){ |
| | | throw new EntityExistException(Menu.class,"componentName",resources.getComponentName()); |
| | | } |
| | | } |
| | | menu.setTitle(resources.getTitle()); |
| | | menu.setComponent(resources.getComponent()); |
| | | menu.setPath(resources.getPath()); |
| | | menu.setIcon(resources.getIcon()); |
| | | menu.setIFrame(resources.getIFrame()); |
| | | menu.setPid(resources.getPid()); |
| | | menu.setMenuSort(resources.getMenuSort()); |
| | | menu.setCache(resources.getCache()); |
| | | menu.setHidden(resources.getHidden()); |
| | | menu.setComponentName(resources.getComponentName()); |
| | | menu.setPermission(resources.getPermission()); |
| | | menu.setType(resources.getType()); |
| | | menuRepository.save(menu); |
| | | // 计算父级菜单节点数目 |
| | | updateSubCnt(oldPid); |
| | | updateSubCnt(newPid); |
| | | // 清理缓存 |
| | | delCaches(resources.getId()); |
| | | } |
| | | |
| | | @Override |
| | | public Set<Menu> getChildMenus(List<Menu> menuList, Set<Menu> menuSet) { |
| | | for (Menu menu : menuList) { |
| | | menuSet.add(menu); |
| | | List<Menu> menus = menuRepository.findByPidOrderByMenuSort(menu.getId()); |
| | | if(menus!=null && menus.size()!=0){ |
| | | getChildMenus(menus, menuSet); |
| | | } |
| | | } |
| | | return menuSet; |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void delete(Set<Menu> menuSet) { |
| | | for (Menu menu : menuSet) { |
| | | // 清理缓存 |
| | | delCaches(menu.getId()); |
| | | roleService.untiedMenu(menu.getId()); |
| | | menuRepository.deleteById(menu.getId()); |
| | | updateSubCnt(menu.getPid()); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public List<MenuDto> getMenus(Long pid) { |
| | | List<Menu> menus; |
| | | if(pid != null && !pid.equals(0L)){ |
| | | menus = menuRepository.findByPidOrderByMenuSort(pid); |
| | | } else { |
| | | menus = menuRepository.findByPidIsNullOrderByMenuSort(); |
| | | } |
| | | return menuMapper.toDto(menus); |
| | | } |
| | | |
| | | @Override |
| | | public List<MenuDto> getSuperior(MenuDto menuDto, List<Menu> menus) { |
| | | if(menuDto.getPid() == null){ |
| | | menus.addAll(menuRepository.findByPidIsNullOrderByMenuSort()); |
| | | return menuMapper.toDto(menus); |
| | | } |
| | | menus.addAll(menuRepository.findByPidOrderByMenuSort(menuDto.getPid())); |
| | | return getSuperior(findById(menuDto.getPid()), menus); |
| | | } |
| | | |
| | | @Override |
| | | public List<MenuDto> buildTree(List<MenuDto> menuDtos) { |
| | | List<MenuDto> trees = new ArrayList<>(); |
| | | Set<Long> ids = new HashSet<>(); |
| | | for (MenuDto menuDTO : menuDtos) { |
| | | if (menuDTO.getPid() == null) { |
| | | trees.add(menuDTO); |
| | | } |
| | | for (MenuDto it : menuDtos) { |
| | | if (menuDTO.getId().equals(it.getPid())) { |
| | | if (menuDTO.getChildren() == null) { |
| | | menuDTO.setChildren(new ArrayList<>()); |
| | | } |
| | | menuDTO.getChildren().add(it); |
| | | ids.add(it.getId()); |
| | | } |
| | | } |
| | | } |
| | | if(trees.size() == 0){ |
| | | trees = menuDtos.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList()); |
| | | } |
| | | return trees; |
| | | } |
| | | |
| | | @Override |
| | | public List<MenuVo> buildMenus(List<MenuDto> menuDtos) { |
| | | List<MenuVo> list = new LinkedList<>(); |
| | | menuDtos.forEach(menuDTO -> { |
| | | if (menuDTO!=null){ |
| | | List<MenuDto> menuDtoList = menuDTO.getChildren(); |
| | | MenuVo menuVo = new MenuVo(); |
| | | menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getTitle()); |
| | | // 一级目录需要加斜杠,不然会报警告 |
| | | menuVo.setPath(menuDTO.getPid() == null ? "/" + menuDTO.getPath() :menuDTO.getPath()); |
| | | menuVo.setHidden(menuDTO.getHidden()); |
| | | // 如果不是外链 |
| | | if(!menuDTO.getIFrame()){ |
| | | if(menuDTO.getPid() == null){ |
| | | menuVo.setComponent(StringUtils.isEmpty(menuDTO.getComponent())?"Layout":menuDTO.getComponent()); |
| | | // 如果不是一级菜单,并且菜单类型为目录,则代表是多级菜单 |
| | | }else if(menuDTO.getType() == 0){ |
| | | menuVo.setComponent(StringUtils.isEmpty(menuDTO.getComponent())?"ParentView":menuDTO.getComponent()); |
| | | }else if(StringUtils.isNoneBlank(menuDTO.getComponent())){ |
| | | menuVo.setComponent(menuDTO.getComponent()); |
| | | } |
| | | } |
| | | menuVo.setMeta(new MenuMetaVo(menuDTO.getTitle(),menuDTO.getIcon(),!menuDTO.getCache())); |
| | | if(CollectionUtil.isNotEmpty(menuDtoList)){ |
| | | menuVo.setAlwaysShow(true); |
| | | menuVo.setRedirect("noredirect"); |
| | | menuVo.setChildren(buildMenus(menuDtoList)); |
| | | // 处理是一级菜单并且没有子菜单的情况 |
| | | } else if(menuDTO.getPid() == null){ |
| | | MenuVo menuVo1 = new MenuVo(); |
| | | menuVo1.setMeta(menuVo.getMeta()); |
| | | // 非外链 |
| | | if(!menuDTO.getIFrame()){ |
| | | menuVo1.setPath("index"); |
| | | menuVo1.setName(menuVo.getName()); |
| | | menuVo1.setComponent(menuVo.getComponent()); |
| | | } else { |
| | | menuVo1.setPath(menuDTO.getPath()); |
| | | } |
| | | menuVo.setName(null); |
| | | menuVo.setMeta(null); |
| | | menuVo.setComponent("Layout"); |
| | | List<MenuVo> list1 = new ArrayList<>(); |
| | | list1.add(menuVo1); |
| | | menuVo.setChildren(list1); |
| | | } |
| | | list.add(menuVo); |
| | | } |
| | | } |
| | | ); |
| | | return list; |
| | | } |
| | | |
| | | @Override |
| | | public Menu findOne(Long id) { |
| | | Menu menu = menuRepository.findById(id).orElseGet(Menu::new); |
| | | ValidationUtil.isNull(menu.getId(),"Menu","id",id); |
| | | return menu; |
| | | } |
| | | |
| | | @Override |
| | | public void download(List<MenuDto> menuDtos, HttpServletResponse response) throws IOException { |
| | | List<Map<String, Object>> list = new ArrayList<>(); |
| | | for (MenuDto menuDTO : menuDtos) { |
| | | Map<String,Object> map = new LinkedHashMap<>(); |
| | | map.put("菜单标题", menuDTO.getTitle()); |
| | | map.put("菜单类型", menuDTO.getType() == null ? "目录" : menuDTO.getType() == 1 ? "菜单" : "按钮"); |
| | | map.put("权限标识", menuDTO.getPermission()); |
| | | map.put("外链菜单", menuDTO.getIFrame() ? YES_STR : NO_STR); |
| | | map.put("菜单可见", menuDTO.getHidden() ? NO_STR : YES_STR); |
| | | map.put("是否缓存", menuDTO.getCache() ? YES_STR : NO_STR); |
| | | map.put("创建日期", menuDTO.getCreateTime()); |
| | | list.add(map); |
| | | } |
| | | FileUtil.downloadExcel(list, response); |
| | | } |
| | | |
| | | private void updateSubCnt(Long menuId){ |
| | | if(menuId != null){ |
| | | int count = menuRepository.countByPid(menuId); |
| | | menuRepository.updateSubCntById(count, menuId); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 清理缓存 |
| | | * @param id 菜单ID |
| | | */ |
| | | public void delCaches(Long id){ |
| | | List<User> users = userRepository.findByMenuId(id); |
| | | redisUtils.del(CacheKey.MENU_ID + id); |
| | | redisUtils.delByKeys(CacheKey.MENU_USER, users.stream().map(User::getId).collect(Collectors.toSet())); |
| | | // 清除 Role 缓存 |
| | | List<Role> roles = roleService.findInMenuId(new ArrayList<Long>(){{ |
| | | add(id); |
| | | }}); |
| | | redisUtils.delByKeys(CacheKey.ROLE_ID, roles.stream().map(Role::getId).collect(Collectors.toSet())); |
| | | } |
| | | } |
| eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/MonitorServiceImpl.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/RoleServiceImpl.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/VerifyServiceImpl.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/DeptMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/DeptSmallMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/DictDetailMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/DictMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/DictSmallMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/JobMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/JobSmallMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/MenuMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/RoleMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/RoleSmallMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/UserLoginMapper.java
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/mapstruct/UserMapper.java
eladmin-master/eladmin-system/src/main/resources/banner.txt
eladmin-master/eladmin-system/src/main/resources/config/application-dev.yml
eladmin-master/eladmin-system/src/main/resources/config/application-prod.yml
eladmin-master/eladmin-system/src/main/resources/config/application.yml
eladmin-master/eladmin-system/src/main/resources/generator.properties
eladmin-master/eladmin-system/src/main/resources/log4jdbc.log4j2.properties
eladmin-master/eladmin-system/src/main/resources/logback.xml
eladmin-master/eladmin-system/src/main/resources/template/email/email.ftl
eladmin-master/eladmin-system/src/main/resources/template/email/taskAlarm.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Controller.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Dto.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Entity.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Mapper.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/QueryCriteria.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Repository.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/Service.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/admin/ServiceImpl.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/front/api.ftl
eladmin-master/eladmin-system/src/main/resources/template/generator/front/index.ftl
eladmin-master/eladmin-system/src/test/java/me/zhengjie/EladminSystemApplicationTests.java
eladmin-master/eladmin-tools/pom.xml
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/config/MultipartConfig.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/AlipayConfig.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/EmailConfig.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/LocalStorage.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuConfig.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuContent.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/vo/EmailVo.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/domain/vo/TradeVo.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/repository/AliPayRepository.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/repository/EmailRepository.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/repository/LocalStorageRepository.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/repository/QiNiuConfigRepository.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/repository/QiniuContentRepository.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/rest/EmailController.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/rest/LocalStorageController.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/rest/QiniuController.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/AliPayService.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/EmailService.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/LocalStorageService.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/dto/LocalStorageDto.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/dto/LocalStorageQueryCriteria.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/dto/PictureQueryCriteria.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/dto/QiniuQueryCriteria.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/impl/AliPayServiceImpl.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/service/mapstruct/LocalStorageMapper.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/utils/AliPayStatusEnum.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/utils/AlipayUtils.java
eladmin-master/eladmin-tools/src/main/java/me/zhengjie/utils/QiNiuUtil.java
eladmin-master/pom.xml
eladmin-master/sql/eladmin.sql
eladmin-master/sql/tool_picture.sql
eladmin-master/sql/脚本如何选择.md
eladmin-web-master/.editorconfig
eladmin-web-master/.env.development
eladmin-web-master/.env.production
eladmin-web-master/.eslintignore
eladmin-web-master/.eslintrc.js
eladmin-web-master/.gitignore
eladmin-web-master/.travis.yml
eladmin-web-master/LICENSE
eladmin-web-master/README.md
eladmin-web-master/babel.config.js
eladmin-web-master/jest.config.js
eladmin-web-master/package.json
eladmin-web-master/plopfile.js
eladmin-web-master/postcss.config.js
eladmin-web-master/public/favicon.ico
eladmin-web-master/public/index.html
eladmin-web-master/public/robots.txt
eladmin-web-master/src/App.vue
eladmin-web-master/src/api/data.js
eladmin-web-master/src/api/generator/genConfig.js
eladmin-web-master/src/api/generator/generator.js
eladmin-web-master/src/api/login.js
eladmin-web-master/src/api/mnt/app.js
eladmin-web-master/src/api/mnt/connect.js
eladmin-web-master/src/api/mnt/database.js
eladmin-web-master/src/api/mnt/deploy.js
eladmin-web-master/src/api/mnt/deployHistory.js
eladmin-web-master/src/api/mnt/serverDeploy.js
eladmin-web-master/src/api/monitor/log.js
eladmin-web-master/src/api/monitor/online.js
eladmin-web-master/src/api/system/code.js
eladmin-web-master/src/api/system/dept.js
eladmin-web-master/src/api/system/dict.js
eladmin-web-master/src/api/system/dictDetail.js
eladmin-web-master/src/api/system/job.js
eladmin-web-master/src/api/system/menu.js
eladmin-web-master/src/api/system/role.js
eladmin-web-master/src/api/system/timing.js
eladmin-web-master/src/api/system/user.js
eladmin-web-master/src/api/tools/alipay.js
eladmin-web-master/src/api/tools/email.js
eladmin-web-master/src/api/tools/localStorage.js
eladmin-web-master/src/api/tools/qiniu.js
eladmin-web-master/src/assets/401_images/401.gif
eladmin-web-master/src/assets/404_images/404.png
eladmin-web-master/src/assets/404_images/404_cloud.png
eladmin-web-master/src/assets/icons/index.js
eladmin-web-master/src/assets/icons/svg/Steve-Jobs.svg
eladmin-web-master/src/assets/icons/svg/alipay.svg
eladmin-web-master/src/assets/icons/svg/anq.svg
eladmin-web-master/src/assets/icons/svg/app.svg
eladmin-web-master/src/assets/icons/svg/backup.svg
eladmin-web-master/src/assets/icons/svg/blog.svg
eladmin-web-master/src/assets/icons/svg/chain.svg
eladmin-web-master/src/assets/icons/svg/chart.svg
eladmin-web-master/src/assets/icons/svg/codeConsole.svg
eladmin-web-master/src/assets/icons/svg/dashboard.svg
eladmin-web-master/src/assets/icons/svg/database.svg
eladmin-web-master/src/assets/icons/svg/date.svg
eladmin-web-master/src/assets/icons/svg/deploy.svg
eladmin-web-master/src/assets/icons/svg/dept.svg
eladmin-web-master/src/assets/icons/svg/dev.svg
eladmin-web-master/src/assets/icons/svg/develop.svg
eladmin-web-master/src/assets/icons/svg/dictionary.svg
eladmin-web-master/src/assets/icons/svg/doc.svg
eladmin-web-master/src/assets/icons/svg/download.svg
eladmin-web-master/src/assets/icons/svg/edit.svg
eladmin-web-master/src/assets/icons/svg/education.svg
eladmin-web-master/src/assets/icons/svg/email.svg
eladmin-web-master/src/assets/icons/svg/error.svg
eladmin-web-master/src/assets/icons/svg/exit-fullscreen.svg
eladmin-web-master/src/assets/icons/svg/fullscreen.svg
eladmin-web-master/src/assets/icons/svg/fwb.svg
eladmin-web-master/src/assets/icons/svg/github.svg
eladmin-web-master/src/assets/icons/svg/gonggao.svg
eladmin-web-master/src/assets/icons/svg/icon.svg
eladmin-web-master/src/assets/icons/svg/image.svg
eladmin-web-master/src/assets/icons/svg/index.svg
eladmin-web-master/src/assets/icons/svg/international.svg
eladmin-web-master/src/assets/icons/svg/ipvisits.svg
eladmin-web-master/src/assets/icons/svg/java.svg
eladmin-web-master/src/assets/icons/svg/link.svg
eladmin-web-master/src/assets/icons/svg/list.svg
eladmin-web-master/src/assets/icons/svg/lock.svg
eladmin-web-master/src/assets/icons/svg/log.svg
eladmin-web-master/src/assets/icons/svg/login.svg
eladmin-web-master/src/assets/icons/svg/markdown.svg
eladmin-web-master/src/assets/icons/svg/menu.svg
eladmin-web-master/src/assets/icons/svg/message.svg
eladmin-web-master/src/assets/icons/svg/mnt.svg
eladmin-web-master/src/assets/icons/svg/money.svg
eladmin-web-master/src/assets/icons/svg/monitor.svg
eladmin-web-master/src/assets/icons/svg/nested.svg
eladmin-web-master/src/assets/icons/svg/password.svg
eladmin-web-master/src/assets/icons/svg/people.svg
eladmin-web-master/src/assets/icons/svg/peoples.svg
eladmin-web-master/src/assets/icons/svg/permission.svg
eladmin-web-master/src/assets/icons/svg/phone.svg
eladmin-web-master/src/assets/icons/svg/qiniu.svg
eladmin-web-master/src/assets/icons/svg/redis.svg
eladmin-web-master/src/assets/icons/svg/role.svg
eladmin-web-master/src/assets/icons/svg/search.svg
eladmin-web-master/src/assets/icons/svg/server.svg
eladmin-web-master/src/assets/icons/svg/shopping.svg
eladmin-web-master/src/assets/icons/svg/size.svg
eladmin-web-master/src/assets/icons/svg/skill.svg
eladmin-web-master/src/assets/icons/svg/source.svg
eladmin-web-master/src/assets/icons/svg/sqlMonitor.svg
eladmin-web-master/src/assets/icons/svg/swagger.svg
eladmin-web-master/src/assets/icons/svg/sys-tools.svg
eladmin-web-master/src/assets/icons/svg/system.svg
eladmin-web-master/src/assets/icons/svg/system1.svg
eladmin-web-master/src/assets/icons/svg/tab.svg
eladmin-web-master/src/assets/icons/svg/theme.svg
eladmin-web-master/src/assets/icons/svg/timing.svg
eladmin-web-master/src/assets/icons/svg/tools.svg
eladmin-web-master/src/assets/icons/svg/tree-table.svg
eladmin-web-master/src/assets/icons/svg/tree.svg
eladmin-web-master/src/assets/icons/svg/unlock.svg
eladmin-web-master/src/assets/icons/svg/user.svg
eladmin-web-master/src/assets/icons/svg/user1.svg
eladmin-web-master/src/assets/icons/svg/validCode.svg
eladmin-web-master/src/assets/icons/svg/visits.svg
eladmin-web-master/src/assets/icons/svg/web.svg
eladmin-web-master/src/assets/icons/svg/wechat.svg
eladmin-web-master/src/assets/icons/svg/weixin.svg
eladmin-web-master/src/assets/icons/svg/zujian.svg
eladmin-web-master/src/assets/icons/svgo.yml
eladmin-web-master/src/assets/images/avatar.png
eladmin-web-master/src/assets/images/background.webp
eladmin-web-master/src/assets/images/logo.png
eladmin-web-master/src/assets/styles/btn.scss
eladmin-web-master/src/assets/styles/eladmin.scss
eladmin-web-master/src/assets/styles/element-ui.scss
eladmin-web-master/src/assets/styles/element-variables.scss
eladmin-web-master/src/assets/styles/index.scss
eladmin-web-master/src/assets/styles/mixin.scss
eladmin-web-master/src/assets/styles/sidebar.scss
eladmin-web-master/src/assets/styles/transition.scss
eladmin-web-master/src/assets/styles/variables.scss
eladmin-web-master/src/components/Breadcrumb/index.vue
eladmin-web-master/src/components/Crud/CRUD.operation.vue
eladmin-web-master/src/components/Crud/Pagination.vue
eladmin-web-master/src/components/Crud/RR.operation.vue
eladmin-web-master/src/components/Crud/UD.operation.vue
eladmin-web-master/src/components/Crud/crud.js
eladmin-web-master/src/components/DateRangePicker/index.vue
eladmin-web-master/src/components/Dict/Dict.js
eladmin-web-master/src/components/Dict/index.js
eladmin-web-master/src/components/Doc/index.vue
eladmin-web-master/src/components/Echarts/BarChart.vue
eladmin-web-master/src/components/Echarts/Category.vue
eladmin-web-master/src/components/Echarts/Funnel.vue
eladmin-web-master/src/components/Echarts/Gauge.vue
eladmin-web-master/src/components/Echarts/Graph.vue
eladmin-web-master/src/components/Echarts/HeatMap.vue
eladmin-web-master/src/components/Echarts/PieChart.vue
eladmin-web-master/src/components/Echarts/Point.vue
eladmin-web-master/src/components/Echarts/RadarChart.vue
eladmin-web-master/src/components/Echarts/Rich.vue
eladmin-web-master/src/components/Echarts/Sankey.vue
eladmin-web-master/src/components/Echarts/Scatter.vue
eladmin-web-master/src/components/Echarts/Sunburst.vue
eladmin-web-master/src/components/Echarts/ThemeRiver.vue
eladmin-web-master/src/components/GithubCorner/index.vue
eladmin-web-master/src/components/Hamburger/index.vue
eladmin-web-master/src/components/HeaderSearch/index.vue
eladmin-web-master/src/components/IconSelect/index.vue
eladmin-web-master/src/components/IconSelect/requireIcons.js
eladmin-web-master/src/components/Iframe/index.vue
eladmin-web-master/src/components/JavaEdit/index.vue
eladmin-web-master/src/components/Pagination/index.vue
eladmin-web-master/src/components/PanThumb/index.vue
eladmin-web-master/src/components/ParentView/index.vue
eladmin-web-master/src/components/Permission/index.js
eladmin-web-master/src/components/Permission/permission.js
eladmin-web-master/src/components/RightPanel/index.vue
eladmin-web-master/src/components/Screenfull/index.vue
eladmin-web-master/src/components/SizeSelect/index.vue
eladmin-web-master/src/components/SvgIcon/index.vue
eladmin-web-master/src/components/ThemePicker/index.vue
eladmin-web-master/src/components/UploadExcel/index.vue
eladmin-web-master/src/components/YamlEdit/index.vue
eladmin-web-master/src/layout/components/AppMain.vue
eladmin-web-master/src/layout/components/Navbar.vue
eladmin-web-master/src/layout/components/Settings/index.vue
eladmin-web-master/src/layout/components/Sidebar/FixiOSBug.js
eladmin-web-master/src/layout/components/Sidebar/Item.vue
eladmin-web-master/src/layout/components/Sidebar/Link.vue
eladmin-web-master/src/layout/components/Sidebar/Logo.vue
eladmin-web-master/src/layout/components/Sidebar/SidebarItem.vue
eladmin-web-master/src/layout/components/Sidebar/index.vue
eladmin-web-master/src/layout/components/TagsView/ScrollPane.vue
eladmin-web-master/src/layout/components/TagsView/index.vue
eladmin-web-master/src/layout/components/index.js
eladmin-web-master/src/layout/index.vue
eladmin-web-master/src/layout/mixin/ResizeHandler.js
eladmin-web-master/src/main.js
eladmin-web-master/src/mixins/crud.js
eladmin-web-master/src/router/index.js
eladmin-web-master/src/router/routers.js
eladmin-web-master/src/settings.js
eladmin-web-master/src/store/getters.js
eladmin-web-master/src/store/index.js
eladmin-web-master/src/store/modules/api.js
eladmin-web-master/src/store/modules/app.js
eladmin-web-master/src/store/modules/permission.js
eladmin-web-master/src/store/modules/settings.js
eladmin-web-master/src/store/modules/tagsView.js
eladmin-web-master/src/store/modules/user.js
eladmin-web-master/src/utils/auth.js
eladmin-web-master/src/utils/clipboard.js
eladmin-web-master/src/utils/datetime.js
eladmin-web-master/src/utils/index.js
eladmin-web-master/src/utils/permission.js
eladmin-web-master/src/utils/request.js
eladmin-web-master/src/utils/rsaEncrypt.js
eladmin-web-master/src/utils/shortcuts.js
eladmin-web-master/src/utils/upload.js
eladmin-web-master/src/utils/validate.js
eladmin-web-master/src/views/components/Echarts.vue
eladmin-web-master/src/views/components/Editor.vue
eladmin-web-master/src/views/components/MarkDown.vue
eladmin-web-master/src/views/components/YamlEdit.vue
eladmin-web-master/src/views/components/excel/upload-excel.vue
eladmin-web-master/src/views/components/icons/element-icons.js
eladmin-web-master/src/views/components/icons/index.vue
eladmin-web-master/src/views/components/icons/svg-icons.js
eladmin-web-master/src/views/dashboard/LineChart.vue
eladmin-web-master/src/views/dashboard/PanelGroup.vue
eladmin-web-master/src/views/dashboard/mixins/resize.js
eladmin-web-master/src/views/features/401.vue
eladmin-web-master/src/views/features/404.vue
eladmin-web-master/src/views/features/redirect.vue
eladmin-web-master/src/views/generator/config.vue
eladmin-web-master/src/views/generator/index.vue
eladmin-web-master/src/views/generator/preview.vue
eladmin-web-master/src/views/home.vue
eladmin-web-master/src/views/login.vue
eladmin-web-master/src/views/mnt/app/index.vue
eladmin-web-master/src/views/mnt/database/execute.vue
eladmin-web-master/src/views/mnt/database/index.vue
eladmin-web-master/src/views/mnt/deploy/deploy.vue
eladmin-web-master/src/views/mnt/deploy/index.vue
eladmin-web-master/src/views/mnt/deploy/sysRestore.vue
eladmin-web-master/src/views/mnt/deployHistory/index.vue
eladmin-web-master/src/views/mnt/server/index.vue
eladmin-web-master/src/views/monitor/log/errorLog.vue
eladmin-web-master/src/views/monitor/log/index.vue
eladmin-web-master/src/views/monitor/log/search.vue
eladmin-web-master/src/views/monitor/online/index.vue
eladmin-web-master/src/views/monitor/server/index.vue
eladmin-web-master/src/views/monitor/sql/index.vue
eladmin-web-master/src/views/nested/menu1/menu1-1/index.vue
eladmin-web-master/src/views/nested/menu1/menu1-2/index.vue
eladmin-web-master/src/views/nested/menu2/index.vue
eladmin-web-master/src/views/system/dept/index.vue
eladmin-web-master/src/views/system/dict/dictDetail.vue
eladmin-web-master/src/views/system/dict/index.vue
eladmin-web-master/src/views/system/job/index.vue
eladmin-web-master/src/views/system/job/module/form.vue
eladmin-web-master/src/views/system/job/module/header.vue
eladmin-web-master/src/views/system/menu/index.vue
eladmin-web-master/src/views/system/role/index.vue
eladmin-web-master/src/views/system/timing/index.vue
eladmin-web-master/src/views/system/timing/log.vue
eladmin-web-master/src/views/system/user/center.vue
eladmin-web-master/src/views/system/user/center/updateEmail.vue
eladmin-web-master/src/views/system/user/center/updatePass.vue
eladmin-web-master/src/views/system/user/index.vue
eladmin-web-master/src/views/tools/aliPay/config.vue
eladmin-web-master/src/views/tools/aliPay/index.vue
eladmin-web-master/src/views/tools/aliPay/toPay.vue
eladmin-web-master/src/views/tools/email/config.vue
eladmin-web-master/src/views/tools/email/index.vue
eladmin-web-master/src/views/tools/email/send.vue
eladmin-web-master/src/views/tools/storage/index.vue
eladmin-web-master/src/views/tools/storage/local/index.vue
eladmin-web-master/src/views/tools/storage/qiniu/form.vue
eladmin-web-master/src/views/tools/storage/qiniu/index.vue
eladmin-web-master/src/views/tools/swagger/index.vue
eladmin-web-master/vue.config.js |